summaryrefslogtreecommitdiff
path: root/tests/test_tools
diff options
context:
space:
mode:
authorxue <>2006-07-07 14:54:15 +0000
committerxue <>2006-07-07 14:54:15 +0000
commit61bb16ee2e5f0a66234e1575242169a10fde47b5 (patch)
tree3ee24dcc36ceae2c213130df1ea3d5c9fc110a27 /tests/test_tools
parent7b84938b1b5964f2274d66e28ba17435924ffe35 (diff)
Merge from 3.0 branch till 1253.
Diffstat (limited to 'tests/test_tools')
-rw-r--r--tests/test_tools/README.txt532
-rw-r--r--tests/test_tools/functional_tests.php66
-rw-r--r--tests/test_tools/selenium/core/SeleniumLog.html78
-rw-r--r--tests/test_tools/selenium/core/TestRunner-splash.html52
-rw-r--r--tests/test_tools/selenium/core/scripts/find_matching_child.js69
-rw-r--r--tests/test_tools/selenium/core/scripts/htmlutils.js463
-rw-r--r--tests/test_tools/selenium/core/scripts/prototype-1.4.0.js1781
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-api.js1402
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-browserbot.js1114
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-browserdetect.js115
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-commandhandlers.js371
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-executionloop.js266
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-logging.js112
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-seleneserunner.js300
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-testrunner.js748
-rw-r--r--tests/test_tools/selenium/core/scripts/selenium-version.js5
-rw-r--r--tests/test_tools/selenium/core/scripts/user-extensions.js.sample75
-rw-r--r--tests/test_tools/selenium/core/scripts/xmlextras.js153
-rw-r--r--tests/test_tools/selenium/core/selenium.css211
-rw-r--r--tests/test_tools/selenium/core/xpath/dom.js428
-rw-r--r--tests/test_tools/selenium/core/xpath/misc.js255
-rw-r--r--tests/test_tools/selenium/core/xpath/xpath.js2182
-rw-r--r--tests/test_tools/selenium/php/TestRunner.php169
-rw-r--r--tests/test_tools/selenium/php/results.php160
-rw-r--r--tests/test_tools/selenium/php/selenium.php477
-rw-r--r--tests/test_tools/selenium/prado-functional-test.js247
-rwxr-xr-xtests/test_tools/simpletest/CHANGELOG6
-rwxr-xr-xtests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE201
-rw-r--r--tests/test_tools/simpletest/HtmlReporterWithCoverage.php268
-rwxr-xr-xtests/test_tools/simpletest/LICENSE49
-rwxr-xr-xtests/test_tools/simpletest/README110
-rwxr-xr-xtests/test_tools/simpletest/VERSION1
-rw-r--r--tests/test_tools/simpletest/authentication.php219
-rw-r--r--tests/test_tools/simpletest/browser.php1016
-rwxr-xr-xtests/test_tools/simpletest/docs/en/authentication_documentation.html320
-rwxr-xr-xtests/test_tools/simpletest/docs/en/browser_documentation.html386
-rwxr-xr-xtests/test_tools/simpletest/docs/en/docs.css84
-rwxr-xr-xtests/test_tools/simpletest/docs/en/expectation_documentation.html356
-rwxr-xr-xtests/test_tools/simpletest/docs/en/form_testing_documentation.html277
-rwxr-xr-xtests/test_tools/simpletest/docs/en/group_test_documentation.html357
-rwxr-xr-xtests/test_tools/simpletest/docs/en/index.html467
-rwxr-xr-xtests/test_tools/simpletest/docs/en/mock_objects_documentation.html713
-rwxr-xr-xtests/test_tools/simpletest/docs/en/overview.html422
-rwxr-xr-xtests/test_tools/simpletest/docs/en/partial_mocks_documentation.html426
-rwxr-xr-xtests/test_tools/simpletest/docs/en/reporter_documentation.html515
-rwxr-xr-xtests/test_tools/simpletest/docs/en/server_stubs_documentation.html388
-rwxr-xr-xtests/test_tools/simpletest/docs/en/unit_test_documentation.html387
-rwxr-xr-xtests/test_tools/simpletest/docs/en/web_tester_documentation.html508
-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.php380
-rw-r--r--tests/test_tools/simpletest/encoding.php156
-rw-r--r--tests/test_tools/simpletest/errors.php141
-rw-r--r--tests/test_tools/simpletest/expectation.php568
-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.php619
-rw-r--r--tests/test_tools/simpletest/frames.php673
-rw-r--r--tests/test_tools/simpletest/http.php853
-rw-r--r--tests/test_tools/simpletest/mock_objects.php1323
-rw-r--r--tests/test_tools/simpletest/options.php366
-rw-r--r--tests/test_tools/simpletest/page.php961
-rw-r--r--tests/test_tools/simpletest/parser.php750
-rw-r--r--tests/test_tools/simpletest/remote.php115
-rw-r--r--tests/test_tools/simpletest/reporter.php241
-rw-r--r--tests/test_tools/simpletest/runner.php300
-rw-r--r--tests/test_tools/simpletest/scorer.php378
-rw-r--r--tests/test_tools/simpletest/shell_tester.php271
-rw-r--r--tests/test_tools/simpletest/simple_test.php553
-rw-r--r--tests/test_tools/simpletest/socket.php216
-rw-r--r--tests/test_tools/simpletest/tag.php1241
-rw-r--r--tests/test_tools/simpletest/unit_tester.php303
-rw-r--r--tests/test_tools/simpletest/url.php508
-rw-r--r--tests/test_tools/simpletest/user_agent.php490
-rw-r--r--tests/test_tools/simpletest/web_tester.php1330
-rw-r--r--tests/test_tools/simpletest/xml.php615
-rw-r--r--tests/test_tools/unit_tests.php134
89 files changed, 37392 insertions, 0 deletions
diff --git a/tests/test_tools/README.txt b/tests/test_tools/README.txt
new file mode 100644
index 00000000..cfa02abe
--- /dev/null
+++ b/tests/test_tools/README.txt
@@ -0,0 +1,532 @@
+== PRADO Functional Tests ==
+
+Functional tests are browser based that tests the overall functional of a Prado application. The tests can be written in PHP, see "framework/..." within this directory to see some examples. To run the tests, open your browser to "../tests/FunctionalTests/index.php" and click on the "All" button.
+
+
+=== Writing Tests ===
+Lets test some part of a Prado application. Create a new php file, e.g.
+
+testExample1.php
+
+<php>
+<?php
+class testExample1 extends SeleniumTestCase
+{
+ function setup()
+ {
+ $this->open('../examples/myexample/index.php');
+ }
+
+ function testButtonClickExample()
+ {
+ //using xpath to find the button with value "Click Me!"
+ $this->click('//input[@value="Click Me!"]');
+
+ //..more commands and assertions
+ }
+}
+?>
+</php>
+
+=== Tests as part of Example code ===
+Tests can also be place within the example page, e.g. suppose we have an example call MyButtonExample.
+
+File: MyButtonExample.php
+<php>
+<?php
+//Example class, changes the Text of a button when clicked.
+class MyButtonExample extends TPage
+{
+ function button_clicked($sender, $param)
+ {
+ $sender->Text = "Hello World!";
+ }
+}
+
+
+class testMyButtonExample extends SeleniumTestCase
+{
+ function setup()
+ {
+ //get the test page url
+ $page = Prado::getApplication()->getTestPage(__FILE__);
+
+ //open MyButtonExample page
+ $this->open($page);
+ }
+
+ function testButtonClick()
+ {
+ $this->assertTextPresent("My Button Example");
+ $this->click('//input[@value="Click Me!"]');
+ $this->click('//input[@value="Hello World!"]');
+ }
+}
+?>
+</php>
+
+File: MyButtonExample.tpl
+<prado>
+<com:TForm>
+ <h1>My Button Example</h1>
+ <com:TButton Text="Click Me!"
+ Click="button_clicked" />
+</com:TForm>
+</prado>
+
+== Selenium Reference ==
+
+A '''command''' is what tells Selenium what to do. Selenium commands come in two 'flavors', '''Actions''' and '''Assertions'''. Each command call has the following syntax
+<php>
+ $this->[command]([target], [value]);
+</php>
+Note that some commands does not need a [value].
+
+'''Actions''' are commands that generally manipulate the state of the application. They do things like "click this link" and "select that option". If an Action fails, or has an error, the execution of the current test is stopped.
+
+
+'''Checks''' verify the state of the application conforms to what is expected. Examples include "make sure the page title is X" and "check that this checkbox is checked". It is possible to tell Selenium to stop the test when an Assertion fails, or to simply record the failure and continue.
+
+'''Element Locators''' tell Selenium which HTML element a command refers to. Many commands require an Element Locator as the "target" attribute. Examples of Element Locators include "elementId" and "document.forms[0].element". These are described more clearly in the next section.
+
+'''Patterns''' are used for various reasons, e.g. to specify the expected value of an input field, or identify a select option. Selenium supports various types of pattern, including regular-expressions, all of which are described in more detail below.
+
+=== Element Locators ===
+
+Element Locators allow Selenium to identify which HTML element a command refers to. Selenium support the following strategies for locating elements:
+
+==== '''id='''''id'' ====
+Select the element with the specified @id attribute.
+
+==== '''name='''''name'' ====
+Select the first element with the specified @name attribute.
+
+==== '''identifier='''''id''====
+Select the element with the specified @id attribute. If no match is found, select the first element whose @name attribute is ''id''.
+
+==== '''dom='''''javascriptExpression''====
+Find an element using JavaScript traversal of the HTML Document Object Model. DOM locators ''must'' begin with "document.".
+* dom=document.forms['myForm'].myDropdown
+* dom=document.images[56]
+
+==== '''xpath='''''xpathExpression''====
+Locate an element using an XPath expression. XPath locators ''must'' begin with "//".
+* xpath=//img[@alt='The image alt text']
+* xpath=//table[@id='table1']//tr[4]/td[2]
+
+==== '''link='''''textPattern'' ====
+Select the link (anchor) element which contains text matching the specified ''pattern''.
+* link=The link text
+
+Without a locator prefix, Selenium uses:
+
+* dom, for locators starting with "document."
+* xpath, for locators starting with "//"
+* identifier, otherwise
+
+
+=== Select Option Specifiers ===
+
+Select Option Specifiers provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Specifier.
+
+==== label=labelPattern ====
+matches options based on their labels, i.e. the visible text.
+* label=regexp:^[Oo]ther
+
+==== value=valuePattern ====
+matches options based on their values.
+* value=other
+
+==== id=id ====
+matches options based on their ids.
+* id=option1
+
+==== index=index ====
+matches an option based on its index (offset from zero).
+* index=2
+
+Without a prefix, the default behaviour is to only match on labels.
+
+String-match Patterns
+
+ Various Pattern syntaxes are available for matching string values:
+
+ glob:pattern
+ Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a kind of limited regular-expression syntax typically used in command-line shells. In a glob pattern, "*" represents any sequence of characters, and "?" represents any single character. Glob patterns match against the entire string.
+ regexp:regexp
+ Match a string using a regular-expression. The full power of JavaScript regular-expressions is available.
+ exact:string
+ Match a string exactly, verbatim, without any of that fancy wildcard stuff.
+
+ If no pattern prefix is specified, Selenium assumes that it's a "glob" pattern.
+
+Selenium Actions
+
+ Actions tell Selenium to do something in the application. They generally represent something a user would do.
+
+ Many Actions can be called with the "AndWait" suffix. This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load. The exceptions to this pattern are the "open" and "click" actions, which will both wait for a page to load by default.
+
+ open( url )
+
+ Opens a URL in the test frame. This accepts both relative and absolute URLs.
+
+ Note: The URL must be on the same site as Selenium due to security restrictions in the browser (Cross Site Scripting).
+
+ examples:
+
+ open /mypage
+ open http://localhost/
+
+ click( elementLocator )
+
+ Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), use "clickAndWait".
+
+ examples:
+
+ click aCheckbox
+ clickAndWait submitButton
+ clickAndWait anyLink
+
+ note:
+ Selenium will always automatically click on a popup dialog raised by the alert() or confirm() methods. (The exception is those raised during 'onload', which are not yet handled by Selenium). You must use [verify|assert]Alert or [verify|assert]Confirmation to tell Selenium that you expect the popup dialog. You may use chooseCancelOnNextConfirmation to click 'cancel' on the next confirmation dialog instead of clicking 'OK'.
+
+ type( inputLocator, value )
+
+ Sets the value of an input field, as though you typed it in.
+
+ Can also be used to set the value of combo boxes, check boxes, etc. In these cases, value should be the value of the option selected, not the visible text.
+
+ examples:
+
+ type nameField John Smith
+ typeAndWait textBoxThatSubmitsOnChange newValue
+
+ select( dropDownLocator, optionSpecifier )
+
+ Select an option from a drop-down, based on the optionSpecifier. If more than one option matches the specifier (e.g. due to the use of globs like "f*b*", or due to more than one option having the same label or value), then the first matches is selected.
+
+ examples:
+
+ select dropDown Australian Dollars
+ select dropDown index=0
+ selectAndWait currencySelector value=AUD
+ selectAndWait currencySelector label=Aus*lian D*rs
+
+ selectWindow( windowId )
+
+ Selects a popup window. Once a popup window has been selected, all commands go to that window. To select the main window again, use "null" as the target.
+
+ target: The id of the window to select.
+
+ value: ignored
+
+ examples:
+
+ selectWindow myPopupWindow
+ selectWindow null
+
+ goBack()
+
+ Simulates the user clicking the "back" button on their browser.
+
+ examples:
+
+ goBack
+
+ close()
+
+ Simulates the user clicking the "close" button in the titlebar of a popup window.
+
+ examples:
+
+ close
+
+ pause( milliseconds )
+
+ Pauses the execution of the test script for a specified amount of time. This is useful for debugging a script or pausing to wait for some server side action.
+
+ examples:
+
+ pause 5000
+ pause 2000
+
+ fireEvent( elementLocator, eventName )
+
+ Explicitly simulate an event, to trigger the corresponding "onevent" handler.
+
+ examples:
+
+ fireEvent textField focus
+ fireEvent dropDown blur
+
+ waitForValue( inputLocator, value )
+
+ Waits for a specified input (e.g. a hidden field) to have a specified value. Will succeed immediately if the input already has the value. This is implemented by polling for the value. Warning: can block indefinitely if the input never has the specified value.
+
+ example:
+
+ waitForValue finishIndication isfinished
+
+ store( valueToStore, variableName )
+
+ Stores a value into a variable. The value can be constructed using either variable substitution or javascript evaluation, as detailed in 'Parameter construction and Variables' (below).
+
+ examples:
+
+ store Mr John Smith fullname
+ store ${title} ${firstname} ${surname} fullname
+ store javascript{Math.round(Math.PI * 100) / 100} PI
+
+ storeValue( inputLocator, variableName )
+
+ Stores the value of an input field into a variable.
+
+ examples:
+
+ storeValue userName userID
+ type userName ${userID}
+
+ storeText( elementLocator, variableName )
+
+ Stores the text of an element into a variable.
+
+ examples:
+
+ storeText currentDate expectedStartDate
+ verifyValue startDate ${expectedStartDate}
+
+ storeAttribute( elementLocator@attributeName, variableName )
+
+ Stores the value of an element attribute into a variable.
+
+ examples:
+
+ storeAttribute input1@class classOfInput1
+ verifyAttribute input2@class ${classOfInput1}
+
+ chooseCancelOnNextConfirmation()
+
+ Instructs Selenium to click Cancel on the next javascript confirmation dialog to be raised. By default, the confirm function will return true, having the same effect as manually clicking OK. After running this command, the next confirmation will behave as if the user had clicked Cancel.
+
+ examples:
+
+ chooseCancelOnNextConfirmation
+
+ answerOnNextPrompt( answerString )
+
+ Instructs Selenium to return the specified answerString in response to the next prompt.
+
+ examples:
+
+ answerOnNextPrompt Kangaroo
+
+Selenium Checks
+
+ Checks are used to verify the state of the application. They can be used to check the value of a form field, the presense of some text, or the URL of the current page.
+
+ All Selenium Checks can be used in 2 modes, "assert" and "verify". These behave identically, except that when an "assert" check fails, the test is aborted. When a "verify" check fails, the test will continue execution. This allows a single "assert" to ensure that the application is on the correct page, followed by a bunch of "verify" checks to test form field values, labels, etc.
+
+ assertLocation( relativeLocation )
+
+ examples:
+
+ verifyLocation /mypage
+ assertLocation /mypage
+
+ assertTitle( titlePattern )
+
+ Verifies the title of the current page.
+
+ examples:
+
+ verifyTitle My Page
+ assertTitle My Page
+
+ assertValue( inputLocator, valuePattern )
+
+ Verifies the value of an input field (or anything else with a value parameter). For checkbox/radio elements, the value will be "on" or "off" depending on whether the element is checked or not.
+
+ examples:
+
+ verifyValue nameField John Smith
+ assertValue document.forms[2].nameField John Smith
+
+ assertSelected( selectLocator, optionSpecifier )
+
+ Verifies that the selected option of a drop-down satisfies the optionSpecifier.
+
+ examples:
+
+ verifySelected dropdown2 John Smith
+ verifySelected dropdown2 value=js*123
+ assertSelected document.forms[2].dropDown label=J* Smith
+ assertSelected document.forms[2].dropDown index=0
+
+ assertSelectOptions( selectLocator, optionLabelList )
+
+ Verifies the labels of all options in a drop-down against a comma-separated list. Commas in an expected option can be escaped as ",".
+
+ examples:
+
+ verifySelectOptions dropdown2 John Smith,Dave Bird
+ assertSelectOptions document.forms[2].dropDown Smith\, J,Bird\, D
+
+ assertText( elementLocator, textPattern )
+
+ Verifies the text of an element. This works for any element that contains text. This command uses either the textContent (Mozilla-like browsers) or the innerText (IE-like browsers) of the element, which is the rendered text shown to the user.
+
+ examples:
+
+ verifyText statusMessage Successful
+ assertText //div[@id='foo']//h1 Successful
+
+ assertAttribute( elementLocator@attributeName, valuePattern )
+
+ Verifies the value of an element attribute.
+
+ examples:
+
+ verifyAttribute txt1@class bigAndBold
+ assertAttribute document.images[0]@alt alt-text
+ verifyAttribute //img[@id='foo']/@alt alt-text
+
+ assertTextPresent( text )
+
+ Verifies that the specified text appears somewhere on the rendered page shown to the user.
+
+ examples:
+
+ verifyTextPresent You are now logged in.
+ assertTextPresent You are now logged in.
+
+ assertTextNotPresent( text )
+
+ Verifies that the specified text does NOT appear anywhere on the rendered page.
+
+ assertElementPresent( elementLocator )
+
+ Verifies that the specified element is somewhere on the page.
+
+ examples:
+
+ verifyElementPresent submitButton
+ assertElementPresent //img[@alt='foo']
+
+ assertElementNotPresent( elementLocator )
+
+ Verifies that the specified element is NOT on the page.
+
+ examples:
+
+ verifyElementNotPresent cancelButton
+ assertElementNotPresent cancelButton
+
+ assertTable( cellAddress, valuePattern )
+
+ Verifies the text in a cell of a table. The cellAddress syntax tableName.row.column, where row and column start at 0.
+
+ examples:
+
+ verifyTable myTable.1.6 Submitted
+ assertTable results.0.2 13
+
+ assertVisible( elementLocator )
+
+ Verifies that the specified element is both present and visible. An element can be rendered invisible by setting the CSS "visibility" property to "hidden", or the "display" property to "none", either for the element itself or one if its ancestors.
+
+ examples:
+
+ verifyVisible postcode
+ assertVisible postcode
+
+ assertNotVisible( elementLocator )
+
+ Verifies that the specified element is NOT visible. Elements that are simply not present are also considered invisible.
+
+ examples:
+
+ verifyNotVisible postcode
+ assertNotVisible postcode
+
+ verifyEditable / assertEditable( inputLocator )
+
+ Verifies that the specified element is editable, ie. it's an input element, and hasn't been disabled.
+
+ examples:
+
+ verifyEditable shape
+ assertEditable colour
+
+ assertNotEditable( inputLocator )
+
+ Verifies that the specified element is NOT editable, ie. it's NOT an input element, or has been disabled.
+
+ assertAlert( messagePattern )
+
+ Verifies that a javascript alert with the specified message was generated. Alerts must be verified in the same order that they were generated.
+
+ Verifying an alert has the same effect as manually clicking OK. If an alert is generated but you do not verify it, the next Selenium action will fail.
+
+ NOTE: under Selenium, javascript alerts will NOT pop up a visible alert dialog.
+
+ NOTE: Selenium does NOT support javascript alerts that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until you manually click OK.
+
+ examples:
+
+ verifyAlert Invalid Phone Number
+ assertAlert Invalid Phone Number
+
+ assertConfirmation( messagePattern )
+
+ Verifies that a javascript confirmation dialog with the specified message was generated. Like alerts, confirmations must be verified in the same order that they were generated.
+
+ By default, the confirm function will return true, having the same effect as manually clicking OK. This can be changed by prior execution of the chooseCancelOnNextConfirmation command (see above). If an confirmation is generated but you do not verify it, the next Selenium action will fail.
+
+ NOTE: under Selenium, javascript confirmations will NOT pop up a visible dialog.
+
+ NOTE: Selenium does NOT support javascript confirmations that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until you manually click OK.
+
+ examples:
+
+ assertConfirmation Remove this user?
+ verifyConfirmation Are you sure?
+
+ assertPrompt( messagePattern )
+
+ Verifies that a javascript prompt dialog with the specified message was generated. Like alerts, prompts must be verified in the same order that they were generated.
+
+ Successful handling of the prompt requires prior execution of the answerOnNextPrompt command (see above). If a prompt is generated but you do not verify it, the next Selenium action will fail.
+
+ examples:
+
+ answerOnNextPrompt Joe
+ click id=delegate
+ verifyPrompt Delegate to who?
+
+Parameter construction and Variables
+
+ All Selenium command parameters can be constructed using both simple variable substitution as well as full javascript. Both of these mechanisms can access previously stored variables, but do so using different syntax.
+
+ Stored Variables
+
+ The commands store, storeValue and storeText can be used to store a variable value for later access. Internally, these variables are stored in a map called "storedVars", with values keyed by the variable name. These commands are documented in the command reference.
+
+ Variable substitution
+
+ Variable substitution provides a simple way to include a previously stored variable in a command parameter. This is a simple mechanism, by which the variable to substitute is indicated by ${variableName}. Multiple variables can be substituted, and intermixed with static text.
+
+ Example:
+
+ store Mr title
+ storeValue nameField surname
+ store ${title} ${surname} fullname
+ type textElement Full name is: ${fullname}
+
+ Javascript evaluation
+
+ Javascript evaluation provides the full power of javascript in constructing a command parameter. To use this mechanism, the entire parameter value must be prefixed by 'javascript{' with a trailing '}'. The text inside the braces is evaluated as a javascript expression, and can access previously stored variables using the storedVars map detailed above. Note that variable substitution cannot be combined with javascript evaluation.
+
+ Example:
+
+ store javascript{'merchant' + (new Date()).getTime()} merchantId
+ type textElement javascript{storedVars['merchantId'].toUpperCase()} \ No newline at end of file
diff --git a/tests/test_tools/functional_tests.php b/tests/test_tools/functional_tests.php
new file mode 100644
index 00000000..73bd6226
--- /dev/null
+++ b/tests/test_tools/functional_tests.php
@@ -0,0 +1,66 @@
+<?php
+
+$TEST_TOOLS = dirname(__FILE__);
+
+if(isset($_GET['sr']))
+{
+
+ if(($selenium_resource=realpath($TEST_TOOLS.'/selenium/'.$_GET['sr']))!==false)
+ echo file_get_contents($selenium_resource);
+ exit;
+}
+
+require_once($TEST_TOOLS.'/simpletest/unit_tester.php');
+require_once($TEST_TOOLS.'/simpletest/web_tester.php');
+require_once($TEST_TOOLS.'/simpletest/mock_objects.php');
+require_once($TEST_TOOLS.'/simpletest/reporter.php');
+require_once($TEST_TOOLS.'/selenium/php/selenium.php');
+
+class PradoFunctionalTester
+{
+ private $_name;
+ private $_basePath;
+ private $_selenium;
+
+ public function __construct($basePath,$selenium='',$name='All Tests')
+ {
+ $this->_name=$name;
+ if($basePath==='' || ($this->_basePath=realpath($basePath))===false)
+ throw new Exception('Invalid base path '.$basePath);
+ $this->_basePath=strtr($this->_basePath,'\\','/');
+
+ $this->_selenium = $selenium.'selenium/';
+ }
+
+ public function run($simpleReporter)
+ {
+ $server=SimpleSeleniumProxyServer::getInstance(dirname(__FILE__));//, '', $this->_selenium);
+
+ $groupTest=new GroupTest($this->_name);
+ $this->collectTestFiles($groupTest,$this->_basePath);
+ $groupTest->run($simpleReporter);
+
+ $server->handleRequest();
+ }
+
+ protected function collectTestFiles($groupTest,$basePath)
+ {
+ $folder=@opendir($basePath);
+ while($entry=@readdir($folder))
+ {
+ $fullPath=strtr($basePath.'/'.$entry,'\\','/');
+ if(is_file($fullPath) && $this->isValidFile($entry))
+ $groupTest->addTestFile($fullPath);
+ else if($entry[0]!=='.')
+ $this->collectTestFiles($groupTest,$fullPath);
+ }
+ @closedir($folder);
+ }
+
+ protected function isValidFile($entry)
+ {
+ return preg_match('/\w+\.php$/',$entry);
+ }
+}
+
+?> \ No newline at end of file
diff --git a/tests/test_tools/selenium/core/SeleniumLog.html b/tests/test_tools/selenium/core/SeleniumLog.html
new file mode 100644
index 00000000..dfa0080a
--- /dev/null
+++ b/tests/test_tools/selenium/core/SeleniumLog.html
@@ -0,0 +1,78 @@
+<html>
+
+<head>
+<title>Selenium Log Console</title>
+
+</head>
+<body id="logging-console">
+
+<script language="JavaScript">
+
+var logLevels = {
+ debug: 0,
+ info: 1,
+ warn: 2,
+ error: 3
+};
+
+var logLevelThreshold = null;
+
+function getThresholdLevel() {
+ var buttons = document.getElementById('logLevelChooser').level;
+ for (var i = 0; i < buttons.length; i++) {
+ if (buttons[i].checked) {
+ return buttons[i].value;
+ }
+ }
+}
+
+function setThresholdLevel(logLevel) {
+ logLevelThreshold = logLevel;
+ var buttons = document.getElementById('logLevelChooser').level;
+ for (var i = 0; i < buttons.length; i++) {
+ if (buttons[i].value==logLevel) {
+ buttons[i].checked = true;
+ }
+ else {
+ buttons[i].checked = false;
+ }
+ }
+}
+
+function append(message, logLevel) {
+ if (logLevelThreshold==null) {
+ logLevelThreshold = getThresholdLevel();
+ }
+ if (logLevels[logLevel] < logLevels[logLevelThreshold]) {
+ return;
+ }
+ var log = document.getElementById('log');
+ var newEntry = document.createElement('li');
+ newEntry.className = logLevel;
+ newEntry.appendChild(document.createTextNode(message));
+ log.appendChild(newEntry);
+ if (newEntry.scrollIntoView) {
+ newEntry.scrollIntoView();
+ }
+}
+
+</script>
+
+<div id="banner">
+ <form id="logLevelChooser">
+ <input id="level-error" type="radio" name="level"
+ value="error" /><label for="level-error">Error</label>
+ <input id="level-warn" type="radio" name="level"
+ value="warn" /><label for="level-warn">Warn</label>
+ <input id="level-info" type="radio" name="level" checked="yes"
+ value="info" /><label for="level-info">Info</label>
+ <input id="level-debug" type="radio" name="level"
+ value="debug" /><label for="level-debug">Debug</label>
+ </form>
+ <h1>Selenium Log Console</h1>
+</div>
+
+<ul id="log"></ul>
+
+</body>
+</html>
diff --git a/tests/test_tools/selenium/core/TestRunner-splash.html b/tests/test_tools/selenium/core/TestRunner-splash.html
new file mode 100644
index 00000000..205bb8ef
--- /dev/null
+++ b/tests/test_tools/selenium/core/TestRunner-splash.html
@@ -0,0 +1,52 @@
+<!--
+Copyright 2005 ThoughtWorks, Inc
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<html>
+<body>
+<table width="100%">
+
+<tr>
+ <th>&uarr;</th>
+ <th>&uarr;</th>
+ <th>&uarr;</th>
+</tr>
+<tr>
+ <th width="25%">Test Suite</th>
+ <th width="50%">Current Test</th>
+ <th width="25%">Control Panel</th>
+</tr>
+<tr><td>&nbsp;</td></tr>
+
+<tr>
+<td></td>
+<td class="selenium splash">
+
+<h1>Selenium</h1>
+<h2>by <a href="http://www.thoughtworks.com">ThoughtWorks</a> and friends</h2>
+
+<p>
+For more information on Selenium, visit
+
+<pre>
+ <a href="http://selenium.openqa.org" target="_blank">http://selenium.openqa.org</a>
+</pre>
+
+</td>
+<tr>
+
+</table>
+</body>
+</html>
diff --git a/tests/test_tools/selenium/core/scripts/find_matching_child.js b/tests/test_tools/selenium/core/scripts/find_matching_child.js
new file mode 100644
index 00000000..197d1032
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/find_matching_child.js
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2004 ThoughtWorks, Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+Element.findMatchingChildren = function(element, selector) {
+ var matches = $A([]);
+
+ var childCount = element.childNodes.length;
+ for (var i=0; i<childCount; i++) {
+ var child = element.childNodes[i];
+ if (selector(child)) {
+ matches.push(child);
+ } else {
+ childMatches = Element.findMatchingChildren(child, selector);
+ matches.push(childMatches);
+ }
+ }
+
+ return matches.flatten();
+}
+
+ELEMENT_NODE_TYPE = 1;
+
+Element.findFirstMatchingChild = function(element, selector) {
+
+ var childCount = element.childNodes.length;
+ for (var i=0; i<childCount; i++) {
+ var child = element.childNodes[i];
+ if (child.nodeType == ELEMENT_NODE_TYPE) {
+ if (selector(child)) {
+ return child;
+ }
+ result = Element.findFirstMatchingChild(child, selector);
+ if (result) {
+ return result;
+ }
+ }
+ }
+ return null;
+}
+
+Element.findFirstMatchingParent = function(element, selector) {
+ var current = element.parentNode;
+ while (current != null) {
+ if (selector(current)) {
+ break;
+ }
+ current = current.parentNode;
+ }
+ return current;
+}
+
+Element.findMatchingChildById = function(element, id) {
+ return Element.findFirstMatchingChild(element, function(element){return element.id==id} );
+}
+
diff --git a/tests/test_tools/selenium/core/scripts/htmlutils.js b/tests/test_tools/selenium/core/scripts/htmlutils.js
new file mode 100644
index 00000000..fcb1ee44
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/htmlutils.js
@@ -0,0 +1,463 @@
+/*
+ * Copyright 2004 ThoughtWorks, Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// This script contains some HTML utility functions that
+// make it possible to handle elements in a way that is
+// compatible with both IE-like and Mozilla-like browsers
+
+String.prototype.trim = function() {
+ var result = this.replace( /^\s+/g, "" );// strip leading
+ return result.replace( /\s+$/g, "" );// strip trailing
+};
+String.prototype.lcfirst = function() {
+ return this.charAt(0).toLowerCase() + this.substr(1);
+};
+String.prototype.ucfirst = function() {
+ return this.charAt(0).toUpperCase() + this.substr(1);
+};
+String.prototype.startsWith = function(str) {
+ return this.indexOf(str) == 0;
+};
+
+// Returns the text in this element
+function getText(element) {
+ var text = "";
+
+ if(browserVersion.isFirefox && browserVersion.firefoxVersion >= "1.5")
+ {
+ var dummyElement = element.cloneNode(true);
+ renderWhitespaceInTextContent(dummyElement);
+ text = dummyElement.textContent;
+ } else if (browserVersion.isOpera) {
+ var dummyElement = element.cloneNode(true);
+ renderWhitespaceInTextContent(dummyElement);
+ text = dummyElement.innerText;
+ text = xmlDecode(text);
+ }
+ else if(element.textContent)
+ {
+ text = element.textContent;
+ }
+ else if(element.innerText)
+ {
+ text = element.innerText;
+ }
+
+ text = normalizeNewlines(text);
+ text = normalizeSpaces(text);
+
+ return text.trim();
+}
+
+function renderWhitespaceInTextContent(element) {
+ // Remove non-visible newlines in text nodes
+ if (element.nodeType == Node.TEXT_NODE)
+ {
+ element.data = element.data.replace(/\n|\r|\t/g, " ");
+ return;
+ }
+
+ if (element.nodeType == Node.COMMENT_NODE)
+ {
+ element.data = "";
+ return;
+ }
+
+ // Don't modify PRE elements
+ if (element.tagName == "PRE")
+ {
+ return;
+ }
+
+ // Handle inline element that force newlines
+ if (tagIs(element, ["BR", "HR"]))
+ {
+ // Replace this element with a newline text element
+ element.parentNode.replaceChild(element.ownerDocument.createTextNode("\n"), element)
+ }
+
+ for (var i = 0; i < element.childNodes.length; i++)
+ {
+ var child = element.childNodes.item(i)
+ renderWhitespaceInTextContent(child);
+ }
+
+ // Handle block elements that introduce newlines
+// -- From HTML spec:
+//<!ENTITY % block
+// "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT |
+// BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS">
+ if (tagIs(element, ["P", "DIV"]))
+ {
+ element.appendChild(element.ownerDocument.createTextNode("\n"), element)
+ }
+
+}
+
+function tagIs(element, tags)
+{
+ var tag = element.tagName;
+ for (var i = 0; i < tags.length; i++)
+ {
+ if (tags[i] == tag)
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Convert all newlines to \m
+ */
+function normalizeNewlines(text)
+{
+ return text.replace(/\r\n|\r/g, "\n");
+}
+
+/**
+ * Replace multiple sequential spaces with a single space, and then convert &nbsp; to space.
+ */
+function normalizeSpaces(text)
+{
+ // IE has already done this conversion, so doing it again will remove multiple nbsp
+ if (browserVersion.isIE)
+ {
+ return text;
+ }
+
+ // Replace multiple spaces with a single space
+ // TODO - this shouldn't occur inside PRE elements
+ text = text.replace(/\ +/g, " ");
+
+ // Replace &nbsp; with a space
+ var pat = String.fromCharCode(160); // Opera doesn't like /\240/g
+ var re = new RegExp(pat, "g");
+ return text.replace(re, " ");
+}
+
+function xmlDecode(text) {
+ text = text.replace(/&quot;/g, '"');
+ text = text.replace(/&apos;/g, "'");
+ text = text.replace(/&lt;/g, "<");
+ text = text.replace(/&gt;/g, ">");
+ text = text.replace(/&amp;/g, "&");
+ return text;
+}
+
+// Sets the text in this element
+function setText(element, text) {
+ if(element.textContent) {
+ element.textContent = text;
+ } else if(element.innerText) {
+ element.innerText = text;
+ }
+}
+
+// Get the value of an <input> element
+function getInputValue(inputElement) {
+ if (inputElement.type.toUpperCase() == 'CHECKBOX' ||
+ inputElement.type.toUpperCase() == 'RADIO')
+ {
+ return (inputElement.checked ? 'on' : 'off');
+ }
+ return inputElement.value;
+}
+
+/* Fire an event in a browser-compatible manner */
+function triggerEvent(element, eventType, canBubble) {
+ canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
+ if (element.fireEvent) {
+ element.fireEvent('on' + eventType);
+ }
+ else {
+ var evt = document.createEvent('HTMLEvents');
+ evt.initEvent(eventType, canBubble, true);
+ element.dispatchEvent(evt);
+ }
+}
+
+function triggerKeyEvent(element, eventType, keycode, canBubble) {
+ canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
+ if (element.fireEvent) {
+ keyEvent = parent.frames['myiframe'].document.createEventObject();
+ keyEvent.keyCode=keycode;
+ element.fireEvent('on' + eventType, keyEvent);
+ }
+ else {
+ var evt;
+ if( window.KeyEvent ) {
+ evt = document.createEvent('KeyEvents');
+ evt.initKeyEvent(eventType, true, true, window, false, false, false, false, keycode, keycode);
+ } else {
+ evt = document.createEvent('UIEvents');
+ evt.initUIEvent( eventType, true, true, window, 1 );
+ evt.keyCode = keycode;
+ }
+
+ element.dispatchEvent(evt);
+ }
+}
+
+/* Fire a mouse event in a browser-compatible manner */
+function triggerMouseEvent(element, eventType, canBubble) {
+ canBubble = (typeof(canBubble) == undefined) ? true : canBubble;
+ if (element.fireEvent) {
+ element.fireEvent('on' + eventType);
+ }
+ else {
+ var evt = document.createEvent('MouseEvents');
+ if (evt.initMouseEvent)
+ {
+ evt.initMouseEvent(eventType, canBubble, true, document.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null)
+ }
+ else
+ {
+ // Safari
+ // TODO we should be initialising other mouse-event related attributes here
+ evt.initEvent(eventType, canBubble, true);
+ }
+ element.dispatchEvent(evt);
+ }
+}
+
+function removeLoadListener(element, command) {
+ if (window.removeEventListener)
+ element.removeEventListener("load", command, true);
+ else if (window.detachEvent)
+ element.detachEvent("onload", command);
+}
+
+function addLoadListener(element, command) {
+ if (window.addEventListener && !browserVersion.isOpera)
+ element.addEventListener("load",command, true);
+ else if (window.attachEvent)
+ element.attachEvent("onload",command);
+}
+
+function addUnloadListener(element, command) {
+ if (window.addEventListener)
+ element.addEventListener("unload",command, true);
+ else if (window.attachEvent)
+ element.attachEvent("onunload",command);
+}
+
+/**
+ * Override the broken getFunctionName() method from JsUnit
+ * This file must be loaded _after_ the jsunitCore.js
+ */
+function getFunctionName(aFunction) {
+ var regexpResult = aFunction.toString().match(/function (\w*)/);
+ if (regexpResult && regexpResult[1]) {
+ return regexpResult[1];
+ }
+ return 'anonymous';
+}
+
+function getDocumentBase(doc) {
+ var bases = document.getElementsByTagName("base");
+ if (bases && bases.length && bases[0].href) {
+ return bases[0].href;
+ }
+ return "";
+}
+
+function describe(object, delimiter) {
+ var props = new Array();
+ for (var prop in object) {
+ props.push(prop + " -> " + object[prop]);
+ }
+ return props.join(delimiter || '\n');
+}
+
+var PatternMatcher = function(pattern) {
+ this.selectStrategy(pattern);
+};
+PatternMatcher.prototype = {
+
+ selectStrategy: function(pattern) {
+ this.pattern = pattern;
+ var strategyName = 'glob'; // by default
+ if (/^([a-z-]+):(.*)/.test(pattern)) {
+ strategyName = RegExp.$1;
+ pattern = RegExp.$2;
+ }
+ var matchStrategy = PatternMatcher.strategies[strategyName];
+ if (!matchStrategy) {
+ throw new SeleniumError("cannot find PatternMatcher.strategies." + strategyName);
+ }
+ this.strategy = matchStrategy;
+ this.matcher = new matchStrategy(pattern);
+ },
+
+ matches: function(actual) {
+ return this.matcher.matches(actual + '');
+ // Note: appending an empty string avoids a Konqueror bug
+ }
+
+};
+
+/**
+ * A "static" convenience method for easy matching
+ */
+PatternMatcher.matches = function(pattern, actual) {
+ return new PatternMatcher(pattern).matches(actual);
+};
+
+PatternMatcher.strategies = {
+
+ /**
+ * Exact matching, e.g. "exact:***"
+ */
+ exact: function(expected) {
+ this.expected = expected;
+ this.matches = function(actual) {
+ return actual == this.expected;
+ };
+ },
+
+ /**
+ * Match by regular expression, e.g. "regexp:^[0-9]+$"
+ */
+ regexp: function(regexpString) {
+ this.regexp = new RegExp(regexpString);
+ this.matches = function(actual) {
+ return this.regexp.test(actual);
+ };
+ },
+
+ /**
+ * "globContains" (aka "wildmat") patterns, e.g. "glob:one,two,*",
+ * but don't require a perfect match; instead succeed if actual
+ * contains something that matches globString.
+ * Making this distinction is motivated by a bug in IE6 which
+ * leads to the browser hanging if we implement *TextPresent tests
+ * by just matching against a regular expression beginning and
+ * ending with ".*". The globcontains strategy allows us to satisfy
+ * the functional needs of the *TextPresent ops more efficiently
+ * and so avoid running into this IE6 freeze.
+ */
+ globContains: function(globString) {
+ this.regexp = new RegExp(PatternMatcher.regexpFromGlobContains(globString));
+ this.matches = function(actual) {
+ return this.regexp.test(actual);
+ };
+ },
+
+
+ /**
+ * "glob" (aka "wildmat") patterns, e.g. "glob:one,two,*"
+ */
+ glob: function(globString) {
+ this.regexp = new RegExp(PatternMatcher.regexpFromGlob(globString));
+ this.matches = function(actual) {
+ return this.regexp.test(actual);
+ };
+ }
+
+};
+
+PatternMatcher.convertGlobMetaCharsToRegexpMetaChars = function(glob) {
+ var re = glob;
+ re = re.replace(/([.^$+(){}\[\]\\|])/g, "\\$1");
+ re = re.replace(/\?/g, "(.|[\r\n])");
+ re = re.replace(/\*/g, "(.|[\r\n])*");
+ return re;
+};
+
+PatternMatcher.regexpFromGlobContains = function(globContains) {
+ return PatternMatcher.convertGlobMetaCharsToRegexpMetaChars(globContains);
+};
+
+PatternMatcher.regexpFromGlob = function(glob) {
+ return "^" + PatternMatcher.convertGlobMetaCharsToRegexpMetaChars(glob) + "$";
+};
+
+var Assert = {
+
+ fail: function(message) {
+ throw new AssertionFailedError(message);
+ },
+
+ /*
+ * Assert.equals(comment?, expected, actual)
+ */
+ equals: function() {
+ var args = new AssertionArguments(arguments);
+ if (args.expected === args.actual) {
+ return;
+ }
+ Assert.fail(args.comment +
+ "Expected '" + args.expected +
+ "' but was '" + args.actual + "'");
+ },
+
+ /*
+ * Assert.matches(comment?, pattern, actual)
+ */
+ matches: function() {
+ var args = new AssertionArguments(arguments);
+ if (PatternMatcher.matches(args.expected, args.actual)) {
+ return;
+ }
+ Assert.fail(args.comment +
+ "Actual value '" + args.actual +
+ "' did not match '" + args.expected + "'");
+ },
+
+ /*
+ * Assert.notMtches(comment?, pattern, actual)
+ */
+ notMatches: function() {
+ var args = new AssertionArguments(arguments);
+ if (!PatternMatcher.matches(args.expected, args.actual)) {
+ return;
+ }
+ Assert.fail(args.comment +
+ "Actual value '" + args.actual +
+ "' did match '" + args.expected + "'");
+ }
+
+};
+
+// Preprocess the arguments to allow for an optional comment.
+function AssertionArguments(args) {
+ if (args.length == 2) {
+ this.comment = "";
+ this.expected = args[0];
+ this.actual = args[1];
+ } else {
+ this.comment = args[0] + "; ";
+ this.expected = args[1];
+ this.actual = args[2];
+ }
+}
+
+
+
+function AssertionFailedError(message) {
+ this.isAssertionFailedError = true;
+ this.isSeleniumError = true;
+ this.message = message;
+ this.failureMessage = message;
+}
+
+function SeleniumError(message) {
+ var error = new Error(message);
+ error.isSeleniumError = true;
+ return error;
+};
diff --git a/tests/test_tools/selenium/core/scripts/prototype-1.4.0.js b/tests/test_tools/selenium/core/scripts/prototype-1.4.0.js
new file mode 100644
index 00000000..0e85338b
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/prototype-1.4.0.js
@@ -0,0 +1,1781 @@
+/* Prototype JavaScript framework, version 1.4.0
+ * (c) 2005 Sam Stephenson <sam@conio.net>
+ *
+ * Prototype is freely distributable under the terms of an MIT-style license.
+ * For details, see the Prototype web site: http://prototype.conio.net/
+ *
+/*--------------------------------------------------------------------------*/
+
+var Prototype = {
+ Version: '1.4.0',
+ ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
+
+ emptyFunction: function() {},
+ K: function(x) {return x}
+}
+
+var Class = {
+ create: function() {
+ return function() {
+ this.initialize.apply(this, arguments);
+ }
+ }
+}
+
+var Abstract = new Object();
+
+Object.extend = function(destination, source) {
+ for (property in source) {
+ destination[property] = source[property];
+ }
+ return destination;
+}
+
+Object.inspect = function(object) {
+ try {
+ if (object == undefined) return 'undefined';
+ if (object == null) return 'null';
+ return object.inspect ? object.inspect() : object.toString();
+ } catch (e) {
+ if (e instanceof RangeError) return '...';
+ throw e;
+ }
+}
+
+Function.prototype.bind = function() {
+ var __method = this, args = $A(arguments), object = args.shift();
+ return function() {
+ return __method.apply(object, args.concat($A(arguments)));
+ }
+}
+
+Function.prototype.bindAsEventListener = function(object) {
+ var __method = this;
+ return function(event) {
+ return __method.call(object, event || window.event);
+ }
+}
+
+Object.extend(Number.prototype, {
+ toColorPart: function() {
+ var digits = this.toString(16);
+ if (this < 16) return '0' + digits;
+ return digits;
+ },
+
+ succ: function() {
+ return this + 1;
+ },
+
+ times: function(iterator) {
+ $R(0, this, true).each(iterator);
+ return this;
+ }
+});
+
+var Try = {
+ these: function() {
+ var returnValue;
+
+ for (var i = 0; i < arguments.length; i++) {
+ var lambda = arguments[i];
+ try {
+ returnValue = lambda();
+ break;
+ } catch (e) {}
+ }
+
+ return returnValue;
+ }
+}
+
+/*--------------------------------------------------------------------------*/
+
+var PeriodicalExecuter = Class.create();
+PeriodicalExecuter.prototype = {
+ initialize: function(callback, frequency) {
+ this.callback = callback;
+ this.frequency = frequency;
+ this.currentlyExecuting = false;
+
+ this.registerCallback();
+ },
+
+ registerCallback: function() {
+ setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
+ },
+
+ onTimerEvent: function() {
+ if (!this.currentlyExecuting) {
+ try {
+ this.currentlyExecuting = true;
+ this.callback();
+ } finally {
+ this.currentlyExecuting = false;
+ }
+ }
+ }
+}
+
+/*--------------------------------------------------------------------------*/
+
+function $() {
+ var elements = new Array();
+
+ for (var i = 0; i < arguments.length; i++) {
+ var element = arguments[i];
+ if (typeof element == 'string')
+ element = document.getElementById(element);
+
+ if (arguments.length == 1)
+ return element;
+
+ elements.push(element);
+ }
+
+ return elements;
+}
+Object.extend(String.prototype, {
+ stripTags: function() {
+ return this.replace(/<\/?[^>]+>/gi, '');
+ },
+
+ stripScripts: function() {
+ return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
+ },
+
+ extractScripts: function() {
+ var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
+ var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
+ return (this.match(matchAll) || []).map(function(scriptTag) {
+ return (scriptTag.match(matchOne) || ['', ''])[1];
+ });
+ },
+
+ evalScripts: function() {
+ return this.extractScripts().map(eval);
+ },
+
+ escapeHTML: function() {
+ var div = document.createElement('div');
+ var text = document.createTextNode(this);
+ div.appendChild(text);
+ return div.innerHTML;
+ },
+
+ unescapeHTML: function() {
+ var div = document.createElement('div');
+ div.innerHTML = this.stripTags();
+ return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
+ },
+
+ toQueryParams: function() {
+ var pairs = this.match(/^\??(.*)$/)[1].split('&');
+ return pairs.inject({}, function(params, pairString) {
+ var pair = pairString.split('=');
+ params[pair[0]] = pair[1];
+ return params;
+ });
+ },
+
+ toArray: function() {
+ return this.split('');
+ },
+
+ camelize: function() {
+ var oStringList = this.split('-');
+ if (oStringList.length == 1) return oStringList[0];
+
+ var camelizedString = this.indexOf('-') == 0
+ ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
+ : oStringList[0];
+
+ for (var i = 1, len = oStringList.length; i < len; i++) {
+ var s = oStringList[i];
+ camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
+ }
+
+ return camelizedString;
+ },
+
+ inspect: function() {
+ return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
+ }
+});
+
+String.prototype.parseQuery = String.prototype.toQueryParams;
+
+var $break = new Object();
+var $continue = new Object();
+
+var Enumerable = {
+ each: function(iterator) {
+ var index = 0;
+ try {
+ this._each(function(value) {
+ try {
+ iterator(value, index++);
+ } catch (e) {
+ if (e != $continue) throw e;
+ }
+ });
+ } catch (e) {
+ if (e != $break) throw e;
+ }
+ },
+
+ all: function(iterator) {
+ var result = true;
+ this.each(function(value, index) {
+ result = result && !!(iterator || Prototype.K)(value, index);
+ if (!result) throw $break;
+ });
+ return result;
+ },
+
+ any: function(iterator) {
+ var result = true;
+ this.each(function(value, index) {
+ if (result = !!(iterator || Prototype.K)(value, index))
+ throw $break;
+ });
+ return result;
+ },
+
+ collect: function(iterator) {
+ var results = [];
+ this.each(function(value, index) {
+ results.push(iterator(value, index));
+ });
+ return results;
+ },
+
+ detect: function (iterator) {
+ var result;
+ this.each(function(value, index) {
+ if (iterator(value, index)) {
+ result = value;
+ throw $break;
+ }
+ });
+ return result;
+ },
+
+ findAll: function(iterator) {
+ var results = [];
+ this.each(function(value, index) {
+ if (iterator(value, index))
+ results.push(value);
+ });
+ return results;
+ },
+
+ grep: function(pattern, iterator) {
+ var results = [];
+ this.each(function(value, index) {
+ var stringValue = value.toString();
+ if (stringValue.match(pattern))
+ results.push((iterator || Prototype.K)(value, index));
+ })
+ return results;
+ },
+
+ include: function(object) {
+ var found = false;
+ this.each(function(value) {
+ if (value == object) {
+ found = true;
+ throw $break;
+ }
+ });
+ return found;
+ },
+
+ inject: function(memo, iterator) {
+ this.each(function(value, index) {
+ memo = iterator(memo, value, index);
+ });
+ return memo;
+ },
+
+ invoke: function(method) {
+ var args = $A(arguments).slice(1);
+ return this.collect(function(value) {
+ return value[method].apply(value, args);
+ });
+ },
+
+ max: function(iterator) {
+ var result;
+ this.each(function(value, index) {
+ value = (iterator || Prototype.K)(value, index);
+ if (value >= (result || value))
+ result = value;
+ });
+ return result;
+ },
+
+ min: function(iterator) {
+ var result;
+ this.each(function(value, index) {
+ value = (iterator || Prototype.K)(value, index);
+ if (value <= (result || value))
+ result = value;
+ });
+ return result;
+ },
+
+ partition: function(iterator) {
+ var trues = [], falses = [];
+ this.each(function(value, index) {
+ ((iterator || Prototype.K)(value, index) ?
+ trues : falses).push(value);
+ });
+ return [trues, falses];
+ },
+
+ pluck: function(property) {
+ var results = [];
+ this.each(function(value, index) {
+ results.push(value[property]);
+ });
+ return results;
+ },
+
+ reject: function(iterator) {
+ var results = [];
+ this.each(function(value, index) {
+ if (!iterator(value, index))
+ results.push(value);
+ });
+ return results;
+ },
+
+ sortBy: function(iterator) {
+ return this.collect(function(value, index) {
+ return {value: value, criteria: iterator(value, index)};
+ }).sort(function(left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }).pluck('value');
+ },
+
+ toArray: function() {
+ return this.collect(Prototype.K);
+ },
+
+ zip: function() {
+ var iterator = Prototype.K, args = $A(arguments);
+ if (typeof args.last() == 'function')
+ iterator = args.pop();
+
+ var collections = [this].concat(args).map($A);
+ return this.map(function(value, index) {
+ iterator(value = collections.pluck(index));
+ return value;
+ });
+ },
+
+ inspect: function() {
+ return '#<Enumerable:' + this.toArray().inspect() + '>';
+ }
+}
+
+Object.extend(Enumerable, {
+ map: Enumerable.collect,
+ find: Enumerable.detect,
+ select: Enumerable.findAll,
+ member: Enumerable.include,
+ entries: Enumerable.toArray
+});
+var $A = Array.from = function(iterable) {
+ if (!iterable) return [];
+ if (iterable.toArray) {
+ return iterable.toArray();
+ } else {
+ var results = [];
+ for (var i = 0; i < iterable.length; i++)
+ results.push(iterable[i]);
+ return results;
+ }
+}
+
+Object.extend(Array.prototype, Enumerable);
+
+Array.prototype._reverse = Array.prototype.reverse;
+
+Object.extend(Array.prototype, {
+ _each: function(iterator) {
+ for (var i = 0; i < this.length; i++)
+ iterator(this[i]);
+ },
+
+ clear: function() {
+ this.length = 0;
+ return this;
+ },
+
+ first: function() {
+ return this[0];
+ },
+
+ last: function() {
+ return this[this.length - 1];
+ },
+
+ compact: function() {
+ return this.select(function(value) {
+ return value != undefined || value != null;
+ });
+ },
+
+ flatten: function() {
+ return this.inject([], function(array, value) {
+ return array.concat(value.constructor == Array ?
+ value.flatten() : [value]);
+ });
+ },
+
+ without: function() {
+ var values = $A(arguments);
+ return this.select(function(value) {
+ return !values.include(value);
+ });
+ },
+
+ indexOf: function(object) {
+ for (var i = 0; i < this.length; i++)
+ if (this[i] == object) return i;
+ return -1;
+ },
+
+ reverse: function(inline) {
+ return (inline !== false ? this : this.toArray())._reverse();
+ },
+
+ shift: function() {
+ var result = this[0];
+ for (var i = 0; i < this.length - 1; i++)
+ this[i] = this[i + 1];
+ this.length--;
+ return result;
+ },
+
+ inspect: function() {
+ return '[' + this.map(Object.inspect).join(', ') + ']';
+ }
+});
+var Hash = {
+ _each: function(iterator) {
+ for (key in this) {
+ var value = this[key];
+ if (typeof value == 'function') continue;
+
+ var pair = [key, value];
+ pair.key = key;
+ pair.value = value;
+ iterator(pair);
+ }
+ },
+
+ keys: function() {
+ return this.pluck('key');
+ },
+
+ values: function() {
+ return this.pluck('value');
+ },
+
+ merge: function(hash) {
+ return $H(hash).inject($H(this), function(mergedHash, pair) {
+ mergedHash[pair.key] = pair.value;
+ return mergedHash;
+ });
+ },
+
+ toQueryString: function() {
+ return this.map(function(pair) {
+ return pair.map(encodeURIComponent).join('=');
+ }).join('&');
+ },
+
+ inspect: function() {
+ return '#<Hash:{' + this.map(function(pair) {
+ return pair.map(Object.inspect).join(': ');
+ }).join(', ') + '}>';
+ }
+}
+
+function $H(object) {
+ var hash = Object.extend({}, object || {});
+ Object.extend(hash, Enumerable);
+ Object.extend(hash, Hash);
+ return hash;
+}
+ObjectRange = Class.create();
+Object.extend(ObjectRange.prototype, Enumerable);
+Object.extend(ObjectRange.prototype, {
+ initialize: function(start, end, exclusive) {
+ this.start = start;
+ this.end = end;
+ this.exclusive = exclusive;
+ },
+
+ _each: function(iterator) {
+ var value = this.start;
+ do {
+ iterator(value);
+ value = value.succ();
+ } while (this.include(value));
+ },
+
+ include: function(value) {
+ if (value < this.start)
+ return false;
+ if (this.exclusive)
+ return value < this.end;
+ return value <= this.end;
+ }
+});
+
+var $R = function(start, end, exclusive) {
+ return new ObjectRange(start, end, exclusive);
+}
+
+var Ajax = {
+ getTransport: function() {
+ return Try.these(
+ function() {return new ActiveXObject('Msxml2.XMLHTTP')},
+ function() {return new ActiveXObject('Microsoft.XMLHTTP')},
+ function() {return new XMLHttpRequest()}
+ ) || false;
+ },
+
+ activeRequestCount: 0
+}
+
+Ajax.Responders = {
+ responders: [],
+
+ _each: function(iterator) {
+ this.responders._each(iterator);
+ },
+
+ register: function(responderToAdd) {
+ if (!this.include(responderToAdd))
+ this.responders.push(responderToAdd);
+ },
+
+ unregister: function(responderToRemove) {
+ this.responders = this.responders.without(responderToRemove);
+ },
+
+ dispatch: function(callback, request, transport, json) {
+ this.each(function(responder) {
+ if (responder[callback] && typeof responder[callback] == 'function') {
+ try {
+ responder[callback].apply(responder, [request, transport, json]);
+ } catch (e) {}
+ }
+ });
+ }
+};
+
+Object.extend(Ajax.Responders, Enumerable);
+
+Ajax.Responders.register({
+ onCreate: function() {
+ Ajax.activeRequestCount++;
+ },
+
+ onComplete: function() {
+ Ajax.activeRequestCount--;
+ }
+});
+
+Ajax.Base = function() {};
+Ajax.Base.prototype = {
+ setOptions: function(options) {
+ this.options = {
+ method: 'post',
+ asynchronous: true,
+ parameters: ''
+ }
+ Object.extend(this.options, options || {});
+ },
+
+ responseIsSuccess: function() {
+ return this.transport.status == undefined
+ || this.transport.status == 0
+ || (this.transport.status >= 200 && this.transport.status < 300);
+ },
+
+ responseIsFailure: function() {
+ return !this.responseIsSuccess();
+ }
+}
+
+Ajax.Request = Class.create();
+Ajax.Request.Events =
+ ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
+
+Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
+ initialize: function(url, options) {
+ this.transport = Ajax.getTransport();
+ this.setOptions(options);
+ this.request(url);
+ },
+
+ request: function(url) {
+ var parameters = this.options.parameters || '';
+ if (parameters.length > 0) parameters += '&_=';
+
+ try {
+ this.url = url;
+ if (this.options.method == 'get' && parameters.length > 0)
+ this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
+
+ Ajax.Responders.dispatch('onCreate', this, this.transport);
+
+ this.transport.open(this.options.method, this.url,
+ this.options.asynchronous);
+
+ if (this.options.asynchronous) {
+ this.transport.onreadystatechange = this.onStateChange.bind(this);
+ setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
+ }
+
+ this.setRequestHeaders();
+
+ var body = this.options.postBody ? this.options.postBody : parameters;
+ this.transport.send(this.options.method == 'post' ? body : null);
+
+ } catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
+ setRequestHeaders: function() {
+ var requestHeaders =
+ ['X-Requested-With', 'XMLHttpRequest',
+ 'X-Prototype-Version', Prototype.Version];
+
+ if (this.options.method == 'post') {
+ requestHeaders.push('Content-type',
+ 'application/x-www-form-urlencoded');
+
+ /* Force "Connection: close" for Mozilla browsers to work around
+ * a bug where XMLHttpReqeuest sends an incorrect Content-length
+ * header. See Mozilla Bugzilla #246651.
+ */
+ if (this.transport.overrideMimeType)
+ requestHeaders.push('Connection', 'close');
+ }
+
+ if (this.options.requestHeaders)
+ requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
+
+ for (var i = 0; i < requestHeaders.length; i += 2)
+ this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
+ },
+
+ onStateChange: function() {
+ var readyState = this.transport.readyState;
+ if (readyState != 1)
+ this.respondToReadyState(this.transport.readyState);
+ },
+
+ header: function(name) {
+ try {
+ return this.transport.getResponseHeader(name);
+ } catch (e) {}
+ },
+
+ evalJSON: function() {
+ try {
+ return eval(this.header('X-JSON'));
+ } catch (e) {}
+ },
+
+ evalResponse: function() {
+ try {
+ return eval(this.transport.responseText);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
+ respondToReadyState: function(readyState) {
+ var event = Ajax.Request.Events[readyState];
+ var transport = this.transport, json = this.evalJSON();
+
+ if (event == 'Complete') {
+ try {
+ (this.options['on' + this.transport.status]
+ || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
+ || Prototype.emptyFunction)(transport, json);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ if ((this.header('Content-type') || '').match(/^text\/javascript/i))
+ this.evalResponse();
+ }
+
+ try {
+ (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
+ Ajax.Responders.dispatch('on' + event, this, transport, json);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
+ if (event == 'Complete')
+ this.transport.onreadystatechange = Prototype.emptyFunction;
+ },
+
+ dispatchException: function(exception) {
+ (this.options.onException || Prototype.emptyFunction)(this, exception);
+ Ajax.Responders.dispatch('onException', this, exception);
+ }
+});
+
+Ajax.Updater = Class.create();
+
+Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
+ initialize: function(container, url, options) {
+ this.containers = {
+ success: container.success ? $(container.success) : $(container),
+ failure: container.failure ? $(container.failure) :
+ (container.success ? null : $(container))
+ }
+
+ this.transport = Ajax.getTransport();
+ this.setOptions(options);
+
+ var onComplete = this.options.onComplete || Prototype.emptyFunction;
+ this.options.onComplete = (function(transport, object) {
+ this.updateContent();
+ onComplete(transport, object);
+ }).bind(this);
+
+ this.request(url);
+ },
+
+ updateContent: function() {
+ var receiver = this.responseIsSuccess() ?
+ this.containers.success : this.containers.failure;
+ var response = this.transport.responseText;
+
+ if (!this.options.evalScripts)
+ response = response.stripScripts();
+
+ if (receiver) {
+ if (this.options.insertion) {
+ new this.options.insertion(receiver, response);
+ } else {
+ Element.update(receiver, response);
+ }
+ }
+
+ if (this.responseIsSuccess()) {
+ if (this.onComplete)
+ setTimeout(this.onComplete.bind(this), 10);
+ }
+ }
+});
+
+Ajax.PeriodicalUpdater = Class.create();
+Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
+ initialize: function(container, url, options) {
+ this.setOptions(options);
+ this.onComplete = this.options.onComplete;
+
+ this.frequency = (this.options.frequency || 2);
+ this.decay = (this.options.decay || 1);
+
+ this.updater = {};
+ this.container = container;
+ this.url = url;
+
+ this.start();
+ },
+
+ start: function() {
+ this.options.onComplete = this.updateComplete.bind(this);
+ this.onTimerEvent();
+ },
+
+ stop: function() {
+ this.updater.onComplete = undefined;
+ clearTimeout(this.timer);
+ (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
+ },
+
+ updateComplete: function(request) {
+ if (this.options.decay) {
+ this.decay = (request.responseText == this.lastText ?
+ this.decay * this.options.decay : 1);
+
+ this.lastText = request.responseText;
+ }
+ this.timer = setTimeout(this.onTimerEvent.bind(this),
+ this.decay * this.frequency * 1000);
+ },
+
+ onTimerEvent: function() {
+ this.updater = new Ajax.Updater(this.container, this.url, this.options);
+ }
+});
+document.getElementsByClassName = function(className, parentElement) {
+ var children = ($(parentElement) || document.body).getElementsByTagName('*');
+ return $A(children).inject([], function(elements, child) {
+ if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
+ elements.push(child);
+ return elements;
+ });
+}
+
+/*--------------------------------------------------------------------------*/
+
+if (!window.Element) {
+ var Element = new Object();
+}
+
+Object.extend(Element, {
+ visible: function(element) {
+ return $(element).style.display != 'none';
+ },
+
+ toggle: function() {
+ for (var i = 0; i < arguments.length; i++) {
+ var element = $(arguments[i]);
+ Element[Element.visible(element) ? 'hide' : 'show'](element);
+ }
+ },
+
+ hide: function() {
+ for (var i = 0; i < arguments.length; i++) {
+ var element = $(arguments[i]);
+ element.style.display = 'none';
+ }
+ },
+
+ show: function() {
+ for (var i = 0; i < arguments.length; i++) {
+ var element = $(arguments[i]);
+ element.style.display = '';
+ }
+ },
+
+ remove: function(element) {
+ element = $(element);
+ element.parentNode.removeChild(element);
+ },
+
+ update: function(element, html) {
+ $(element).innerHTML = html.stripScripts();
+ setTimeout(function() {html.evalScripts()}, 10);
+ },
+
+ getHeight: function(element) {
+ element = $(element);
+ return element.offsetHeight;
+ },
+
+ classNames: function(element) {
+ return new Element.ClassNames(element);
+ },
+
+ hasClassName: function(element, className) {
+ if (!(element = $(element))) return;
+ return Element.classNames(element).include(className);
+ },
+
+ addClassName: function(element, className) {
+ if (!(element = $(element))) return;
+ return Element.classNames(element).add(className);
+ },
+
+ removeClassName: function(element, className) {
+ if (!(element = $(element))) return;
+ return Element.classNames(element).remove(className);
+ },
+
+ // removes whitespace-only text node children
+ cleanWhitespace: function(element) {
+ element = $(element);
+ for (var i = 0; i < element.childNodes.length; i++) {
+ var node = element.childNodes[i];
+ if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
+ Element.remove(node);
+ }
+ },
+
+ empty: function(element) {
+ return $(element).innerHTML.match(/^\s*$/);
+ },
+
+ scrollTo: function(element) {
+ element = $(element);
+ var x = element.x ? element.x : element.offsetLeft,
+ y = element.y ? element.y : element.offsetTop;
+ window.scrollTo(x, y);
+ },
+
+ getStyle: function(element, style) {
+ element = $(element);
+ var value = element.style[style.camelize()];
+ if (!value) {
+ if (document.defaultView && document.defaultView.getComputedStyle) {
+ var css = document.defaultView.getComputedStyle(element, null);
+ value = css ? css.getPropertyValue(style) : null;
+ } else if (element.currentStyle) {
+ value = element.currentStyle[style.camelize()];
+ }
+ }
+
+ if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
+ if (Element.getStyle(element, 'position') == 'static') value = 'auto';
+
+ return value == 'auto' ? null : value;
+ },
+
+ setStyle: function(element, style) {
+ element = $(element);
+ for (name in style)
+ element.style[name.camelize()] = style[name];
+ },
+
+ getDimensions: function(element) {
+ element = $(element);
+ if (Element.getStyle(element, 'display') != 'none')
+ return {width: element.offsetWidth, height: element.offsetHeight};
+
+ // All *Width and *Height properties give 0 on elements with display none,
+ // so enable the element temporarily
+ var els = element.style;
+ var originalVisibility = els.visibility;
+ var originalPosition = els.position;
+ els.visibility = 'hidden';
+ els.position = 'absolute';
+ els.display = '';
+ var originalWidth = element.clientWidth;
+ var originalHeight = element.clientHeight;
+ els.display = 'none';
+ els.position = originalPosition;
+ els.visibility = originalVisibility;
+ return {width: originalWidth, height: originalHeight};
+ },
+
+ makePositioned: function(element) {
+ element = $(element);
+ var pos = Element.getStyle(element, 'position');
+ if (pos == 'static' || !pos) {
+ element._madePositioned = true;
+ element.style.position = 'relative';
+ // Opera returns the offset relative to the positioning context, when an
+ // element is position relative but top and left have not been defined
+ if (window.opera) {
+ element.style.top = 0;
+ element.style.left = 0;
+ }
+ }
+ },
+
+ undoPositioned: function(element) {
+ element = $(element);
+ if (element._madePositioned) {
+ element._madePositioned = undefined;
+ element.style.position =
+ element.style.top =
+ element.style.left =
+ element.style.bottom =
+ element.style.right = '';
+ }
+ },
+
+ makeClipping: function(element) {
+ element = $(element);
+ if (element._overflow) return;
+ element._overflow = element.style.overflow;
+ if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
+ element.style.overflow = 'hidden';
+ },
+
+ undoClipping: function(element) {
+ element = $(element);
+ if (element._overflow) return;
+ element.style.overflow = element._overflow;
+ element._overflow = undefined;
+ }
+});
+
+var Toggle = new Object();
+Toggle.display = Element.toggle;
+
+/*--------------------------------------------------------------------------*/
+
+Abstract.Insertion = function(adjacency) {
+ this.adjacency = adjacency;
+}
+
+Abstract.Insertion.prototype = {
+ initialize: function(element, content) {
+ this.element = $(element);
+ this.content = content.stripScripts();
+
+ if (this.adjacency && this.element.insertAdjacentHTML) {
+ try {
+ this.element.insertAdjacentHTML(this.adjacency, this.content);
+ } catch (e) {
+ if (this.element.tagName.toLowerCase() == 'tbody') {
+ this.insertContent(this.contentFromAnonymousTable());
+ } else {
+ throw e;
+ }
+ }
+ } else {
+ this.range = this.element.ownerDocument.createRange();
+ if (this.initializeRange) this.initializeRange();
+ this.insertContent([this.range.createContextualFragment(this.content)]);
+ }
+
+ setTimeout(function() {content.evalScripts()}, 10);
+ },
+
+ contentFromAnonymousTable: function() {
+ var div = document.createElement('div');
+ div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
+ return $A(div.childNodes[0].childNodes[0].childNodes);
+ }
+}
+
+var Insertion = new Object();
+
+Insertion.Before = Class.create();
+Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
+ initializeRange: function() {
+ this.range.setStartBefore(this.element);
+ },
+
+ insertContent: function(fragments) {
+ fragments.each((function(fragment) {
+ this.element.parentNode.insertBefore(fragment, this.element);
+ }).bind(this));
+ }
+});
+
+Insertion.Top = Class.create();
+Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
+ initializeRange: function() {
+ this.range.selectNodeContents(this.element);
+ this.range.collapse(true);
+ },
+
+ insertContent: function(fragments) {
+ fragments.reverse(false).each((function(fragment) {
+ this.element.insertBefore(fragment, this.element.firstChild);
+ }).bind(this));
+ }
+});
+
+Insertion.Bottom = Class.create();
+Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
+ initializeRange: function() {
+ this.range.selectNodeContents(this.element);
+ this.range.collapse(this.element);
+ },
+
+ insertContent: function(fragments) {
+ fragments.each((function(fragment) {
+ this.element.appendChild(fragment);
+ }).bind(this));
+ }
+});
+
+Insertion.After = Class.create();
+Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
+ initializeRange: function() {
+ this.range.setStartAfter(this.element);
+ },
+
+ insertContent: function(fragments) {
+ fragments.each((function(fragment) {
+ this.element.parentNode.insertBefore(fragment,
+ this.element.nextSibling);
+ }).bind(this));
+ }
+});
+
+/*--------------------------------------------------------------------------*/
+
+Element.ClassNames = Class.create();
+Element.ClassNames.prototype = {
+ initialize: function(element) {
+ this.element = $(element);
+ },
+
+ _each: function(iterator) {
+ this.element.className.split(/\s+/).select(function(name) {
+ return name.length > 0;
+ })._each(iterator);
+ },
+
+ set: function(className) {
+ this.element.className = className;
+ },
+
+ add: function(classNameToAdd) {
+ if (this.include(classNameToAdd)) return;
+ this.set(this.toArray().concat(classNameToAdd).join(' '));
+ },
+
+ remove: function(classNameToRemove) {
+ if (!this.include(classNameToRemove)) return;
+ this.set(this.select(function(className) {
+ return className != classNameToRemove;
+ }).join(' '));
+ },
+
+ toString: function() {
+ return this.toArray().join(' ');
+ }
+}
+
+Object.extend(Element.ClassNames.prototype, Enumerable);
+var Field = {
+ clear: function() {
+ for (var i = 0; i < arguments.length; i++)
+ $(arguments[i]).value = '';
+ },
+
+ focus: function(element) {
+ $(element).focus();
+ },
+
+ present: function() {
+ for (var i = 0; i < arguments.length; i++)
+ if ($(arguments[i]).value == '') return false;
+ return true;
+ },
+
+ select: function(element) {
+ $(element).select();
+ },
+
+ activate: function(element) {
+ element = $(element);
+ element.focus();
+ if (element.select)
+ element.select();
+ }
+}
+
+/*--------------------------------------------------------------------------*/
+
+var Form = {
+ serialize: function(form) {
+ var elements = Form.getElements($(form));
+ var queryComponents = new Array();
+
+ for (var i = 0; i < elements.length; i++) {
+ var queryComponent = Form.Element.serialize(elements[i]);
+ if (queryComponent)
+ queryComponents.push(queryComponent);
+ }
+
+ return queryComponents.join('&');
+ },
+
+ getElements: function(form) {
+ form = $(form);
+ var elements = new Array();
+
+ for (tagName in Form.Element.Serializers) {
+ var tagElements = form.getElementsByTagName(tagName);
+ for (var j = 0; j < tagElements.length; j++)
+ elements.push(tagElements[j]);
+ }
+ return elements;
+ },
+
+ getInputs: function(form, typeName, name) {
+ form = $(form);
+ var inputs = form.getElementsByTagName('input');
+
+ if (!typeName && !name)
+ return inputs;
+
+ var matchingInputs = new Array();
+ for (var i = 0; i < inputs.length; i++) {
+ var input = inputs[i];
+ if ((typeName && input.type != typeName) ||
+ (name && input.name != name))
+ continue;
+ matchingInputs.push(input);
+ }
+
+ return matchingInputs;
+ },
+
+ disable: function(form) {
+ var elements = Form.getElements(form);
+ for (var i = 0; i < elements.length; i++) {
+ var element = elements[i];
+ element.blur();
+ element.disabled = 'true';
+ }
+ },
+
+ enable: function(form) {
+ var elements = Form.getElements(form);
+ for (var i = 0; i < elements.length; i++) {
+ var element = elements[i];
+ element.disabled = '';
+ }
+ },
+
+ findFirstElement: function(form) {
+ return Form.getElements(form).find(function(element) {
+ return element.type != 'hidden' && !element.disabled &&
+ ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
+ });
+ },
+
+ focusFirstElement: function(form) {
+ Field.activate(Form.findFirstElement(form));
+ },
+
+ reset: function(form) {
+ $(form).reset();
+ }
+}
+
+Form.Element = {
+ serialize: function(element) {
+ element = $(element);
+ var method = element.tagName.toLowerCase();
+ var parameter = Form.Element.Serializers[method](element);
+
+ if (parameter) {
+ var key = encodeURIComponent(parameter[0]);
+ if (key.length == 0) return;
+
+ if (parameter[1].constructor != Array)
+ parameter[1] = [parameter[1]];
+
+ return parameter[1].map(function(value) {
+ return key + '=' + encodeURIComponent(value);
+ }).join('&');
+ }
+ },
+
+ getValue: function(element) {
+ element = $(element);
+ var method = element.tagName.toLowerCase();
+ var parameter = Form.Element.Serializers[method](element);
+
+ if (parameter)
+ return parameter[1];
+ }
+}
+
+Form.Element.Serializers = {
+ input: function(element) {
+ switch (element.type.toLowerCase()) {
+ case 'submit':
+ case 'hidden':
+ case 'password':
+ case 'text':
+ return Form.Element.Serializers.textarea(element);
+ case 'checkbox':
+ case 'radio':
+ return Form.Element.Serializers.inputSelector(element);
+ }
+ return false;
+ },
+
+ inputSelector: function(element) {
+ if (element.checked)
+ return [element.name, element.value];
+ },
+
+ textarea: function(element) {
+ return [element.name, element.value];
+ },
+
+ select: function(element) {
+ return Form.Element.Serializers[element.type == 'select-one' ?
+ 'selectOne' : 'selectMany'](element);
+ },
+
+ selectOne: function(element) {
+ var value = '', opt, index = element.selectedIndex;
+ if (index >= 0) {
+ opt = element.options[index];
+ value = opt.value;
+ if (!value && !('value' in opt))
+ value = opt.text;
+ }
+ return [element.name, value];
+ },
+
+ selectMany: function(element) {
+ var value = new Array();
+ for (var i = 0; i < element.length; i++) {
+ var opt = element.options[i];
+ if (opt.selected) {
+ var optValue = opt.value;
+ if (!optValue && !('value' in opt))
+ optValue = opt.text;
+ value.push(optValue);
+ }
+ }
+ return [element.name, value];
+ }
+}
+
+/*--------------------------------------------------------------------------*/
+
+var $F = Form.Element.getValue;
+
+/*--------------------------------------------------------------------------*/
+
+Abstract.TimedObserver = function() {}
+Abstract.TimedObserver.prototype = {
+ initialize: function(element, frequency, callback) {
+ this.frequency = frequency;
+ this.element = $(element);
+ this.callback = callback;
+
+ this.lastValue = this.getValue();
+ this.registerCallback();
+ },
+
+ registerCallback: function() {
+ setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
+ },
+
+ onTimerEvent: function() {
+ var value = this.getValue();
+ if (this.lastValue != value) {
+ this.callback(this.element, value);
+ this.lastValue = value;
+ }
+ }
+}
+
+Form.Element.Observer = Class.create();
+Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
+ getValue: function() {
+ return Form.Element.getValue(this.element);
+ }
+});
+
+Form.Observer = Class.create();
+Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
+ getValue: function() {
+ return Form.serialize(this.element);
+ }
+});
+
+/*--------------------------------------------------------------------------*/
+
+Abstract.EventObserver = function() {}
+Abstract.EventObserver.prototype = {
+ initialize: function(element, callback) {
+ this.element = $(element);
+ this.callback = callback;
+
+ this.lastValue = this.getValue();
+ if (this.element.tagName.toLowerCase() == 'form')
+ this.registerFormCallbacks();
+ else
+ this.registerCallback(this.element);
+ },
+
+ onElementEvent: function() {
+ var value = this.getValue();
+ if (this.lastValue != value) {
+ this.callback(this.element, value);
+ this.lastValue = value;
+ }
+ },
+
+ registerFormCallbacks: function() {
+ var elements = Form.getElements(this.element);
+ for (var i = 0; i < elements.length; i++)
+ this.registerCallback(elements[i]);
+ },
+
+ registerCallback: function(element) {
+ if (element.type) {
+ switch (element.type.toLowerCase()) {
+ case 'checkbox':
+ case 'radio':
+ Event.observe(element, 'click', this.onElementEvent.bind(this));
+ break;
+ case 'password':
+ case 'text':
+ case 'textarea':
+ case 'select-one':
+ case 'select-multiple':
+ Event.observe(element, 'change', this.onElementEvent.bind(this));
+ break;
+ }
+ }
+ }
+}
+
+Form.Element.EventObserver = Class.create();
+Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
+ getValue: function() {
+ return Form.Element.getValue(this.element);
+ }
+});
+
+Form.EventObserver = Class.create();
+Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
+ getValue: function() {
+ return Form.serialize(this.element);
+ }
+});
+if (!window.Event) {
+ var Event = new Object();
+}
+
+Object.extend(Event, {
+ KEY_BACKSPACE: 8,
+ KEY_TAB: 9,
+ KEY_RETURN: 13,
+ KEY_ESC: 27,
+ KEY_LEFT: 37,
+ KEY_UP: 38,
+ KEY_RIGHT: 39,
+ KEY_DOWN: 40,
+ KEY_DELETE: 46,
+
+ element: function(event) {
+ return event.target || event.srcElement;
+ },
+
+ isLeftClick: function(event) {
+ return (((event.which) && (event.which == 1)) ||
+ ((event.button) && (event.button == 1)));
+ },
+
+ pointerX: function(event) {
+ return event.pageX || (event.clientX +
+ (document.documentElement.scrollLeft || document.body.scrollLeft));
+ },
+
+ pointerY: function(event) {
+ return event.pageY || (event.clientY +
+ (document.documentElement.scrollTop || document.body.scrollTop));
+ },
+
+ stop: function(event) {
+ if (event.preventDefault) {
+ event.preventDefault();
+ event.stopPropagation();
+ } else {
+ event.returnValue = false;
+ event.cancelBubble = true;
+ }
+ },
+
+ // find the first node with the given tagName, starting from the
+ // node the event was triggered on; traverses the DOM upwards
+ findElement: function(event, tagName) {
+ var element = Event.element(event);
+ while (element.parentNode && (!element.tagName ||
+ (element.tagName.toUpperCase() != tagName.toUpperCase())))
+ element = element.parentNode;
+ return element;
+ },
+
+ observers: false,
+
+ _observeAndCache: function(element, name, observer, useCapture) {
+ if (!this.observers) this.observers = [];
+ if (element.addEventListener) {
+ this.observers.push([element, name, observer, useCapture]);
+ element.addEventListener(name, observer, useCapture);
+ } else if (element.attachEvent) {
+ this.observers.push([element, name, observer, useCapture]);
+ element.attachEvent('on' + name, observer);
+ }
+ },
+
+ unloadCache: function() {
+ if (!Event.observers) return;
+ for (var i = 0; i < Event.observers.length; i++) {
+ Event.stopObserving.apply(this, Event.observers[i]);
+ Event.observers[i][0] = null;
+ }
+ Event.observers = false;
+ },
+
+ observe: function(element, name, observer, useCapture) {
+ var element = $(element);
+ useCapture = useCapture || false;
+
+ if (name == 'keypress' &&
+ (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
+ || element.attachEvent))
+ name = 'keydown';
+
+ this._observeAndCache(element, name, observer, useCapture);
+ },
+
+ stopObserving: function(element, name, observer, useCapture) {
+ var element = $(element);
+ useCapture = useCapture || false;
+
+ if (name == 'keypress' &&
+ (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
+ || element.detachEvent))
+ name = 'keydown';
+
+ if (element.removeEventListener) {
+ element.removeEventListener(name, observer, useCapture);
+ } else if (element.detachEvent) {
+ element.detachEvent('on' + name, observer);
+ }
+ }
+});
+
+/* prevent memory leaks in IE */
+Event.observe(window, 'unload', Event.unloadCache, false);
+var Position = {
+ // set to true if needed, warning: firefox performance problems
+ // NOT neeeded for page scrolling, only if draggable contained in
+ // scrollable elements
+ includeScrollOffsets: false,
+
+ // must be called before calling withinIncludingScrolloffset, every time the
+ // page is scrolled
+ prepare: function() {
+ this.deltaX = window.pageXOffset
+ || document.documentElement.scrollLeft
+ || document.body.scrollLeft
+ || 0;
+ this.deltaY = window.pageYOffset
+ || document.documentElement.scrollTop
+ || document.body.scrollTop
+ || 0;
+ },
+
+ realOffset: function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.scrollTop || 0;
+ valueL += element.scrollLeft || 0;
+ element = element.parentNode;
+ } while (element);
+ return [valueL, valueT];
+ },
+
+ cumulativeOffset: function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ } while (element);
+ return [valueL, valueT];
+ },
+
+ positionedOffset: function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ if (element) {
+ p = Element.getStyle(element, 'position');
+ if (p == 'relative' || p == 'absolute') break;
+ }
+ } while (element);
+ return [valueL, valueT];
+ },
+
+ offsetParent: function(element) {
+ if (element.offsetParent) return element.offsetParent;
+ if (element == document.body) return element;
+
+ while ((element = element.parentNode) && element != document.body)
+ if (Element.getStyle(element, 'position') != 'static')
+ return element;
+
+ return document.body;
+ },
+
+ // caches x/y coordinate pair to use with overlap
+ within: function(element, x, y) {
+ if (this.includeScrollOffsets)
+ return this.withinIncludingScrolloffsets(element, x, y);
+ this.xcomp = x;
+ this.ycomp = y;
+ this.offset = this.cumulativeOffset(element);
+
+ return (y >= this.offset[1] &&
+ y < this.offset[1] + element.offsetHeight &&
+ x >= this.offset[0] &&
+ x < this.offset[0] + element.offsetWidth);
+ },
+
+ withinIncludingScrolloffsets: function(element, x, y) {
+ var offsetcache = this.realOffset(element);
+
+ this.xcomp = x + offsetcache[0] - this.deltaX;
+ this.ycomp = y + offsetcache[1] - this.deltaY;
+ this.offset = this.cumulativeOffset(element);
+
+ return (this.ycomp >= this.offset[1] &&
+ this.ycomp < this.offset[1] + element.offsetHeight &&
+ this.xcomp >= this.offset[0] &&
+ this.xcomp < this.offset[0] + element.offsetWidth);
+ },
+
+ // within must be called directly before
+ overlap: function(mode, element) {
+ if (!mode) return 0;
+ if (mode == 'vertical')
+ return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
+ element.offsetHeight;
+ if (mode == 'horizontal')
+ return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
+ element.offsetWidth;
+ },
+
+ clone: function(source, target) {
+ source = $(source);
+ target = $(target);
+ target.style.position = 'absolute';
+ var offsets = this.cumulativeOffset(source);
+ target.style.top = offsets[1] + 'px';
+ target.style.left = offsets[0] + 'px';
+ target.style.width = source.offsetWidth + 'px';
+ target.style.height = source.offsetHeight + 'px';
+ },
+
+ page: function(forElement) {
+ var valueT = 0, valueL = 0;
+
+ var element = forElement;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+
+ // Safari fix
+ if (element.offsetParent==document.body)
+ if (Element.getStyle(element,'position')=='absolute') break;
+
+ } while (element = element.offsetParent);
+
+ element = forElement;
+ do {
+ valueT -= element.scrollTop || 0;
+ valueL -= element.scrollLeft || 0;
+ } while (element = element.parentNode);
+
+ return [valueL, valueT];
+ },
+
+ clone: function(source, target) {
+ var options = Object.extend({
+ setLeft: true,
+ setTop: true,
+ setWidth: true,
+ setHeight: true,
+ offsetTop: 0,
+ offsetLeft: 0
+ }, arguments[2] || {})
+
+ // find page position of source
+ source = $(source);
+ var p = Position.page(source);
+
+ // find coordinate system to use
+ target = $(target);
+ var delta = [0, 0];
+ var parent = null;
+ // delta [0,0] will do fine with position: fixed elements,
+ // position:absolute needs offsetParent deltas
+ if (Element.getStyle(target,'position') == 'absolute') {
+ parent = Position.offsetParent(target);
+ delta = Position.page(parent);
+ }
+
+ // correct by body offsets (fixes Safari)
+ if (parent == document.body) {
+ delta[0] -= document.body.offsetLeft;
+ delta[1] -= document.body.offsetTop;
+ }
+
+ // set position
+ if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
+ if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
+ if(options.setWidth) target.style.width = source.offsetWidth + 'px';
+ if(options.setHeight) target.style.height = source.offsetHeight + 'px';
+ },
+
+ absolutize: function(element) {
+ element = $(element);
+ if (element.style.position == 'absolute') return;
+ Position.prepare();
+
+ var offsets = Position.positionedOffset(element);
+ var top = offsets[1];
+ var left = offsets[0];
+ var width = element.clientWidth;
+ var height = element.clientHeight;
+
+ element._originalLeft = left - parseFloat(element.style.left || 0);
+ element._originalTop = top - parseFloat(element.style.top || 0);
+ element._originalWidth = element.style.width;
+ element._originalHeight = element.style.height;
+
+ element.style.position = 'absolute';
+ element.style.top = top + 'px';;
+ element.style.left = left + 'px';;
+ element.style.width = width + 'px';;
+ element.style.height = height + 'px';;
+ },
+
+ relativize: function(element) {
+ element = $(element);
+ if (element.style.position == 'relative') return;
+ Position.prepare();
+
+ element.style.position = 'relative';
+ var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
+ var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
+
+ element.style.top = top + 'px';
+ element.style.left = left + 'px';
+ element.style.height = element._originalHeight;
+ element.style.width = element._originalWidth;
+ }
+}
+
+// Safari returns margins on body which is incorrect if the child is absolutely
+// positioned. For performance reasons, redefine Position.cumulativeOffset for
+// KHTML/WebKit only.
+if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
+ Position.cumulativeOffset = function(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ if (element.offsetParent == document.body)
+ if (Element.getStyle(element, 'position') == 'absolute') break;
+
+ element = element.offsetParent;
+ } while (element);
+
+ return [valueL, valueT];
+ }
+} \ No newline at end of file
diff --git a/tests/test_tools/selenium/core/scripts/selenium-api.js b/tests/test_tools/selenium/core/scripts/selenium-api.js
new file mode 100644
index 00000000..ad0509ee
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-api.js
@@ -0,0 +1,1402 @@
+/*
+ * Copyright 2004 ThoughtWorks, Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var storedVars = new Object();
+
+function Selenium(browserbot) {
+ /**
+ * Defines an object that runs Selenium commands.
+ *
+ * <h3><a name="locators"></a>Element Locators</h3>
+ * <p>
+ * Element Locators tell Selenium which HTML element a command refers to.
+ * The format of a locator is:</p>
+ * <blockquote>
+ * <em>locatorType</em><strong>=</strong><em>argument</em>
+ * </blockquote>
+ *
+ * <p>
+ * We support the following strategies for locating elements:
+ * </p>
+ * <blockquote>
+ * <dl>
+ * <dt><strong>identifier</strong>=<em>id</em></dt>
+ * <dd>Select the element with the specified &#64;id attribute. If no match is
+ * found, select the first element whose &#64;name attribute is <em>id</em>.
+ * (This is normally the default; see below.)</dd>
+ * <dt><strong>id</strong>=<em>id</em></dt>
+ * <dd>Select the element with the specified &#64;id attribute.</dd>
+ *
+ * <dt><strong>name</strong>=<em>name</em></dt>
+ * <dd>Select the first element with the specified &#64;name attribute.</dd>
+ * <dd><ul class="first last simple">
+ * <li>username</li>
+ * <li>name=username</li>
+ * </ul>
+ * </dd>
+ * <dd>The name may optionally be followed by one or more <em>element-filters</em>, separated from the name by whitespace. If the <em>filterType</em> is not specified, <strong>value</strong> is assumed.</dd>
+ *
+ * <dd><ul class="first last simple">
+ * <li>name=flavour value=chocolate</li>
+ * </ul>
+ * </dd>
+ * <dt><strong>dom</strong>=<em>javascriptExpression</em></dt>
+ *
+ * <dd>
+ *
+ * <dd>Find an element using JavaScript traversal of the HTML Document Object
+ * Model. DOM locators <em>must</em> begin with &quot;document.&quot;.
+ * <ul class="first last simple">
+ * <li>dom=document.forms['myForm'].myDropdown</li>
+ * <li>dom=document.images[56]</li>
+ * </ul>
+ * </dd>
+ *
+ * </dd>
+ *
+ * <dt><strong>xpath</strong>=<em>xpathExpression</em></dt>
+ * <dd>Locate an element using an XPath expression.
+ * <ul class="first last simple">
+ * <li>xpath=//img[&#64;alt='The image alt text']</li>
+ * <li>xpath=//table[&#64;id='table1']//tr[4]/td[2]</li>
+ *
+ * </ul>
+ * </dd>
+ * <dt><strong>link</strong>=<em>textPattern</em></dt>
+ * <dd>Select the link (anchor) element which contains text matching the
+ * specified <em>pattern</em>.
+ * <ul class="first last simple">
+ * <li>link=The link text</li>
+ * </ul>
+ *
+ * </dd>
+ * </dl>
+ * </blockquote>
+ * <p>
+ * Without an explicit locator prefix, Selenium uses the following default
+ * strategies:
+ * </p>
+ *
+ * <ul class="simple">
+ * <li><strong>dom</strong>, for locators starting with &quot;document.&quot;</li>
+ * <li><strong>xpath</strong>, for locators starting with &quot;//&quot;</li>
+ * <li><strong>identifier</strong>, otherwise</li>
+ * </ul>
+ *
+ * <h3><a name="element-filters">Element Filters</a></h3>
+ * <blockquote>
+ * <p>Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator.</p>
+ * <p>Filters look much like locators, ie.</p>
+ * <blockquote>
+ * <em>filterType</em><strong>=</strong><em>argument</em></blockquote>
+ *
+ * <p>Supported element-filters are:</p>
+ * <p><strong>value=</strong><em>valuePattern</em></p>
+ * <blockquote>
+ * Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons.</blockquote>
+ * <p><strong>index=</strong><em>index</em></p>
+ * <blockquote>
+ * Selects a single element based on its position in the list (offset from zero).</blockquote>
+ * </blockquote>
+ *
+ * <h3><a name="patterns"></a>String-match Patterns</h3>
+ *
+ * <p>
+ * Various Pattern syntaxes are available for matching string values:
+ * </p>
+ * <blockquote>
+ * <dl>
+ * <dt><strong>glob:</strong><em>pattern</em></dt>
+ * <dd>Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a
+ * kind of limited regular-expression syntax typically used in command-line
+ * shells. In a glob pattern, "*" represents any sequence of characters, and "?"
+ * represents any single character. Glob patterns match against the entire
+ * string.</dd>
+ * <dt><strong>regexp:</strong><em>regexp</em></dt>
+ * <dd>Match a string using a regular-expression. The full power of JavaScript
+ * regular-expressions is available.</dd>
+ * <dt><strong>exact:</strong><em>string</em></dt>
+ *
+ * <dd>Match a string exactly, verbatim, without any of that fancy wildcard
+ * stuff.</dd>
+ * </dl>
+ * </blockquote>
+ * <p>
+ * If no pattern prefix is specified, Selenium assumes that it's a "glob"
+ * pattern.
+ * </p>
+ */
+ this.browserbot = browserbot;
+ this.optionLocatorFactory = new OptionLocatorFactory();
+ this.page = function() {
+ return browserbot.getCurrentPage();
+ };
+}
+
+Selenium.createForFrame = function(frame) {
+ return new Selenium(BrowserBot.createForFrame(frame));
+};
+
+Selenium.prototype.reset = function() {
+ /**
+ * Clear out all stored variables and select the null (starting) window
+ */
+ storedVars = new Object();
+ this.browserbot.selectWindow("null");
+};
+
+Selenium.prototype.doClick = function(locator) {
+ /**
+ * Clicks on a link, button, checkbox or radio button. If the click action
+ * causes a new page to load (like a link usually does), call
+ * waitForPageToLoad.
+ *
+ * @param locator an element locator
+ *
+ */
+ var element = this.page().findElement(locator);
+ this.page().clickElement(element);
+};
+
+Selenium.prototype.doFireEvent = function(locator, eventName) {
+ /**
+ * Explicitly simulate an event, to trigger the corresponding &quot;on<em>event</em>&quot;
+ * handler.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @param eventName the event name, e.g. "focus" or "blur"
+ */
+ var element = this.page().findElement(locator);
+ triggerEvent(element, eventName, false);
+};
+
+Selenium.prototype.doKeyPress = function(locator, keycode) {
+ /**
+ * Simulates a user pressing and releasing a key.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @param keycode the numeric keycode of the key to be pressed, normally the
+ * ASCII value of that key.
+ */
+ var element = this.page().findElement(locator);
+ triggerKeyEvent(element, 'keypress', keycode, true);
+};
+
+Selenium.prototype.doKeyDown = function(locator, keycode) {
+ /**
+ * Simulates a user pressing a key (without releasing it yet).
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @param keycode the numeric keycode of the key to be pressed, normally the
+ * ASCII value of that key.
+ */
+ var element = this.page().findElement(locator);
+ triggerKeyEvent(element, 'keydown', keycode, true);
+};
+
+Selenium.prototype.doKeyUp = function(locator, keycode) {
+ /**
+ * Simulates a user releasing a key.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @param keycode the numeric keycode of the key to be released, normally the
+ * ASCII value of that key.
+ */
+ var element = this.page().findElement(locator);
+ triggerKeyEvent(element, 'keyup', keycode, true);
+};
+
+Selenium.prototype.doMouseOver = function(locator) {
+ /**
+ * Simulates a user hovering a mouse over the specified element.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ */
+ var element = this.page().findElement(locator);
+ triggerMouseEvent(element, 'mouseover', true);
+};
+
+Selenium.prototype.doMouseDown = function(locator) {
+ /**
+ * Simulates a user pressing the mouse button (without releasing it yet) on
+ * the specified element.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ */
+ var element = this.page().findElement(locator);
+ triggerMouseEvent(element, 'mousedown', true);
+};
+
+Selenium.prototype.doType = function(locator, value) {
+ /**
+ * Sets the value of an input field, as though you typed it in.
+ *
+ * <p>Can also be used to set the value of combo boxes, check boxes, etc. In these cases,
+ * value should be the value of the option selected, not the visible text.</p>
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @param value the value to type
+ */
+ // TODO fail if it can't be typed into.
+ var element = this.page().findElement(locator);
+ this.page().replaceText(element, value);
+};
+
+Selenium.prototype.findToggleButton = function(locator) {
+ var element = this.page().findElement(locator);
+ if (element.checked == null) {
+ Assert.fail("Element " + locator + " is not a toggle-button.");
+ }
+ return element;
+}
+
+Selenium.prototype.doCheck = function(locator) {
+ /**
+ * Check a toggle-button (checkbox/radio)
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ */
+ this.findToggleButton(locator).checked = true;
+};
+
+Selenium.prototype.doUncheck = function(locator) {
+ /**
+ * Uncheck a toggle-button (checkbox/radio)
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ */
+ this.findToggleButton(locator).checked = false;
+};
+
+Selenium.prototype.doSelect = function(selectLocator, optionLocator) {
+ /**
+ * Select an option from a drop-down using an option locator.
+ *
+ * <p>
+ * Option locators provide different ways of specifying options of an HTML
+ * Select element (e.g. for selecting a specific option, or for asserting
+ * that the selected option satisfies a specification). There are several
+ * forms of Select Option Locator.
+ * </p>
+ * <dl>
+ * <dt><strong>label</strong>=<em>labelPattern</em></dt>
+ * <dd>matches options based on their labels, i.e. the visible text. (This
+ * is the default.)
+ * <ul class="first last simple">
+ * <li>label=regexp:^[Oo]ther</li>
+ * </ul>
+ * </dd>
+ * <dt><strong>value</strong>=<em>valuePattern</em></dt>
+ * <dd>matches options based on their values.
+ * <ul class="first last simple">
+ * <li>value=other</li>
+ * </ul>
+ *
+ *
+ * </dd>
+ * <dt><strong>id</strong>=<em>id</em></dt>
+ *
+ * <dd>matches options based on their ids.
+ * <ul class="first last simple">
+ * <li>id=option1</li>
+ * </ul>
+ * </dd>
+ * <dt><strong>index</strong>=<em>index</em></dt>
+ * <dd>matches an option based on its index (offset from zero).
+ * <ul class="first last simple">
+ *
+ * <li>index=2</li>
+ * </ul>
+ * </dd>
+ * </dl>
+ * <p>
+ * If no option locator prefix is provided, the default behaviour is to match on <strong>label</strong>.
+ * </p>
+ *
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @param optionLocator an option locator (a label by default)
+ */
+ var element = this.page().findElement(selectLocator);
+ if (!("options" in element)) {
+ throw new SeleniumError("Specified element is not a Select (has no options)");
+ }
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
+ var option = locator.findOption(element);
+ this.page().selectOption(element, option);
+};
+
+Selenium.prototype.doAddSelection = function(locator, optionLocator) {
+ /**
+ * Add a selection to the set of selected options in a multi-select element using an option locator.
+ *
+ * @see #doSelect for details of option locators
+ *
+ * @param locator an <a href="#locators">element locator</a> identifying a multi-select box
+ * @param optionLocator an option locator (a label by default)
+ */
+ var element = this.page().findElement(locator);
+ if (!("options" in element)) {
+ throw new SeleniumError("Specified element is not a Select (has no options)");
+ }
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
+ var option = locator.findOption(element);
+ this.page().addSelection(element, option);
+};
+
+Selenium.prototype.doRemoveSelection = function(locator, optionLocator) {
+ /**
+ * Remove a selection from the set of selected options in a multi-select element using an option locator.
+ *
+ * @see #doSelect for details of option locators
+ *
+ * @param locator an <a href="#locators">element locator</a> identifying a multi-select box
+ * @param optionLocator an option locator (a label by default)
+ */
+
+ var element = this.page().findElement(locator);
+ if (!("options" in element)) {
+ throw new SeleniumError("Specified element is not a Select (has no options)");
+ }
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
+ var option = locator.findOption(element);
+ this.page().removeSelection(element, option);
+};
+
+Selenium.prototype.doSubmit = function(formLocator) {
+ /**
+ * Submit the specified form. This is particularly useful for forms without
+ * submit buttons, e.g. single-input "Search" forms.
+ *
+ * @param formLocator an <a href="#locators">element locator</a> for the form you want to submit
+ */
+ var form = this.page().findElement(formLocator);
+ var actuallySubmit = true;
+ if (form.onsubmit) {
+ // apply this to the correct window so alerts are properly handled, even in IE HTA mode
+ actuallySubmit = form.onsubmit.apply(this.browserbot.getContentWindow());
+ }
+ if (actuallySubmit) {
+ form.submit();
+ }
+
+};
+
+Selenium.prototype.doOpen = function(url) {
+ /**
+ * Opens an URL in the test frame. This accepts both relative and absolute
+ * URLs.
+ *
+ * The &quot;open&quot; command waits for the page to load before proceeding,
+ * ie. the &quot;AndWait&quot; suffix is implicit.
+ *
+ * <em>Note</em>: The URL must be on the same domain as the runner HTML
+ * due to security restrictions in the browser (Same Origin Policy). If you
+ * need to open an URL on another domain, use the Selenium Server to start a
+ * new browser session on that domain.
+ *
+ * @param url the URL to open; may be relative or absolute
+ */
+ this.browserbot.openLocation(url);
+ return SELENIUM_PROCESS_WAIT;
+};
+
+Selenium.prototype.doSelectWindow = function(windowID) {
+ /**
+ * Selects a popup window; once a popup window has been selected, all
+ * commands go to that window. To select the main window again, use "null"
+ * as the target.
+ *
+ * @param windowID the JavaScript window ID of the window to select
+ */
+ this.browserbot.selectWindow(windowID);
+};
+
+Selenium.prototype.doWaitForPopUp = function(windowID, timeout) {
+ /**
+ * Waits for a popup window to appear and load up.
+ *
+ * @param windowID the JavaScript window ID of the window that will appear
+ * @param timeout a timeout in milliseconds, after which the action will return with an error
+ */
+ if (isNaN(timeout)) {
+ throw new SeleniumError("Timeout is not a number: " + timeout);
+ }
+
+ testLoop.waitForCondition = function () {
+ var targetWindow = selenium.browserbot.getTargetWindow(windowID);
+ if (!targetWindow) return false;
+ if (!targetWindow.location) return false;
+ if ("about:blank" == targetWindow.location) return false;
+ if (!targetWindow.document) return false;
+ if (!targetWindow.document.readyState) return true;
+ if ('complete' != targetWindow.document.readyState) return false;
+ return true;
+ };
+
+ testLoop.waitForConditionStart = new Date().getTime();
+ testLoop.waitForConditionTimeout = timeout;
+
+}
+
+Selenium.prototype.doWaitForPopUp.dontCheckAlertsAndConfirms = true;
+
+Selenium.prototype.doChooseCancelOnNextConfirmation = function() {
+ /**
+ * By default, Selenium's overridden window.confirm() function will
+ * return true, as if the user had manually clicked OK. After running
+ * this command, the next call to confirm() will return false, as if
+ * the user had clicked Cancel.
+ *
+ */
+ this.browserbot.cancelNextConfirmation();
+};
+
+
+Selenium.prototype.doAnswerOnNextPrompt = function(answer) {
+ /**
+ * Instructs Selenium to return the specified answer string in response to
+ * the next JavaScript prompt [window.prompt()].
+ *
+ *
+ * @param answer the answer to give in response to the prompt pop-up
+ */
+ this.browserbot.setNextPromptResult(answer);
+};
+
+Selenium.prototype.doGoBack = function() {
+ /**
+ * Simulates the user clicking the "back" button on their browser.
+ *
+ */
+ this.page().goBack();
+};
+
+Selenium.prototype.doRefresh = function() {
+ /**
+ * Simulates the user clicking the "Refresh" button on their browser.
+ *
+ */
+ this.page().refresh();
+};
+
+Selenium.prototype.doClose = function() {
+ /**
+ * Simulates the user clicking the "close" button in the titlebar of a popup
+ * window or tab.
+ */
+ this.page().close();
+};
+
+Selenium.prototype.isAlertPresent = function() {
+ /**
+ * Has an alert occurred?
+ *
+ * <p>
+ * This function never throws an exception
+ * </p>
+ * @return boolean true if there is an alert
+ */
+ return this.browserbot.hasAlerts();
+};
+Selenium.prototype.isPromptPresent = function() {
+ /**
+ * Has a prompt occurred?
+ *
+ * <p>
+ * This function never throws an exception
+ * </p>
+ * @return boolean true if there is a pending prompt
+ */
+ return this.browserbot.hasPrompts();
+};
+Selenium.prototype.isConfirmationPresent = function() {
+ /**
+ * Has confirm() been called?
+ *
+ * <p>
+ * This function never throws an exception
+ * </p>
+ * @return boolean true if there is a pending confirmation
+ */
+ return this.browserbot.hasConfirmations();
+};
+Selenium.prototype.getAlert = function() {
+ /**
+ * Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts.
+ *
+ * <p>Getting an alert has the same effect as manually clicking OK. If an
+ * alert is generated but you do not get/verify it, the next Selenium action
+ * will fail.</p>
+ *
+ * <p>NOTE: under Selenium, JavaScript alerts will NOT pop up a visible alert
+ * dialog.</p>
+ *
+ * <p>NOTE: Selenium does NOT support JavaScript alerts that are generated in a
+ * page's onload() event handler. In this case a visible dialog WILL be
+ * generated and Selenium will hang until someone manually clicks OK.</p>
+ * @return string The message of the most recent JavaScript alert
+ */
+ if (!this.browserbot.hasAlerts()) {
+ Assert.fail("There were no alerts");
+ }
+ return this.browserbot.getNextAlert();
+};
+Selenium.prototype.getAlert.dontCheckAlertsAndConfirms = true;
+
+Selenium.prototype.getConfirmation = function() {
+ /**
+ * Retrieves the message of a JavaScript confirmation dialog generated during
+ * the previous action.
+ *
+ * <p>
+ * By default, the confirm function will return true, having the same effect
+ * as manually clicking OK. This can be changed by prior execution of the
+ * chooseCancelOnNextConfirmation command. If an confirmation is generated
+ * but you do not get/verify it, the next Selenium action will fail.
+ * </p>
+ *
+ * <p>
+ * NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible
+ * dialog.
+ * </p>
+ *
+ * <p>
+ * NOTE: Selenium does NOT support JavaScript confirmations that are
+ * generated in a page's onload() event handler. In this case a visible
+ * dialog WILL be generated and Selenium will hang until you manually click
+ * OK.
+ * </p>
+ *
+ * @return string the message of the most recent JavaScript confirmation dialog
+ */
+ if (!this.browserbot.hasConfirmations()) {
+ Assert.fail("There were no confirmations");
+ }
+ return this.browserbot.getNextConfirmation();
+};
+Selenium.prototype.getConfirmation.dontCheckAlertsAndConfirms = true;
+
+Selenium.prototype.getPrompt = function() {
+ /**
+ * Retrieves the message of a JavaScript question prompt dialog generated during
+ * the previous action.
+ *
+ * <p>Successful handling of the prompt requires prior execution of the
+ * answerOnNextPrompt command. If a prompt is generated but you
+ * do not get/verify it, the next Selenium action will fail.</p>
+ *
+ * <p>NOTE: under Selenium, JavaScript prompts will NOT pop up a visible
+ * dialog.</p>
+ *
+ * <p>NOTE: Selenium does NOT support JavaScript prompts that are generated in a
+ * page's onload() event handler. In this case a visible dialog WILL be
+ * generated and Selenium will hang until someone manually clicks OK.</p>
+ * @return string the message of the most recent JavaScript question prompt
+ */
+ if (! this.browserbot.hasPrompts()) {
+ Assert.fail("There were no prompts");
+ }
+ return this.browserbot.getNextPrompt();
+};
+
+Selenium.prototype.getLocation = function() {
+ /** Gets the absolute URL of the current page.
+ *
+ * @return string the absolute URL of the current page
+ */
+ return this.page().location;
+};
+
+Selenium.prototype.getTitle = function() {
+ /** Gets the title of the current page.
+ *
+ * @return string the title of the current page
+ */
+ return this.page().title();
+};
+
+
+Selenium.prototype.getBodyText = function() {
+ /**
+ * Gets the entire text of the page.
+ * @return string the entire text of the page
+ */
+ return this.page().bodyText();
+};
+
+
+Selenium.prototype.getValue = function(locator) {
+ /**
+ * Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter).
+ * For checkbox/radio elements, the value will be "on" or "off" depending on
+ * whether the element is checked or not.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @return string the element value, or "on/off" for checkbox/radio elements
+ */
+ var element = this.page().findElement(locator)
+ return getInputValue(element).trim();
+}
+
+Selenium.prototype.getText = function(locator) {
+ /**
+ * Gets the text of an element. This works for any element that contains
+ * text. This command uses either the textContent (Mozilla-like browsers) or
+ * the innerText (IE-like browsers) of the element, which is the rendered
+ * text shown to the user.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @return string the text of the element
+ */
+ var element = this.page().findElement(locator);
+ return getText(element).trim();
+};
+
+Selenium.prototype.getEval = function(script) {
+ /** Gets the result of evaluating the specified JavaScript snippet. The snippet may
+ * have multiple lines, but only the result of the last line will be returned.
+ *
+ * <p>Note that, by default, the snippet will run in the context of the "selenium"
+ * object itself, so <code>this</code> will refer to the Selenium object, and <code>window</code> will
+ * refer to the top-level runner test window, not the window of your application.</p>
+ *
+ * <p>If you need a reference to the window of your application, you can refer
+ * to <code>this.browserbot.getCurrentWindow()</code> and if you need to use
+ * a locator to refer to a single element in your application page, you can
+ * use <code>this.page().findElement("foo")</code> where "foo" is your locator.</p>
+ *
+ * @param script the JavaScript snippet to run
+ * @return string the results of evaluating the snippet
+ */
+ try {
+ var result = eval(script);
+ // Selenium RC doesn't allow returning null
+ if (null == result) return "null";
+ return result;
+ } catch (e) {
+ throw new SeleniumError("Threw an exception: " + e.message);
+ }
+};
+
+Selenium.prototype.isChecked = function(locator) {
+ /**
+ * Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button.
+ * @param locator an <a href="#locators">element locator</a> pointing to a checkbox or radio button
+ * @return string either "true" or "false" depending on whether the checkbox is checked
+ */
+ var element = this.page().findElement(locator);
+ if (element.checked == null) {
+ throw new SeleniumError("Element " + locator + " is not a toggle-button.");
+ }
+ return element.checked;
+};
+
+Selenium.prototype.getTable = function(tableCellAddress) {
+ /**
+ * Gets the text from a cell of a table. The cellAddress syntax
+ * tableLocator.row.column, where row and column start at 0.
+ *
+ * @param tableCellAddress a cell address, e.g. "foo.1.4"
+ * @return string the text from the specified cell
+ */
+ // This regular expression matches "tableName.row.column"
+ // For example, "mytable.3.4"
+ pattern = /(.*)\.(\d+)\.(\d+)/;
+
+ if(!pattern.test(tableCellAddress)) {
+ throw new SeleniumError("Invalid target format. Correct format is tableName.rowNum.columnNum");
+ }
+
+ pieces = tableCellAddress.match(pattern);
+
+ tableName = pieces[1];
+ row = pieces[2];
+ col = pieces[3];
+
+ var table = this.page().findElement(tableName);
+ if (row > table.rows.length) {
+ Assert.fail("Cannot access row " + row + " - table has " + table.rows.length + " rows");
+ }
+ else if (col > table.rows[row].cells.length) {
+ Assert.fail("Cannot access column " + col + " - table row has " + table.rows[row].cells.length + " columns");
+ }
+ else {
+ actualContent = getText(table.rows[row].cells[col]);
+ return actualContent.trim();
+ }
+ return null;
+};
+
+Selenium.prototype.assertSelected = function(selectLocator, optionLocator) {
+ /**
+ * Verifies that the selected option of a drop-down satisfies the optionSpecifier.
+ *
+ * <p>See the select command for more information about option locators.</p>
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @param optionLocator an option locator, typically just an option label (e.g. "John Smith")
+ */
+ var element = this.page().findElement(selectLocator);
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
+ if (element.selectedIndex == -1)
+ {
+ Assert.fail("No option selected");
+ }
+ locator.assertSelected(element);
+};
+
+Selenium.prototype.getSelectedLabels = function(selectLocator) {
+ /** Gets all option labels (visible text) for selected options in the specified select or multi-select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string[] an array of all selected option labels in the specified select drop-down
+ */
+ return this.findSelectedOptionProperties(selectLocator, "text").join(",");
+}
+
+Selenium.prototype.getSelectedLabel = function(selectLocator) {
+ /** Gets option label (visible text) for selected option in the specified select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string the selected option label in the specified select drop-down
+ */
+ return this.findSelectedOptionProperty(selectLocator, "text");
+}
+
+Selenium.prototype.getSelectedValues = function(selectLocator) {
+ /** Gets all option values (value attributes) for selected options in the specified select or multi-select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string[] an array of all selected option values in the specified select drop-down
+ */
+ return this.findSelectedOptionProperties(selectLocator, "value").join(",");
+}
+
+Selenium.prototype.getSelectedValue = function(selectLocator) {
+ /** Gets option value (value attribute) for selected option in the specified select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string the selected option value in the specified select drop-down
+ */
+ return this.findSelectedOptionProperty(selectLocator, "value");
+}
+
+Selenium.prototype.getSelectedIndexes = function(selectLocator) {
+ /** Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string[] an array of all selected option indexes in the specified select drop-down
+ */
+ return this.findSelectedOptionProperties(selectLocator, "index").join(",");
+}
+
+Selenium.prototype.getSelectedIndex = function(selectLocator) {
+ /** Gets option index (option number, starting at 0) for selected option in the specified select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string the selected option index in the specified select drop-down
+ */
+ return this.findSelectedOptionProperty(selectLocator, "index");
+}
+
+Selenium.prototype.getSelectedIds = function(selectLocator) {
+ /** Gets all option element IDs for selected options in the specified select or multi-select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string[] an array of all selected option IDs in the specified select drop-down
+ */
+ return this.findSelectedOptionProperties(selectLocator, "id").join(",");
+}
+
+Selenium.prototype.getSelectedId = function(selectLocator) {
+ /** Gets option element ID for selected option in the specified select element.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string the selected option ID in the specified select drop-down
+ */
+ return this.findSelectedOptionProperty(selectLocator, "id");
+}
+
+Selenium.prototype.isSomethingSelected = function(selectLocator) {
+ /** Determines whether some option in a drop-down menu is selected.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return boolean true if some option has been selected, false otherwise
+ */
+ var element = this.page().findElement(selectLocator);
+ if (!("options" in element)) {
+ throw new SeleniumError("Specified element is not a Select (has no options)");
+ }
+
+ var selectedOptions = [];
+
+ for (var i = 0; i < element.options.length; i++) {
+ if (element.options[i].selected)
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+Selenium.prototype.findSelectedOptionProperties = function(locator, property) {
+ var element = this.page().findElement(locator);
+ if (!("options" in element)) {
+ throw new SeleniumError("Specified element is not a Select (has no options)");
+ }
+
+ var selectedOptions = [];
+
+ for (var i = 0; i < element.options.length; i++) {
+ if (element.options[i].selected)
+ {
+ var propVal = element.options[i][property];
+ if (propVal.replace) {
+ propVal.replace(/,/g, "\\,");
+ }
+ selectedOptions.push(propVal);
+ }
+ }
+ if (selectedOptions.length == 0) Assert.fail("No option selected");
+ return selectedOptions;
+}
+
+Selenium.prototype.findSelectedOptionProperty = function(locator, property) {
+ var selectedOptions = this.findSelectedOptionProperties(locator, property);
+ if (selectedOptions.length > 1) {
+ Assert.fail("More than one selected option!");
+ }
+ return selectedOptions[0];
+}
+
+Selenium.prototype.getSelectOptions = function(selectLocator) {
+ /** Gets all option labels in the specified select drop-down.
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @return string[] an array of all option labels in the specified select drop-down
+ */
+ var element = this.page().findElement(selectLocator);
+
+ var selectOptions = [];
+
+ for (var i = 0; i < element.options.length; i++) {
+ var option = element.options[i].text.replace(/,/g, "\\,");
+ selectOptions.push(option);
+ }
+
+ return selectOptions.join(",");
+};
+
+
+Selenium.prototype.getAttribute = function(attributeLocator) {
+ /**
+ * Gets the value of an element attribute.
+ * @param attributeLocator an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar"
+ * @return string the value of the specified attribute
+ */
+ var result = this.page().findAttribute(attributeLocator);
+ if (result == null) {
+ throw new SeleniumError("Could not find element attribute: " + attributeLocator);
+ }
+ return result;
+};
+
+Selenium.prototype.isTextPresent = function(pattern) {
+ /**
+ * Verifies that the specified text pattern appears somewhere on the rendered page shown to the user.
+ * @param pattern a <a href="#patterns">pattern</a> to match with the text of the page
+ * @return boolean true if the pattern matches the text, false otherwise
+ */
+ var allText = this.page().bodyText();
+
+ if(allText == "") {
+ Assert.fail("Page text not found");
+ } else {
+ var patternMatcher = new PatternMatcher(pattern);
+ if (patternMatcher.strategy == PatternMatcher.strategies.glob) {
+ patternMatcher.matcher = new PatternMatcher.strategies.globContains(pattern);
+ }
+ return patternMatcher.matches(allText);
+ }
+};
+
+Selenium.prototype.isElementPresent = function(locator) {
+ /**
+ * Verifies that the specified element is somewhere on the page.
+ * @param locator an <a href="#locators">element locator</a>
+ * @return boolean true if the element is present, false otherwise
+ */
+ try {
+ this.page().findElement(locator);
+ } catch (e) {
+ return false;
+ }
+ return true;
+};
+
+Selenium.prototype.isVisible = function(locator) {
+ /**
+ * Determines if the specified element is visible. An
+ * element can be rendered invisible by setting the CSS "visibility"
+ * property to "hidden", or the "display" property to "none", either for the
+ * element itself or one if its ancestors. This method will fail if
+ * the element is not present.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @return boolean true if the specified element is visible, false otherwise
+ */
+ var element;
+ element = this.page().findElement(locator);
+
+ if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
+ var visibility = element.style["visibility"];
+ else
+ var visibility = this.findEffectiveStyleProperty(element, "visibility");
+
+ var _isDisplayed = this._isDisplayed(element);
+ return (visibility != "hidden" && _isDisplayed);
+};
+
+Selenium.prototype.findEffectiveStyleProperty = function(element, property) {
+ var effectiveStyle = this.findEffectiveStyle(element);
+ var propertyValue = effectiveStyle[property];
+ if (propertyValue == 'inherit' && element.parentNode.style) {
+ return this.findEffectiveStyleProperty(element.parentNode, property);
+ }
+ return propertyValue;
+};
+
+Selenium.prototype._isDisplayed = function(element) {
+ if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
+ var display = element.style["display"];
+ else
+ var display = this.findEffectiveStyleProperty(element, "display");
+ if (display == "none") return false;
+ if (element.parentNode.style) {
+ return this._isDisplayed(element.parentNode);
+ }
+ return true;
+};
+
+Selenium.prototype.findEffectiveStyle = function(element) {
+ if (element.style == undefined) {
+ return undefined; // not a styled element
+ }
+ var window = this.browserbot.getContentWindow();
+ if (window.getComputedStyle) {
+ // DOM-Level-2-CSS
+ return window.getComputedStyle(element, null);
+ }
+ if (element.currentStyle) {
+ // non-standard IE alternative
+ return element.currentStyle;
+ // TODO: this won't really work in a general sense, as
+ // currentStyle is not identical to getComputedStyle()
+ // ... but it's good enough for "visibility"
+ }
+ throw new SeleniumError("cannot determine effective stylesheet in this browser");
+};
+
+Selenium.prototype.isEditable = function(locator) {
+ /**
+ * Determines whether the specified input element is editable, ie hasn't been disabled.
+ * This method will fail if the specified element isn't an input element.
+ *
+ * @param locator an <a href="#locators">element locator</a>
+ * @return boolean true if the input element is editable, false otherwise
+ */
+ var element = this.page().findElement(locator);
+ if (element.value == undefined) {
+ Assert.fail("Element " + locator + " is not an input.");
+ }
+ return !element.disabled;
+};
+
+Selenium.prototype.getAllButtons = function() {
+ /** Returns the IDs of all buttons on the page.
+ *
+ * <p>If a given button has no ID, it will appear as "" in this array.</p>
+ *
+ * @return string[] the IDs of all buttons on the page
+ */
+ return this.page().getAllButtons();
+};
+
+Selenium.prototype.getAllLinks = function() {
+ /** Returns the IDs of all links on the page.
+ *
+ * <p>If a given link has no ID, it will appear as "" in this array.</p>
+ *
+ * @return string[] the IDs of all links on the page
+ */
+ return this.page().getAllLinks();
+};
+
+Selenium.prototype.getAllFields = function() {
+ /** Returns the IDs of all input fields on the page.
+ *
+ * <p>If a given field has no ID, it will appear as "" in this array.</p>
+ *
+ * @return string[] the IDs of all field on the page
+ */
+ return this.page().getAllFields();
+};
+
+Selenium.prototype.getHtmlSource = function() {
+ /** Returns the entire HTML source between the opening and
+ * closing "html" tags.
+ *
+ * @return string the entire HTML source
+ */
+ return this.page().currentDocument.getElementsByTagName("html")[0].innerHTML;
+};
+
+Selenium.prototype.doSetCursorPosition = function(locator, position) {
+ /**
+ * Moves the text cursor to the specified position in the given input element or textarea.
+ * This method will fail if the specified element isn't an input element or textarea.
+ *
+ * @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
+ * @param position the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field.
+ */
+ var element = this.page().findElement(locator);
+ if (element.value == undefined) {
+ Assert.fail("Element " + locator + " is not an input.");
+ }
+ if (position == -1) {
+ position = element.value.length;
+ }
+
+ if( element.setSelectionRange && !browserVersion.isOpera) {
+ element.focus();
+ element.setSelectionRange(/*start*/position,/*end*/position);
+ }
+ else if( element.createTextRange ) {
+ triggerEvent(element, 'focus', false);
+ var range = element.createTextRange();
+ range.collapse(true);
+ range.moveEnd('character',position);
+ range.moveStart('character',position);
+ range.select();
+ }
+}
+
+Selenium.prototype.getCursorPosition = function(locator) {
+ /**
+ * Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers.
+ *
+ * <p>Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to
+ * return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as <a href="http://jira.openqa.org/browse/SEL-243">SEL-243</a>.</p>
+ * This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element.
+ *
+ * @param locator an <a href="#locators">element locator</a> pointing to an input element or textarea
+ * @return number the numerical position of the cursor in the field
+ */
+ var element = this.page().findElement(locator);
+ var doc = this.page().currentDocument;
+ var win = this.browserbot.getCurrentWindow();
+ if( doc.selection && !browserVersion.isOpera){
+
+ var selectRange = doc.selection.createRange().duplicate();
+ var elementRange = element.createTextRange();
+ selectRange.move("character",0);
+ elementRange.move("character",0);
+ var inRange1 = selectRange.inRange(elementRange);
+ var inRange2 = elementRange.inRange(selectRange);
+ try {
+ elementRange.setEndPoint("EndToEnd", selectRange);
+ } catch (e) {
+ Assert.fail("There is no cursor on this page!");
+ }
+ var answer = String(elementRange.text).replace(/\r/g,"").length;
+ return answer;
+ } else {
+ if (typeof(element.selectionStart) != undefined) {
+ if (win.getSelection && typeof(win.getSelection().rangeCount) != undefined && win.getSelection().rangeCount == 0) {
+ Assert.fail("There is no cursor on this page!");
+ }
+ return element.selectionStart;
+ }
+ }
+ throw new Error("Couldn't detect cursor position on this browser!");
+}
+
+
+Selenium.prototype.doSetContext = function(context, logLevelThreshold) {
+ /**
+ * Writes a message to the status bar and adds a note to the browser-side
+ * log.
+ *
+ * <p>If logLevelThreshold is specified, set the threshold for logging
+ * to that level (debug, info, warn, error).</p>
+ *
+ * <p>(Note that the browser-side logs will <i>not</i> be sent back to the
+ * server, and are invisible to the Client Driver.)</p>
+ *
+ * @param context
+ * the message to be sent to the browser
+ * @param logLevelThreshold one of "debug", "info", "warn", "error", sets the threshold for browser-side logging
+ */
+ if (logLevelThreshold==null || logLevelThreshold=="") {
+ return this.page().setContext(context);
+ }
+ return this.page().setContext(context, logLevelThreshold);
+};
+
+Selenium.prototype.getExpression = function(expression) {
+ /**
+ * Returns the specified expression.
+ *
+ * <p>This is useful because of JavaScript preprocessing.
+ * It is used to generate commands like assertExpression and storeExpression.</p>
+ *
+ * @param expression the value to return
+ * @return string the value passed in
+ */
+ return expression;
+}
+
+Selenium.prototype.doWaitForCondition = function(script, timeout) {
+ /**
+ * Runs the specified JavaScript snippet repeatedly until it evaluates to "true".
+ * The snippet may have multiple lines, but only the result of the last line
+ * will be considered.
+ *
+ * <p>Note that, by default, the snippet will be run in the runner's test window, not in the window
+ * of your application. To get the window of your application, you can use
+ * the JavaScript snippet <code>selenium.browserbot.getCurrentWindow()</code>, and then
+ * run your JavaScript in there</p>
+ * @param script the JavaScript snippet to run
+ * @param timeout a timeout in milliseconds, after which this command will return with an error
+ */
+ if (isNaN(timeout)) {
+ throw new SeleniumError("Timeout is not a number: " + timeout);
+ }
+
+ testLoop.waitForCondition = function () {
+ return eval(script);
+ };
+
+ testLoop.waitForConditionStart = new Date().getTime();
+ testLoop.waitForConditionTimeout = timeout;
+};
+
+Selenium.prototype.doWaitForCondition.dontCheckAlertsAndConfirms = true;
+
+Selenium.prototype.doSetTimeout = function(timeout) {
+ /**
+ * Specifies the amount of time that Selenium will wait for actions to complete.
+ *
+ * <p>Actions that require waiting include "open" and the "waitFor*" actions.</p>
+ * The default timeout is 30 seconds.
+ * @param timeout a timeout in milliseconds, after which the action will return with an error
+ */
+ testLoop.waitForConditionTimeout = timeout;
+}
+
+Selenium.prototype.doWaitForPageToLoad = function(timeout) {
+ /**
+ * Waits for a new page to load.
+ *
+ * <p>You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc.
+ * (which are only available in the JS API).</p>
+ *
+ * <p>Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded"
+ * flag when it first notices a page load. Running any other Selenium command after
+ * turns the flag to false. Hence, if you want to wait for a page to load, you must
+ * wait immediately after a Selenium command that caused a page-load.</p>
+ * @param timeout a timeout in milliseconds, after which this command will return with an error
+ */
+ this.doWaitForCondition("selenium.browserbot.isNewPageLoaded()", timeout);
+};
+
+Selenium.prototype.doWaitForPageToLoad.dontCheckAlertsAndConfirms = true;
+
+/**
+ * Evaluate a parameter, performing JavaScript evaluation and variable substitution.
+ * If the string matches the pattern "javascript{ ... }", evaluate the string between the braces.
+ */
+Selenium.prototype.preprocessParameter = function(value) {
+ var match = value.match(/^javascript\{((.|\r?\n)+)\}$/);
+ if (match && match[1]) {
+ return eval(match[1]).toString();
+ }
+ return this.replaceVariables(value);
+};
+
+/*
+ * Search through str and replace all variable references ${varName} with their
+ * value in storedVars.
+ */
+Selenium.prototype.replaceVariables = function(str) {
+ var stringResult = str;
+
+ // Find all of the matching variable references
+ var match = stringResult.match(/\$\{\w+\}/g);
+ if (!match) {
+ return stringResult;
+ }
+
+ // For each match, lookup the variable value, and replace if found
+ for (var i = 0; match && i < match.length; i++) {
+ var variable = match[i]; // The replacement variable, with ${}
+ var name = variable.substring(2, variable.length - 1); // The replacement variable without ${}
+ var replacement = storedVars[name];
+ if (replacement != undefined) {
+ stringResult = stringResult.replace(variable, replacement);
+ }
+ }
+ return stringResult;
+};
+
+
+/**
+ * Factory for creating "Option Locators".
+ * An OptionLocator is an object for dealing with Select options (e.g. for
+ * finding a specified option, or asserting that the selected option of
+ * Select element matches some condition.
+ * The type of locator returned by the factory depends on the locator string:
+ * label=<exp> (OptionLocatorByLabel)
+ * value=<exp> (OptionLocatorByValue)
+ * index=<exp> (OptionLocatorByIndex)
+ * id=<exp> (OptionLocatorById)
+ * <exp> (default is OptionLocatorByLabel).
+ */
+function OptionLocatorFactory() {
+}
+
+OptionLocatorFactory.prototype.fromLocatorString = function(locatorString) {
+ var locatorType = 'label';
+ var locatorValue = locatorString;
+ // If there is a locator prefix, use the specified strategy
+ var result = locatorString.match(/^([a-zA-Z]+)=(.*)/);
+ if (result) {
+ locatorType = result[1];
+ locatorValue = result[2];
+ }
+ if (this.optionLocators == undefined) {
+ this.registerOptionLocators();
+ }
+ if (this.optionLocators[locatorType]) {
+ return new this.optionLocators[locatorType](locatorValue);
+ }
+ throw new SeleniumError("Unkown option locator type: " + locatorType);
+};
+
+/**
+ * To allow for easy extension, all of the option locators are found by
+ * searching for all methods of OptionLocatorFactory.prototype that start
+ * with "OptionLocatorBy".
+ * TODO: Consider using the term "Option Specifier" instead of "Option Locator".
+ */
+OptionLocatorFactory.prototype.registerOptionLocators = function() {
+ this.optionLocators={};
+ for (var functionName in this) {
+ var result = /OptionLocatorBy([A-Z].+)$/.exec(functionName);
+ if (result != null) {
+ var locatorName = result[1].lcfirst();
+ this.optionLocators[locatorName] = this[functionName];
+ }
+ }
+};
+
+/**
+ * OptionLocator for options identified by their labels.
+ */
+OptionLocatorFactory.prototype.OptionLocatorByLabel = function(label) {
+ this.label = label;
+ this.labelMatcher = new PatternMatcher(this.label);
+ this.findOption = function(element) {
+ for (var i = 0; i < element.options.length; i++) {
+ if (this.labelMatcher.matches(element.options[i].text)) {
+ return element.options[i];
+ }
+ }
+ throw new SeleniumError("Option with label '" + this.label + "' not found");
+ };
+
+ this.assertSelected = function(element) {
+ var selectedLabel = element.options[element.selectedIndex].text;
+ Assert.matches(this.label, selectedLabel)
+ };
+};
+
+/**
+ * OptionLocator for options identified by their values.
+ */
+OptionLocatorFactory.prototype.OptionLocatorByValue = function(value) {
+ this.value = value;
+ this.valueMatcher = new PatternMatcher(this.value);
+ this.findOption = function(element) {
+ for (var i = 0; i < element.options.length; i++) {
+ if (this.valueMatcher.matches(element.options[i].value)) {
+ return element.options[i];
+ }
+ }
+ throw new SeleniumError("Option with value '" + this.value + "' not found");
+ };
+
+ this.assertSelected = function(element) {
+ var selectedValue = element.options[element.selectedIndex].value;
+ Assert.matches(this.value, selectedValue)
+ };
+};
+
+/**
+ * OptionLocator for options identified by their index.
+ */
+OptionLocatorFactory.prototype.OptionLocatorByIndex = function(index) {
+ this.index = Number(index);
+ if (isNaN(this.index) || this.index < 0) {
+ throw new SeleniumError("Illegal Index: " + index);
+ }
+
+ this.findOption = function(element) {
+ if (element.options.length <= this.index) {
+ throw new SeleniumError("Index out of range. Only " + element.options.length + " options available");
+ }
+ return element.options[this.index];
+ };
+
+ this.assertSelected = function(element) {
+ Assert.equals(this.index, element.selectedIndex);
+ };
+};
+
+/**
+ * OptionLocator for options identified by their id.
+ */
+OptionLocatorFactory.prototype.OptionLocatorById = function(id) {
+ this.id = id;
+ this.idMatcher = new PatternMatcher(this.id);
+ this.findOption = function(element) {
+ for (var i = 0; i < element.options.length; i++) {
+ if (this.idMatcher.matches(element.options[i].id)) {
+ return element.options[i];
+ }
+ }
+ throw new SeleniumError("Option with id '" + this.id + "' not found");
+ };
+
+ this.assertSelected = function(element) {
+ var selectedId = element.options[element.selectedIndex].id;
+ Assert.matches(this.id, selectedId)
+ };
+};
+
+
diff --git a/tests/test_tools/selenium/core/scripts/selenium-browserbot.js b/tests/test_tools/selenium/core/scripts/selenium-browserbot.js
new file mode 100644
index 00000000..8df46865
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-browserbot.js
@@ -0,0 +1,1114 @@
+/*
+* Copyright 2004 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+
+/*
+* This script provides the Javascript API to drive the test application contained within
+* a Browser Window.
+* TODO:
+* Add support for more events (keyboard and mouse)
+* Allow to switch "user-entry" mode from mouse-based to keyboard-based, firing different
+* events in different modes.
+*/
+
+// The window to which the commands will be sent. For example, to click on a
+// popup window, first select that window, and then do a normal click command.
+
+var BrowserBot = function(frame) {
+ this.frame = frame;
+ this.currentPage = null;
+ this.currentWindowName = null;
+
+ this.modalDialogTest = null;
+ this.recordedAlerts = new Array();
+ this.recordedConfirmations = new Array();
+ this.recordedPrompts = new Array();
+ this.openedWindows = {};
+ this.nextConfirmResult = true;
+ this.nextPromptResult = '';
+ this.newPageLoaded = false;
+ this.pageLoadError = null;
+
+ var self = this;
+ this.recordPageLoad = function() {
+ LOG.debug("Page load detected");
+ try {
+ LOG.debug("Page load location=" + self.getCurrentWindow().location);
+ } catch (e) {
+ self.pageLoadError = e;
+ return;
+ }
+ self.currentPage = null;
+ self.newPageLoaded = true;
+ };
+
+ this.isNewPageLoaded = function() {
+ if (this.pageLoadError) throw this.pageLoadError;
+ return self.newPageLoaded;
+ };
+};
+
+BrowserBot.createForFrame = function(frame) {
+ var browserbot;
+ LOG.debug("browserName: " + browserVersion.name);
+ LOG.debug("userAgent: " + navigator.userAgent);
+ if (browserVersion.isIE) {
+ browserbot = new IEBrowserBot(frame);
+ }
+ else if (browserVersion.isKonqueror) {
+ browserbot = new KonquerorBrowserBot(frame);
+ }
+ else if (browserVersion.isSafari) {
+ browserbot = new SafariBrowserBot(frame);
+ }
+ else {
+ LOG.info("Using MozillaBrowserBot")
+ // Use mozilla by default
+ browserbot = new MozillaBrowserBot(frame);
+ }
+
+ // Modify the test IFrame so that page loads are detected.
+ addLoadListener(browserbot.getFrame(), browserbot.recordPageLoad);
+ return browserbot;
+};
+
+BrowserBot.prototype.doModalDialogTest = function(test) {
+ this.modalDialogTest = test;
+};
+
+BrowserBot.prototype.cancelNextConfirmation = function() {
+ this.nextConfirmResult = false;
+};
+
+BrowserBot.prototype.setNextPromptResult = function(result) {
+ this.nextPromptResult = result;
+};
+
+BrowserBot.prototype.hasAlerts = function() {
+ return (this.recordedAlerts.length > 0) ;
+};
+
+BrowserBot.prototype.getNextAlert = function() {
+ return this.recordedAlerts.shift();
+};
+
+BrowserBot.prototype.hasConfirmations = function() {
+ return (this.recordedConfirmations.length > 0) ;
+};
+
+BrowserBot.prototype.getNextConfirmation = function() {
+ return this.recordedConfirmations.shift();
+};
+
+BrowserBot.prototype.hasPrompts = function() {
+ return (this.recordedPrompts.length > 0) ;
+};
+
+BrowserBot.prototype.getNextPrompt = function() {
+ return this.recordedPrompts.shift();
+};
+
+BrowserBot.prototype.getFrame = function() {
+ return this.frame;
+};
+
+BrowserBot.prototype.selectWindow = function(target) {
+ // we've moved to a new page - clear the current one
+ this.currentPage = null;
+ this.currentWindowName = null;
+ if (target && target != "null") {
+ // If window exists
+ if (this.getTargetWindow(target)) {
+ this.currentWindowName = target;
+ }
+ }
+};
+
+BrowserBot.prototype.openLocation = function(target) {
+ // We're moving to a new page - clear the current one
+ this.currentPage = null;
+ this.newPageLoaded = false;
+
+ this.setOpenLocation(target);
+};
+
+BrowserBot.prototype.setIFrameLocation = function(iframe, location) {
+ iframe.src = location;
+};
+
+BrowserBot.prototype.setOpenLocation = function(location) {
+ this.getCurrentWindow().location.href = location;
+};
+
+BrowserBot.prototype.getCurrentPage = function() {
+ if (this.currentPage == null) {
+ var testWindow = this.getCurrentWindow();
+ this.modifyWindowToRecordPopUpDialogs(testWindow, this);
+ this.modifySeparateTestWindowToDetectPageLoads(testWindow);
+ this.currentPage = PageBot.createForWindow(testWindow);
+ this.newPageLoaded = false;
+ }
+
+ return this.currentPage;
+};
+
+BrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
+ windowToModify.alert = function(alert) {
+ browserBot.recordedAlerts.push(alert);
+ };
+
+ windowToModify.confirm = function(message) {
+ browserBot.recordedConfirmations.push(message);
+ var result = browserBot.nextConfirmResult;
+ browserBot.nextConfirmResult = true;
+ return result;
+ };
+
+ windowToModify.prompt = function(message) {
+ browserBot.recordedPrompts.push(message);
+ var result = !browserBot.nextConfirmResult ? null : browserBot.nextPromptResult;
+ browserBot.nextConfirmResult = true;
+ browserBot.nextPromptResult = '';
+ return result;
+ };
+
+ // Keep a reference to all popup windows by name
+ // note that in IE the "windowName" argument must be a valid javascript identifier, it seems.
+ var originalOpen = windowToModify.open;
+ windowToModify.open = function(url, windowName, windowFeatures, replaceFlag) {
+ var openedWindow = originalOpen(url, windowName, windowFeatures, replaceFlag);
+ selenium.browserbot.openedWindows[windowName] = openedWindow;
+ return openedWindow;
+ };
+};
+
+/**
+ * The main IFrame has a single, long-lived onload handler that clears
+ * Browserbot.currentPage and sets the "newPageLoaded" flag. For separate
+ * windows, we need to attach a handler each time. This uses the
+ * "callOnWindowPageTransition" mechanism, which is implemented differently
+ * for different browsers.
+ */
+BrowserBot.prototype.modifySeparateTestWindowToDetectPageLoads = function(windowToModify) {
+ if (this.currentWindowName != null) {
+ this.callOnWindowPageTransition(this.recordPageLoad, windowToModify);
+ }
+};
+
+/**
+ * Call the supplied function when a the current page unloads and a new one loads.
+ * This is done by polling continuously until the document changes and is fully loaded.
+ */
+BrowserBot.prototype.callOnWindowPageTransition = function(loadFunction, windowObject) {
+ // Since the unload event doesn't fire in Safari 1.3, we start polling immediately
+ if (windowObject && !windowObject.closed) {
+ LOG.debug("Starting pollForLoad: " + windowObject.document.location);
+ this.pollingForLoad = true;
+ this.pollForLoad(loadFunction, windowObject, windowObject.location, windowObject.location.href);
+ }
+};
+
+/**
+ * Set up a polling timer that will keep checking the readyState of the document until it's complete.
+ * Since we might call this before the original page is unloaded, we first check to see that the current location
+ * or href is different from the original one.
+ */
+BrowserBot.prototype.pollForLoad = function(loadFunction, windowObject, originalLocation, originalHref) {
+ var windowClosed = true;
+ try {
+ windowClosed = windowObject.closed;
+ } catch (e) {
+ LOG.debug("exception detecting closed window (I guess it must be closed)");
+ LOG.exception(e);
+ // swallow exceptions which may occur in HTA mode when the window is closed
+ }
+ if (null == windowClosed) windowClosed = true;
+ if (windowClosed) {
+ this.pollingForLoad = false;
+ return;
+ }
+
+ LOG.debug("pollForLoad original: " + originalHref);
+ try {
+
+ var currentLocation = windowObject.location;
+ var currentHref = currentLocation.href
+
+ var sameLoc = (originalLocation === currentLocation);
+ var sameHref = (originalHref === currentHref);
+ var rs = windowObject.document.readyState;
+
+ if (rs == null) rs = 'complete';
+
+ if (!(sameLoc && sameHref) && rs == 'complete') {
+ LOG.debug("pollForLoad complete: " + rs + " (" + currentHref + ")");
+ loadFunction();
+ this.pollingForLoad = false;
+ return;
+ }
+ var self = this;
+ LOG.debug("pollForLoad continue: " + currentHref);
+ window.setTimeout(function() {self.pollForLoad(loadFunction, windowObject, originalLocation, originalHref);}, 500);
+ } catch (e) {
+ LOG.error("Exception during pollForLoad; this should get noticed soon!");
+ LOG.exception(e);
+ this.pageLoadError = e;
+ }
+};
+
+
+BrowserBot.prototype.getContentWindow = function() {
+ return this.getFrame().contentWindow || frames[this.getFrame().id];
+};
+
+BrowserBot.prototype.getTargetWindow = function(windowName) {
+ LOG.debug("getTargetWindow(" + windowName + ")");
+ // First look in the map of opened windows
+ var targetWindow = this.openedWindows[windowName];
+ if (!targetWindow) {
+ var evalString = "this.getContentWindow().window." + windowName;
+ targetWindow = eval(evalString);
+ }
+ if (!targetWindow) {
+ throw new SeleniumError("Window does not exist");
+ }
+ return targetWindow;
+};
+
+BrowserBot.prototype.getCurrentWindow = function() {
+ var testWindow = this.getContentWindow().window;
+ if (this.currentWindowName != null) {
+ testWindow = this.getTargetWindow(this.currentWindowName);
+ }
+ return testWindow;
+};
+
+function MozillaBrowserBot(frame) {
+ BrowserBot.call(this, frame);
+}
+MozillaBrowserBot.prototype = new BrowserBot;
+
+function KonquerorBrowserBot(frame) {
+ BrowserBot.call(this, frame);
+}
+KonquerorBrowserBot.prototype = new BrowserBot;
+
+KonquerorBrowserBot.prototype.setIFrameLocation = function(iframe, location) {
+ // Window doesn't fire onload event when setting src to the current value,
+ // so we set it to blank first.
+ iframe.src = "about:blank";
+ iframe.src = location;
+};
+
+KonquerorBrowserBot.prototype.setOpenLocation = function(location) {
+ // Window doesn't fire onload event when setting src to the current value,
+ // so we set it to blank first.
+ this.getCurrentWindow().location.href = "about:blank";
+ this.getCurrentWindow().location.href = location;
+};
+
+function SafariBrowserBot(frame) {
+ BrowserBot.call(this, frame);
+}
+SafariBrowserBot.prototype = new BrowserBot;
+
+SafariBrowserBot.prototype.setIFrameLocation = KonquerorBrowserBot.prototype.setIFrameLocation;
+
+function IEBrowserBot(frame) {
+ BrowserBot.call(this, frame);
+}
+IEBrowserBot.prototype = new BrowserBot;
+
+IEBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
+ BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);
+
+ // we will call the previous version of this method from within our own interception
+ oldShowModalDialog = windowToModify.showModalDialog;
+
+ windowToModify.showModalDialog = function(url, args, features) {
+ // Get relative directory to where TestRunner.html lives
+ // A risky assumption is that the user's TestRunner is named TestRunner.html
+ var doc_location = document.location.toString();
+ var end_of_base_ref = doc_location.indexOf('TestRunner.html');
+ var base_ref = doc_location.substring(0, end_of_base_ref);
+
+ var fullURL = base_ref + "TestRunner.html?singletest=" + escape(browserBot.modalDialogTest) + "&autoURL=" + escape(url) + "&runInterval=" + runInterval;
+ browserBot.modalDialogTest = null;
+
+ var returnValue = oldShowModalDialog(fullURL, args, features);
+ return returnValue;
+ };
+};
+
+SafariBrowserBot.prototype.modifyWindowToRecordPopUpDialogs = function(windowToModify, browserBot) {
+ BrowserBot.prototype.modifyWindowToRecordPopUpDialogs(windowToModify, browserBot);
+
+ var originalOpen = windowToModify.open;
+ /*
+ * Safari seems to be broken, so that when we manually trigger the onclick method
+ * of a button/href, any window.open calls aren't resolved relative to the app location.
+ * So here we replace the open() method with one that does resolve the url correctly.
+ */
+ windowToModify.open = function(url, windowName, windowFeatures, replaceFlag) {
+
+ if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/")) {
+ return originalOpen(url, windowName, windowFeatures, replaceFlag);
+ }
+
+ // Reduce the current path to the directory
+ var currentPath = windowToModify.location.pathname || "/";
+ currentPath = currentPath.replace(/\/[^\/]*$/, "/");
+
+ // Remove any leading "./" from the new url.
+ url = url.replace(/^\.\//, "");
+
+ newUrl = currentPath + url;
+
+ return originalOpen(newUrl, windowName, windowFeatures, replaceFlag);
+ };
+};
+
+var PageBot = function(pageWindow) {
+ if (pageWindow) {
+ this.currentWindow = pageWindow;
+ this.currentDocument = pageWindow.document;
+ this.location = pageWindow.location;
+ this.title = function() {return this.currentDocument.title;};
+ }
+
+ // Register all locateElementBy* functions
+ // TODO - don't do this in the constructor - only needed once ever
+ this.locationStrategies = {};
+ for (var functionName in this) {
+ var result = /^locateElementBy([A-Z].+)$/.exec(functionName);
+ if (result != null) {
+ var locatorFunction = this[functionName];
+ if (typeof(locatorFunction) != 'function') {
+ continue;
+ }
+ // Use a specified prefix in preference to one generated from
+ // the function name
+ var locatorPrefix = locatorFunction.prefix || result[1].toLowerCase();
+ this.locationStrategies[locatorPrefix] = locatorFunction;
+ }
+ }
+
+ /**
+ * Find a locator based on a prefix.
+ */
+ this.findElementBy = function(locatorType, locator, inDocument) {
+ var locatorFunction = this.locationStrategies[locatorType];
+ if (! locatorFunction) {
+ throw new SeleniumError("Unrecognised locator type: '" + locatorType + "'");
+ }
+ return locatorFunction.call(this, locator, inDocument);
+ };
+
+ /**
+ * The implicit locator, that is used when no prefix is supplied.
+ */
+ this.locationStrategies['implicit'] = function(locator, inDocument) {
+ if (locator.startsWith('//')) {
+ return this.locateElementByXPath(locator, inDocument);
+ }
+ if (locator.startsWith('document.')) {
+ return this.locateElementByDomTraversal(locator, inDocument);
+ }
+ return this.locateElementByIdentifier(locator, inDocument);
+ };
+
+};
+
+PageBot.createForWindow = function(windowObject) {
+ if (browserVersion.isIE) {
+ return new IEPageBot(windowObject);
+ }
+ else if (browserVersion.isKonqueror) {
+ return new KonquerorPageBot(windowObject);
+ }
+ else if (browserVersion.isSafari) {
+ return new SafariPageBot(windowObject);
+ }
+ else if (browserVersion.isOpera) {
+ return new OperaPageBot(windowObject);
+ }
+ else {
+ LOG.info("Using MozillaPageBot")
+ // Use mozilla by default
+ return new MozillaPageBot(windowObject);
+ }
+};
+
+var MozillaPageBot = function(pageWindow) {
+ PageBot.call(this, pageWindow);
+};
+MozillaPageBot.prototype = new PageBot();
+
+var KonquerorPageBot = function(pageWindow) {
+ PageBot.call(this, pageWindow);
+};
+KonquerorPageBot.prototype = new PageBot();
+
+var SafariPageBot = function(pageWindow) {
+ PageBot.call(this, pageWindow);
+};
+SafariPageBot.prototype = new PageBot();
+
+var IEPageBot = function(pageWindow) {
+ PageBot.call(this, pageWindow);
+};
+IEPageBot.prototype = new PageBot();
+
+OperaPageBot = function(pageWindow) {
+ PageBot.call(this, pageWindow);
+};
+OperaPageBot.prototype = new PageBot();
+
+/*
+* Finds an element on the current page, using various lookup protocols
+*/
+PageBot.prototype.findElement = function(locator) {
+ var locatorType = 'implicit';
+ var locatorString = locator;
+
+ // If there is a locator prefix, use the specified strategy
+ var result = locator.match(/^([A-Za-z]+)=(.+)/);
+ if (result) {
+ locatorType = result[1].toLowerCase();
+ locatorString = result[2];
+ }
+
+ var element = this.findElementBy(locatorType, locatorString, this.currentDocument);
+ if (element != null) {
+ return element;
+ }
+ for (var i = 0; i < this.currentWindow.frames.length; i++) {
+ element = this.findElementBy(locatorType, locatorString, this.currentWindow.frames[i].document);
+ if (element != null) {
+ return element;
+ }
+ }
+
+ // Element was not found by any locator function.
+ throw new SeleniumError("Element " + locator + " not found");
+};
+
+/**
+ * In non-IE browsers, getElementById() does not search by name. Instead, we
+ * we search separately by id and name.
+ */
+PageBot.prototype.locateElementByIdentifier = function(identifier, inDocument) {
+ return PageBot.prototype.locateElementById(identifier, inDocument)
+ || PageBot.prototype.locateElementByName(identifier, inDocument)
+ || null;
+};
+
+/**
+ * In IE, getElementById() also searches by name - this is an optimisation for IE.
+ */
+IEPageBot.prototype.locateElementByIdentifer = function(identifier, inDocument) {
+ return inDocument.getElementById(identifier);
+};
+
+/**
+ * Find the element with id - can't rely on getElementById, coz it returns by name as well in IE..
+ */
+PageBot.prototype.locateElementById = function(identifier, inDocument) {
+ var element = inDocument.getElementById(identifier);
+ if (element && element.id === identifier) {
+ return element;
+ }
+ else {
+ return null;
+ }
+};
+
+/**
+ * Find an element by name, refined by (optional) element-filter
+ * expressions.
+ */
+PageBot.prototype.locateElementByName = function(locator, document) {
+ var elements = document.getElementsByTagName("*");
+
+ var filters = locator.split(' ');
+ filters[0] = 'name=' + filters[0];
+
+ while (filters.length) {
+ var filter = filters.shift();
+ elements = this.selectElements(filter, elements, 'value');
+ }
+
+ if (elements.length > 0) {
+ return elements[0];
+ }
+ return null;
+};
+
+/**
+* Finds an element using by evaluating the "document.*" string against the
+* current document object. Dom expressions must begin with "document."
+*/
+PageBot.prototype.locateElementByDomTraversal = function(domTraversal, inDocument) {
+ if (domTraversal.indexOf("document.") != 0) {
+ return null;
+ }
+
+ // Trim the leading 'document'
+ domTraversal = domTraversal.substr(9);
+ var locatorScript = "inDocument." + domTraversal;
+ var element = eval(locatorScript);
+
+ if (!element) {
+ return null;
+ }
+
+ return element;
+};
+PageBot.prototype.locateElementByDomTraversal.prefix = "dom";
+
+/**
+* Finds an element identified by the xpath expression. Expressions _must_
+* begin with "//".
+*/
+PageBot.prototype.locateElementByXPath = function(xpath, inDocument) {
+
+ // Trim any trailing "/": not valid xpath, and remains from attribute
+ // locator.
+ if (xpath.charAt(xpath.length - 1) == '/') {
+ xpath = xpath.slice(0, -1);
+ }
+
+ // Handle //tag
+ var match = xpath.match(/^\/\/(\w+|\*)$/);
+ if (match) {
+ var elements = inDocument.getElementsByTagName(match[1].toUpperCase());
+ if (elements == null) return null;
+ return elements[0];
+ }
+
+ // Handle //tag[@attr='value']
+ var match = xpath.match(/^\/\/(\w+|\*)\[@(\w+)=('([^\']+)'|"([^\"]+)")\]$/);
+ if (match) {
+ return this.findElementByTagNameAndAttributeValue(
+ inDocument,
+ match[1].toUpperCase(),
+ match[2].toLowerCase(),
+ match[3].slice(1, -1)
+ );
+ }
+
+ // Handle //tag[text()='value']
+ var match = xpath.match(/^\/\/(\w+|\*)\[text\(\)=('([^\']+)'|"([^\"]+)")\]$/);
+ if (match) {
+ return this.findElementByTagNameAndText(
+ inDocument,
+ match[1].toUpperCase(),
+ match[2].slice(1, -1)
+ );
+ }
+
+ return this.findElementUsingFullXPath(xpath, inDocument);
+};
+
+PageBot.prototype.findElementByTagNameAndAttributeValue = function(
+ inDocument, tagName, attributeName, attributeValue
+) {
+ if (browserVersion.isIE && attributeName == "class") {
+ attributeName = "className";
+ }
+ var elements = inDocument.getElementsByTagName(tagName);
+ for (var i = 0; i < elements.length; i++) {
+ var elementAttr = elements[i].getAttribute(attributeName);
+ if (elementAttr == attributeValue) {
+ return elements[i];
+ }
+ }
+ return null;
+};
+
+PageBot.prototype.findElementByTagNameAndText = function(
+ inDocument, tagName, text
+) {
+ var elements = inDocument.getElementsByTagName(tagName);
+ for (var i = 0; i < elements.length; i++) {
+ if (getText(elements[i]) == text) {
+ return elements[i];
+ }
+ }
+ return null;
+};
+
+PageBot.prototype.findElementUsingFullXPath = function(xpath, inDocument) {
+ // Use document.evaluate() if it's available
+ if (inDocument.evaluate) {
+ return inDocument.evaluate(xpath, inDocument, null, 0, null).iterateNext();
+ }
+
+ // If not, fall back to slower JavaScript implementation
+ var context = new ExprContext(inDocument);
+ var xpathObj = xpathParse(xpath);
+ var xpathResult = xpathObj.evaluate(context);
+ if (xpathResult && xpathResult.value) {
+ return xpathResult.value[0];
+ }
+ return null;
+};
+
+/**
+* Finds a link element with text matching the expression supplied. Expressions must
+* begin with "link:".
+*/
+PageBot.prototype.locateElementByLinkText = function(linkText, inDocument) {
+ var links = inDocument.getElementsByTagName('a');
+ for (var i = 0; i < links.length; i++) {
+ var element = links[i];
+ if (PatternMatcher.matches(linkText, getText(element))) {
+ return element;
+ }
+ }
+ return null;
+};
+PageBot.prototype.locateElementByLinkText.prefix = "link";
+
+/**
+* Returns an attribute based on an attribute locator. This is made up of an element locator
+* suffixed with @attribute-name.
+*/
+PageBot.prototype.findAttribute = function(locator) {
+ // Split into locator + attributeName
+ var attributePos = locator.lastIndexOf("@");
+ var elementLocator = locator.slice(0, attributePos);
+ var attributeName = locator.slice(attributePos + 1);
+
+ // Find the element.
+ var element = this.findElement(elementLocator);
+
+ // Handle missing "class" attribute in IE.
+ if (browserVersion.isIE && attributeName == "class") {
+ attributeName = "className";
+ }
+
+ // Get the attribute value.
+ var attributeValue = element.getAttribute(attributeName);
+
+ return attributeValue ? attributeValue.toString() : null;
+};
+
+/*
+* Select the specified option and trigger the relevant events of the element.
+*/
+PageBot.prototype.selectOption = function(element, optionToSelect) {
+ triggerEvent(element, 'focus', false);
+ var changed = false;
+ for (var i = 0; i < element.options.length; i++) {
+ var option = element.options[i];
+ if (option.selected && option != optionToSelect) {
+ option.selected = false;
+ changed = true;
+ }
+ else if (!option.selected && option == optionToSelect) {
+ option.selected = true;
+ changed = true;
+ }
+ }
+
+ if (changed) {
+ triggerEvent(element, 'change', true);
+ }
+ triggerEvent(element, 'blur', false);
+};
+
+/*
+* Select the specified option and trigger the relevant events of the element.
+*/
+PageBot.prototype.addSelection = function(element, option) {
+ this.checkMultiselect(element);
+ triggerEvent(element, 'focus', false);
+ if (!option.selected) {
+ option.selected = true;
+ triggerEvent(element, 'change', true);
+ }
+ triggerEvent(element, 'blur', false);
+};
+
+/*
+* Select the specified option and trigger the relevant events of the element.
+*/
+PageBot.prototype.removeSelection = function(element, option) {
+ this.checkMultiselect(element);
+ triggerEvent(element, 'focus', false);
+ if (option.selected) {
+ option.selected = false;
+ triggerEvent(element, 'change', true);
+ }
+ triggerEvent(element, 'blur', false);
+};
+
+PageBot.prototype.checkMultiselect = function(element) {
+ if (!element.multiple)
+ {
+ throw new SeleniumError("Not a multi-select");
+ }
+
+};
+
+PageBot.prototype.replaceText = function(element, stringValue) {
+ triggerEvent(element, 'focus', false);
+ triggerEvent(element, 'select', true);
+ element.value=stringValue;
+ if (!browserVersion.isChrome) {
+ // In chrome URL, The change event is already fired by setting the value.
+ triggerEvent(element, 'change', true);
+ }
+ triggerEvent(element, 'blur', false);
+};
+
+MozillaPageBot.prototype.clickElement = function(element) {
+
+ triggerEvent(element, 'focus', false);
+
+ // Add an event listener that detects if the default action has been prevented.
+ // (This is caused by a javascript onclick handler returning false)
+ var preventDefault = false;
+
+ element.addEventListener("click", function(evt) {preventDefault = evt.getPreventDefault();}, false);
+
+ // Trigger the click event.
+ triggerMouseEvent(element, 'click', true);
+
+ // Perform the link action if preventDefault was set.
+ // In chrome URL, the link action is already executed by triggerMouseEvent.
+ if (!browserVersion.isChrome && !preventDefault) {
+ // Try the element itself, as well as it's parent - this handles clicking images inside links.
+ if (element.href) {
+ this.currentWindow.location.href = element.href;
+ }
+ else if (element.parentNode && element.parentNode.href) {
+ this.currentWindow.location.href = element.parentNode.href;
+ }
+ }
+
+ if (this.windowClosed()) {
+ return;
+ }
+
+ triggerEvent(element, 'blur', false);
+};
+
+OperaPageBot.prototype.clickElement = function(element) {
+
+ triggerEvent(element, 'focus', false);
+
+ // Trigger the click event.
+ triggerMouseEvent(element, 'click', true);
+
+ if (isDefined(element.checked)) {
+ // In Opera, clicking won't check/uncheck
+ if (element.type == "checkbox") {
+ element.checked = !element.checked;
+ } else {
+ element.checked = true;
+ }
+ }
+
+ if (this.windowClosed()) {
+ return;
+ }
+
+ triggerEvent(element, 'blur', false);
+};
+
+
+KonquerorPageBot.prototype.clickElement = function(element) {
+
+ triggerEvent(element, 'focus', false);
+
+ if (element.click) {
+ element.click();
+ }
+ else {
+ triggerMouseEvent(element, 'click', true);
+ }
+
+ if (this.windowClosed()) {
+ return;
+ }
+
+ triggerEvent(element, 'blur', false);
+};
+
+SafariPageBot.prototype.clickElement = function(element) {
+
+ triggerEvent(element, 'focus', false);
+
+ var wasChecked = element.checked;
+
+ // For form element it is simple.
+ if (element.click) {
+ element.click();
+ }
+ // For links and other elements, event emulation is required.
+ else {
+ triggerMouseEvent(element, 'click', true);
+
+ // Unfortunately, triggering the event doesn't seem to activate onclick handlers.
+ // We currently call onclick for the link, but I'm guessing that the onclick for containing
+ // elements is not being called.
+ var success = true;
+ if (element.onclick) {
+ var evt = document.createEvent('HTMLEvents');
+ evt.initEvent('click', true, true);
+ var onclickResult = element.onclick(evt);
+ if (onclickResult === false) {
+ success = false;
+ }
+ }
+
+ if (success) {
+ // Try the element itself, as well as it's parent - this handles clicking images inside links.
+ if (element.href) {
+ this.currentWindow.location.href = element.href;
+ }
+ else if (element.parentNode.href) {
+ this.currentWindow.location.href = element.parentNode.href;
+ } else {
+ // This is true for buttons outside of forms, and maybe others.
+ LOG.warn("Ignoring 'click' call for button outside form, or link without href."
+ + "Using buttons without an enclosing form can cause wierd problems with URL resolution in Safari." );
+ // I implemented special handling for window.open, but unfortunately this behaviour is also displayed
+ // when we have a button without an enclosing form that sets document.location in the onclick handler.
+ // The solution is to always use an enclosing form for a button.
+ }
+ }
+ }
+
+ if (this.windowClosed()) {
+ return;
+ }
+
+ triggerEvent(element, 'blur', false);
+};
+
+IEPageBot.prototype.clickElement = function(element) {
+
+ triggerEvent(element, 'focus', false);
+
+ var wasChecked = element.checked;
+
+ // Set a flag that records if the page will unload - this isn't always accurate, because
+ // <a href="javascript:alert('foo'):"> triggers the onbeforeunload event, even thought the page won't unload
+ var pageUnloading = false;
+ var pageUnloadDetector = function() {pageUnloading = true;};
+ this.currentWindow.attachEvent("onbeforeunload", pageUnloadDetector);
+
+ element.click();
+
+ // If the page is going to unload - still attempt to fire any subsequent events.
+ // However, we can't guarantee that the page won't unload half way through, so we need to handle exceptions.
+ try {
+ this.currentWindow.detachEvent("onbeforeunload", pageUnloadDetector);
+
+ if (this.windowClosed()) {
+ return;
+ }
+
+ // Onchange event is not triggered automatically in IE.
+ if (isDefined(element.checked) && wasChecked != element.checked) {
+ triggerEvent(element, 'change', true);
+ }
+
+ triggerEvent(element, 'blur', false);
+ }
+ catch (e) {
+ // If the page is unloading, we may get a "Permission denied" or "Unspecified error".
+ // Just ignore it, because the document may have unloaded.
+ if (pageUnloading) {
+ LOG.warn("Caught exception when firing events on unloading page: " + e.message);
+ return;
+ }
+ throw e;
+ }
+};
+
+PageBot.prototype.windowClosed = function(element) {
+ return this.currentWindow.closed;
+};
+
+PageBot.prototype.bodyText = function() {
+ return getText(this.currentDocument.body);
+};
+
+PageBot.prototype.getAllButtons = function() {
+ var elements = this.currentDocument.getElementsByTagName('input');
+ var result = '';
+
+ for (var i = 0; i < elements.length; i++) {
+ if (elements[i].type == 'button' || elements[i].type == 'submit' || elements[i].type == 'reset') {
+ result += elements[i].id;
+
+ result += ',';
+ }
+ }
+
+ return result;
+};
+
+
+PageBot.prototype.getAllFields = function() {
+ var elements = this.currentDocument.getElementsByTagName('input');
+ var result = '';
+
+ for (var i = 0; i < elements.length; i++) {
+ if (elements[i].type == 'text') {
+ result += elements[i].id;
+
+ result += ',';
+ }
+ }
+
+ return result;
+};
+
+PageBot.prototype.getAllLinks = function() {
+ var elements = this.currentDocument.getElementsByTagName('a');
+ var result = '';
+
+ for (var i = 0; i < elements.length; i++) {
+ result += elements[i].id;
+
+ result += ',';
+ }
+
+ return result;
+};
+
+PageBot.prototype.setContext = function(strContext, logLevel) {
+ //set the current test title
+ document.getElementById("context").innerHTML=strContext;
+ if (logLevel!=null) {
+ LOG.setLogLevelThreshold(logLevel);
+ }
+};
+
+function isDefined(value) {
+ return typeof(value) != undefined;
+}
+
+PageBot.prototype.goBack = function() {
+ this.currentWindow.history.back();
+ if (browserVersion.isOpera && !selenium.browserbot.pollingForLoad) {
+ // DGF On Opera, goBack doesn't re-trigger a load event, so we have to poll for it
+ selenium.browserbot.callOnWindowPageTransition(selenium.browserbot.recordPageLoad, this.currentWindow);
+ }
+};
+
+PageBot.prototype.goForward = function() {
+ this.currentWindow.history.forward();
+};
+
+PageBot.prototype.close = function() {
+ if (browserVersion.isChrome) {
+ this.currentWindow.close();
+ } else {
+ this.currentWindow.eval("window.close();");
+ }
+};
+
+PageBot.prototype.refresh = function() {
+ this.currentWindow.location.reload(true);
+};
+
+/**
+ * Refine a list of elements using a filter.
+ */
+PageBot.prototype.selectElementsBy = function(filterType, filter, elements) {
+ var filterFunction = PageBot.filterFunctions[filterType];
+ if (! filterFunction) {
+ throw new SeleniumError("Unrecognised element-filter type: '" + filterType + "'");
+ }
+
+ return filterFunction(filter, elements);
+};
+
+PageBot.filterFunctions = {};
+
+PageBot.filterFunctions.name = function(name, elements) {
+ var selectedElements = [];
+ for (var i = 0; i < elements.length; i++) {
+ if (elements[i].name === name) {
+ selectedElements.push(elements[i]);
+ }
+ }
+ return selectedElements;
+};
+
+PageBot.filterFunctions.value = function(value, elements) {
+ var selectedElements = [];
+ for (var i = 0; i < elements.length; i++) {
+ if (elements[i].value === value) {
+ selectedElements.push(elements[i]);
+ }
+ }
+ return selectedElements;
+};
+
+PageBot.filterFunctions.index = function(index, elements) {
+ index = Number(index);
+ if (isNaN(index) || index < 0) {
+ throw new SeleniumError("Illegal Index: " + index);
+ }
+ if (elements.length <= index) {
+ throw new SeleniumError("Index out of range: " + index);
+ }
+ return [elements[index]];
+};
+
+PageBot.prototype.selectElements = function(filterExpr, elements, defaultFilterType) {
+
+ var filterType = (defaultFilterType || 'value');
+
+ // If there is a filter prefix, use the specified strategy
+ var result = filterExpr.match(/^([A-Za-z]+)=(.+)/);
+ if (result) {
+ filterType = result[1].toLowerCase();
+ filterExpr = result[2];
+ }
+
+ return this.selectElementsBy(filterType, filterExpr, elements);
+};
+
+/**
+ * Find an element by class
+ */
+PageBot.prototype.locateElementByClass = function(locator, document) {
+ return Element.findFirstMatchingChild(document,
+ function(element) {
+ return element.className == locator
+ }
+ );
+}
+
+/**
+ * Find an element by alt
+ */
+PageBot.prototype.locateElementByAlt = function(locator, document) {
+ return Element.findFirstMatchingChild(document,
+ function(element) {
+ return element.alt == locator
+ }
+ );
+}
+
diff --git a/tests/test_tools/selenium/core/scripts/selenium-browserdetect.js b/tests/test_tools/selenium/core/scripts/selenium-browserdetect.js
new file mode 100644
index 00000000..137a1518
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-browserdetect.js
@@ -0,0 +1,115 @@
+/*
+* Copyright 2004 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+
+// Although it's generally better web development practice not to use browser-detection
+// (feature detection is better), the subtle browser differences that Selenium has to
+// work around seem to make it necessary. Maybe as we learn more about what we need,
+// we can do this in a more "feature-centric" rather than "browser-centric" way.
+
+BrowserVersion = function() {
+ this.name = navigator.appName;
+
+ if (window.opera != null)
+ {
+ this.browser = BrowserVersion.OPERA;
+ this.isOpera = true;
+ return;
+ }
+
+ var self = this;
+
+ var checkChrome = function() {
+ var loc = window.document.location.href;
+ try {
+ loc = window.top.document.location.href;
+ } catch (e) {
+ // can't see the top (that means we might be chrome, but it's impossible to be sure)
+ self.isChromeDetectable = "no, top location couldn't be read in this window";
+ }
+
+ if (/^chrome:\/\//.test(loc)) {
+ self.isChrome = true;
+ } else {
+ self.isChrome = false;
+ }
+ }
+
+ if (this.name == "Microsoft Internet Explorer")
+ {
+ this.browser = BrowserVersion.IE;
+ this.isIE = true;
+ if (window.top.SeleniumHTARunner && window.top.document.location.pathname.match(/.hta$/i)) {
+ this.isHTA = true;
+ }
+ if ("0" == navigator.appMinorVersion) {
+ this.preSV1 = true;
+ }
+ return;
+ }
+
+ if (navigator.userAgent.indexOf('Safari') != -1)
+ {
+ this.browser = BrowserVersion.SAFARI;
+ this.isSafari = true;
+ this.khtml = true;
+ return;
+ }
+
+ if (navigator.userAgent.indexOf('Konqueror') != -1)
+ {
+ this.browser = BrowserVersion.KONQUEROR;
+ this.isKonqueror = true;
+ this.khtml = true;
+ return;
+ }
+
+ if (navigator.userAgent.indexOf('Firefox') != -1)
+ {
+ this.browser = BrowserVersion.FIREFOX;
+ this.isFirefox = true;
+ this.isGecko = true;
+ var result = /.*Firefox\/([\d\.]+).*/.exec(navigator.userAgent);
+ if (result)
+ {
+ this.firefoxVersion = result[1];
+ }
+ checkChrome();
+ return;
+ }
+
+ if (navigator.userAgent.indexOf('Gecko') != -1)
+ {
+ this.browser = BrowserVersion.MOZILLA;
+ this.isMozilla = true;
+ this.isGecko = true;
+ checkChrome();
+ return;
+ }
+
+ this.browser = BrowserVersion.UNKNOWN;
+}
+
+BrowserVersion.OPERA = "Opera";
+BrowserVersion.IE = "IE";
+BrowserVersion.KONQUEROR = "Konqueror";
+BrowserVersion.SAFARI = "Safari";
+BrowserVersion.FIREFOX = "Firefox";
+BrowserVersion.MOZILLA = "Mozilla";
+BrowserVersion.UNKNOWN = "Unknown";
+
+browserVersion = new BrowserVersion();
+
diff --git a/tests/test_tools/selenium/core/scripts/selenium-commandhandlers.js b/tests/test_tools/selenium/core/scripts/selenium-commandhandlers.js
new file mode 100644
index 00000000..ee01ea76
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-commandhandlers.js
@@ -0,0 +1,371 @@
+/*
+* Copyright 2004 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+function CommandHandlerFactory() {
+ this.actions = {};
+ this.asserts = {};
+ this.accessors = {};
+
+ var self = this;
+
+ this.registerAction = function(name, action, wait, dontCheckAlertsAndConfirms) {
+ var handler = new ActionHandler(action, wait, dontCheckAlertsAndConfirms);
+ this.actions[name] = handler;
+ };
+
+ this.registerAccessor = function(name, accessor) {
+ var handler = new AccessorHandler(accessor);
+ this.accessors[name] = handler;
+ };
+
+ this.registerAssert = function(name, assertion, haltOnFailure) {
+ var handler = new AssertHandler(assertion, haltOnFailure);
+ this.asserts[name] = handler;
+ };
+
+ this.getCommandHandler = function(name) {
+ return this.actions[name] || this.accessors[name] || this.asserts[name] || null;
+ };
+
+ this.registerAll = function(commandObject) {
+ registerAllAccessors(commandObject);
+ registerAllActions(commandObject);
+ registerAllAsserts(commandObject);
+ };
+
+ var registerAllActions = function(commandObject) {
+ for (var functionName in commandObject) {
+ var result = /^do([A-Z].+)$/.exec(functionName);
+ if (result != null) {
+ var actionName = result[1].lcfirst();
+
+ // Register the action without the wait flag.
+ var action = commandObject[functionName];
+ self.registerAction(actionName, action, false, action.dontCheckAlertsAndConfirms);
+
+ // Register actionName + "AndWait" with the wait flag;
+ var waitActionName = actionName + "AndWait";
+ self.registerAction(waitActionName, action, true, action.dontCheckAlertsAndConfirms);
+ }
+ }
+ };
+
+
+ var registerAllAsserts = function(commandObject) {
+ for (var functionName in commandObject) {
+ var result = /^assert([A-Z].+)$/.exec(functionName);
+ if (result != null) {
+ var assert = commandObject[functionName];
+
+ // Register the assert with the "assert" prefix, and halt on failure.
+ var assertName = functionName;
+ self.registerAssert(assertName, assert, true);
+
+ // Register the assert with the "verify" prefix, and do not halt on failure.
+ var verifyName = "verify" + result[1];
+ self.registerAssert(verifyName, assert, false);
+ }
+ }
+ };
+
+
+ // Given an accessor function getBlah(target),
+ // return a "predicate" equivalient to isBlah(target, value) that
+ // is true when the value returned by the accessor matches the specified value.
+ this.createPredicateFromSingleArgAccessor = function(accessor) {
+ return function(target, value) {
+ var accessorResult = accessor.call(this, target);
+ if (PatternMatcher.matches(value, accessorResult)) {
+ return new PredicateResult(true, "Actual value '" + accessorResult + "' did match '" + value + "'");
+ } else {
+ return new PredicateResult(false, "Actual value '" + accessorResult + "' did not match '" + value + "'");
+ }
+ };
+ };
+
+ // Given a (no-arg) accessor function getBlah(),
+ // return a "predicate" equivalient to isBlah(value) that
+ // is true when the value returned by the accessor matches the specified value.
+ this.createPredicateFromNoArgAccessor = function(accessor) {
+ return function(value) {
+ var accessorResult = accessor.call(this);
+ if (PatternMatcher.matches(value, accessorResult)) {
+ return new PredicateResult(true, "Actual value '" + accessorResult + "' did match '" + value + "'");
+ } else {
+ return new PredicateResult(false, "Actual value '" + accessorResult + "' did not match '" + value + "'");
+ }
+ };
+ };
+
+ // Given a boolean accessor function isBlah(),
+ // return a "predicate" equivalient to isBlah() that
+ // returns an appropriate PredicateResult value.
+ this.createPredicateFromBooleanAccessor = function(accessor) {
+ return function() {
+ var accessorResult;
+ if (arguments.length > 2) throw new SeleniumError("Too many arguments! " + arguments.length);
+ if (arguments.length == 2) {
+ accessorResult = accessor.call(this, arguments[0], arguments[1]);
+ } else if (arguments.length == 1) {
+ accessorResult = accessor.call(this, arguments[0]);
+ } else {
+ accessorResult = accessor.call(this);
+ }
+ if (accessorResult) {
+ return new PredicateResult(true, "true");
+ } else {
+ return new PredicateResult(false, "false");
+ }
+ };
+ };
+
+ // Given an accessor fuction getBlah([target]) (target is optional)
+ // return a predicate equivalent to isBlah([target,] value) that
+ // is true when the value returned by the accessor matches the specified value.
+ this.createPredicateFromAccessor = function(accessor) {
+ if (accessor.length == 0) {
+ return self.createPredicateFromNoArgAccessor(accessor);
+ }
+ return self.createPredicateFromSingleArgAccessor(accessor);
+ };
+
+ // Given a predicate, return the negation of that predicate.
+ // Leaves the message unchanged.
+ // Used to create assertNot, verifyNot, and waitForNot commands.
+ this.invertPredicate = function(predicate) {
+ return function(target, value) {
+ var result = predicate.call(this, target, value);
+ result.isTrue = ! result.isTrue;
+ return result;
+ };
+ };
+
+ // Convert an isBlahBlah(target, value) function into an assertBlahBlah(target, value) function.
+ this.createAssertionFromPredicate = function(predicate) {
+ return function(target, value) {
+ var result = predicate.call(this, target, value);
+ if (!result.isTrue) {
+ Assert.fail(result.message);
+ }
+ };
+ };
+
+ // Register an assertion, a verification, a negative assertion,
+ // and a negative verification based on the specified accessor.
+ this.registerAssertionsBasedOnAccessor = function(accessor, baseName, predicate) {
+ if (predicate==null) {
+ predicate = self.createPredicateFromAccessor(accessor);
+ }
+ var assertion = self.createAssertionFromPredicate(predicate);
+ // Register an assert with the "assert" prefix, and halt on failure.
+ self.registerAssert("assert" + baseName, assertion, true);
+ // Register a verify with the "verify" prefix, and do not halt on failure.
+ self.registerAssert("verify" + baseName, assertion, false);
+
+ var invertedPredicate = self.invertPredicate(predicate);
+ var negativeAssertion = self.createAssertionFromPredicate(invertedPredicate);
+
+ var result = /^(.*)Present$/.exec(baseName);
+ if (result==null) {
+ // Register an assertNot with the "assertNot" prefix, and halt on failure.
+ self.registerAssert("assertNot"+baseName, negativeAssertion, true);
+ // Register a verifyNot with the "verifyNot" prefix, and do not halt on failure.
+ self.registerAssert("verifyNot"+baseName, negativeAssertion, false);
+ }
+ else {
+ var invertedBaseName = result[1] + "NotPresent";
+
+ // Register an assertNot ending w/ "NotPresent", and halt on failure.
+ self.registerAssert("assert"+invertedBaseName, negativeAssertion, true);
+ // Register an assertNot ending w/ "NotPresent", and do not halt on failure.
+ self.registerAssert("verify"+invertedBaseName, negativeAssertion, false);
+ }
+ };
+
+
+ // Convert an isBlahBlah(target, value) function into a waitForBlahBlah(target, value) function.
+ this.createWaitForActionFromPredicate = function(predicate) {
+ var action = function(target, value) {
+ var seleniumApi = this;
+ testLoop.waitForCondition = function () {
+ try {
+ return predicate.call(seleniumApi, target, value).isTrue;
+ } catch (e) {
+ // Treat exceptions as meaning the condition is not yet met.
+ // Useful, for example, for waitForValue when the element has
+ // not even been created yet.
+ // TODO: possibly should rethrow some types of exception.
+ return false;
+ }
+ };
+ };
+ return action;
+ };
+
+ // Register a waitForBlahBlah and waitForNotBlahBlah based on the specified accessor.
+ this.registerWaitForCommandsBasedOnAccessor = function(accessor, baseName, predicate) {
+ if (predicate==null) {
+ predicate = self.createPredicateFromAccessor(accessor);
+ }
+ var waitForAction = self.createWaitForActionFromPredicate(predicate);
+ self.registerAction("waitFor"+baseName, waitForAction, false, true);
+ var invertedPredicate = self.invertPredicate(predicate);
+ var waitForNotAction = self.createWaitForActionFromPredicate(invertedPredicate);
+ self.registerAction("waitForNot"+baseName, waitForNotAction, false, true);
+ }
+
+ // Register a storeBlahBlah based on the specified accessor.
+ this.registerStoreCommandBasedOnAccessor = function(accessor, baseName) {
+ var action;
+ if (accessor.length == 1) {
+ action = function(target, varName) {
+ storedVars[varName] = accessor.call(this, target);
+ };
+ } else {
+ action = function(varName) {
+ storedVars[varName] = accessor.call(this);
+ };
+ }
+ self.registerAction("store"+baseName, action, false, accessor.dontCheckAlertsAndConfirms);
+ };
+
+ // Methods of the form getFoo(target) result in commands:
+ // getFoo, assertFoo, verifyFoo, assertNotFoo, verifyNotFoo
+ // storeFoo, waitForFoo, and waitForNotFoo.
+ var registerAllAccessors = function(commandObject) {
+ for (var functionName in commandObject) {
+ var match = /^get([A-Z].+)$/.exec(functionName);
+ if (match != null) {
+ var accessor = commandObject[functionName];
+ var baseName = match[1];
+ self.registerAccessor(functionName, accessor);
+ self.registerAssertionsBasedOnAccessor(accessor, baseName);
+ self.registerStoreCommandBasedOnAccessor(accessor, baseName);
+ self.registerWaitForCommandsBasedOnAccessor(accessor, baseName);
+ }
+ var match = /^is([A-Z].+)$/.exec(functionName);
+ if (match != null) {
+ var accessor = commandObject[functionName];
+ var baseName = match[1];
+ var predicate = self.createPredicateFromBooleanAccessor(accessor);
+ self.registerAccessor(functionName, accessor);
+ self.registerAssertionsBasedOnAccessor(accessor, baseName, predicate);
+ self.registerStoreCommandBasedOnAccessor(accessor, baseName);
+ self.registerWaitForCommandsBasedOnAccessor(accessor, baseName, predicate);
+ }
+ }
+ };
+
+
+}
+
+function PredicateResult(isTrue, message) {
+ this.isTrue = isTrue;
+ this.message = message;
+}
+
+// NOTE: The CommandHandler is effectively an abstract base for
+// various handlers including ActionHandler, AccessorHandler and AssertHandler.
+// Subclasses need to implement an execute(seleniumApi, command) function,
+// where seleniumApi is the Selenium object, and command a SeleniumCommand object.
+function CommandHandler(type, haltOnFailure, executor) {
+ this.type = type;
+ this.haltOnFailure = haltOnFailure;
+ this.executor = executor;
+}
+
+// An ActionHandler is a command handler that executes the sepcified action,
+// possibly checking for alerts and confirmations (if checkAlerts is set), and
+// possibly waiting for a page load if wait is set.
+function ActionHandler(action, wait, dontCheckAlerts) {
+ CommandHandler.call(this, "action", true, action);
+ if (wait) {
+ this.wait = true;
+ }
+ // note that dontCheckAlerts could be undefined!!!
+ this.checkAlerts = (dontCheckAlerts) ? false : true;
+}
+ActionHandler.prototype = new CommandHandler;
+ActionHandler.prototype.execute = function(seleniumApi, command) {
+ if (this.checkAlerts && (null==/(Alert|Confirmation)(Not)?Present/.exec(command.command))) {
+ this.checkForAlerts(seleniumApi);
+ }
+ var processState = this.executor.call(seleniumApi, command.target, command.value);
+ // If the handler didn't return a wait flag, check to see if the
+ // handler was registered with the wait flag.
+ if (processState == undefined && this.wait) {
+ processState = SELENIUM_PROCESS_WAIT;
+ }
+ return new CommandResult(processState);
+};
+ActionHandler.prototype.checkForAlerts = function(seleniumApi) {
+ if ( seleniumApi.browserbot.hasAlerts() ) {
+ throw new SeleniumError("There was an unexpected Alert! [" + seleniumApi.browserbot.getNextAlert() + "]");
+ }
+ if ( seleniumApi.browserbot.hasConfirmations() ) {
+ throw new SeleniumError("There was an unexpected Confirmation! [" + seleniumApi.browserbot.getNextConfirmation() + "]");
+ }
+};
+
+function AccessorHandler(accessor) {
+ CommandHandler.call(this, "accessor", true, accessor);
+}
+AccessorHandler.prototype = new CommandHandler;
+AccessorHandler.prototype.execute = function(seleniumApi, command) {
+ var returnValue = this.executor.call(seleniumApi, command.target, command.value);
+ var result = new CommandResult();
+ result.result = returnValue;
+ return result;
+};
+
+/**
+ * Handler for assertions and verifications.
+ */
+function AssertHandler(assertion, haltOnFailure) {
+ CommandHandler.call(this, "assert", haltOnFailure || false, assertion);
+}
+AssertHandler.prototype = new CommandHandler;
+AssertHandler.prototype.execute = function(seleniumApi, command) {
+ var result = new CommandResult();
+ try {
+ this.executor.call(seleniumApi, command.target, command.value);
+ result.passed = true;
+ } catch (e) {
+ // If this is not a AssertionFailedError, or we should haltOnFailure, rethrow.
+ if (!e.isAssertionFailedError) {
+ throw e;
+ }
+ if (this.haltOnFailure) {
+ var error = new SeleniumError(e.failureMessage);
+ throw error;
+ }
+ result.failed = true;
+ result.failureMessage = e.failureMessage;
+ }
+ return result;
+};
+
+
+function CommandResult(processState) {
+ this.processState = processState;
+ this.result = null;
+}
+
+function SeleniumCommand(command, target, value) {
+ this.command = command;
+ this.target = target;
+ this.value = value;
+}
diff --git a/tests/test_tools/selenium/core/scripts/selenium-executionloop.js b/tests/test_tools/selenium/core/scripts/selenium-executionloop.js
new file mode 100644
index 00000000..14c1a07a
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-executionloop.js
@@ -0,0 +1,266 @@
+/*
+* Copyright 2004 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+SELENIUM_PROCESS_WAIT = "wait";
+
+function TestLoop(commandFactory) {
+
+ this.commandFactory = commandFactory;
+ this.waitForConditionTimeout = 30 * 1000; // 30 seconds
+
+ this.start = function() {
+ selenium.reset();
+ LOG.debug("testLoop.start()");
+ this.continueTest();
+ };
+
+ /**
+ * Select the next command and continue the test.
+ */
+ this.continueTest = function() {
+ LOG.debug("testLoop.continueTest() - acquire the next command");
+ if (! this.aborted) {
+ this.currentCommand = this.nextCommand();
+ }
+ if (! this.requiresCallBack) {
+ this.beginNextTest();
+ } // otherwise, just finish and let the callback invoke beginNextTest()
+ };
+
+ this.beginNextTest = function() {
+ LOG.debug("testLoop.beginNextTest()");
+ if (this.currentCommand) {
+ // TODO: rename commandStarted to commandSelected, OR roll it into nextCommand
+ this.commandStarted(this.currentCommand);
+ this.resumeAfterDelay();
+ } else {
+ this.testComplete();
+ }
+ }
+
+ /**
+ * Pause, then execute the current command.
+ */
+ this.resumeAfterDelay = function() {
+
+ // Get the command delay. If a pauseInterval is set, use it once
+ // and reset it. Otherwise, use the defined command-interval.
+ var delay = this.pauseInterval || this.getCommandInterval();
+ this.pauseInterval = undefined;
+
+ if (delay < 0) {
+ // Pause: enable the "next/continue" button
+ this.pause();
+ } else {
+ window.setTimeout("testLoop.resume()", delay);
+ }
+ };
+
+ /**
+ * Select the next command and continue the test.
+ */
+ this.resume = function() {
+ LOG.debug("testLoop.resume() - actually execute");
+ try {
+ this.executeCurrentCommand();
+ this.waitForConditionStart = new Date().getTime();
+ this.continueTestWhenConditionIsTrue();
+ } catch (e) {
+ this.handleCommandError(e);
+ this.testComplete();
+ return;
+ }
+ };
+
+ /**
+ * Execute the current command.
+ *
+ * The return value, if not null, should be a function which will be
+ * used to determine when execution can continue.
+ */
+ this.executeCurrentCommand = function() {
+
+ var command = this.currentCommand;
+ LOG.info("Executing: |" + command.command + " | " + command.target + " | " + command.value + " |");
+
+ var handler = this.commandFactory.getCommandHandler(command.command);
+ if (handler == null) {
+ throw new SeleniumError("Unknown command: '" + command.command + "'");
+ }
+
+ command.target = selenium.preprocessParameter(command.target);
+ command.value = selenium.preprocessParameter(command.value);
+ LOG.debug("Command found, going to execute " + command.command);
+ var result = handler.execute(selenium, command);
+ LOG.debug("Command complete");
+ this.commandComplete(result);
+
+ if (result.processState == SELENIUM_PROCESS_WAIT) {
+ this.waitForCondition = function() {
+ LOG.debug("Checking condition: isNewPageLoaded?");
+ return selenium.browserbot.isNewPageLoaded();
+ };
+ }
+ };
+
+ this.handleCommandError = function(e) {
+ if (!e.isSeleniumError) {
+ LOG.exception(e);
+ var msg = "Selenium failure. Please report to selenium-dev@openqa.org, with error details from the log window.";
+ if (e.message) {
+ msg += " The error message is: " + e.message;
+ }
+ this.commandError(msg);
+ } else {
+ LOG.error(e.message);
+ this.commandError(e.message);
+ }
+ };
+
+ /**
+ * Busy wait for waitForCondition() to become true, and then carry on
+ * with test. Fail the current test if there's a timeout or an exception.
+ */
+ this.continueTestWhenConditionIsTrue = function () {
+ LOG.debug("testLoop.continueTestWhenConditionIsTrue()");
+ try {
+ if (this.waitForCondition == null || this.waitForCondition()) {
+ LOG.debug("condition satisfied; let's continueTest()");
+ this.waitForCondition = null;
+ this.waitForConditionStart = null;
+ this.continueTest();
+ } else {
+ LOG.debug("waitForCondition was false; keep waiting!");
+ if (this.waitForConditionTimeout != null) {
+ var now = new Date();
+ if ((now - this.waitForConditionStart) > this.waitForConditionTimeout) {
+ throw new SeleniumError("Timed out after " + this.waitForConditionTimeout + "ms");
+ }
+ }
+ window.setTimeout("testLoop.continueTestWhenConditionIsTrue()", 10);
+ }
+ } catch (e) {
+ var lastResult = new CommandResult();
+ lastResult.failed = true;
+ lastResult.failureMessage = e.message;
+ this.commandComplete(lastResult);
+ this.testComplete();
+ }
+ };
+
+}
+
+/** The default is not to have any interval between commands. */
+TestLoop.prototype.getCommandInterval = function() {
+ return 0;
+};
+
+TestLoop.prototype.nextCommand = noop;
+
+TestLoop.prototype.commandStarted = noop;
+
+TestLoop.prototype.commandError = noop;
+
+TestLoop.prototype.commandComplete = noop;
+
+TestLoop.prototype.testComplete = noop;
+
+TestLoop.prototype.pause = noop;
+
+function noop() {
+
+};
+
+/**
+ * Tell Selenium to expect a failure on the next command execution. This
+ * command temporarily installs a CommandFactory that generates
+ * CommandHandlers that expect a failure.
+ */
+Selenium.prototype.assertFailureOnNext = function(message) {
+ if (!message) {
+ throw new Error("Message must be provided");
+ }
+
+ var expectFailureCommandFactory =
+ new ExpectFailureCommandFactory(testLoop.commandFactory, message, "failure");
+ expectFailureCommandFactory.baseExecutor = executeCommandAndReturnFailureMessage;
+ testLoop.commandFactory = expectFailureCommandFactory;
+};
+
+/**
+ * Tell Selenium to expect an error on the next command execution. This
+ * command temporarily installs a CommandFactory that generates
+ * CommandHandlers that expect a failure.
+ */
+Selenium.prototype.assertErrorOnNext = function(message) {
+ if (!message) {
+ throw new Error("Message must be provided");
+ }
+
+ var expectFailureCommandFactory =
+ new ExpectFailureCommandFactory(testLoop.commandFactory, message, "error");
+ expectFailureCommandFactory.baseExecutor = executeCommandAndReturnErrorMessage;
+ testLoop.commandFactory = expectFailureCommandFactory;
+};
+
+function ExpectFailureCommandFactory(originalCommandFactory, expectedErrorMessage, errorType) {
+ this.getCommandHandler = function(name) {
+ var baseHandler = originalCommandFactory.getCommandHandler(name);
+ var baseExecutor = this.baseExecutor;
+ var expectFailureCommand = {};
+ expectFailureCommand.execute = function() {
+ var baseFailureMessage = baseExecutor(baseHandler, arguments);
+ var result = new CommandResult();
+ if (!baseFailureMessage) {
+ result.failed = true;
+ result.failureMessage = "Expected " + errorType + " did not occur.";
+ }
+ else {
+ if (! PatternMatcher.matches(expectedErrorMessage, baseFailureMessage)) {
+ result.failed = true;
+ result.failureMessage = "Expected " + errorType + " message '" + expectedErrorMessage
+ + "' but was '" + baseFailureMessage + "'";
+ }
+ else {
+ result.passed = true;
+ result.result = baseFailureMessage;
+ }
+ }
+ testLoop.commandFactory = originalCommandFactory;
+ return result;
+ };
+ return expectFailureCommand;
+ };
+};
+
+function executeCommandAndReturnFailureMessage(baseHandler, originalArguments) {
+ var baseResult = baseHandler.execute.apply(baseHandler, originalArguments);
+ if (baseResult.passed) {
+ return null;
+ }
+ return baseResult.failureMessage;
+};
+
+function executeCommandAndReturnErrorMessage(baseHandler, originalArguments) {
+ try {
+ baseHandler.execute.apply(baseHandler, originalArguments);
+ return null;
+ }
+ catch (expected) {
+ return expected.message;
+ }
+};
+
diff --git a/tests/test_tools/selenium/core/scripts/selenium-logging.js b/tests/test_tools/selenium/core/scripts/selenium-logging.js
new file mode 100644
index 00000000..b0fc67e4
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-logging.js
@@ -0,0 +1,112 @@
+/*
+* Copyright 2004 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+var Logger = function() {
+ this.logWindow = null;
+}
+Logger.prototype = {
+
+ setLogLevelThreshold: function(logLevel) {
+ this.pendingLogLevelThreshold = logLevel;
+ this.show();
+ //
+ // The following message does not show up in the log -- _unless_ I step along w/ the debugger
+ // down to the append call. I believe this is because the new log window has not yet loaded,
+ // and therefore the log msg is discarded; but if I step through the debugger, this changes
+ // the scheduling so as to load that window and make it ready.
+ // this.info("Log level programmatically set to " + logLevel + " (presumably by driven-mode test code)");
+ },
+
+ getLogWindow: function() {
+ if (this.logWindow && this.logWindow.closed) {
+ this.logWindow = null;
+ }
+ if (this.logWindow && this.pendingLogLevelThreshold && this.logWindow.setThresholdLevel) {
+ this.logWindow.setThresholdLevel(this.pendingLogLevelThreshold);
+
+ // can't just directly log because that action would loop back to this code infinitely
+ this.pendingInfoMessage = "Log level programmatically set to " + this.pendingLogLevelThreshold + " (presumably by driven-mode test code)";
+
+ this.pendingLogLevelThreshold = null; // let's only go this way one time
+ }
+
+ return this.logWindow;
+ },
+
+ openLogWindow: function() {
+ this.logWindow = window.open(
+ getDocumentBase(document) + "SeleniumLog.html", "SeleniumLog",
+ "width=600,height=250,bottom=0,right=0,status,scrollbars,resizable"
+ );
+ return this.logWindow;
+ },
+
+ show: function() {
+ if (! this.getLogWindow()) {
+ this.openLogWindow();
+ }
+ },
+
+ log: function(message, className) {
+ var logWindow = this.getLogWindow();
+ if (logWindow) {
+ if (logWindow.append) {
+ if (this.pendingInfoMessage) {
+ logWindow.append("info: " + this.pendingInfoMessage, "info");
+ this.pendingInfoMessage = null;
+ }
+ logWindow.append(className + ": " + message, className);
+ }
+ }
+ },
+
+ close: function(message) {
+ if (this.logWindow != null) {
+ try {
+ this.logWindow.close();
+ } catch (e) {
+ // swallow exception
+ // the window is probably closed if we get an exception here
+ }
+ this.logWindow = null;
+ }
+ },
+
+ debug: function(message) {
+ this.log(message, "debug");
+ },
+
+ info: function(message) {
+ this.log(message, "info");
+ },
+
+ warn: function(message) {
+ this.log(message, "warn");
+ },
+
+ error: function(message) {
+ this.log(message, "error");
+ },
+
+ exception: function(exception) {
+ var msg = "Unexpected Exception: " + describe(exception, ', ');
+ this.error(msg);
+ }
+
+};
+
+var LOG = new Logger();
+
diff --git a/tests/test_tools/selenium/core/scripts/selenium-seleneserunner.js b/tests/test_tools/selenium/core/scripts/selenium-seleneserunner.js
new file mode 100644
index 00000000..041b3bf9
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-seleneserunner.js
@@ -0,0 +1,300 @@
+/*
+* Copyright 2005 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+
+passColor = "#cfffcf";
+failColor = "#ffcfcf";
+errorColor = "#ffffff";
+workingColor = "#DEE7EC";
+doneColor = "#FFFFCC";
+
+slowMode = false;
+
+var cmd1 = document.createElement("div");
+var cmd2 = document.createElement("div");
+var cmd3 = document.createElement("div");
+var cmd4 = document.createElement("div");
+
+var postResult = "START";
+
+queryString = null;
+
+function runTest() {
+ var testAppFrame = document.getElementById('myiframe');
+ selenium = Selenium.createForFrame(testAppFrame);
+
+ commandFactory = new CommandHandlerFactory();
+ commandFactory.registerAll(selenium);
+
+ testLoop = new TestLoop(commandFactory);
+
+ testLoop.nextCommand = nextCommand;
+ testLoop.commandStarted = commandStarted;
+ testLoop.commandComplete = commandComplete;
+ testLoop.commandError = commandError;
+ testLoop.requiresCallBack = true;
+ testLoop.testComplete = function() {
+ window.status = "Selenium Tests Complete, for this Test"
+ // Continue checking for new results
+ testLoop.continueTest();
+ postResult = "START";
+ };
+
+ document.getElementById("commandList").appendChild(cmd4);
+ document.getElementById("commandList").appendChild(cmd3);
+ document.getElementById("commandList").appendChild(cmd2);
+ document.getElementById("commandList").appendChild(cmd1);
+
+ var doContinue = getQueryVariable("continue");
+ if (doContinue != null) postResult = "OK";
+
+ testLoop.start();
+}
+
+function getQueryString() {
+ if (queryString != null) return queryString;
+ if (browserVersion.isHTA) {
+ var args = extractArgs();
+ if (args.length < 2) return null;
+ queryString = args[1];
+ return queryString;
+ } else {
+ return location.search.substr(1);
+ }
+}
+
+function extractArgs() {
+ var str = SeleniumHTARunner.commandLine;
+ if (str == null || str == "") return new Array();
+ var matches = str.match(/(?:"([^"]+)"|(?!"([^"]+)")(\S+))/g);
+ // We either want non quote stuff ([^"]+) surrounded by quotes
+ // or we want to look-ahead, see that the next character isn't
+ // a quoted argument, and then grab all the non-space stuff
+ // this will return for the line: "foo" bar
+ // the results "\"foo\"" and "bar"
+
+ // So, let's unquote the quoted arguments:
+ var args = new Array;
+ for (var i = 0; i < matches.length; i++) {
+ args[i] = matches[i];
+ args[i] = args[i].replace(/^"(.*)"$/, "$1");
+ }
+ return args;
+}
+
+function getQueryVariable(variable) {
+ var query = getQueryString();
+ if (query == null) return null;
+ var vars = query.split("&");
+ for (var i=0;i<vars.length;i++) {
+ var pair = vars[i].split("=");
+ if (pair[0] == variable) {
+ return pair[1];
+ }
+ }
+}
+
+function buildBaseUrl() {
+ var baseUrl = getQueryVariable("baseUrl");
+ if (baseUrl != null) return baseUrl;
+ var lastSlash = window.location.href.lastIndexOf('/');
+ baseUrl = window.location.href.substring(0, lastSlash+1);
+ return baseUrl;
+}
+
+function buildDriverParams() {
+ var params = "";
+
+ var host = getQueryVariable("driverhost");
+ var port = getQueryVariable("driverport");
+ if (host != undefined && port != undefined) {
+ params = params + "&driverhost=" + host + "&driverport=" + port;
+ }
+
+ var sessionId = getQueryVariable("sessionId");
+ if (sessionId != undefined) {
+ params = params + "&sessionId=" + sessionId;
+ }
+
+ return params;
+}
+
+function preventBrowserCaching() {
+ var t = (new Date()).getTime();
+ return "&counterToMakeURsUniqueAndSoStopPageCachingInTheBrowser=" + t;
+}
+
+function nextCommand() {
+ xmlHttp = XmlHttp.create();
+ try {
+
+ var url = buildBaseUrl();
+ if (postResult == "START") {
+ url = url + "driver/?seleniumStart=true" + buildDriverParams() + preventBrowserCaching();
+ } else {
+ url = url + "driver/?" + buildDriverParams() + preventBrowserCaching();
+ }
+ LOG.debug("XMLHTTPRequesting " + url);
+ xmlHttp.open("POST", url, true);
+ xmlHttp.onreadystatechange=handleHttpResponse;
+ xmlHttp.send(postResult);
+ } catch(e) {
+ var s = 'xmlHttp returned:\n'
+ for (key in e) {
+ s += "\t" + key + " -> " + e[key] + "\n"
+ }
+ LOG.error(s);
+ return null;
+ }
+ return null;
+}
+
+ function handleHttpResponse() {
+ if (xmlHttp.readyState == 4) {
+ if (xmlHttp.status == 200) {
+ var command = extractCommand(xmlHttp);
+ testLoop.currentCommand = command;
+ testLoop.beginNextTest();
+ } else {
+ var s = 'xmlHttp returned: ' + xmlHttp.status + ": " + xmlHttp.statusText;
+ LOG.error(s);
+ testLoop.currentCommand = null;
+ setTimeout("testLoop.beginNextTest();", 2000);
+ }
+
+ }
+ }
+
+
+function extractCommand(xmlHttp) {
+ if (slowMode) {
+ delay(2000);
+ }
+
+ var command;
+ try {
+ command = xmlHttp.responseText;
+ } catch (e) {
+ alert('could not get responseText: ' + e.message);
+ }
+ if (command.substr(0,'|testComplete'.length)=='|testComplete') {
+ return null;
+ }
+
+ return createCommandFromRequest(command);
+}
+
+function commandStarted(command) {
+ commandNode = document.createElement("div");
+ innerHTML = command.command + '(';
+ if (command.target != null && command.target != "") {
+ innerHTML += command.target;
+ if (command.value != null && command.value != "") {
+ innerHTML += ', ' + command.value;
+ }
+ }
+ innerHTML += ")";
+ commandNode.innerHTML = innerHTML;
+ commandNode.style.backgroundColor = workingColor;
+ document.getElementById("commandList").removeChild(cmd1);
+ document.getElementById("commandList").removeChild(cmd2);
+ document.getElementById("commandList").removeChild(cmd3);
+ document.getElementById("commandList").removeChild(cmd4);
+ cmd4 = cmd3;
+ cmd3 = cmd2;
+ cmd2 = cmd1;
+ cmd1 = commandNode;
+ document.getElementById("commandList").appendChild(cmd4);
+ document.getElementById("commandList").appendChild(cmd3);
+ document.getElementById("commandList").appendChild(cmd2);
+ document.getElementById("commandList").appendChild(cmd1);
+}
+
+function commandComplete(result) {
+ if (result.failed) {
+ if (postResult == "CONTINUATION") {
+ testLoop.aborted = true;
+ }
+ postResult = result.failureMessage;
+ commandNode.title = result.failureMessage;
+ commandNode.style.backgroundColor = failColor;
+ } else if (result.passed) {
+ postResult = "OK";
+ commandNode.style.backgroundColor = passColor;
+ } else {
+ if (result.result == null) {
+ postResult = "OK";
+ } else {
+ postResult = "OK," + result.result;
+ }
+ commandNode.style.backgroundColor = doneColor;
+ }
+}
+
+function commandError(message) {
+ postResult = "ERROR: " + message;
+ commandNode.style.backgroundColor = errorColor;
+ commandNode.title = message;
+}
+
+function slowClicked() {
+ slowMode = !slowMode;
+}
+
+function delay(millis) {
+ startMillis = new Date();
+ while (true) {
+ milli = new Date();
+ if (milli-startMillis > millis) {
+ break;
+ }
+ }
+}
+
+function getIframeDocument(iframe) {
+ if (iframe.contentDocument) {
+ return iframe.contentDocument;
+ }
+ else {
+ return iframe.contentWindow.document;
+ }
+}
+
+// Parses a URI query string into a SeleniumCommand object
+function createCommandFromRequest(commandRequest) {
+ //decodeURIComponent doesn't strip plus signs
+ var processed = commandRequest.replace(/\+/g, "%20");
+ // strip trailing spaces
+ var processed = processed.replace(/\s+$/, "");
+ var vars = processed.split("&");
+ var cmdArgs = new Object();
+ for (var i=0;i<vars.length;i++) {
+ var pair = vars[i].split("=");
+ cmdArgs[pair[0]] = pair[1];
+ }
+ var cmd = cmdArgs['cmd'];
+ var arg1 = cmdArgs['1'];
+ if (null == arg1) arg1 = "";
+ arg1 = decodeURIComponent(arg1);
+ var arg2 = cmdArgs['2'];
+ if (null == arg2) arg2 = "";
+ arg2 = decodeURIComponent(arg2);
+ if (cmd == null) {
+ throw new Error("Bad command request: " + commandRequest);
+ }
+ return new SeleniumCommand(cmd, arg1, arg2);
+}
+
diff --git a/tests/test_tools/selenium/core/scripts/selenium-testrunner.js b/tests/test_tools/selenium/core/scripts/selenium-testrunner.js
new file mode 100644
index 00000000..1ced0a11
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-testrunner.js
@@ -0,0 +1,748 @@
+/*
+* Copyright 2004 ThoughtWorks, Inc
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+
+// The current row in the list of tests (test suite)
+currentRowInSuite = 0;
+
+// An object representing the current test
+currentTest = null;
+
+// Whether or not the jsFT should run all tests in the suite
+runAllTests = false;
+
+// Whether or not the current test has any errors;
+testFailed = false;
+suiteFailed = false;
+
+// Colors used to provide feedback
+passColor = "#ccffcc";
+doneColor = "#eeffee";
+failColor = "#ffcccc";
+workingColor = "#ffffcc";
+
+// Holds the handlers for each command.
+commandHandlers = null;
+
+// The number of tests run
+numTestPasses = 0;
+
+// The number of tests that have failed
+numTestFailures = 0;
+
+// The number of commands which have passed
+numCommandPasses = 0;
+
+// The number of commands which have failed
+numCommandFailures = 0;
+
+// The number of commands which have caused errors (element not found)
+numCommandErrors = 0;
+
+// The time that the test was started.
+startTime = null;
+
+// The current time.
+currentTime = null;
+
+// An simple enum for failureType
+ERROR = 0;
+FAILURE = 1;
+
+runInterval = 0;
+
+queryString = null;
+
+function setRunInterval() {
+ // Get the value of the checked runMode option.
+ // There should be a way of getting the value of the "group", but I don't know how.
+ var runModeOptions = document.forms['controlPanel'].runMode;
+ for (var i = 0; i < runModeOptions.length; i++) {
+ if (runModeOptions[i].checked) {
+ runInterval = runModeOptions[i].value;
+ break;
+ }
+ }
+}
+
+function continueCurrentTest() {
+ document.getElementById('continueTest').disabled = true;
+ testLoop.resume();
+}
+
+function getApplicationFrame() {
+ return document.getElementById('myiframe');
+}
+
+function getSuiteFrame() {
+ return document.getElementById('testSuiteFrame');
+}
+
+function getTestFrame(){
+ return document.getElementById('testFrame');
+}
+
+function loadAndRunIfAuto() {
+ loadSuiteFrame();
+}
+
+function start() {
+ queryString = null;
+ setRunInterval();
+ loadSuiteFrame();
+}
+
+function loadSuiteFrame() {
+ var testAppFrame = document.getElementById('myiframe');
+ selenium = Selenium.createForFrame(testAppFrame);
+ registerCommandHandlers();
+
+ //set the runInterval if there is a queryParameter for it
+ var tempRunInterval = getQueryParameter("runInterval");
+ if (tempRunInterval) {
+ runInterval = tempRunInterval;
+ }
+
+ document.getElementById("modeRun").onclick = setRunInterval;
+ document.getElementById('modeWalk').onclick = setRunInterval;
+ document.getElementById('modeStep').onclick = setRunInterval;
+ document.getElementById('continueTest').onclick = continueCurrentTest;
+
+ var testSuiteName = getQueryParameter("test");
+
+ if (testSuiteName) {
+ addLoadListener(getSuiteFrame(), onloadTestSuite);
+ getSuiteFrame().src = testSuiteName;
+ } else {
+ onloadTestSuite();
+ }
+}
+
+function startSingleTest() {
+ removeLoadListener(getApplicationFrame(), startSingleTest);
+ var singleTestName = getQueryParameter("singletest");
+ addLoadListener(getTestFrame(), startTest);
+ getTestFrame().src = singleTestName;
+}
+
+function getIframeDocument(iframe)
+{
+ if (iframe.contentDocument) {
+ return iframe.contentDocument;
+ }
+ else {
+ return iframe.contentWindow.document;
+ }
+}
+
+function onloadTestSuite() {
+ removeLoadListener(getSuiteFrame(), onloadTestSuite);
+
+ // Add an onclick function to each link in all suite tables
+ var allTables = getIframeDocument(getSuiteFrame()).getElementsByTagName("table");
+ for (var tableNum = 0; tableNum < allTables.length; tableNum++)
+ {
+ var skippedTable = allTables[tableNum];
+ for(rowNum = 1;rowNum < skippedTable.rows.length; rowNum++) {
+ addOnclick(skippedTable, rowNum);
+ }
+ }
+
+ suiteTable = getIframeDocument(getSuiteFrame()).getElementsByTagName("table")[0];
+ if (suiteTable!=null) {
+
+ if (isAutomatedRun()) {
+ startTestSuite();
+ } else if (getQueryParameter("autoURL")) {
+
+ addLoadListener(getApplicationFrame(), startSingleTest);
+
+ getApplicationFrame().src = getQueryParameter("autoURL");
+
+ } else {
+ testLink = suiteTable.rows[currentRowInSuite+1].cells[0].getElementsByTagName("a")[0];
+ getTestFrame().src = testLink.href;
+ }
+ }
+}
+
+// Adds an onclick function to the link in the given row in suite table.
+// This function checks whether the test has already been run and the data is
+// stored. If the data is stored, it sets the test frame to be the stored data.
+// Otherwise, it loads the fresh page.
+function addOnclick(suiteTable, rowNum) {
+ aLink = suiteTable.rows[rowNum].cells[0].getElementsByTagName("a")[0];
+ aLink.onclick = function(eventObj) {
+ srcObj = null;
+
+ // For mozilla-like browsers
+ if(eventObj)
+ srcObj = eventObj.target;
+
+ // For IE-like browsers
+ else if (getSuiteFrame().contentWindow.event)
+ srcObj = getSuiteFrame().contentWindow.event.srcElement;
+
+ // The target row (the event source is not consistently reported by browsers)
+ row = srcObj.parentNode.parentNode.rowIndex || srcObj.parentNode.parentNode.parentNode.rowIndex;
+
+ // If the row has a stored results table, use that
+ if(suiteTable.rows[row].cells[1]) {
+ var bodyElement = getIframeDocument(getTestFrame()).body;
+
+ // Create a div element to hold the results table.
+ var tableNode = getIframeDocument(getTestFrame()).createElement("div");
+ var resultsCell = suiteTable.rows[row].cells[1];
+ tableNode.innerHTML = resultsCell.innerHTML;
+
+ // Append this text node, and remove all the preceding nodes.
+ bodyElement.appendChild(tableNode);
+ while (bodyElement.firstChild != bodyElement.lastChild) {
+ bodyElement.removeChild(bodyElement.firstChild);
+ }
+ }
+ // Otherwise, just open up the fresh page.
+ else {
+ getTestFrame().src = suiteTable.rows[row].cells[0].getElementsByTagName("a")[0].href;
+ }
+
+ return false;
+ };
+}
+
+function isQueryParameterTrue(name) {
+ parameterValue = getQueryParameter(name);
+ return (parameterValue != null && parameterValue.toLowerCase() == "true");
+}
+
+function getQueryString() {
+ if (queryString != null) return queryString;
+ if (browserVersion.isHTA) {
+ var args = extractArgs();
+ if (args.length < 2) return null;
+ queryString = args[1];
+ return queryString;
+ } else {
+ return location.search.substr(1);
+ }
+}
+
+function extractArgs() {
+ var str = SeleniumHTARunner.commandLine;
+ if (str == null || str == "") return new Array();
+ var matches = str.match(/(?:"([^"]+)"|(?!"([^"]+)")(\S+))/g);
+ // We either want non quote stuff ([^"]+) surrounded by quotes
+ // or we want to look-ahead, see that the next character isn't
+ // a quoted argument, and then grab all the non-space stuff
+ // this will return for the line: "foo" bar
+ // the results "\"foo\"" and "bar"
+
+ // So, let's unquote the quoted arguments:
+ var args = new Array;
+ for (var i = 0; i < matches.length; i++) {
+ args[i] = matches[i];
+ args[i] = args[i].replace(/^"(.*)"$/, "$1");
+ }
+ return args;
+}
+
+function getQueryParameter(searchKey) {
+ var str = getQueryString();
+ if (str == null) return null;
+ var clauses = str.split('&');
+ for (var i = 0; i < clauses.length; i++) {
+ var keyValuePair = clauses[i].split('=',2);
+ var key = unescape(keyValuePair[0]);
+ if (key == searchKey) {
+ return unescape(keyValuePair[1]);
+ }
+ }
+ return null;
+}
+
+function isNewWindow() {
+ return isQueryParameterTrue("newWindow");
+}
+
+function isAutomatedRun() {
+ return isQueryParameterTrue("auto");
+}
+
+function resetMetrics() {
+ numTestPasses = 0;
+ numTestFailures = 0;
+ numCommandPasses = 0;
+ numCommandFailures = 0;
+ numCommandErrors = 0;
+ startTime = new Date().getTime();
+}
+
+function runSingleTest() {
+ runAllTests = false;
+ resetMetrics();
+ startTest();
+}
+
+function startTest() {
+ removeLoadListener(getTestFrame(), startTest);
+
+ // Scroll to the top of the test frame
+ if (getTestFrame().contentWindow) {
+ getTestFrame().contentWindow.scrollTo(0,0);
+ }
+ else {
+ frames['testFrame'].scrollTo(0,0);
+ }
+
+ currentTest = new HtmlTest(getIframeDocument(getTestFrame()));
+
+ testFailed = false;
+ storedVars = new Object();
+
+ testLoop = initialiseTestLoop();
+ testLoop.start();
+}
+
+function HtmlTest(testDocument) {
+ this.init(testDocument);
+}
+
+HtmlTest.prototype = {
+
+ init: function(testDocument) {
+ this.document = testDocument;
+ this.document.bgColor = "";
+ this.currentRow = null;
+ this.commandRows = new Array();
+ this.headerRow = null;
+ var tables = this.document.getElementsByTagName("table");
+ for (var i = 0; i < tables.length; i++) {
+ var candidateRows = tables[i].rows;
+ for (var j = 0; j < candidateRows.length; j++) {
+ if (!this.headerRow) {
+ this.headerRow = candidateRows[j];
+ }
+ if (candidateRows[j].cells.length >= 3) {
+ this.addCommandRow(candidateRows[j]);
+ }
+ }
+ }
+ },
+
+ addCommandRow: function(row) {
+ if (row.cells[2] && row.cells[2].originalHTML) {
+ row.cells[2].innerHTML = row.cells[2].originalHTML;
+ }
+ row.bgColor = "";
+ this.commandRows.push(row);
+ },
+
+ nextCommand: function() {
+ if (this.commandRows.length > 0) {
+ this.currentRow = this.commandRows.shift();
+ } else {
+ this.currentRow = null;
+ }
+ return this.currentRow;
+ }
+
+};
+
+function startTestSuite() {
+ resetMetrics();
+ currentRowInSuite = 0;
+ runAllTests = true;
+ suiteFailed = false;
+
+ runNextTest();
+}
+
+function runNextTest() {
+ if (!runAllTests)
+ return;
+
+ suiteTable = getIframeDocument(getSuiteFrame()).getElementsByTagName("table")[0];
+
+ // Do not change the row color of the first row
+ if (currentRowInSuite > 0) {
+ // Provide test-status feedback
+ if (testFailed) {
+ setCellColor(suiteTable.rows, currentRowInSuite, 0, failColor);
+ } else {
+ setCellColor(suiteTable.rows, currentRowInSuite, 0, passColor);
+ }
+
+ // Set the results from the previous test run
+ setResultsData(suiteTable, currentRowInSuite);
+ }
+
+ currentRowInSuite++;
+
+ // If we are done with all of the tests, set the title bar as pass or fail
+ if (currentRowInSuite >= suiteTable.rows.length) {
+ if (suiteFailed) {
+ setCellColor(suiteTable.rows, 0, 0, failColor);
+ } else {
+ setCellColor(suiteTable.rows, 0, 0, passColor);
+ }
+
+ // If this is an automated run (i.e., build script), then submit
+ // the test results by posting to a form
+ if (isAutomatedRun())
+ postTestResults(suiteFailed, suiteTable);
+ }
+
+ else {
+ // Make the current row blue
+ setCellColor(suiteTable.rows, currentRowInSuite, 0, workingColor);
+
+ testLink = suiteTable.rows[currentRowInSuite].cells[0].getElementsByTagName("a")[0];
+ testLink.focus();
+
+ var testFrame = getTestFrame();
+ addLoadListener(testFrame, startTest);
+
+ selenium.browserbot.setIFrameLocation(testFrame, testLink.href);
+ }
+}
+
+function setCellColor(tableRows, row, col, colorStr) {
+ tableRows[row].cells[col].bgColor = colorStr;
+}
+
+// Sets the results from a test into a hidden column on the suite table. So,
+// for each tests, the second column is set to the HTML from the test table.
+function setResultsData(suiteTable, row) {
+ // Create a text node of the test table
+ var resultTable = getIframeDocument(getTestFrame()).body.innerHTML;
+ if (!resultTable) return;
+
+ var tableNode = suiteTable.ownerDocument.createElement("div");
+ tableNode.innerHTML = resultTable;
+
+ var new_column = suiteTable.ownerDocument.createElement("td");
+ new_column.appendChild(tableNode);
+
+ // Set the column to be invisible
+ new_column.style.display = "none";
+
+ // Add the invisible column
+ suiteTable.rows[row].appendChild(new_column);
+}
+
+// Post the results to a servlet, CGI-script, etc. The URL of the
+// results-handler defaults to "/postResults", but an alternative location
+// can be specified by providing a "resultsUrl" query parameter.
+//
+// Parameters passed to the results-handler are:
+// result: passed/failed depending on whether the suite passed or failed
+// totalTime: the total running time in seconds for the suite.
+//
+// numTestPasses: the total number of tests which passed.
+// numTestFailures: the total number of tests which failed.
+//
+// numCommandPasses: the total number of commands which passed.
+// numCommandFailures: the total number of commands which failed.
+// numCommandErrors: the total number of commands which errored.
+//
+// suite: the suite table, including the hidden column of test results
+// testTable.1 to testTable.N: the individual test tables
+//
+function postTestResults(suiteFailed, suiteTable) {
+
+ form = document.createElement("form");
+ document.body.appendChild(form);
+
+ form.id = "resultsForm";
+ form.method="post";
+ form.target="myiframe";
+
+ var resultsUrl = getQueryParameter("resultsUrl");
+ if (!resultsUrl) {
+ resultsUrl = "./postResults";
+ }
+
+ var actionAndParameters = resultsUrl.split('?',2);
+ form.action = actionAndParameters[0];
+ var resultsUrlQueryString = actionAndParameters[1];
+
+ form.createHiddenField = function(name, value) {
+ input = document.createElement("input");
+ input.type = "hidden";
+ input.name = name;
+ input.value = value;
+ this.appendChild(input);
+ };
+
+ if (resultsUrlQueryString) {
+ var clauses = resultsUrlQueryString.split('&');
+ for (var i = 0; i < clauses.length; i++) {
+ var keyValuePair = clauses[i].split('=',2);
+ var key = unescape(keyValuePair[0]);
+ var value = unescape(keyValuePair[1]);
+ form.createHiddenField(key, value);
+ }
+ }
+
+ form.createHiddenField("selenium.version", Selenium.version);
+ form.createHiddenField("selenium.revision", Selenium.revision);
+
+ form.createHiddenField("result", suiteFailed == true ? "failed" : "passed");
+
+ form.createHiddenField("totalTime", Math.floor((currentTime - startTime) / 1000));
+ form.createHiddenField("numTestPasses", numTestPasses);
+ form.createHiddenField("numTestFailures", numTestFailures);
+ form.createHiddenField("numCommandPasses", numCommandPasses);
+ form.createHiddenField("numCommandFailures", numCommandFailures);
+ form.createHiddenField("numCommandErrors", numCommandErrors);
+
+ // Create an input for each test table. The inputs are named
+ // testTable.1, testTable.2, etc.
+ for (rowNum = 1; rowNum < suiteTable.rows.length;rowNum++) {
+ // If there is a second column, then add a new input
+ if (suiteTable.rows[rowNum].cells.length > 1) {
+ var resultCell = suiteTable.rows[rowNum].cells[1];
+ form.createHiddenField("testTable." + rowNum, resultCell.innerHTML);
+ // remove the resultCell, so it's not included in the suite HTML
+ resultCell.parentNode.removeChild(resultCell);
+ }
+ }
+
+ form.createHiddenField("numTestTotal", rowNum);
+
+ // Add HTML for the suite itself
+ form.createHiddenField("suite", suiteTable.parentNode.innerHTML);
+
+ if (isQueryParameterTrue("save")) {
+ saveToFile(resultsUrl, form);
+ } else {
+ form.submit();
+ }
+ document.body.removeChild(form);
+ if (isQueryParameterTrue("close")) {
+ window.top.close();
+ }
+}
+
+function saveToFile(fileName, form) {
+ // This only works when run as an IE HTA
+ var inputs = new Object();
+ for (var i = 0; i < form.elements.length; i++) {
+ inputs[form.elements[i].name] = form.elements[i].value;
+ }
+ var objFSO = new ActiveXObject("Scripting.FileSystemObject")
+ var scriptFile = objFSO.CreateTextFile(fileName);
+ scriptFile.WriteLine("<html><body>\n<h1>Test suite results </h1>" +
+ "\n\n<table>\n<tr>\n<td>result:</td>\n<td>" + inputs["result"] + "</td>\n" +
+ "</tr>\n<tr>\n<td>totalTime:</td>\n<td>" + inputs["totalTime"] + "</td>\n</tr>\n" +
+ "<tr>\n<td>numTestPasses:</td>\n<td>" + inputs["numTestPasses"] + "</td>\n</tr>\n" +
+ "<tr>\n<td>numTestFailures:</td>\n<td>" + inputs["numTestFailures"] + "</td>\n</tr>\n" +
+ "<tr>\n<td>numCommandPasses:</td>\n<td>" + inputs["numCommandPasses"] + "</td>\n</tr>\n" +
+ "<tr>\n<td>numCommandFailures:</td>\n<td>" + inputs["numCommandFailures"] + "</td>\n</tr>\n" +
+ "<tr>\n<td>numCommandErrors:</td>\n<td>" + inputs["numCommandErrors"] + "</td>\n</tr>\n" +
+ "<tr>\n<td>" + inputs["suite"] + "</td>\n<td>&nbsp;</td>\n</tr>");
+ var testNum = inputs["numTestTotal"];
+ for (var rowNum = 1; rowNum < testNum; rowNum++) {
+ scriptFile.WriteLine("<tr>\n<td>" + inputs["testTable." + rowNum] + "</td>\n<td>&nbsp;</td>\n</tr>");
+ }
+ scriptFile.WriteLine("</table></body></html>");
+ scriptFile.Close();
+}
+
+function printMetrics() {
+ setText(document.getElementById("commandPasses"), numCommandPasses);
+ setText(document.getElementById("commandFailures"), numCommandFailures);
+ setText(document.getElementById("commandErrors"), numCommandErrors);
+ setText(document.getElementById("testRuns"), numTestPasses + numTestFailures);
+ setText(document.getElementById("testFailures"), numTestFailures);
+
+ currentTime = new Date().getTime();
+
+ timeDiff = currentTime - startTime;
+ totalSecs = Math.floor(timeDiff / 1000);
+
+ minutes = Math.floor(totalSecs / 60);
+ seconds = totalSecs % 60;
+
+ setText(document.getElementById("elapsedTime"), pad(minutes)+":"+pad(seconds));
+}
+
+// Puts a leading 0 on num if it is less than 10
+function pad (num) {
+ return (num > 9) ? num : "0" + num;
+}
+
+/*
+ * Register all of the built-in command handlers with the CommandHandlerFactory.
+ * TODO work out an easy way for people to register handlers without modifying the Selenium sources.
+ */
+function registerCommandHandlers() {
+ commandFactory = new CommandHandlerFactory();
+ commandFactory.registerAll(selenium);
+
+}
+
+function initialiseTestLoop() {
+ testLoop = new TestLoop(commandFactory);
+
+ testLoop.getCommandInterval = function() { return runInterval; };
+ testLoop.nextCommand = nextCommand;
+ testLoop.commandStarted = commandStarted;
+ testLoop.commandComplete = commandComplete;
+ testLoop.commandError = commandError;
+ testLoop.testComplete = testComplete;
+ testLoop.pause = function() {
+ document.getElementById('continueTest').disabled = false;
+ };
+ return testLoop;
+}
+
+function nextCommand() {
+ var row = currentTest.nextCommand();
+ if (row == null) {
+ return null;
+ }
+ row.cells[2].originalHTML = row.cells[2].innerHTML;
+ return new SeleniumCommand(getText(row.cells[0]),
+ getText(row.cells[1]),
+ getText(row.cells[2]));
+}
+
+function removeNbsp(value) {
+ return value.replace(/\240/g, "");
+}
+
+function scrollIntoView(element) {
+ if (element.scrollIntoView) {
+ element.scrollIntoView(false);
+ return;
+ }
+ // TODO: work out how to scroll browsers that don't support
+ // scrollIntoView (like Konqueror)
+}
+
+function commandStarted() {
+ currentTest.currentRow.bgColor = workingColor;
+ scrollIntoView(currentTest.currentRow.cells[0]);
+ printMetrics();
+}
+
+function commandComplete(result) {
+ if (result.failed) {
+ numCommandFailures += 1;
+ recordFailure(result.failureMessage);
+ } else if (result.passed) {
+ numCommandPasses += 1;
+ currentTest.currentRow.bgColor = passColor;
+ } else {
+ currentTest.currentRow.bgColor = doneColor;
+ }
+}
+
+function commandError(errorMessage) {
+ numCommandErrors += 1;
+ recordFailure(errorMessage);
+}
+
+function recordFailure(errorMsg) {
+ LOG.warn("recordFailure: " + errorMsg);
+ // Set cell background to red
+ currentTest.currentRow.bgColor = failColor;
+
+ // Set error message
+ currentTest.currentRow.cells[2].innerHTML = errorMsg;
+ currentTest.currentRow.title = errorMsg;
+ testFailed = true;
+ suiteFailed = true;
+}
+
+function testComplete() {
+ var resultColor = passColor;
+ if (testFailed) {
+ resultColor = failColor;
+ numTestFailures += 1;
+ } else {
+ numTestPasses += 1;
+ }
+
+ if (currentTest.headerRow) {
+ currentTest.headerRow.bgColor = resultColor;
+ }
+
+ printMetrics();
+
+ window.setTimeout("runNextTest()", 1);
+}
+
+Selenium.prototype.doPause = function(waitTime) {
+ testLoop.pauseInterval = waitTime;
+};
+
+Selenium.prototype.doPause.dontCheckAlertsAndConfirms = true;
+
+Selenium.prototype.doBreak = function() {
+ document.getElementById('modeStep').checked = true;
+ runInterval = -1;
+};
+
+/*
+ * Click on the located element, and attach a callback to notify
+ * when the page is reloaded.
+ */
+Selenium.prototype.doModalDialogTest = function(returnValue) {
+ this.browserbot.doModalDialogTest(returnValue);
+};
+
+/*
+ * Store the value of a form input in a variable
+ */
+Selenium.prototype.doStoreValue = function(target, varName) {
+ if (!varName) {
+ // Backward compatibility mode: read the ENTIRE text of the page
+ // and stores it in a variable with the name of the target
+ value = this.page().bodyText();
+ storedVars[target] = value;
+ return;
+ }
+ var element = this.page().findElement(target);
+ storedVars[varName] = getInputValue(element);
+};
+
+/*
+ * Store the text of an element in a variable
+ */
+Selenium.prototype.doStoreText = function(target, varName) {
+ var element = this.page().findElement(target);
+ storedVars[varName] = getText(element);
+};
+
+/*
+ * Store the value of an element attribute in a variable
+ */
+Selenium.prototype.doStoreAttribute = function(target, varName) {
+ storedVars[varName] = this.page().findAttribute(target);
+};
+
+/*
+ * Store the result of a literal value
+ */
+Selenium.prototype.doStore = function(value, varName) {
+ storedVars[varName] = value;
+};
+
+Selenium.prototype.doEcho = function(msg) {
+ currentTest.currentRow.cells[2].innerHTML = msg;
+}
diff --git a/tests/test_tools/selenium/core/scripts/selenium-version.js b/tests/test_tools/selenium/core/scripts/selenium-version.js
new file mode 100644
index 00000000..1fee837b
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/selenium-version.js
@@ -0,0 +1,5 @@
+Selenium.version = "@VERSION@";
+Selenium.revision = "@REVISION@";
+
+window.top.document.title += " v" + Selenium.version + " [" + Selenium.revision + "]";
+
diff --git a/tests/test_tools/selenium/core/scripts/user-extensions.js.sample b/tests/test_tools/selenium/core/scripts/user-extensions.js.sample
new file mode 100644
index 00000000..0f0ca840
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/user-extensions.js.sample
@@ -0,0 +1,75 @@
+/*
+ * By default, Selenium looks for a file called "user-extensions.js", and loads and javascript
+ * code found in that file. This file is a sample of what that file could look like.
+ *
+ * user-extensions.js provides a convenient location for adding extensions to Selenium, like
+ * new actions, checks and locator-strategies.
+ * By default, this file does not exist. Users can create this file and place their extension code
+ * in this common location, removing the need to modify the Selenium sources, and hopefully assisting
+ * with the upgrade process.
+ *
+ * You can find contributed extensions at http://wiki.openqa.org/display/SEL/Contributed%20User-Extensions
+ */
+
+// The following examples try to give an indication of how Selenium can be extended with javascript.
+
+// All do* methods on the Selenium prototype are added as actions.
+// Eg add a typeRepeated action to Selenium, which types the text twice into a text box.
+// The typeTwiceAndWait command will be available automatically
+Selenium.prototype.doTypeRepeated = function(locator, text) {
+ // All locator-strategies are automatically handled by "findElement"
+ var element = this.page().findElement(locator);
+
+ // Create the text to type
+ var valueToType = text + text;
+
+ // Replace the element text with the new text
+ this.page().replaceText(element, valueToType);
+};
+
+// All assert* methods on the Selenium prototype are added as checks.
+// Eg add a assertValueRepeated check, that makes sure that the element value
+// consists of the supplied text repeated.
+// The verify version will be available automatically.
+Selenium.prototype.assertValueRepeated = function(locator, text) {
+ // All locator-strategies are automatically handled by "findElement"
+ var element = this.page().findElement(locator);
+
+ // Create the text to verify
+ var expectedValue = text + text;
+
+ // Get the actual element value
+ var actualValue = element.value;
+
+ // Make sure the actual value matches the expected
+ Assert.matches(expectedValue, actualValue);
+};
+
+// All get* methods on the Selenium prototype result in
+// store, assert, assertNot, verify, verifyNot, waitFor, and waitForNot commands.
+// E.g. add a getTextLength method that returns the length of the text
+// of a specified element.
+// Will result in support for storeTextLength, assertTextLength, etc.
+Selenium.prototype.getTextLength = function(locator) {
+ return this.getText(locator).length;
+};
+
+// All locateElementBy* methods are added as locator-strategies.
+// Eg add a "valuerepeated=" locator, that finds the first element with the supplied value, repeated.
+// The "inDocument" is a the document you are searching.
+PageBot.prototype.locateElementByValueRepeated = function(text, inDocument) {
+ // Create the text to search for
+ var expectedValue = text + text;
+
+ // Loop through all elements, looking for ones that have a value === our expected value
+ var allElements = inDocument.getElementsByTagName("*");
+ for (var i = 0; i < allElements.length; i++) {
+ var testElement = allElements[i];
+ if (testElement.value && testElement.value === expectedValue) {
+ return testElement;
+ }
+ }
+ return null;
+};
+
+
diff --git a/tests/test_tools/selenium/core/scripts/xmlextras.js b/tests/test_tools/selenium/core/scripts/xmlextras.js
new file mode 100644
index 00000000..267aa058
--- /dev/null
+++ b/tests/test_tools/selenium/core/scripts/xmlextras.js
@@ -0,0 +1,153 @@
+// This is a third party JavaScript library from
+// http://webfx.eae.net/dhtml/xmlextras/xmlextras.html
+// i.e. This has not been written by ThoughtWorks.
+
+//<script>
+//////////////////
+// Helper Stuff //
+//////////////////
+
+// used to find the Automation server name
+function getDomDocumentPrefix() {
+ if (getDomDocumentPrefix.prefix)
+ return getDomDocumentPrefix.prefix;
+
+ var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
+ var o;
+ for (var i = 0; i < prefixes.length; i++) {
+ try {
+ // try to create the objects
+ o = new ActiveXObject(prefixes[i] + ".DomDocument");
+ return getDomDocumentPrefix.prefix = prefixes[i];
+ }
+ catch (ex) {};
+ }
+
+ throw new Error("Could not find an installed XML parser");
+}
+
+function getXmlHttpPrefix() {
+ if (getXmlHttpPrefix.prefix)
+ return getXmlHttpPrefix.prefix;
+
+ var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
+ var o;
+ for (var i = 0; i < prefixes.length; i++) {
+ try {
+ // try to create the objects
+ o = new ActiveXObject(prefixes[i] + ".XmlHttp");
+ return getXmlHttpPrefix.prefix = prefixes[i];
+ }
+ catch (ex) {};
+ }
+
+ throw new Error("Could not find an installed XML parser");
+}
+
+//////////////////////////
+// Start the Real stuff //
+//////////////////////////
+
+
+// XmlHttp factory
+function XmlHttp() {}
+
+XmlHttp.create = function () {
+ try {
+ if (window.XMLHttpRequest) {
+ var req = new XMLHttpRequest();
+
+ // some versions of Moz do not support the readyState property
+ // and the onreadystate event so we patch it!
+ if (req.readyState == null) {
+ req.readyState = 1;
+ req.addEventListener("load", function () {
+ req.readyState = 4;
+ if (typeof req.onreadystatechange == "function")
+ req.onreadystatechange();
+ }, false);
+ }
+
+ return req;
+ }
+ if (window.ActiveXObject) {
+ return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
+ }
+ }
+ catch (ex) {}
+ // fell through
+ throw new Error("Your browser does not support XmlHttp objects");
+};
+
+// XmlDocument factory
+function XmlDocument() {}
+
+XmlDocument.create = function () {
+ try {
+ // DOM2
+ if (document.implementation && document.implementation.createDocument) {
+ var doc = document.implementation.createDocument("", "", null);
+
+ // some versions of Moz do not support the readyState property
+ // and the onreadystate event so we patch it!
+ if (doc.readyState == null) {
+ doc.readyState = 1;
+ doc.addEventListener("load", function () {
+ doc.readyState = 4;
+ if (typeof doc.onreadystatechange == "function")
+ doc.onreadystatechange();
+ }, false);
+ }
+
+ return doc;
+ }
+ if (window.ActiveXObject)
+ return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
+ }
+ catch (ex) {}
+ throw new Error("Your browser does not support XmlDocument objects");
+};
+
+// Create the loadXML method and xml getter for Mozilla
+if (window.DOMParser &&
+ window.XMLSerializer &&
+ window.Node && Node.prototype && Node.prototype.__defineGetter__) {
+
+ // XMLDocument did not extend the Document interface in some versions
+ // of Mozilla. Extend both!
+ //XMLDocument.prototype.loadXML =
+ Document.prototype.loadXML = function (s) {
+
+ // parse the string to a new doc
+ var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
+
+ // remove all initial children
+ while (this.hasChildNodes())
+ this.removeChild(this.lastChild);
+
+ // insert and import nodes
+ for (var i = 0; i < doc2.childNodes.length; i++) {
+ this.appendChild(this.importNode(doc2.childNodes[i], true));
+ }
+ };
+
+
+ /*
+ * xml getter
+ *
+ * This serializes the DOM tree to an XML String
+ *
+ * Usage: var sXml = oNode.xml
+ *
+ */
+ // XMLDocument did not extend the Document interface in some versions
+ // of Mozilla. Extend both!
+ /*
+ XMLDocument.prototype.__defineGetter__("xml", function () {
+ return (new XMLSerializer()).serializeToString(this);
+ });
+ */
+ Document.prototype.__defineGetter__("xml", function () {
+ return (new XMLSerializer()).serializeToString(this);
+ });
+} \ No newline at end of file
diff --git a/tests/test_tools/selenium/core/selenium.css b/tests/test_tools/selenium/core/selenium.css
new file mode 100644
index 00000000..6e9f3f30
--- /dev/null
+++ b/tests/test_tools/selenium/core/selenium.css
@@ -0,0 +1,211 @@
+/*
+ * Copyright 2005 ThoughtWorks, Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*---( Layout )---*/
+
+body {
+ margin: 0;
+ padding: 0;
+ overflow: auto;
+}
+
+td {
+ position: static;
+}
+
+tr {
+ vertical-align: top;
+}
+
+.layout {
+ width: 100%;
+ height: 100%;
+ border-collapse: collapse;
+}
+
+.layout td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+}
+
+iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ background: white;
+ overflow: auto;
+}
+
+/*---( Style )---*/
+
+body, html {
+ font-family: Verdana, Arial, sans-serif;
+}
+
+.selenium th, .selenium td {
+ border: 1px solid #999;
+}
+
+.header {
+ background: #ccc;
+ padding: 0;
+ font-size: 90%;
+}
+
+#controlPanel {
+ padding: 0.5ex;
+ background: #eee;
+ overflow: auto;
+ font-size: 75%;
+ text-align: center;
+}
+
+#controlPanel fieldset {
+ margin: 0.3ex;
+ padding: 0.3ex;
+}
+
+#controlPanel fieldset legend {
+ color: black;
+}
+
+#controlPanel button {
+ margin: 0.5ex;
+}
+
+#controlPanel table {
+ font-size: 100%;
+}
+
+#controlPanel th, #controlPanel td {
+ border: 0;
+}
+
+h1 {
+ margin: 0.2ex;
+ font-size: 130%;
+ font-weight: bold;
+}
+
+h2 {
+ margin: 0.2ex;
+ font-size: 80%;
+ font-weight: normal;
+}
+
+.selenium a {
+ color: black;
+ text-decoration: none;
+}
+
+.selenium a:hover {
+ text-decoration: underline;
+}
+
+button, label {
+ cursor: pointer;
+}
+
+#stats {
+ margin: 0.5em auto 0.5em auto;
+}
+
+#stats th, #stats td {
+ text-align: left;
+ padding-left: 2px;
+}
+
+#stats th {
+ text-decoration: underline;
+}
+
+#stats td.count {
+ font-weight: bold;
+ text-align: right;
+}
+
+#testRuns {
+ color: green;
+}
+
+#testFailures {
+ color: red;
+}
+
+#commandPasses {
+ color: green;
+}
+
+#commandFailures {
+ color: red;
+}
+
+#commandErrors {
+ color: #f90;
+}
+
+.splash {
+ border: 1px solid black;
+ padding: 20px;
+ background: #ccc;
+}
+
+/*---( Logging Console )---*/
+
+#logging-console {
+ background: #fff;
+ font-size: 75%;
+}
+
+#logging-console #banner {
+ display: block;
+ width: 100%;
+ position: fixed;
+ top: 0;
+ background: #ddd;
+ border-bottom: 1px solid #666;
+}
+
+#logging-console #logLevelChooser {
+ float: right;
+ margin: 3px;
+}
+
+#logging-console ul {
+ list-style-type: none;
+ margin: 0px;
+ margin-top: 3em;
+ padding-left: 5px;
+}
+
+#logging-console li {
+ margin: 2px;
+ border-top: 1px solid #ccc;
+}
+
+#logging-console li.error {
+ font-weight: bold;
+ color: red;
+}
+
+#logging-console li.warn {
+ color: red;
+}
+
+#logging-console li.debug {
+ color: green;
+}
diff --git a/tests/test_tools/selenium/core/xpath/dom.js b/tests/test_tools/selenium/core/xpath/dom.js
new file mode 100644
index 00000000..85e0ab08
--- /dev/null
+++ b/tests/test_tools/selenium/core/xpath/dom.js
@@ -0,0 +1,428 @@
+// Copyright 2005 Google Inc.
+// All Rights Reserved
+//
+// An XML parse and a minimal DOM implementation that just supportes
+// the subset of the W3C DOM that is used in the XSLT implementation.
+//
+// References:
+//
+// [DOM] W3C DOM Level 3 Core Specification
+// <http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/>.
+//
+//
+// Author: Steffen Meschkat <mesch@google.com>
+
+// NOTE: The split() method in IE omits empty result strings. This is
+// utterly annoying. So we don't use it here.
+
+// Resolve entities in XML text fragments. According to the DOM
+// specification, the DOM is supposed to resolve entity references at
+// the API level. I.e. no entity references are passed through the
+// API. See "Entities and the DOM core", p.12, DOM 2 Core
+// Spec. However, different browsers actually pass very different
+// values at the API.
+//
+function xmlResolveEntities(s) {
+
+ var parts = stringSplit(s, '&');
+
+ var ret = parts[0];
+ for (var i = 1; i < parts.length; ++i) {
+ var rp = stringSplit(parts[i], ';');
+ if (rp.length == 1) {
+ // no entity reference: just a & but no ;
+ ret += parts[i];
+ continue;
+ }
+
+ var ch;
+ switch (rp[0]) {
+ case 'lt':
+ ch = '<';
+ break;
+ case 'gt':
+ ch = '>';
+ break;
+ case 'amp':
+ ch = '&';
+ break;
+ case 'quot':
+ ch = '"';
+ break;
+ case 'apos':
+ ch = '\'';
+ break;
+ case 'nbsp':
+ ch = String.fromCharCode(160);
+ break;
+ default:
+ // Cool trick: let the DOM do the entity decoding. We assign
+ // the entity text through non-W3C DOM properties and read it
+ // through the W3C DOM. W3C DOM access is specified to resolve
+ // entities.
+ var span = window.document.createElement('span');
+ span.innerHTML = '&' + rp[0] + '; ';
+ ch = span.childNodes[0].nodeValue.charAt(0);
+ }
+ ret += ch + rp[1];
+ }
+
+ return ret;
+}
+
+
+// Parses the given XML string with our custom, JavaScript XML parser. Written
+// by Steffen Meschkat (mesch@google.com).
+function xmlParse(xml) {
+ Timer.start('xmlparse');
+ var regex_empty = /\/$/;
+
+ // See also <http://www.w3.org/TR/REC-xml/#sec-common-syn> for
+ // allowed chars in a tag and attribute name. TODO(mesch): the
+ // following is still not completely correct.
+
+ var regex_tagname = /^([\w:-]*)/;
+ var regex_attribute = /([\w:-]+)\s?=\s?('([^\']*)'|"([^\"]*)")/g;
+
+ var xmldoc = new XDocument();
+ var root = xmldoc;
+
+ // For the record: in Safari, we would create native DOM nodes, but
+ // in Opera that is not possible, because the DOM only allows HTML
+ // element nodes to be created, so we have to do our own DOM nodes.
+
+ // xmldoc = document.implementation.createDocument('','',null);
+ // root = xmldoc; // .createDocumentFragment();
+ // NOTE(mesch): using the DocumentFragment instead of the Document
+ // crashes my Safari 1.2.4 (v125.12).
+ var stack = [];
+
+ var parent = root;
+ stack.push(parent);
+
+ var x = stringSplit(xml, '<');
+ for (var i = 1; i < x.length; ++i) {
+ var xx = stringSplit(x[i], '>');
+ var tag = xx[0];
+ var text = xmlResolveEntities(xx[1] || '');
+
+ if (tag.charAt(0) == '/') {
+ stack.pop();
+ parent = stack[stack.length-1];
+
+ } else if (tag.charAt(0) == '?') {
+ // Ignore XML declaration and processing instructions
+ } else if (tag.charAt(0) == '!') {
+ // Ignore notation and comments
+ } else {
+ var empty = tag.match(regex_empty);
+ var tagname = regex_tagname.exec(tag)[1];
+ var node = xmldoc.createElement(tagname);
+
+ var att;
+ while (att = regex_attribute.exec(tag)) {
+ var val = xmlResolveEntities(att[3] || att[4] || '');
+ node.setAttribute(att[1], val);
+ }
+
+ if (empty) {
+ parent.appendChild(node);
+ } else {
+ parent.appendChild(node);
+ parent = node;
+ stack.push(node);
+ }
+ }
+
+ if (text && parent != root) {
+ parent.appendChild(xmldoc.createTextNode(text));
+ }
+ }
+
+ Timer.end('xmlparse');
+ return root;
+}
+
+
+// Our W3C DOM Node implementation. Note we call it XNode because we
+// can't define the identifier Node. We do this mostly for Opera,
+// where we can't reuse the HTML DOM for parsing our own XML, and for
+// Safari, where it is too expensive to have the template processor
+// operate on native DOM nodes.
+function XNode(type, name, value, owner) {
+ this.attributes = [];
+ this.childNodes = [];
+
+ XNode.init.call(this, type, name, value, owner);
+}
+
+// Don't call as method, use apply() or call().
+XNode.init = function(type, name, value, owner) {
+ this.nodeType = type - 0;
+ this.nodeName = '' + name;
+ this.nodeValue = '' + value;
+ this.ownerDocument = owner;
+
+ this.firstChild = null;
+ this.lastChild = null;
+ this.nextSibling = null;
+ this.previousSibling = null;
+ this.parentNode = null;
+}
+
+XNode.unused_ = [];
+
+XNode.recycle = function(node) {
+ if (!node) {
+ return;
+ }
+
+ if (node.constructor == XDocument) {
+ XNode.recycle(node.documentElement);
+ return;
+ }
+
+ if (node.constructor != this) {
+ return;
+ }
+
+ XNode.unused_.push(node);
+ for (var a = 0; a < node.attributes.length; ++a) {
+ XNode.recycle(node.attributes[a]);
+ }
+ for (var c = 0; c < node.childNodes.length; ++c) {
+ XNode.recycle(node.childNodes[c]);
+ }
+ node.attributes.length = 0;
+ node.childNodes.length = 0;
+ XNode.init.call(node, 0, '', '', null);
+}
+
+XNode.create = function(type, name, value, owner) {
+ if (XNode.unused_.length > 0) {
+ var node = XNode.unused_.pop();
+ XNode.init.call(node, type, name, value, owner);
+ return node;
+ } else {
+ return new XNode(type, name, value, owner);
+ }
+}
+
+XNode.prototype.appendChild = function(node) {
+ // firstChild
+ if (this.childNodes.length == 0) {
+ this.firstChild = node;
+ }
+
+ // previousSibling
+ node.previousSibling = this.lastChild;
+
+ // nextSibling
+ node.nextSibling = null;
+ if (this.lastChild) {
+ this.lastChild.nextSibling = node;
+ }
+
+ // parentNode
+ node.parentNode = this;
+
+ // lastChild
+ this.lastChild = node;
+
+ // childNodes
+ this.childNodes.push(node);
+}
+
+
+XNode.prototype.replaceChild = function(newNode, oldNode) {
+ if (oldNode == newNode) {
+ return;
+ }
+
+ for (var i = 0; i < this.childNodes.length; ++i) {
+ if (this.childNodes[i] == oldNode) {
+ this.childNodes[i] = newNode;
+
+ var p = oldNode.parentNode;
+ oldNode.parentNode = null;
+ newNode.parentNode = p;
+
+ p = oldNode.previousSibling;
+ oldNode.previousSibling = null;
+ newNode.previousSibling = p;
+ if (newNode.previousSibling) {
+ newNode.previousSibling.nextSibling = newNode;
+ }
+
+ p = oldNode.nextSibling;
+ oldNode.nextSibling = null;
+ newNode.nextSibling = p;
+ if (newNode.nextSibling) {
+ newNode.nextSibling.previousSibling = newNode;
+ }
+
+ if (this.firstChild == oldNode) {
+ this.firstChild = newNode;
+ }
+
+ if (this.lastChild == oldNode) {
+ this.lastChild = newNode;
+ }
+
+ break;
+ }
+ }
+}
+
+XNode.prototype.insertBefore = function(newNode, oldNode) {
+ if (oldNode == newNode) {
+ return;
+ }
+
+ if (oldNode.parentNode != this) {
+ return;
+ }
+
+ if (newNode.parentNode) {
+ newNode.parentNode.removeChild(newNode);
+ }
+
+ var newChildren = [];
+ for (var i = 0; i < this.childNodes.length; ++i) {
+ var c = this.childNodes[i];
+ if (c == oldNode) {
+ newChildren.push(newNode);
+
+ newNode.parentNode = this;
+
+ newNode.previousSibling = oldNode.previousSibling;
+ oldNode.previousSibling = newNode;
+ if (newNode.previousSibling) {
+ newNode.previousSibling.nextSibling = newNode;
+ }
+
+ newNode.nextSibling = oldNode;
+
+ if (this.firstChild == oldNode) {
+ this.firstChild = newNode;
+ }
+ }
+ newChildren.push(c);
+ }
+ this.childNodes = newChildren;
+}
+
+XNode.prototype.removeChild = function(node) {
+ var newChildren = [];
+ for (var i = 0; i < this.childNodes.length; ++i) {
+ var c = this.childNodes[i];
+ if (c != node) {
+ newChildren.push(c);
+ } else {
+ if (c.previousSibling) {
+ c.previousSibling.nextSibling = c.nextSibling;
+ }
+ if (c.nextSibling) {
+ c.nextSibling.previousSibling = c.previousSibling;
+ }
+ if (this.firstChild == c) {
+ this.firstChild = c.nextSibling;
+ }
+ if (this.lastChild == c) {
+ this.lastChild = c.previousSibling;
+ }
+ }
+ }
+ this.childNodes = newChildren;
+}
+
+
+XNode.prototype.hasAttributes = function() {
+ return this.attributes.length > 0;
+}
+
+
+XNode.prototype.setAttribute = function(name, value) {
+ for (var i = 0; i < this.attributes.length; ++i) {
+ if (this.attributes[i].nodeName == name) {
+ this.attributes[i].nodeValue = '' + value;
+ return;
+ }
+ }
+ this.attributes.push(new XNode(DOM_ATTRIBUTE_NODE, name, value));
+}
+
+
+XNode.prototype.getAttribute = function(name) {
+ for (var i = 0; i < this.attributes.length; ++i) {
+ if (this.attributes[i].nodeName == name) {
+ return this.attributes[i].nodeValue;
+ }
+ }
+ return null;
+}
+
+XNode.prototype.removeAttribute = function(name) {
+ var a = [];
+ for (var i = 0; i < this.attributes.length; ++i) {
+ if (this.attributes[i].nodeName != name) {
+ a.push(this.attributes[i]);
+ }
+ }
+ this.attributes = a;
+}
+
+
+function XDocument() {
+ XNode.call(this, DOM_DOCUMENT_NODE, '#document', null, this);
+ this.documentElement = null;
+}
+
+XDocument.prototype = new XNode(DOM_DOCUMENT_NODE, '#document');
+
+XDocument.prototype.clear = function() {
+ XNode.recycle(this.documentElement);
+ this.documentElement = null;
+}
+
+XDocument.prototype.appendChild = function(node) {
+ XNode.prototype.appendChild.call(this, node);
+ this.documentElement = this.childNodes[0];
+}
+
+XDocument.prototype.createElement = function(name) {
+ return XNode.create(DOM_ELEMENT_NODE, name, null, this);
+}
+
+XDocument.prototype.createDocumentFragment = function() {
+ return XNode.create(DOM_DOCUMENT_FRAGMENT_NODE, '#document-fragment',
+ null, this);
+}
+
+XDocument.prototype.createTextNode = function(value) {
+ return XNode.create(DOM_TEXT_NODE, '#text', value, this);
+}
+
+XDocument.prototype.createAttribute = function(name) {
+ return XNode.create(DOM_ATTRIBUTE_NODE, name, null, this);
+}
+
+XDocument.prototype.createComment = function(data) {
+ return XNode.create(DOM_COMMENT_NODE, '#comment', data, this);
+}
+
+XNode.prototype.getElementsByTagName = function(name, list) {
+ if (!list) {
+ list = [];
+ }
+
+ if (this.nodeName == name) {
+ list.push(this);
+ }
+
+ for (var i = 0; i < this.childNodes.length; ++i) {
+ this.childNodes[i].getElementsByTagName(name, list);
+ }
+
+ return list;
+}
diff --git a/tests/test_tools/selenium/core/xpath/misc.js b/tests/test_tools/selenium/core/xpath/misc.js
new file mode 100644
index 00000000..b9573a22
--- /dev/null
+++ b/tests/test_tools/selenium/core/xpath/misc.js
@@ -0,0 +1,255 @@
+// Copyright 2005 Google Inc.
+// All Rights Reserved
+//
+// Miscellania that support the ajaxslt implementation.
+//
+// Author: Steffen Meschkat <mesch@google.com>
+//
+
+function el(i) {
+ return document.getElementById(i);
+}
+
+function px(x) {
+ return x + 'px';
+}
+
+// Split a string s at all occurrences of character c. This is like
+// the split() method of the string object, but IE omits empty
+// strings, which violates the invariant (s.split(x).join(x) == s).
+function stringSplit(s, c) {
+ var a = s.indexOf(c);
+ if (a == -1) {
+ return [ s ];
+ }
+
+ var parts = [];
+ parts.push(s.substr(0,a));
+ while (a != -1) {
+ var a1 = s.indexOf(c, a + 1);
+ if (a1 != -1) {
+ parts.push(s.substr(a + 1, a1 - a - 1));
+ } else {
+ parts.push(s.substr(a + 1));
+ }
+ a = a1;
+ }
+
+ return parts;
+}
+
+// Returns the text value if a node; for nodes without children this
+// is the nodeValue, for nodes with children this is the concatenation
+// of the value of all children.
+function xmlValue(node) {
+ if (!node) {
+ return '';
+ }
+
+ var ret = '';
+ if (node.nodeType == DOM_TEXT_NODE ||
+ node.nodeType == DOM_CDATA_SECTION_NODE ||
+ node.nodeType == DOM_ATTRIBUTE_NODE) {
+ ret += node.nodeValue;
+
+ } else if (node.nodeType == DOM_ELEMENT_NODE ||
+ node.nodeType == DOM_DOCUMENT_NODE ||
+ node.nodeType == DOM_DOCUMENT_FRAGMENT_NODE) {
+ for (var i = 0; i < node.childNodes.length; ++i) {
+ ret += arguments.callee(node.childNodes[i]);
+ }
+ }
+ return ret;
+}
+
+// Returns the representation of a node as XML text.
+function xmlText(node) {
+ var ret = '';
+ if (node.nodeType == DOM_TEXT_NODE) {
+ ret += xmlEscapeText(node.nodeValue);
+
+ } else if (node.nodeType == DOM_ELEMENT_NODE) {
+ ret += '<' + node.nodeName;
+ for (var i = 0; i < node.attributes.length; ++i) {
+ var a = node.attributes[i];
+ if (a && a.nodeName && a.nodeValue) {
+ ret += ' ' + a.nodeName;
+ ret += '="' + xmlEscapeAttr(a.nodeValue) + '"';
+ }
+ }
+
+ if (node.childNodes.length == 0) {
+ ret += '/>';
+
+ } else {
+ ret += '>';
+ for (var i = 0; i < node.childNodes.length; ++i) {
+ ret += arguments.callee(node.childNodes[i]);
+ }
+ ret += '</' + node.nodeName + '>';
+ }
+
+ } else if (node.nodeType == DOM_DOCUMENT_NODE ||
+ node.nodeType == DOM_DOCUMENT_FRAGMENT_NODE) {
+ for (var i = 0; i < node.childNodes.length; ++i) {
+ ret += arguments.callee(node.childNodes[i]);
+ }
+ }
+
+ return ret;
+}
+
+// Applies the given function to each element of the array.
+function mapExec(array, func) {
+ for (var i = 0; i < array.length; ++i) {
+ func(array[i]);
+ }
+}
+
+// Returns an array that contains the return value of the given
+// function applied to every element of the input array.
+function mapExpr(array, func) {
+ var ret = [];
+ for (var i = 0; i < array.length; ++i) {
+ ret.push(func(array[i]));
+ }
+ return ret;
+};
+
+// Reverses the given array in place.
+function reverseInplace(array) {
+ for (var i = 0; i < array.length / 2; ++i) {
+ var h = array[i];
+ var ii = array.length - i - 1;
+ array[i] = array[ii];
+ array[ii] = h;
+ }
+}
+
+// Shallow-copies an array.
+function copyArray(dst, src) {
+ for (var i = 0; i < src.length; ++i) {
+ dst.push(src[i]);
+ }
+}
+
+function assert(b) {
+ if (!b) {
+ throw 'assertion failed';
+ }
+}
+
+// Based on
+// <http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247>
+var DOM_ELEMENT_NODE = 1;
+var DOM_ATTRIBUTE_NODE = 2;
+var DOM_TEXT_NODE = 3;
+var DOM_CDATA_SECTION_NODE = 4;
+var DOM_ENTITY_REFERENCE_NODE = 5;
+var DOM_ENTITY_NODE = 6;
+var DOM_PROCESSING_INSTRUCTION_NODE = 7;
+var DOM_COMMENT_NODE = 8;
+var DOM_DOCUMENT_NODE = 9;
+var DOM_DOCUMENT_TYPE_NODE = 10;
+var DOM_DOCUMENT_FRAGMENT_NODE = 11;
+var DOM_NOTATION_NODE = 12;
+
+
+var xpathdebug = false; // trace xpath parsing
+var xsltdebug = false; // trace xslt processing
+
+
+// Escape XML special markup chracters: tag delimiter < > and entity
+// reference start delimiter &. The escaped string can be used in XML
+// text portions (i.e. between tags).
+function xmlEscapeText(s) {
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+}
+
+// Escape XML special markup characters: tag delimiter < > entity
+// reference start delimiter & and quotes ". The escaped string can be
+// used in double quoted XML attribute value portions (i.e. in
+// attributes within start tags).
+function xmlEscapeAttr(s) {
+ return xmlEscapeText(s).replace(/\"/g, '&quot;');
+}
+
+// Escape markup in XML text, but don't touch entity references. The
+// escaped string can be used as XML text (i.e. between tags).
+function xmlEscapeTags(s) {
+ return s.replace(/</g, '&lt;').replace(/>/g, '&gt;');
+}
+
+// An implementation of the debug log.
+
+var logging__ = false;
+
+function Log() {};
+
+Log.lines = [];
+
+Log.write = function(s) {
+ if (logging__) {
+ this.lines.push(xmlEscapeText(s));
+ this.show();
+ }
+};
+
+// Writes the given XML with every tag on a new line.
+Log.writeXML = function(xml) {
+ if (logging__) {
+ var s0 = xml.replace(/</g, '\n<');
+ var s1 = xmlEscapeText(s0);
+ var s2 = s1.replace(/\s*\n(\s|\n)*/g, '<br/>');
+ this.lines.push(s2);
+ this.show();
+ }
+}
+
+// Writes without any escaping
+Log.writeRaw = function(s) {
+ if (logging__) {
+ this.lines.push(s);
+ this.show();
+ }
+}
+
+Log.clear = function() {
+ if (logging__) {
+ var l = this.div();
+ l.innerHTML = '';
+ this.lines = [];
+ }
+}
+
+Log.show = function() {
+ var l = this.div();
+ l.innerHTML += this.lines.join('<br/>') + '<br/>';
+ this.lines = [];
+ l.scrollTop = l.scrollHeight;
+}
+
+Log.div = function() {
+ var l = document.getElementById('log');
+ if (!l) {
+ l = document.createElement('div');
+ l.id = 'log';
+ l.style.position = 'absolute';
+ l.style.right = '5px';
+ l.style.top = '5px';
+ l.style.width = '250px';
+ l.style.height = '150px';
+ l.style.overflow = 'auto';
+ l.style.backgroundColor = '#f0f0f0';
+ l.style.border = '1px solid gray';
+ l.style.fontSize = '10px';
+ l.style.padding = '5px';
+ document.body.appendChild(l);
+ }
+ return l;
+}
+
+
+function Timer() {}
+Timer.start = function() {}
+Timer.end = function() {}
diff --git a/tests/test_tools/selenium/core/xpath/xpath.js b/tests/test_tools/selenium/core/xpath/xpath.js
new file mode 100644
index 00000000..b93469f2
--- /dev/null
+++ b/tests/test_tools/selenium/core/xpath/xpath.js
@@ -0,0 +1,2182 @@
+// Copyright 2005 Google Inc.
+// All Rights Reserved
+//
+// An XPath parser and evaluator written in JavaScript. The
+// implementation is complete except for functions handling
+// namespaces.
+//
+// Reference: [XPATH] XPath Specification
+// <http://www.w3.org/TR/1999/REC-xpath-19991116>.
+//
+//
+// The API of the parser has several parts:
+//
+// 1. The parser function xpathParse() that takes a string and returns
+// an expession object.
+//
+// 2. The expression object that has an evaluate() method to evaluate the
+// XPath expression it represents. (It is actually a hierarchy of
+// objects that resembles the parse tree, but an application will call
+// evaluate() only on the top node of this hierarchy.)
+//
+// 3. The context object that is passed as an argument to the evaluate()
+// method, which represents the DOM context in which the expression is
+// evaluated.
+//
+// 4. The value object that is returned from evaluate() and represents
+// values of the different types that are defined by XPath (number,
+// string, boolean, and node-set), and allows to convert between them.
+//
+// These parts are near the top of the file, the functions and data
+// that are used internally follow after them.
+//
+//
+// TODO(mesch): add jsdoc comments. Use more coherent naming.
+//
+//
+// Author: Steffen Meschkat <mesch@google.com>
+
+
+// The entry point for the parser.
+//
+// @param expr a string that contains an XPath expression.
+// @return an expression object that can be evaluated with an
+// expression context.
+
+function xpathParse(expr) {
+ if (xpathdebug) {
+ Log.write('XPath parse ' + expr);
+ }
+ xpathParseInit();
+
+ var cached = xpathCacheLookup(expr);
+ if (cached) {
+ if (xpathdebug) {
+ Log.write(' ... cached');
+ }
+ return cached;
+ }
+
+ // Optimize for a few common cases: simple attribute node tests
+ // (@id), simple element node tests (page), variable references
+ // ($address), numbers (4), multi-step path expressions where each
+ // step is a plain element node test
+ // (page/overlay/locations/location).
+
+ if (expr.match(/^(\$|@)?\w+$/i)) {
+ var ret = makeSimpleExpr(expr);
+ xpathParseCache[expr] = ret;
+ if (xpathdebug) {
+ Log.write(' ... simple');
+ }
+ return ret;
+ }
+
+ if (expr.match(/^\w+(\/\w+)*$/i)) {
+ var ret = makeSimpleExpr2(expr);
+ xpathParseCache[expr] = ret;
+ if (xpathdebug) {
+ Log.write(' ... simple 2');
+ }
+ return ret;
+ }
+
+ var cachekey = expr; // expr is modified during parse
+ if (xpathdebug) {
+ Timer.start('XPath parse', cachekey);
+ }
+
+ var stack = [];
+ var ahead = null;
+ var previous = null;
+ var done = false;
+
+ var parse_count = 0;
+ var lexer_count = 0;
+ var reduce_count = 0;
+
+ while (!done) {
+ parse_count++;
+ expr = expr.replace(/^\s*/, '');
+ previous = ahead;
+ ahead = null;
+
+ var rule = null;
+ var match = '';
+ for (var i = 0; i < xpathTokenRules.length; ++i) {
+ var result = xpathTokenRules[i].re.exec(expr);
+ lexer_count++;
+ if (result && result.length > 0 && result[0].length > match.length) {
+ rule = xpathTokenRules[i];
+ match = result[0];
+ break;
+ }
+ }
+
+ // Special case: allow operator keywords to be element and
+ // variable names.
+
+ // NOTE(mesch): The parser resolves conflicts by looking ahead,
+ // and this is the only case where we look back to
+ // disambiguate. So this is indeed something different, and
+ // looking back is usually done in the lexer (via states in the
+ // general case, called "start conditions" in flex(1)). Also,the
+ // conflict resolution in the parser is not as robust as it could
+ // be, so I'd like to keep as much off the parser as possible (all
+ // these precedence values should be computed from the grammar
+ // rules and possibly associativity declarations, as in bison(1),
+ // and not explicitly set.
+
+ if (rule &&
+ (rule == TOK_DIV ||
+ rule == TOK_MOD ||
+ rule == TOK_AND ||
+ rule == TOK_OR) &&
+ (!previous ||
+ previous.tag == TOK_AT ||
+ previous.tag == TOK_DSLASH ||
+ previous.tag == TOK_SLASH ||
+ previous.tag == TOK_AXIS ||
+ previous.tag == TOK_DOLLAR)) {
+ rule = TOK_QNAME;
+ }
+
+ if (rule) {
+ expr = expr.substr(match.length);
+ if (xpathdebug) {
+ Log.write('token: ' + match + ' -- ' + rule.label);
+ }
+ ahead = {
+ tag: rule,
+ match: match,
+ prec: rule.prec ? rule.prec : 0, // || 0 is removed by the compiler
+ expr: makeTokenExpr(match)
+ };
+
+ } else {
+ if (xpathdebug) {
+ Log.write('DONE');
+ }
+ done = true;
+ }
+
+ while (xpathReduce(stack, ahead)) {
+ reduce_count++;
+ if (xpathdebug) {
+ Log.write('stack: ' + stackToString(stack));
+ }
+ }
+ }
+
+ if (xpathdebug) {
+ Log.write(stackToString(stack));
+ }
+
+ if (stack.length != 1) {
+ throw 'XPath parse error ' + cachekey + ':\n' + stackToString(stack);
+ }
+
+ var result = stack[0].expr;
+ xpathParseCache[cachekey] = result;
+
+ if (xpathdebug) {
+ Timer.end('XPath parse', cachekey);
+ }
+
+ if (xpathdebug) {
+ Log.write('XPath parse: ' + parse_count + ' / ' +
+ lexer_count + ' / ' + reduce_count);
+ }
+
+ return result;
+}
+
+var xpathParseCache = {};
+
+function xpathCacheLookup(expr) {
+ return xpathParseCache[expr];
+}
+
+function xpathReduce(stack, ahead) {
+ var cand = null;
+
+ if (stack.length > 0) {
+ var top = stack[stack.length-1];
+ var ruleset = xpathRules[top.tag.key];
+
+ if (ruleset) {
+ for (var i = 0; i < ruleset.length; ++i) {
+ var rule = ruleset[i];
+ var match = xpathMatchStack(stack, rule[1]);
+ if (match.length) {
+ cand = {
+ tag: rule[0],
+ rule: rule,
+ match: match
+ };
+ cand.prec = xpathGrammarPrecedence(cand);
+ break;
+ }
+ }
+ }
+ }
+
+ var ret;
+ if (cand && (!ahead || cand.prec > ahead.prec ||
+ (ahead.tag.left && cand.prec >= ahead.prec))) {
+ for (var i = 0; i < cand.match.matchlength; ++i) {
+ stack.pop();
+ }
+
+ if (xpathdebug) {
+ Log.write('reduce ' + cand.tag.label + ' ' + cand.prec +
+ ' ahead ' + (ahead ? ahead.tag.label + ' ' + ahead.prec +
+ (ahead.tag.left ? ' left' : '')
+ : ' none '));
+ }
+
+ var matchexpr = mapExpr(cand.match, function(m) { return m.expr; });
+ cand.expr = cand.rule[3].apply(null, matchexpr);
+
+ stack.push(cand);
+ ret = true;
+
+ } else {
+ if (ahead) {
+ if (xpathdebug) {
+ Log.write('shift ' + ahead.tag.label + ' ' + ahead.prec +
+ (ahead.tag.left ? ' left' : '') +
+ ' over ' + (cand ? cand.tag.label + ' ' +
+ cand.prec : ' none'));
+ }
+ stack.push(ahead);
+ }
+ ret = false;
+ }
+ return ret;
+}
+
+function xpathMatchStack(stack, pattern) {
+
+ // NOTE(mesch): The stack matches for variable cardinality are
+ // greedy but don't do backtracking. This would be an issue only
+ // with rules of the form A* A, i.e. with an element with variable
+ // cardinality followed by the same element. Since that doesn't
+ // occur in the grammar at hand, all matches on the stack are
+ // unambiguous.
+
+ var S = stack.length;
+ var P = pattern.length;
+ var p, s;
+ var match = [];
+ match.matchlength = 0;
+ var ds = 0;
+ for (p = P - 1, s = S - 1; p >= 0 && s >= 0; --p, s -= ds) {
+ ds = 0;
+ var qmatch = [];
+ if (pattern[p] == Q_MM) {
+ p -= 1;
+ match.push(qmatch);
+ while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) {
+ qmatch.push(stack[s - ds]);
+ ds += 1;
+ match.matchlength += 1;
+ }
+
+ } else if (pattern[p] == Q_01) {
+ p -= 1;
+ match.push(qmatch);
+ while (s - ds >= 0 && ds < 2 && stack[s - ds].tag == pattern[p]) {
+ qmatch.push(stack[s - ds]);
+ ds += 1;
+ match.matchlength += 1;
+ }
+
+ } else if (pattern[p] == Q_1M) {
+ p -= 1;
+ match.push(qmatch);
+ if (stack[s].tag == pattern[p]) {
+ while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) {
+ qmatch.push(stack[s - ds]);
+ ds += 1;
+ match.matchlength += 1;
+ }
+ } else {
+ return [];
+ }
+
+ } else if (stack[s].tag == pattern[p]) {
+ match.push(stack[s]);
+ ds += 1;
+ match.matchlength += 1;
+
+ } else {
+ return [];
+ }
+
+ reverseInplace(qmatch);
+ qmatch.expr = mapExpr(qmatch, function(m) { return m.expr; });
+ }
+
+ reverseInplace(match);
+
+ if (p == -1) {
+ return match;
+
+ } else {
+ return [];
+ }
+}
+
+function xpathTokenPrecedence(tag) {
+ return tag.prec || 2;
+}
+
+function xpathGrammarPrecedence(frame) {
+ var ret = 0;
+
+ if (frame.rule) { /* normal reduce */
+ if (frame.rule.length >= 3 && frame.rule[2] >= 0) {
+ ret = frame.rule[2];
+
+ } else {
+ for (var i = 0; i < frame.rule[1].length; ++i) {
+ var p = xpathTokenPrecedence(frame.rule[1][i]);
+ ret = Math.max(ret, p);
+ }
+ }
+ } else if (frame.tag) { /* TOKEN match */
+ ret = xpathTokenPrecedence(frame.tag);
+
+ } else if (frame.length) { /* Q_ match */
+ for (var j = 0; j < frame.length; ++j) {
+ var p = xpathGrammarPrecedence(frame[j]);
+ ret = Math.max(ret, p);
+ }
+ }
+
+ return ret;
+}
+
+function stackToString(stack) {
+ var ret = '';
+ for (var i = 0; i < stack.length; ++i) {
+ if (ret) {
+ ret += '\n';
+ }
+ ret += stack[i].tag.label;
+ }
+ return ret;
+}
+
+
+// XPath expression evaluation context. An XPath context consists of a
+// DOM node, a list of DOM nodes that contains this node, a number
+// that represents the position of the single node in the list, and a
+// current set of variable bindings. (See XPath spec.)
+//
+// The interface of the expression context:
+//
+// Constructor -- gets the node, its position, the node set it
+// belongs to, and a parent context as arguments. The parent context
+// is used to implement scoping rules for variables: if a variable
+// is not found in the current context, it is looked for in the
+// parent context, recursively. Except for node, all arguments have
+// default values: default position is 0, default node set is the
+// set that contains only the node, and the default parent is null.
+//
+// Notice that position starts at 0 at the outside interface;
+// inside XPath expressions this shows up as position()=1.
+//
+// clone() -- creates a new context with the current context as
+// parent. If passed as argument to clone(), the new context has a
+// different node, position, or node set. What is not passed is
+// inherited from the cloned context.
+//
+// setVariable(name, expr) -- binds given XPath expression to the
+// name.
+//
+// getVariable(name) -- what the name says.
+//
+// setNode(node, position) -- sets the context to the new node and
+// its corresponding position. Needed to implement scoping rules for
+// variables in XPath. (A variable is visible to all subsequent
+// siblings, not only to its children.)
+
+function ExprContext(node, position, nodelist, parent) {
+ this.node = node;
+ this.position = position || 0;
+ this.nodelist = nodelist || [ node ];
+ this.variables = {};
+ this.parent = parent || null;
+ this.root = parent ? parent.root : node.ownerDocument;
+}
+
+ExprContext.prototype.clone = function(node, position, nodelist) {
+ return new
+ ExprContext(node || this.node,
+ typeof position != 'undefined' ? position : this.position,
+ nodelist || this.nodelist, this);
+};
+
+ExprContext.prototype.setVariable = function(name, value) {
+ this.variables[name] = value;
+};
+
+ExprContext.prototype.getVariable = function(name) {
+ if (typeof this.variables[name] != 'undefined') {
+ return this.variables[name];
+
+ } else if (this.parent) {
+ return this.parent.getVariable(name);
+
+ } else {
+ return null;
+ }
+}
+
+ExprContext.prototype.setNode = function(node, position) {
+ this.node = node;
+ this.position = position;
+}
+
+
+// XPath expression values. They are what XPath expressions evaluate
+// to. Strangely, the different value types are not specified in the
+// XPath syntax, but only in the semantics, so they don't show up as
+// nonterminals in the grammar. Yet, some expressions are required to
+// evaluate to particular types, and not every type can be coerced
+// into every other type. Although the types of XPath values are
+// similar to the types present in JavaScript, the type coercion rules
+// are a bit peculiar, so we explicitly model XPath types instead of
+// mapping them onto JavaScript types. (See XPath spec.)
+//
+// The four types are:
+//
+// StringValue
+//
+// NumberValue
+//
+// BooleanValue
+//
+// NodeSetValue
+//
+// The common interface of the value classes consists of methods that
+// implement the XPath type coercion rules:
+//
+// stringValue() -- returns the value as a JavaScript String,
+//
+// numberValue() -- returns the value as a JavaScript Number,
+//
+// booleanValue() -- returns the value as a JavaScript Boolean,
+//
+// nodeSetValue() -- returns the value as a JavaScript Array of DOM
+// Node objects.
+//
+
+function StringValue(value) {
+ this.value = value;
+ this.type = 'string';
+}
+
+StringValue.prototype.stringValue = function() {
+ return this.value;
+}
+
+StringValue.prototype.booleanValue = function() {
+ return this.value.length > 0;
+}
+
+StringValue.prototype.numberValue = function() {
+ return this.value - 0;
+}
+
+StringValue.prototype.nodeSetValue = function() {
+ throw this + ' ' + Error().stack;
+}
+
+function BooleanValue(value) {
+ this.value = value;
+ this.type = 'boolean';
+}
+
+BooleanValue.prototype.stringValue = function() {
+ return '' + this.value;
+}
+
+BooleanValue.prototype.booleanValue = function() {
+ return this.value;
+}
+
+BooleanValue.prototype.numberValue = function() {
+ return this.value ? 1 : 0;
+}
+
+BooleanValue.prototype.nodeSetValue = function() {
+ throw this + ' ' + Error().stack;
+}
+
+function NumberValue(value) {
+ this.value = value;
+ this.type = 'number';
+}
+
+NumberValue.prototype.stringValue = function() {
+ return '' + this.value;
+}
+
+NumberValue.prototype.booleanValue = function() {
+ return !!this.value;
+}
+
+NumberValue.prototype.numberValue = function() {
+ return this.value - 0;
+}
+
+NumberValue.prototype.nodeSetValue = function() {
+ throw this + ' ' + Error().stack;
+}
+
+function NodeSetValue(value) {
+ this.value = value;
+ this.type = 'node-set';
+}
+
+NodeSetValue.prototype.stringValue = function() {
+ if (this.value.length == 0) {
+ return '';
+ } else {
+ return xmlValue(this.value[0]);
+ }
+}
+
+NodeSetValue.prototype.booleanValue = function() {
+ return this.value.length > 0;
+}
+
+NodeSetValue.prototype.numberValue = function() {
+ return this.stringValue() - 0;
+}
+
+NodeSetValue.prototype.nodeSetValue = function() {
+ return this.value;
+};
+
+// XPath expressions. They are used as nodes in the parse tree and
+// possess an evaluate() method to compute an XPath value given an XPath
+// context. Expressions are returned from the parser. Teh set of
+// expression classes closely mirrors the set of non terminal symbols
+// in the grammar. Every non trivial nonterminal symbol has a
+// corresponding expression class.
+//
+// The common expression interface consists of the following methods:
+//
+// evaluate(context) -- evaluates the expression, returns a value.
+//
+// toString() -- returns the XPath text representation of the
+// expression (defined in xsltdebug.js).
+//
+// parseTree(indent) -- returns a parse tree representation of the
+// expression (defined in xsltdebug.js).
+
+function TokenExpr(m) {
+ this.value = m;
+}
+
+TokenExpr.prototype.evaluate = function() {
+ return new StringValue(this.value);
+};
+
+function LocationExpr() {
+ this.absolute = false;
+ this.steps = [];
+}
+
+LocationExpr.prototype.appendStep = function(s) {
+ this.steps.push(s);
+}
+
+LocationExpr.prototype.prependStep = function(s) {
+ var steps0 = this.steps;
+ this.steps = [ s ];
+ for (var i = 0; i < steps0.length; ++i) {
+ this.steps.push(steps0[i]);
+ }
+};
+
+LocationExpr.prototype.evaluate = function(ctx) {
+ var start;
+ if (this.absolute) {
+ start = ctx.root;
+
+ } else {
+ start = ctx.node;
+ }
+
+ var nodes = [];
+ xPathStep(nodes, this.steps, 0, start, ctx);
+ return new NodeSetValue(nodes);
+};
+
+function xPathStep(nodes, steps, step, input, ctx) {
+ var s = steps[step];
+ var ctx2 = ctx.clone(input);
+ var nodelist = s.evaluate(ctx2).nodeSetValue();
+
+ for (var i = 0; i < nodelist.length; ++i) {
+ if (step == steps.length - 1) {
+ nodes.push(nodelist[i]);
+ } else {
+ xPathStep(nodes, steps, step + 1, nodelist[i], ctx);
+ }
+ }
+}
+
+function StepExpr(axis, nodetest, predicate) {
+ this.axis = axis;
+ this.nodetest = nodetest;
+ this.predicate = predicate || [];
+}
+
+StepExpr.prototype.appendPredicate = function(p) {
+ this.predicate.push(p);
+}
+
+StepExpr.prototype.evaluate = function(ctx) {
+ var input = ctx.node;
+ var nodelist = [];
+
+ // NOTE(mesch): When this was a switch() statement, it didn't work
+ // in Safari/2.0. Not sure why though; it resulted in the JavaScript
+ // console output "undefined" (without any line number or so).
+
+ if (this.axis == xpathAxis.ANCESTOR_OR_SELF) {
+ nodelist.push(input);
+ for (var n = input.parentNode; n; n = input.parentNode) {
+ nodelist.push(n);
+ }
+
+ } else if (this.axis == xpathAxis.ANCESTOR) {
+ for (var n = input.parentNode; n; n = input.parentNode) {
+ nodelist.push(n);
+ }
+
+ } else if (this.axis == xpathAxis.ATTRIBUTE) {
+ copyArray(nodelist, input.attributes);
+
+ } else if (this.axis == xpathAxis.CHILD) {
+ copyArray(nodelist, input.childNodes);
+
+ } else if (this.axis == xpathAxis.DESCENDANT_OR_SELF) {
+ nodelist.push(input);
+ xpathCollectDescendants(nodelist, input);
+
+ } else if (this.axis == xpathAxis.DESCENDANT) {
+ xpathCollectDescendants(nodelist, input);
+
+ } else if (this.axis == xpathAxis.FOLLOWING) {
+ for (var n = input.parentNode; n; n = n.parentNode) {
+ for (var nn = n.nextSibling; nn; nn = nn.nextSibling) {
+ nodelist.push(nn);
+ xpathCollectDescendants(nodelist, nn);
+ }
+ }
+
+ } else if (this.axis == xpathAxis.FOLLOWING_SIBLING) {
+ for (var n = input.nextSibling; n; n = input.nextSibling) {
+ nodelist.push(n);
+ }
+
+ } else if (this.axis == xpathAxis.NAMESPACE) {
+ alert('not implemented: axis namespace');
+
+ } else if (this.axis == xpathAxis.PARENT) {
+ if (input.parentNode) {
+ nodelist.push(input.parentNode);
+ }
+
+ } else if (this.axis == xpathAxis.PRECEDING) {
+ for (var n = input.parentNode; n; n = n.parentNode) {
+ for (var nn = n.previousSibling; nn; nn = nn.previousSibling) {
+ nodelist.push(nn);
+ xpathCollectDescendantsReverse(nodelist, nn);
+ }
+ }
+
+ } else if (this.axis == xpathAxis.PRECEDING_SIBLING) {
+ for (var n = input.previousSibling; n; n = input.previousSibling) {
+ nodelist.push(n);
+ }
+
+ } else if (this.axis == xpathAxis.SELF) {
+ nodelist.push(input);
+
+ } else {
+ throw 'ERROR -- NO SUCH AXIS: ' + this.axis;
+ }
+
+ // process node test
+ var nodelist0 = nodelist;
+ nodelist = [];
+ for (var i = 0; i < nodelist0.length; ++i) {
+ var n = nodelist0[i];
+ if (this.nodetest.evaluate(ctx.clone(n, i, nodelist0)).booleanValue()) {
+ nodelist.push(n);
+ }
+ }
+
+ // process predicates
+ for (var i = 0; i < this.predicate.length; ++i) {
+ var nodelist0 = nodelist;
+ nodelist = [];
+ for (var ii = 0; ii < nodelist0.length; ++ii) {
+ var n = nodelist0[ii];
+ if (this.predicate[i].evaluate(ctx.clone(n, ii, nodelist0)).booleanValue()) {
+ nodelist.push(n);
+ }
+ }
+ }
+
+ return new NodeSetValue(nodelist);
+};
+
+function NodeTestAny() {
+ this.value = new BooleanValue(true);
+}
+
+NodeTestAny.prototype.evaluate = function(ctx) {
+ return this.value;
+};
+
+function NodeTestElement() {}
+
+NodeTestElement.prototype.evaluate = function(ctx) {
+ return new BooleanValue(ctx.node.nodeType == DOM_ELEMENT_NODE);
+}
+
+function NodeTestText() {}
+
+NodeTestText.prototype.evaluate = function(ctx) {
+ return new BooleanValue(ctx.node.nodeType == DOM_TEXT_NODE);
+}
+
+function NodeTestComment() {}
+
+NodeTestComment.prototype.evaluate = function(ctx) {
+ return new BooleanValue(ctx.node.nodeType == DOM_COMMENT_NODE);
+}
+
+function NodeTestPI(target) {
+ this.target = target;
+}
+
+NodeTestPI.prototype.evaluate = function(ctx) {
+ return new
+ BooleanValue(ctx.node.nodeType == DOM_PROCESSING_INSTRUCTION_NODE &&
+ (!this.target || ctx.node.nodeName == this.target));
+}
+
+function NodeTestNC(nsprefix) {
+ this.regex = new RegExp("^" + nsprefix + ":");
+ this.nsprefix = nsprefix;
+}
+
+NodeTestNC.prototype.evaluate = function(ctx) {
+ var n = ctx.node;
+ return new BooleanValue(this.regex.match(n.nodeName));
+}
+
+function NodeTestName(name) {
+ this.name = name;
+}
+
+NodeTestName.prototype.evaluate = function(ctx) {
+ var n = ctx.node;
+ // NOTE (Patrick Lightbody): this change allows node selection to be case-insensitive
+ return new BooleanValue(n.nodeName.toUpperCase() == this.name.toUpperCase());
+}
+
+function PredicateExpr(expr) {
+ this.expr = expr;
+}
+
+PredicateExpr.prototype.evaluate = function(ctx) {
+ var v = this.expr.evaluate(ctx);
+ if (v.type == 'number') {
+ // NOTE(mesch): Internally, position is represented starting with
+ // 0, however in XPath position starts with 1. See functions
+ // position() and last().
+ return new BooleanValue(ctx.position == v.numberValue() - 1);
+ } else {
+ return new BooleanValue(v.booleanValue());
+ }
+};
+
+function FunctionCallExpr(name) {
+ this.name = name;
+ this.args = [];
+}
+
+FunctionCallExpr.prototype.appendArg = function(arg) {
+ this.args.push(arg);
+};
+
+FunctionCallExpr.prototype.evaluate = function(ctx) {
+ var fn = '' + this.name.value;
+ var f = this.xpathfunctions[fn];
+ if (f) {
+ return f.call(this, ctx);
+ } else {
+ Log.write('XPath NO SUCH FUNCTION ' + fn);
+ return new BooleanValue(false);
+ }
+};
+
+FunctionCallExpr.prototype.xpathfunctions = {
+ 'last': function(ctx) {
+ assert(this.args.length == 0);
+ // NOTE(mesch): XPath position starts at 1.
+ return new NumberValue(ctx.nodelist.length);
+ },
+
+ 'position': function(ctx) {
+ assert(this.args.length == 0);
+ // NOTE(mesch): XPath position starts at 1.
+ return new NumberValue(ctx.position + 1);
+ },
+
+ 'count': function(ctx) {
+ assert(this.args.length == 1);
+ var v = this.args[0].evaluate(ctx);
+ return new NumberValue(v.nodeSetValue().length);
+ },
+
+ 'id': function(ctx) {
+ assert(this.args.length == 1);
+ var e = this.args.evaluate(ctx);
+ var ret = [];
+ var ids;
+ if (e.type == 'node-set') {
+ ids = [];
+ for (var i = 0; i < e.length; ++i) {
+ var v = xmlValue(e[i]).split(/\s+/);
+ for (var ii = 0; ii < v.length; ++ii) {
+ ids.push(v[ii]);
+ }
+ }
+ } else {
+ ids = e.split(/\s+/);
+ }
+ var d = ctx.node.ownerDocument;
+ for (var i = 0; i < ids.length; ++i) {
+ var n = d.getElementById(ids[i]);
+ if (n) {
+ ret.push(n);
+ }
+ }
+ return new NodeSetValue(ret);
+ },
+
+ 'local-name': function(ctx) {
+ alert('not implmented yet: XPath function local-name()');
+ },
+
+ 'namespace-uri': function(ctx) {
+ alert('not implmented yet: XPath function namespace-uri()');
+ },
+
+ 'name': function(ctx) {
+ assert(this.args.length == 1 || this.args.length == 0);
+ var n;
+ if (this.args.length == 0) {
+ n = [ ctx.node ];
+ } else {
+ n = this.args[0].evaluate(ctx).nodeSetValue();
+ }
+
+ if (n.length == 0) {
+ return new StringValue('');
+ } else {
+ return new StringValue(n[0].nodeName);
+ }
+ },
+
+ 'string': function(ctx) {
+ assert(this.args.length == 1 || this.args.length == 0);
+ if (this.args.length == 0) {
+ return new StringValue(new NodeSetValue([ ctx.node ]).stringValue());
+ } else {
+ return new StringValue(this.args[0].evaluate(ctx).stringValue());
+ }
+ },
+
+ 'concat': function(ctx) {
+ var ret = '';
+ for (var i = 0; i < this.args.length; ++i) {
+ ret += this.args[i].evaluate(ctx).stringValue();
+ }
+ return new StringValue(ret);
+ },
+
+ 'starts-with': function(ctx) {
+ assert(this.args.length == 2);
+ var s0 = this.args[0].evaluate(ctx).stringValue();
+ var s1 = this.args[1].evaluate(ctx).stringValue();
+ return new BooleanValue(s0.indexOf(s1) == 0);
+ },
+
+ 'contains': function(ctx) {
+ assert(this.args.length == 2);
+ var s0 = this.args[0].evaluate(ctx).stringValue();
+ var s1 = this.args[1].evaluate(ctx).stringValue();
+ return new BooleanValue(s0.indexOf(s1) != -1);
+ },
+
+ 'substring-before': function(ctx) {
+ assert(this.args.length == 2);
+ var s0 = this.args[0].evaluate(ctx).stringValue();
+ var s1 = this.args[1].evaluate(ctx).stringValue();
+ var i = s0.indexOf(s1);
+ var ret;
+ if (i == -1) {
+ ret = '';
+ } else {
+ ret = s0.substr(0,i);
+ }
+ return new StringValue(ret);
+ },
+
+ 'substring-after': function(ctx) {
+ assert(this.args.length == 2);
+ var s0 = this.args[0].evaluate(ctx).stringValue();
+ var s1 = this.args[1].evaluate(ctx).stringValue();
+ var i = s0.indexOf(s1);
+ var ret;
+ if (i == -1) {
+ ret = '';
+ } else {
+ ret = s0.substr(i + s1.length);
+ }
+ return new StringValue(ret);
+ },
+
+ 'substring': function(ctx) {
+ // NOTE: XPath defines the position of the first character in a
+ // string to be 1, in JavaScript this is 0 ([XPATH] Section 4.2).
+ assert(this.args.length == 2 || this.args.length == 3);
+ var s0 = this.args[0].evaluate(ctx).stringValue();
+ var s1 = this.args[1].evaluate(ctx).numberValue();
+ var ret;
+ if (this.args.length == 2) {
+ var i1 = Math.max(0, Math.round(s1) - 1);
+ ret = s0.substr(i1);
+
+ } else {
+ var s2 = this.args[2].evaluate(ctx).numberValue();
+ var i0 = Math.round(s1) - 1;
+ var i1 = Math.max(0, i0);
+ var i2 = Math.round(s2) - Math.max(0, -i0);
+ ret = s0.substr(i1, i2);
+ }
+ return new StringValue(ret);
+ },
+
+ 'string-length': function(ctx) {
+ var s;
+ if (this.args.length > 0) {
+ s = this.args[0].evaluate(ctx).stringValue();
+ } else {
+ s = new NodeSetValue([ ctx.node ]).stringValue();
+ }
+ return new NumberValue(s.length);
+ },
+
+ 'normalize-space': function(ctx) {
+ var s;
+ if (this.args.length > 0) {
+ s = this.args[0].evaluate(ctx).stringValue();
+ } else {
+ s = new NodeSetValue([ ctx.node ]).stringValue();
+ }
+ s = s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g, ' ');
+ return new StringValue(s);
+ },
+
+ 'translate': function(ctx) {
+ assert(this.args.length == 3);
+ var s0 = this.args[0].evaluate(ctx).stringValue();
+ var s1 = this.args[1].evaluate(ctx).stringValue();
+ var s2 = this.args[2].evaluate(ctx).stringValue();
+
+ for (var i = 0; i < s1.length; ++i) {
+ s0 = s0.replace(new RegExp(s1.charAt(i), 'g'), s2.charAt(i));
+ }
+ return new StringValue(s0);
+ },
+
+ 'boolean': function(ctx) {
+ assert(this.args.length == 1);
+ return new BooleanValue(this.args[0].evaluate(ctx).booleanValue());
+ },
+
+ 'not': function(ctx) {
+ assert(this.args.length == 1);
+ var ret = !this.args[0].evaluate(ctx).booleanValue();
+ return new BooleanValue(ret);
+ },
+
+ 'true': function(ctx) {
+ assert(this.args.length == 0);
+ return new BooleanValue(true);
+ },
+
+ 'false': function(ctx) {
+ assert(this.args.length == 0);
+ return new BooleanValue(false);
+ },
+
+ 'lang': function(ctx) {
+ assert(this.args.length == 1);
+ var lang = this.args[0].evaluate(ctx).stringValue();
+ var xmllang;
+ var n = ctx.node;
+ while (n && n != n.parentNode /* just in case ... */) {
+ xmllang = n.getAttribute('xml:lang');
+ if (xmllang) {
+ break;
+ }
+ n = n.parentNode;
+ }
+ if (!xmllang) {
+ return new BooleanValue(false);
+ } else {
+ var re = new RegExp('^' + lang + '$', 'i');
+ return new BooleanValue(xmllang.match(re) ||
+ xmllang.replace(/_.*$/,'').match(re));
+ }
+ },
+
+ 'number': function(ctx) {
+ assert(this.args.length == 1 || this.args.length == 0);
+
+ if (this.args.length == 1) {
+ return new NumberValue(this.args[0].evaluate(ctx).numberValue());
+ } else {
+ return new NumberValue(new NodeSetValue([ ctx.node ]).numberValue());
+ }
+ },
+
+ 'sum': function(ctx) {
+ assert(this.args.length == 1);
+ var n = this.args[0].evaluate(ctx).nodeSetValue();
+ var sum = 0;
+ for (var i = 0; i < n.length; ++i) {
+ sum += xmlValue(n[i]) - 0;
+ }
+ return new NumberValue(sum);
+ },
+
+ 'floor': function(ctx) {
+ assert(this.args.length == 1);
+ var num = this.args[0].evaluate(ctx).numberValue();
+ return new NumberValue(Math.floor(num));
+ },
+
+ 'ceiling': function(ctx) {
+ assert(this.args.length == 1);
+ var num = this.args[0].evaluate(ctx).numberValue();
+ return new NumberValue(Math.ceil(num));
+ },
+
+ 'round': function(ctx) {
+ assert(this.args.length == 1);
+ var num = this.args[0].evaluate(ctx).numberValue();
+ return new NumberValue(Math.round(num));
+ },
+
+ // TODO(mesch): The following functions are custom. There is a
+ // standard that defines how to add functions, which should be
+ // applied here.
+
+ 'ext-join': function(ctx) {
+ assert(this.args.length == 2);
+ var nodes = this.args[0].evaluate(ctx).nodeSetValue();
+ var delim = this.args[1].evaluate(ctx).stringValue();
+ var ret = '';
+ for (var i = 0; i < nodes.length; ++i) {
+ if (ret) {
+ ret += delim;
+ }
+ ret += xmlValue(nodes[i]);
+ }
+ return new StringValue(ret);
+ },
+
+ // ext-if() evaluates and returns its second argument, if the
+ // boolean value of its first argument is true, otherwise it
+ // evaluates and returns its third argument.
+
+ 'ext-if': function(ctx) {
+ assert(this.args.length == 3);
+ if (this.args[0].evaluate(ctx).booleanValue()) {
+ return this.args[1].evaluate(ctx);
+ } else {
+ return this.args[2].evaluate(ctx);
+ }
+ },
+
+ 'ext-sprintf': function(ctx) {
+ assert(this.args.length >= 1);
+ var args = [];
+ for (var i = 0; i < this.args.length; ++i) {
+ args.push(this.args[i].evaluate(ctx).stringValue());
+ }
+ return new StringValue(sprintf.apply(null, args));
+ },
+
+ // ext-cardinal() evaluates its single argument as a number, and
+ // returns the current node that many times. It can be used in the
+ // select attribute to iterate over an integer range.
+
+ 'ext-cardinal': function(ctx) {
+ assert(this.args.length >= 1);
+ var c = this.args[0].evaluate(ctx).numberValue();
+ var ret = [];
+ for (var i = 0; i < c; ++i) {
+ ret.push(ctx.node);
+ }
+ return new NodeSetValue(ret);
+ }
+};
+
+function UnionExpr(expr1, expr2) {
+ this.expr1 = expr1;
+ this.expr2 = expr2;
+}
+
+UnionExpr.prototype.evaluate = function(ctx) {
+ var nodes1 = this.expr1.evaluate(ctx).nodeSetValue();
+ var nodes2 = this.expr2.evaluate(ctx).nodeSetValue();
+ var I1 = nodes1.length;
+ for (var i2 = 0; i2 < nodes2.length; ++i2) {
+ for (var i1 = 0; i1 < I1; ++i1) {
+ if (nodes1[i1] == nodes2[i2]) {
+ // break inner loop and continue outer loop, labels confuse
+ // the js compiler, so we don't use them here.
+ i1 = I1;
+ }
+ }
+ nodes1.push(nodes2[i2]);
+ }
+ return new NodeSetValue(nodes2);
+};
+
+function PathExpr(filter, rel) {
+ this.filter = filter;
+ this.rel = rel;
+}
+
+PathExpr.prototype.evaluate = function(ctx) {
+ var nodes = this.filter.evaluate(ctx).nodeSetValue();
+ var nodes1 = [];
+ for (var i = 0; i < nodes.length; ++i) {
+ var nodes0 = this.rel.evaluate(ctx.clone(nodes[i], i, nodes)).nodeSetValue();
+ for (var ii = 0; ii < nodes0.length; ++ii) {
+ nodes1.push(nodes0[ii]);
+ }
+ }
+ return new NodeSetValue(nodes1);
+};
+
+function FilterExpr(expr, predicate) {
+ this.expr = expr;
+ this.predicate = predicate;
+}
+
+FilterExpr.prototype.evaluate = function(ctx) {
+ var nodes = this.expr.evaluate(ctx).nodeSetValue();
+ for (var i = 0; i < this.predicate.length; ++i) {
+ var nodes0 = nodes;
+ nodes = [];
+ for (var j = 0; j < nodes0.length; ++j) {
+ var n = nodes0[j];
+ if (this.predicate[i].evaluate(ctx.clone(n, j, nodes0)).booleanValue()) {
+ nodes.push(n);
+ }
+ }
+ }
+
+ return new NodeSetValue(nodes);
+}
+
+function UnaryMinusExpr(expr) {
+ this.expr = expr;
+}
+
+UnaryMinusExpr.prototype.evaluate = function(ctx) {
+ return new NumberValue(-this.expr.evaluate(ctx).numberValue());
+};
+
+function BinaryExpr(expr1, op, expr2) {
+ this.expr1 = expr1;
+ this.expr2 = expr2;
+ this.op = op;
+}
+
+BinaryExpr.prototype.evaluate = function(ctx) {
+ var ret;
+ switch (this.op.value) {
+ case 'or':
+ ret = new BooleanValue(this.expr1.evaluate(ctx).booleanValue() ||
+ this.expr2.evaluate(ctx).booleanValue());
+ break;
+
+ case 'and':
+ ret = new BooleanValue(this.expr1.evaluate(ctx).booleanValue() &&
+ this.expr2.evaluate(ctx).booleanValue());
+ break;
+
+ case '+':
+ ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() +
+ this.expr2.evaluate(ctx).numberValue());
+ break;
+
+ case '-':
+ ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() -
+ this.expr2.evaluate(ctx).numberValue());
+ break;
+
+ case '*':
+ ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() *
+ this.expr2.evaluate(ctx).numberValue());
+ break;
+
+ case 'mod':
+ ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() %
+ this.expr2.evaluate(ctx).numberValue());
+ break;
+
+ case 'div':
+ ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() /
+ this.expr2.evaluate(ctx).numberValue());
+ break;
+
+ case '=':
+ ret = this.compare(ctx, function(x1, x2) { return x1 == x2; });
+ break;
+
+ case '!=':
+ ret = this.compare(ctx, function(x1, x2) { return x1 != x2; });
+ break;
+
+ case '<':
+ ret = this.compare(ctx, function(x1, x2) { return x1 < x2; });
+ break;
+
+ case '<=':
+ ret = this.compare(ctx, function(x1, x2) { return x1 <= x2; });
+ break;
+
+ case '>':
+ ret = this.compare(ctx, function(x1, x2) { return x1 > x2; });
+ break;
+
+ case '>=':
+ ret = this.compare(ctx, function(x1, x2) { return x1 >= x2; });
+ break;
+
+ default:
+ alert('BinaryExpr.evaluate: ' + this.op.value);
+ }
+ return ret;
+};
+
+BinaryExpr.prototype.compare = function(ctx, cmp) {
+ var v1 = this.expr1.evaluate(ctx);
+ var v2 = this.expr2.evaluate(ctx);
+
+ var ret;
+ if (v1.type == 'node-set' && v2.type == 'node-set') {
+ var n1 = v1.nodeSetValue();
+ var n2 = v2.nodeSetValue();
+ ret = false;
+ for (var i1 = 0; i1 < n1.length; ++i1) {
+ for (var i2 = 0; i2 < n2.length; ++i2) {
+ if (cmp(xmlValue(n1[i1]), xmlValue(n2[i2]))) {
+ ret = true;
+ // Break outer loop. Labels confuse the jscompiler and we
+ // don't use them.
+ i2 = n2.length;
+ i1 = n1.length;
+ }
+ }
+ }
+
+ } else if (v1.type == 'node-set' || v2.type == 'node-set') {
+
+ if (v1.type == 'number') {
+ var s = v1.numberValue();
+ var n = v2.nodeSetValue();
+
+ ret = false;
+ for (var i = 0; i < n.length; ++i) {
+ var nn = xmlValue(n[i]) - 0;
+ if (cmp(s, nn)) {
+ ret = true;
+ break;
+ }
+ }
+
+ } else if (v2.type == 'number') {
+ var n = v1.nodeSetValue();
+ var s = v2.numberValue();
+
+ ret = false;
+ for (var i = 0; i < n.length; ++i) {
+ var nn = xmlValue(n[i]) - 0;
+ if (cmp(nn, s)) {
+ ret = true;
+ break;
+ }
+ }
+
+ } else if (v1.type == 'string') {
+ var s = v1.stringValue();
+ var n = v2.nodeSetValue();
+
+ ret = false;
+ for (var i = 0; i < n.length; ++i) {
+ var nn = xmlValue(n[i]);
+ if (cmp(s, nn)) {
+ ret = true;
+ break;
+ }
+ }
+
+ } else if (v2.type == 'string') {
+ var n = v1.nodeSetValue();
+ var s = v2.stringValue();
+
+ ret = false;
+ for (var i = 0; i < n.length; ++i) {
+ var nn = xmlValue(n[i]);
+ if (cmp(nn, s)) {
+ ret = true;
+ break;
+ }
+ }
+
+ } else {
+ ret = cmp(v1.booleanValue(), v2.booleanValue());
+ }
+
+ } else if (v1.type == 'boolean' || v2.type == 'boolean') {
+ ret = cmp(v1.booleanValue(), v2.booleanValue());
+
+ } else if (v1.type == 'number' || v2.type == 'number') {
+ ret = cmp(v1.numberValue(), v2.numberValue());
+
+ } else {
+ ret = cmp(v1.stringValue(), v2.stringValue());
+ }
+
+ return new BooleanValue(ret);
+}
+
+function LiteralExpr(value) {
+ this.value = value;
+}
+
+LiteralExpr.prototype.evaluate = function(ctx) {
+ return new StringValue(this.value);
+};
+
+function NumberExpr(value) {
+ this.value = value;
+}
+
+NumberExpr.prototype.evaluate = function(ctx) {
+ return new NumberValue(this.value);
+};
+
+function VariableExpr(name) {
+ this.name = name;
+}
+
+VariableExpr.prototype.evaluate = function(ctx) {
+ return ctx.getVariable(this.name);
+}
+
+// Factory functions for semantic values (i.e. Expressions) of the
+// productions in the grammar. When a production is matched to reduce
+// the current parse state stack, the function is called with the
+// semantic values of the matched elements as arguments, and returns
+// another semantic value. The semantic value is a node of the parse
+// tree, an expression object with an evaluate() method that evaluates the
+// expression in an actual context. These factory functions are used
+// in the specification of the grammar rules, below.
+
+function makeTokenExpr(m) {
+ return new TokenExpr(m);
+}
+
+function passExpr(e) {
+ return e;
+}
+
+function makeLocationExpr1(slash, rel) {
+ rel.absolute = true;
+ return rel;
+}
+
+function makeLocationExpr2(dslash, rel) {
+ rel.absolute = true;
+ rel.prependStep(makeAbbrevStep(dslash.value));
+ return rel;
+}
+
+function makeLocationExpr3(slash) {
+ var ret = new LocationExpr();
+ ret.appendStep(makeAbbrevStep('.'));
+ ret.absolute = true;
+ return ret;
+}
+
+function makeLocationExpr4(dslash) {
+ var ret = new LocationExpr();
+ ret.absolute = true;
+ ret.appendStep(makeAbbrevStep(dslash.value));
+ return ret;
+}
+
+function makeLocationExpr5(step) {
+ var ret = new LocationExpr();
+ ret.appendStep(step);
+ return ret;
+}
+
+function makeLocationExpr6(rel, slash, step) {
+ rel.appendStep(step);
+ return rel;
+}
+
+function makeLocationExpr7(rel, dslash, step) {
+ rel.appendStep(makeAbbrevStep(dslash.value));
+ return rel;
+}
+
+function makeStepExpr1(dot) {
+ return makeAbbrevStep(dot.value);
+}
+
+function makeStepExpr2(ddot) {
+ return makeAbbrevStep(ddot.value);
+}
+
+function makeStepExpr3(axisname, axis, nodetest) {
+ return new StepExpr(axisname.value, nodetest);
+}
+
+function makeStepExpr4(at, nodetest) {
+ return new StepExpr('attribute', nodetest);
+}
+
+function makeStepExpr5(nodetest) {
+ return new StepExpr('child', nodetest);
+}
+
+function makeStepExpr6(step, predicate) {
+ step.appendPredicate(predicate);
+ return step;
+}
+
+function makeAbbrevStep(abbrev) {
+ switch (abbrev) {
+ case '//':
+ return new StepExpr('descendant-or-self', new NodeTestAny);
+
+ case '.':
+ return new StepExpr('self', new NodeTestAny);
+
+ case '..':
+ return new StepExpr('parent', new NodeTestAny);
+ }
+}
+
+function makeNodeTestExpr1(asterisk) {
+ return new NodeTestElement;
+}
+
+function makeNodeTestExpr2(ncname, colon, asterisk) {
+ return new NodeTestNC(ncname.value);
+}
+
+function makeNodeTestExpr3(qname) {
+ return new NodeTestName(qname.value);
+}
+
+function makeNodeTestExpr4(typeo, parenc) {
+ var type = typeo.value.replace(/\s*\($/, '');
+ switch(type) {
+ case 'node':
+ return new NodeTestAny;
+
+ case 'text':
+ return new NodeTestText;
+
+ case 'comment':
+ return new NodeTestComment;
+
+ case 'processing-instruction':
+ return new NodeTestPI;
+ }
+}
+
+function makeNodeTestExpr5(typeo, target, parenc) {
+ var type = typeo.replace(/\s*\($/, '');
+ if (type != 'processing-instruction') {
+ throw type + ' ' + Error().stack;
+ }
+ return new NodeTestPI(target.value);
+}
+
+function makePredicateExpr(pareno, expr, parenc) {
+ return new PredicateExpr(expr);
+}
+
+function makePrimaryExpr(pareno, expr, parenc) {
+ return expr;
+}
+
+function makeFunctionCallExpr1(name, pareno, parenc) {
+ return new FunctionCallExpr(name);
+}
+
+function makeFunctionCallExpr2(name, pareno, arg1, args, parenc) {
+ var ret = new FunctionCallExpr(name);
+ ret.appendArg(arg1);
+ for (var i = 0; i < args.length; ++i) {
+ ret.appendArg(args[i]);
+ }
+ return ret;
+}
+
+function makeArgumentExpr(comma, expr) {
+ return expr;
+}
+
+function makeUnionExpr(expr1, pipe, expr2) {
+ return new UnionExpr(expr1, expr2);
+}
+
+function makePathExpr1(filter, slash, rel) {
+ return new PathExpr(filter, rel);
+}
+
+function makePathExpr2(filter, dslash, rel) {
+ rel.prependStep(makeAbbrevStep(dslash.value));
+ return new PathExpr(filter, rel);
+}
+
+function makeFilterExpr(expr, predicates) {
+ if (predicates.length > 0) {
+ return new FilterExpr(expr, predicates);
+ } else {
+ return expr;
+ }
+}
+
+function makeUnaryMinusExpr(minus, expr) {
+ return new UnaryMinusExpr(expr);
+}
+
+function makeBinaryExpr(expr1, op, expr2) {
+ return new BinaryExpr(expr1, op, expr2);
+}
+
+function makeLiteralExpr(token) {
+ // remove quotes from the parsed value:
+ var value = token.value.substring(1, token.value.length - 1);
+ return new LiteralExpr(value);
+}
+
+function makeNumberExpr(token) {
+ return new NumberExpr(token.value);
+}
+
+function makeVariableReference(dollar, name) {
+ return new VariableExpr(name.value);
+}
+
+// Used before parsing for optimization of common simple cases. See
+// the begin of xpathParse() for which they are.
+function makeSimpleExpr(expr) {
+ if (expr.charAt(0) == '$') {
+ return new VariableExpr(expr.substr(1));
+ } else if (expr.charAt(0) == '@') {
+ var a = new NodeTestName(expr.substr(1));
+ var b = new StepExpr('attribute', a);
+ var c = new LocationExpr();
+ c.appendStep(b);
+ return c;
+ } else if (expr.match(/^[0-9]+$/)) {
+ return new NumberExpr(expr);
+ } else {
+ var a = new NodeTestName(expr);
+ var b = new StepExpr('child', a);
+ var c = new LocationExpr();
+ c.appendStep(b);
+ return c;
+ }
+}
+
+function makeSimpleExpr2(expr) {
+ var steps = expr.split('/');
+ var c = new LocationExpr();
+ for (var i in steps) {
+ var a = new NodeTestName(steps[i]);
+ var b = new StepExpr('child', a);
+ c.appendStep(b);
+ }
+ return c;
+}
+
+// The axes of XPath expressions.
+
+var xpathAxis = {
+ ANCESTOR_OR_SELF: 'ancestor-or-self',
+ ANCESTOR: 'ancestor',
+ ATTRIBUTE: 'attribute',
+ CHILD: 'child',
+ DESCENDANT_OR_SELF: 'descendant-or-self',
+ DESCENDANT: 'descendant',
+ FOLLOWING_SIBLING: 'following-sibling',
+ FOLLOWING: 'following',
+ NAMESPACE: 'namespace',
+ PARENT: 'parent',
+ PRECEDING_SIBLING: 'preceding-sibling',
+ PRECEDING: 'preceding',
+ SELF: 'self'
+};
+
+var xpathAxesRe = [
+ xpathAxis.ANCESTOR_OR_SELF,
+ xpathAxis.ANCESTOR,
+ xpathAxis.ATTRIBUTE,
+ xpathAxis.CHILD,
+ xpathAxis.DESCENDANT_OR_SELF,
+ xpathAxis.DESCENDANT,
+ xpathAxis.FOLLOWING_SIBLING,
+ xpathAxis.FOLLOWING,
+ xpathAxis.NAMESPACE,
+ xpathAxis.PARENT,
+ xpathAxis.PRECEDING_SIBLING,
+ xpathAxis.PRECEDING,
+ xpathAxis.SELF
+].join('|');
+
+
+// The tokens of the language. The label property is just used for
+// generating debug output. The prec property is the precedence used
+// for shift/reduce resolution. Default precedence is 0 as a lookahead
+// token and 2 on the stack. TODO(mesch): this is certainly not
+// necessary and too complicated. Simplify this!
+
+// NOTE: tabular formatting is the big exception, but here it should
+// be OK.
+
+var TOK_PIPE = { label: "|", prec: 17, re: new RegExp("^\\|") };
+var TOK_DSLASH = { label: "//", prec: 19, re: new RegExp("^//") };
+var TOK_SLASH = { label: "/", prec: 30, re: new RegExp("^/") };
+var TOK_AXIS = { label: "::", prec: 20, re: new RegExp("^::") };
+var TOK_COLON = { label: ":", prec: 1000, re: new RegExp("^:") };
+var TOK_AXISNAME = { label: "[axis]", re: new RegExp('^(' + xpathAxesRe + ')') };
+var TOK_PARENO = { label: "(", prec: 34, re: new RegExp("^\\(") };
+var TOK_PARENC = { label: ")", re: new RegExp("^\\)") };
+var TOK_DDOT = { label: "..", prec: 34, re: new RegExp("^\\.\\.") };
+var TOK_DOT = { label: ".", prec: 34, re: new RegExp("^\\.") };
+var TOK_AT = { label: "@", prec: 34, re: new RegExp("^@") };
+
+var TOK_COMMA = { label: ",", re: new RegExp("^,") };
+
+var TOK_OR = { label: "or", prec: 10, re: new RegExp("^or\\b") };
+var TOK_AND = { label: "and", prec: 11, re: new RegExp("^and\\b") };
+var TOK_EQ = { label: "=", prec: 12, re: new RegExp("^=") };
+var TOK_NEQ = { label: "!=", prec: 12, re: new RegExp("^!=") };
+var TOK_GE = { label: ">=", prec: 13, re: new RegExp("^>=") };
+var TOK_GT = { label: ">", prec: 13, re: new RegExp("^>") };
+var TOK_LE = { label: "<=", prec: 13, re: new RegExp("^<=") };
+var TOK_LT = { label: "<", prec: 13, re: new RegExp("^<") };
+var TOK_PLUS = { label: "+", prec: 14, re: new RegExp("^\\+"), left: true };
+var TOK_MINUS = { label: "-", prec: 14, re: new RegExp("^\\-"), left: true };
+var TOK_DIV = { label: "div", prec: 15, re: new RegExp("^div\\b"), left: true };
+var TOK_MOD = { label: "mod", prec: 15, re: new RegExp("^mod\\b"), left: true };
+
+var TOK_BRACKO = { label: "[", prec: 32, re: new RegExp("^\\[") };
+var TOK_BRACKC = { label: "]", re: new RegExp("^\\]") };
+var TOK_DOLLAR = { label: "$", re: new RegExp("^\\$") };
+
+var TOK_NCNAME = { label: "[ncname]", re: new RegExp('^[a-z][-\\w]*','i') };
+
+var TOK_ASTERISK = { label: "*", prec: 15, re: new RegExp("^\\*"), left: true };
+var TOK_LITERALQ = { label: "[litq]", prec: 20, re: new RegExp("^'[^\\']*'") };
+var TOK_LITERALQQ = {
+ label: "[litqq]",
+ prec: 20,
+ re: new RegExp('^"[^\\"]*"')
+};
+
+var TOK_NUMBER = {
+ label: "[number]",
+ prec: 35,
+ re: new RegExp('^\\d+(\\.\\d*)?') };
+
+var TOK_QNAME = {
+ label: "[qname]",
+ re: new RegExp('^([a-z][-\\w]*:)?[a-z][-\\w]*','i')
+};
+
+var TOK_NODEO = {
+ label: "[nodetest-start]",
+ re: new RegExp('^(processing-instruction|comment|text|node)\\(')
+};
+
+// The table of the tokens of our grammar, used by the lexer: first
+// column the tag, second column a regexp to recognize it in the
+// input, third column the precedence of the token, fourth column a
+// factory function for the semantic value of the token.
+//
+// NOTE: order of this list is important, because the first match
+// counts. Cf. DDOT and DOT, and AXIS and COLON.
+
+var xpathTokenRules = [
+ TOK_DSLASH,
+ TOK_SLASH,
+ TOK_DDOT,
+ TOK_DOT,
+ TOK_AXIS,
+ TOK_COLON,
+ TOK_AXISNAME,
+ TOK_NODEO,
+ TOK_PARENO,
+ TOK_PARENC,
+ TOK_BRACKO,
+ TOK_BRACKC,
+ TOK_AT,
+ TOK_COMMA,
+ TOK_OR,
+ TOK_AND,
+ TOK_NEQ,
+ TOK_EQ,
+ TOK_GE,
+ TOK_GT,
+ TOK_LE,
+ TOK_LT,
+ TOK_PLUS,
+ TOK_MINUS,
+ TOK_ASTERISK,
+ TOK_PIPE,
+ TOK_MOD,
+ TOK_DIV,
+ TOK_LITERALQ,
+ TOK_LITERALQQ,
+ TOK_NUMBER,
+ TOK_QNAME,
+ TOK_NCNAME,
+ TOK_DOLLAR
+];
+
+// All the nonterminals of the grammar. The nonterminal objects are
+// identified by object identity; the labels are used in the debug
+// output only.
+var XPathLocationPath = { label: "LocationPath" };
+var XPathRelativeLocationPath = { label: "RelativeLocationPath" };
+var XPathAbsoluteLocationPath = { label: "AbsoluteLocationPath" };
+var XPathStep = { label: "Step" };
+var XPathNodeTest = { label: "NodeTest" };
+var XPathPredicate = { label: "Predicate" };
+var XPathLiteral = { label: "Literal" };
+var XPathExpr = { label: "Expr" };
+var XPathPrimaryExpr = { label: "PrimaryExpr" };
+var XPathVariableReference = { label: "Variablereference" };
+var XPathNumber = { label: "Number" };
+var XPathFunctionCall = { label: "FunctionCall" };
+var XPathArgumentRemainder = { label: "ArgumentRemainder" };
+var XPathPathExpr = { label: "PathExpr" };
+var XPathUnionExpr = { label: "UnionExpr" };
+var XPathFilterExpr = { label: "FilterExpr" };
+var XPathDigits = { label: "Digits" };
+
+var xpathNonTerminals = [
+ XPathLocationPath,
+ XPathRelativeLocationPath,
+ XPathAbsoluteLocationPath,
+ XPathStep,
+ XPathNodeTest,
+ XPathPredicate,
+ XPathLiteral,
+ XPathExpr,
+ XPathPrimaryExpr,
+ XPathVariableReference,
+ XPathNumber,
+ XPathFunctionCall,
+ XPathArgumentRemainder,
+ XPathPathExpr,
+ XPathUnionExpr,
+ XPathFilterExpr,
+ XPathDigits
+];
+
+// Quantifiers that are used in the productions of the grammar.
+var Q_01 = { label: "?" };
+var Q_MM = { label: "*" };
+var Q_1M = { label: "+" };
+
+// Tag for left associativity (right assoc is implied by undefined).
+var ASSOC_LEFT = true;
+
+// The productions of the grammar. Columns of the table:
+//
+// - target nonterminal,
+// - pattern,
+// - precedence,
+// - semantic value factory
+//
+// The semantic value factory is a function that receives parse tree
+// nodes from the stack frames of the matched symbols as arguments and
+// returns an a node of the parse tree. The node is stored in the top
+// stack frame along with the target object of the rule. The node in
+// the parse tree is an expression object that has an evaluate() method
+// and thus evaluates XPath expressions.
+//
+// The precedence is used to decide between reducing and shifting by
+// comparing the precendence of the rule that is candidate for
+// reducing with the precedence of the look ahead token. Precedence of
+// -1 means that the precedence of the tokens in the pattern is used
+// instead. TODO: It shouldn't be necessary to explicitly assign
+// precedences to rules.
+
+var xpathGrammarRules =
+ [
+ [ XPathLocationPath, [ XPathRelativeLocationPath ], 18,
+ passExpr ],
+ [ XPathLocationPath, [ XPathAbsoluteLocationPath ], 18,
+ passExpr ],
+
+ [ XPathAbsoluteLocationPath, [ TOK_SLASH, XPathRelativeLocationPath ], 18,
+ makeLocationExpr1 ],
+ [ XPathAbsoluteLocationPath, [ TOK_DSLASH, XPathRelativeLocationPath ], 18,
+ makeLocationExpr2 ],
+
+ [ XPathAbsoluteLocationPath, [ TOK_SLASH ], 0,
+ makeLocationExpr3 ],
+ [ XPathAbsoluteLocationPath, [ TOK_DSLASH ], 0,
+ makeLocationExpr4 ],
+
+ [ XPathRelativeLocationPath, [ XPathStep ], 31,
+ makeLocationExpr5 ],
+ [ XPathRelativeLocationPath,
+ [ XPathRelativeLocationPath, TOK_SLASH, XPathStep ], 31,
+ makeLocationExpr6 ],
+ [ XPathRelativeLocationPath,
+ [ XPathRelativeLocationPath, TOK_DSLASH, XPathStep ], 31,
+ makeLocationExpr7 ],
+
+ [ XPathStep, [ TOK_DOT ], 33,
+ makeStepExpr1 ],
+ [ XPathStep, [ TOK_DDOT ], 33,
+ makeStepExpr2 ],
+ [ XPathStep,
+ [ TOK_AXISNAME, TOK_AXIS, XPathNodeTest ], 33,
+ makeStepExpr3 ],
+ [ XPathStep, [ TOK_AT, XPathNodeTest ], 33,
+ makeStepExpr4 ],
+ [ XPathStep, [ XPathNodeTest ], 33,
+ makeStepExpr5 ],
+ [ XPathStep, [ XPathStep, XPathPredicate ], 33,
+ makeStepExpr6 ],
+
+ [ XPathNodeTest, [ TOK_ASTERISK ], 33,
+ makeNodeTestExpr1 ],
+ [ XPathNodeTest, [ TOK_NCNAME, TOK_COLON, TOK_ASTERISK ], 33,
+ makeNodeTestExpr2 ],
+ [ XPathNodeTest, [ TOK_QNAME ], 33,
+ makeNodeTestExpr3 ],
+ [ XPathNodeTest, [ TOK_NODEO, TOK_PARENC ], 33,
+ makeNodeTestExpr4 ],
+ [ XPathNodeTest, [ TOK_NODEO, XPathLiteral, TOK_PARENC ], 33,
+ makeNodeTestExpr5 ],
+
+ [ XPathPredicate, [ TOK_BRACKO, XPathExpr, TOK_BRACKC ], 33,
+ makePredicateExpr ],
+
+ [ XPathPrimaryExpr, [ XPathVariableReference ], 33,
+ passExpr ],
+ [ XPathPrimaryExpr, [ TOK_PARENO, XPathExpr, TOK_PARENC ], 33,
+ makePrimaryExpr ],
+ [ XPathPrimaryExpr, [ XPathLiteral ], 30,
+ passExpr ],
+ [ XPathPrimaryExpr, [ XPathNumber ], 30,
+ passExpr ],
+ [ XPathPrimaryExpr, [ XPathFunctionCall ], 30,
+ passExpr ],
+
+ [ XPathFunctionCall, [ TOK_QNAME, TOK_PARENO, TOK_PARENC ], -1,
+ makeFunctionCallExpr1 ],
+ [ XPathFunctionCall,
+ [ TOK_QNAME, TOK_PARENO, XPathExpr, XPathArgumentRemainder, Q_MM,
+ TOK_PARENC ], -1,
+ makeFunctionCallExpr2 ],
+ [ XPathArgumentRemainder, [ TOK_COMMA, XPathExpr ], -1,
+ makeArgumentExpr ],
+
+ [ XPathUnionExpr, [ XPathPathExpr ], 20,
+ passExpr ],
+ [ XPathUnionExpr, [ XPathUnionExpr, TOK_PIPE, XPathPathExpr ], 20,
+ makeUnionExpr ],
+
+ [ XPathPathExpr, [ XPathLocationPath ], 20,
+ passExpr ],
+ [ XPathPathExpr, [ XPathFilterExpr ], 19,
+ passExpr ],
+ [ XPathPathExpr,
+ [ XPathFilterExpr, TOK_SLASH, XPathRelativeLocationPath ], 20,
+ makePathExpr1 ],
+ [ XPathPathExpr,
+ [ XPathFilterExpr, TOK_DSLASH, XPathRelativeLocationPath ], 20,
+ makePathExpr2 ],
+
+ [ XPathFilterExpr, [ XPathPrimaryExpr, XPathPredicate, Q_MM ], 20,
+ makeFilterExpr ],
+
+ [ XPathExpr, [ XPathPrimaryExpr ], 16,
+ passExpr ],
+ [ XPathExpr, [ XPathUnionExpr ], 16,
+ passExpr ],
+
+ [ XPathExpr, [ TOK_MINUS, XPathExpr ], -1,
+ makeUnaryMinusExpr ],
+
+ [ XPathExpr, [ XPathExpr, TOK_OR, XPathExpr ], -1,
+ makeBinaryExpr ],
+ [ XPathExpr, [ XPathExpr, TOK_AND, XPathExpr ], -1,
+ makeBinaryExpr ],
+
+ [ XPathExpr, [ XPathExpr, TOK_EQ, XPathExpr ], -1,
+ makeBinaryExpr ],
+ [ XPathExpr, [ XPathExpr, TOK_NEQ, XPathExpr ], -1,
+ makeBinaryExpr ],
+
+ [ XPathExpr, [ XPathExpr, TOK_LT, XPathExpr ], -1,
+ makeBinaryExpr ],
+ [ XPathExpr, [ XPathExpr, TOK_LE, XPathExpr ], -1,
+ makeBinaryExpr ],
+ [ XPathExpr, [ XPathExpr, TOK_GT, XPathExpr ], -1,
+ makeBinaryExpr ],
+ [ XPathExpr, [ XPathExpr, TOK_GE, XPathExpr ], -1,
+ makeBinaryExpr ],
+
+ [ XPathExpr, [ XPathExpr, TOK_PLUS, XPathExpr ], -1,
+ makeBinaryExpr, ASSOC_LEFT ],
+ [ XPathExpr, [ XPathExpr, TOK_MINUS, XPathExpr ], -1,
+ makeBinaryExpr, ASSOC_LEFT ],
+
+ [ XPathExpr, [ XPathExpr, TOK_ASTERISK, XPathExpr ], -1,
+ makeBinaryExpr, ASSOC_LEFT ],
+ [ XPathExpr, [ XPathExpr, TOK_DIV, XPathExpr ], -1,
+ makeBinaryExpr, ASSOC_LEFT ],
+ [ XPathExpr, [ XPathExpr, TOK_MOD, XPathExpr ], -1,
+ makeBinaryExpr, ASSOC_LEFT ],
+
+ [ XPathLiteral, [ TOK_LITERALQ ], -1,
+ makeLiteralExpr ],
+ [ XPathLiteral, [ TOK_LITERALQQ ], -1,
+ makeLiteralExpr ],
+
+ [ XPathNumber, [ TOK_NUMBER ], -1,
+ makeNumberExpr ],
+
+ [ XPathVariableReference, [ TOK_DOLLAR, TOK_QNAME ], 200,
+ makeVariableReference ]
+ ];
+
+// That function computes some optimizations of the above data
+// structures and will be called right here. It merely takes the
+// counter variables out of the global scope.
+
+var xpathRules = [];
+
+function xpathParseInit() {
+ if (xpathRules.length) {
+ return;
+ }
+
+ // Some simple optimizations for the xpath expression parser: sort
+ // grammar rules descending by length, so that the longest match is
+ // first found.
+
+ xpathGrammarRules.sort(function(a,b) {
+ var la = a[1].length;
+ var lb = b[1].length;
+ if (la < lb) {
+ return 1;
+ } else if (la > lb) {
+ return -1;
+ } else {
+ return 0;
+ }
+ });
+
+ var k = 1;
+ for (var i = 0; i < xpathNonTerminals.length; ++i) {
+ xpathNonTerminals[i].key = k++;
+ }
+
+ for (i = 0; i < xpathTokenRules.length; ++i) {
+ xpathTokenRules[i].key = k++;
+ }
+
+ Log.write('XPath parse INIT: ' + k + ' rules');
+
+ // Another slight optimization: sort the rules into bins according
+ // to the last element (observing quantifiers), so we can restrict
+ // the match against the stack to the subest of rules that match the
+ // top of the stack.
+ //
+ // TODO(mesch): What we actually want is to compute states as in
+ // bison, so that we don't have to do any explicit and iterated
+ // match against the stack.
+
+ function push_(array, position, element) {
+ if (!array[position]) {
+ array[position] = [];
+ }
+ array[position].push(element);
+ }
+
+ for (i = 0; i < xpathGrammarRules.length; ++i) {
+ var rule = xpathGrammarRules[i];
+ var pattern = rule[1];
+
+ for (var j = pattern.length - 1; j >= 0; --j) {
+ if (pattern[j] == Q_1M) {
+ push_(xpathRules, pattern[j-1].key, rule);
+ break;
+
+ } else if (pattern[j] == Q_MM || pattern[j] == Q_01) {
+ push_(xpathRules, pattern[j-1].key, rule);
+ --j;
+
+ } else {
+ push_(xpathRules, pattern[j].key, rule);
+ break;
+ }
+ }
+ }
+
+ Log.write('XPath parse INIT: ' + xpathRules.length + ' rule bins');
+
+ var sum = 0;
+ mapExec(xpathRules, function(i) {
+ if (i) {
+ sum += i.length;
+ }
+ });
+
+ Log.write('XPath parse INIT: ' + (sum / xpathRules.length) + ' average bin size');
+}
+
+// Local utility functions that are used by the lexer or parser.
+
+function xpathCollectDescendants(nodelist, node) {
+ for (var n = node.firstChild; n; n = n.nextSibling) {
+ nodelist.push(n);
+ arguments.callee(nodelist, n);
+ }
+}
+
+function xpathCollectDescendantsReverse(nodelist, node) {
+ for (var n = node.lastChild; n; n = n.previousSibling) {
+ nodelist.push(n);
+ arguments.callee(nodelist, n);
+ }
+}
+
+
+// The entry point for the library: match an expression against a DOM
+// node. Returns an XPath value.
+function xpathDomEval(expr, node) {
+ var expr1 = xpathParse(expr);
+ var ret = expr1.evaluate(new ExprContext(node));
+ return ret;
+}
+
+// Utility function to sort a list of nodes. Used by xsltSort() and
+// nxslSelect().
+function xpathSort(input, sort) {
+ if (sort.length == 0) {
+ return;
+ }
+
+ var sortlist = [];
+
+ for (var i = 0; i < input.nodelist.length; ++i) {
+ var node = input.nodelist[i];
+ var sortitem = { node: node, key: [] };
+ var context = input.clone(node, 0, [ node ]);
+
+ for (var j = 0; j < sort.length; ++j) {
+ var s = sort[j];
+ var value = s.expr.evaluate(context);
+
+ var evalue;
+ if (s.type == 'text') {
+ evalue = value.stringValue();
+ } else if (s.type == 'number') {
+ evalue = value.numberValue();
+ }
+ sortitem.key.push({ value: evalue, order: s.order });
+ }
+
+ // Make the sort stable by adding a lowest priority sort by
+ // id. This is very convenient and furthermore required by the
+ // spec ([XSLT] - Section 10 Sorting).
+ sortitem.key.push({ value: i, order: 'ascending' });
+
+ sortlist.push(sortitem);
+ }
+
+ sortlist.sort(xpathSortByKey);
+
+ var nodes = [];
+ for (var i = 0; i < sortlist.length; ++i) {
+ nodes.push(sortlist[i].node);
+ }
+ input.nodelist = nodes;
+ input.setNode(nodes[0], 0);
+}
+
+
+// Sorts by all order criteria defined. According to the JavaScript
+// spec ([ECMA] Section 11.8.5), the compare operators compare strings
+// as strings and numbers as numbers.
+//
+// NOTE: In browsers which do not follow the spec, this breaks only in
+// the case that numbers should be sorted as strings, which is very
+// uncommon.
+
+function xpathSortByKey(v1, v2) {
+ // NOTE: Sort key vectors of different length never occur in
+ // xsltSort.
+
+ for (var i = 0; i < v1.key.length; ++i) {
+ var o = v1.key[i].order == 'descending' ? -1 : 1;
+ if (v1.key[i].value > v2.key[i].value) {
+ return +1 * o;
+ } else if (v1.key[i].value < v2.key[i].value) {
+ return -1 * o;
+ }
+ }
+
+ return 0;
+}
diff --git a/tests/test_tools/selenium/php/TestRunner.php b/tests/test_tools/selenium/php/TestRunner.php
new file mode 100644
index 00000000..a82ce0dd
--- /dev/null
+++ b/tests/test_tools/selenium/php/TestRunner.php
@@ -0,0 +1,169 @@
+
+<html>
+
+<head>
+<HTA:APPLICATION ID="SeleniumHTARunner" APPLICATIONNAME="Selenium" >
+<!-- the previous line is only relevant if you rename this
+ file to "TestRunner.hta" -->
+
+<!-- The copyright notice and other comments have been moved to after the HTA declaration,
+ to work-around a bug in IE on Win2K whereby the HTA application doesn't function correctly -->
+<!--
+Copyright 2004 ThoughtWorks, Inc
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
+
+<title>Selenium Functional Test Runner</title>
+<link rel="stylesheet" type="text/css" href="<?php echo $base_dir; ?>core/selenium.css" />
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-browserdetect.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-browserbot.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/prototype-1.4.0.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/find_matching_child.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-api.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-commandhandlers.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-executionloop.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-testrunner.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-logging.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/selenium-version.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/scripts/htmlutils.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/xpath/misc.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/xpath/dom.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>core/xpath/xpath.js"></script>
+<script language="JavaScript" type="text/javascript" src="<?php echo $base_dir; ?>prado-functional-test.js"></script>
+<script language="JavaScript" type="text/javascript">
+ function openDomViewer() {
+ var autFrame = document.getElementById('myiframe');
+ var autFrameDocument = getIframeDocument(autFrame);
+ this.rootDocument = autFrameDocument;
+ var domViewer = window.open('<?php echo $base_dir; ?>core/domviewer/domviewer.html');
+ return false;
+ }
+
+ Logger.prototype.openLogWindow = function()
+ {
+ this.logWindow = window.open(
+ "<?php echo $base_dir; ?>core/SeleniumLog.html", "SeleniumLog",
+ "width=600,height=250,bottom=0,right=0,status,scrollbars,resizable"
+ );
+ return this.logWindow;
+ }
+
+ var post_results_to = "<?php echo $driver; ?>";
+
+</script>
+</head>
+
+<body onLoad="start();">
+
+ <table class="layout">
+ <form action="" name="controlPanel">
+
+ <!-- Suite, Test, Control Panel -->
+
+ <tr class="selenium">
+ <td width="25%" height="30%" ><iframe name="testSuiteFrame" id="testSuiteFrame" src="<?php echo $driver; ?>?testSuites" application="yes"></iframe></td>
+ <td width="50%" height="30%" ><iframe name="testFrame" id="testFrame" application="yes"></iframe></td>
+
+ <td width="25%">
+ <table class="layout">
+ <tr class="selenium">
+ <th width="25%" height="1" class="header">
+ <h3><a href="http://selenium.thoughtworks.com" title="The Selenium Project">Selenium</a></h3>
+ </th>
+ </tr>
+ <tr>
+ <td width="25%" height="30%" id="controlPanel">
+
+ <fieldset>
+ <legend>Execute Tests</legend>
+
+ <div>
+ <input id="modeRun" type="radio" name="runMode" value="0" checked="checked"/><label for="modeRun">Run</label>
+ <input id="modeWalk" type="radio" name="runMode" value="500" /><label for="modeWalk">Walk</label>
+ <input id="modeStep" type="radio" name="runMode" value="-1" /><label for="modeStep">Step</label>
+ </div>
+
+ <div>
+ <button type="button" id="runSuite" onClick="startTestSuite();"
+ title="Run the entire Test-Suite">
+ <strong>All</strong>
+ </button>
+ <button type="button" id="runTest" onClick="runSingleTest();"
+ title="Run the current Test">
+ <em>Selected</em>
+ </button>
+ <button type="button" id="continueTest" disabled="disabled"
+ title="Continue the Test">
+ Continue
+ </button>
+ </div>
+
+ </fieldset>
+
+ <table id="stats" align="center">
+ <tr>
+ <td colspan="2" align="right">Elapsed:</td>
+ <td id="elapsedTime" colspan="2">00.00</td>
+ </tr>
+ <tr>
+ <th colspan="2">Tests</th>
+ <th colspan="2">Commands</th>
+ </tr>
+ <tr>
+ <td class="count" id="testRuns">0</td>
+ <td>run</td>
+ <td class="count" id="commandPasses">0</td>
+ <td>passed</td>
+ </tr>
+ <tr>
+ <td class="count" id="testFailures">0</td>
+ <td>failed</td>
+ <td class="count" id="commandFailures">0</td>
+ <td>failed</td>
+ </tr>
+ <tr>
+ <td colspan="2"></td>
+ <td class="count" id="commandErrors">0</td>
+ <td>incomplete</td>
+ </tr>
+ </table>
+ <!--
+ <fieldset>
+ <legend>Tools</legend>
+ <button type="button" id="domViewer1" onClick="openDomViewer();">
+ View DOM
+ </button>
+ <button type="button" onClick="LOG.show();">
+ Show Log
+ </button>
+
+ </fieldset>
+ -->
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+
+ <!-- AUT -->
+
+ <tr>
+ <td colspan="3" height="70%"><iframe name="myiframe" id="myiframe" src="<?php echo $base_dir; ?>core/TestRunner-splash.html"></iframe></td>
+ </tr>
+ </form>
+ </table>
+
+</body>
+</html> \ No newline at end of file
diff --git a/tests/test_tools/selenium/php/results.php b/tests/test_tools/selenium/php/results.php
new file mode 100644
index 00000000..77dab43b
--- /dev/null
+++ b/tests/test_tools/selenium/php/results.php
@@ -0,0 +1,160 @@
+<?php
+
+class SeleniumTestCaseResult
+{
+ public $name;
+ public $commands = array();
+ public $result = 'passed';
+ public $failures = array();
+}
+
+class SeleniumTestResult
+{
+ public $result = 'passed';
+ public $totalTime = 0;
+ public $numTestPasses = 0;
+ public $numTestFailures = 0;
+ public $numCommandPasses = 0;
+ public $numCommandFailures = 0;
+ public $numCommandErrors = 0;
+ public $suites = array();
+ public $browser = '';
+ public $date;
+
+ public function __construct()
+ {
+ $this->parse_data();
+ $this->browser = $_SERVER['HTTP_USER_AGENT'];
+ $this->date = time();
+ }
+
+ protected function parse_data()
+ {
+ $this->result = $_POST['result']; // failed || passed
+ $this->totalTime = $_POST['totalTime'];
+ $this->numTestPasses = $_POST['numTestPasses'];
+ $this->numTestFailures = $_POST['numTestFailures'];
+ $this->numCommandPasses = $_POST['numCommandPasses'];
+ $this->numCommandFailures = $_POST['numCommandFailures'];
+ $this->numCommandErrors = $_POST['numCommandErrors'];
+
+ foreach($_POST['tests'] as $test)
+ {
+ $case = new SeleniumTestCaseResult();
+ $case->name = $test['testcase'];
+ $case->commands = $test['commands'];
+ for($i = 0; $i < count($case->commands); $i++)
+ {
+ //$trace = $case->commands[$i]['trace'];
+ //$trace = html_entity_decode($trace);
+ //$case->commands[$i]['trace'] = @unserialize($trace);
+ if($case->commands[$i]['result'] == 'failed')
+ {
+ $case->result = 'failed';
+ array_push($case->failures, $case->commands[$i]);
+ }
+ }
+
+ $this->suites[$case->name] = $case;
+ }
+
+ }
+}
+
+class SeleniumHtmlReporter
+{
+ protected $test;
+
+ public function __construct($result)
+ {
+ $this->test = $result;
+ }
+
+ protected function renderHeader()
+ {
+ $contents = <<<EOD
+<html>
+<head>
+<title>Functional Test Results</title>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+<style type="text/css">
+body {font-family:"Verdana";font-weight:normal;color:black;background-color:white;}
+.failed { background-color: red; } .error0 { background-color: lightgray; }
+.info { padding: 0.5em; margin-top: 1em; color: white; }
+.passed { background-color: green; }
+.error_case div { padding: 0.3em 0.2em; margin: 0.5em 0; }
+.error_msg { padding: 0.5em; border-bottom:1px solid #ccc; }
+.msg { color:#c00; }
+.function { font-family:"Lucida Console";color: gray;}
+.file { border-bottom: 1px dashed gray; }
+.env { color: gray; font-size:10pt; padding: 0.5em; }
+.odd { background-color: #fee; }
+</style>
+</head>
+<body>
+EOD;
+ return $contents;
+ }
+
+ public function render()
+ {
+ echo $this->renderHeader();
+ echo $this->renderBody();
+ echo $this->renderFooter();
+ }
+
+ protected function renderBody()
+ {
+ /* SeleniumTestResult */
+ $test = $this->test;
+ $total = count($test->suites);
+ $date = @strftime('%Y-%m-%d %H:%M',$test->date);
+$contents = <<<EOD
+<h1 class="suite">Functional Test Results</h1>
+<div class="info {$test->result}">
+ <strong>{$total}</strong> test cases completed,
+ <strong>{$test->numTestPasses}</strong> passes
+ ({$test->numCommandPasses} commands), and
+ <strong>{$test->numTestFailures}</strong> fails
+ ({$test->numCommandErrors} commands).
+</div>
+<div class="env">
+ {$date}, {$test->browser}
+</div>
+EOD;
+ $count = 1;
+ foreach($test->suites as $suite)
+ {
+ foreach($suite->failures as $error)
+ $contents .= $this->getErrorMsg($suite, $error, $count++);
+ }
+
+ return $contents;
+ }
+
+
+ protected function getErrorMsg($suite, $info, $count)
+ {
+ $parity = $count%2==0 ? 'even' : 'odd';
+ $command = explode("|",$info['command']);
+$msg = <<<EOD
+ <div class="error_msg {$parity}">
+ <strong>#{$count}.</strong>
+ &quot;<span class="msg">{$info['msg']}</span>&quot; in
+ <span class="function">
+ {$suite->name}::{$command[1]}('{$command[2]}');
+ </span>
+ </div>
+EOD;
+
+ return $msg;
+ }
+
+ protected function renderFooter()
+ {
+ return "</body></html>";
+ }
+}
+
+
+?> \ No newline at end of file
diff --git a/tests/test_tools/selenium/php/selenium.php b/tests/test_tools/selenium/php/selenium.php
new file mode 100644
index 00000000..9ad4955b
--- /dev/null
+++ b/tests/test_tools/selenium/php/selenium.php
@@ -0,0 +1,477 @@
+<?php
+/**
+ * Selenium PHP driver. Saves the test command in a "out" queue (in session),
+ * and for each selenese request, remove the first comand from the "out" queue
+ * and push the results into the "in" queque (also in session). When "out" queque
+ * is empty, write the results to disk.
+ *
+ * Usage: See ../../example.php
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the BSD License.
+ *
+ * Copyright(c) 2004 by Wei Zhuo. All rights reserved.
+ *
+ * To contact the author write to {@link mailto:weizhuo[at]gmail[dot]com Wei Zhuo}
+ * The latest version of PRADO can be obtained from:
+ * {@link http://prado.sourceforge.net/}
+ *
+ * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
+ * @version $Revision: 1.66 $ $Date: Wed Nov 02 10:13:17 EST 2005 10:13:17 $
+ * @package Prado.tests
+ */
+
+/**
+ * Selenium automatic client runner,
+ *
+ * @author Wei Zhuo<weizhuo[at]gmail[dot]com>
+ * @version $Revision: 1.66 $ $Date: Fri Nov 04 13:20:12 EST 2005 13:20:12 $
+ * @package Prado.tests
+ */
+
+require_once(dirname(__FILE__).'/results.php');
+
+class SeleniumTestRunner
+{
+ protected $driver;
+ protected $base_dir = '';
+
+ public function __construct($driver=null, $base_dir='../javascript/')
+ {
+ if(is_null($driver) && !(php_sapi_name() == 'cli'))
+ $driver = $_SERVER['SCRIPT_NAME'];
+ $this->driver = $driver;
+ $this->base_dir = $base_dir;
+ }
+
+ public function render()
+ {
+ if((php_sapi_name() == 'cli')) return;
+ $file = dirname(__FILE__).'/TestRunner.php';
+ $driver = $this->driver;
+
+ //$base_dir = $this->base_dir;
+ $base_dir = $driver.'?sr=';
+ include($file);
+ }
+
+ public function getDriver()
+ {
+ return $this->driver;
+ }
+}
+
+class SeleniumTestStorage
+{
+ protected $outputs = array();
+ protected $tests = array();
+
+ public function getTests()
+ {
+ return $this->tests;
+ }
+
+ public function addCommand($test_case_id, $command)
+ {
+ $data = array($test_case_id, $command);
+ array_push($this->outputs, $data);
+ }
+
+ public function getCommand()
+ {
+ return array_shift($this->outputs);
+ }
+
+ public function addTestCase($command, $trace_details, $test_name, $test_suite)
+ {
+ $data = array(0, 0, $command, "", $trace_details, $test_name, $test_suite);
+ array_push($this->tests, $data);
+ }
+}
+
+class SeleneseInterpreter
+{
+ protected $storage;
+ protected $tracer;
+
+ public function __construct($storage, $tracer)
+ {
+ $this->storage = $storage;
+ $this->tracer = $tracer;
+ }
+
+ public function getTests()
+ {
+ return $this->storage->getTests();
+ }
+
+ public function getCommand()
+ {
+ $command = $this->storage->getCommand();
+ return empty($command) ? "|testComplete|||" : "{$command[1]}<{$command[0]}>";
+ }
+
+ public function __call($func, $args)
+ {
+ if($func{0} == '_') return;
+
+ $ID = isset($args[0]) ? $args[0] : "";
+ $value = isset($args[1]) ? $args[1] : "";
+ if(strpos(strtolower($func),'htmlpresent') || strpos(strtolower($func),'htmlnotpresent'))
+ $ID = htmlspecialchars($ID);
+ $command = array($func, $ID, $value);
+ $trace = debug_backtrace();
+
+ if(is_int(strpos(strtolower($func), 'visible')))
+ $this->addCommand(array('pause','500',''),$trace);
+
+ return $this->addCommand($command, $trace);
+ }
+
+ protected function addCommand($command, $trace)
+ {
+ list($trace, $test, $suite) = $this->tracer->getTrace($trace);
+ $test_id = $this->storage->addTestCase($command, $trace, $test, $suite);
+ $this->storage->addCommand($test_id, $command);
+ }
+}
+
+class SeleniumTestTrace
+{
+ protected $root;
+
+ public function __construct($root)
+ {
+ $this->root = $root;
+ }
+
+ public function getTrace($trace)
+ {
+ $group = array_pop($trace);
+ $info = $trace[3];
+ $test = $group['args'][0]->getTestList();
+ $i = count($test);
+ $name = $test[$i-2].'::'.$test[$i-1];
+ $suite = $test[0];
+ unset($info['object']);
+ /*
+ for($i = 0; $i < count($info['args']); $i++)
+ {
+ if($info['args'][$i] instanceof TControl)
+ $info['args'][$i] = $info['args'][$i]->ClientID;
+ }*/
+ $file = str_replace($this->root, '', $info['file']);
+ $info['file'] = substr($file, 1);
+ return array($info, $name, $suite);
+ }
+}
+
+class SimpleSeleniumProxyServer
+{
+ protected $runner;
+ protected $int;
+ protected $result_file;
+
+ public function __construct($runner, $int, $result_file)
+ {
+ $this->int = $int;
+ $this->runner = $runner;
+ $this->result_file = $result_file;
+ }
+
+ public function proxy()
+ {
+ return $this->int;
+ }
+
+
+ public static function getInstance($root='/', $result_file='results.dat', $base_dir='selenium/')
+ {
+ static $instance;
+ if(!isset($instance))
+ {
+ $storage = new SeleniumTestStorage();
+ $tracer = new SeleniumTestTrace($root);
+ $interpreter = new SeleneseInterpreter($storage, $tracer);
+ $runner = new SeleniumTestRunner(null, $base_dir);
+ $instance = new SimpleSeleniumProxyServer($runner, $interpreter, $result_file);
+ }
+ $instance->serveResults();
+ return $instance;
+ }
+
+ public function handleRequest()
+ {
+ $client = new SeleniumTestRunnerServer($this->int, $this->runner);
+ $client->serve();
+ return true;
+ }
+
+ public function serveResults()
+ {
+ if(isset($_POST['result']))
+ {
+ $result = new SeleniumTestResult();
+ $reporter = new SeleniumHtmlReporter($result);
+ $reporter->render();
+ exit();
+ }
+ }
+
+}
+
+class SeleniumTestSuiteWriter
+{
+ protected $suites;
+ protected $name;
+ protected $runner;
+
+ function __construct($suites, $name, $runner)
+ {
+ $this->suites = $suites;
+ $this->name = $name;
+ $this->runner = $runner;
+
+ }
+
+ protected function renderHeader()
+ {
+ $contents = <<<EOD
+<html>
+<head>
+<meta content="text/html; charset=UTF-8" http-equiv="content-type">
+<title>Test Suite</title>
+
+</head>
+
+<body>
+
+<table cellpadding="1"
+ cellspacing="1"
+ border="1">
+ <tbody>
+ <tr><td><b>{$this->name}</b></td></tr>
+EOD;
+ return $contents;
+ }
+
+ public function render()
+ {
+ echo $this->renderHeader();
+ foreach($this->suites as $name => $suite)
+ {
+ $file = $suite[0]['trace']['file'];
+ $file = strtr($file,'\\','/');
+ $url = $this->runner->getDriver()."?case={$name}&file={$file}";
+ echo "<tr>\n";
+ echo "<td><a href=\"{$url}\">{$name}</a></td>\n";
+ echo "</tr>\n";
+ }
+ echo $this->renderFooter();
+ }
+
+ protected function getJsTraceInfo()
+ {
+ $contents = "var prado_trace = {};\n";
+ foreach($this->suites as $name => $suite)
+ {
+ $name = $name;
+ $contents .= "prado_trace['{$name}'] = [";
+ $cases = array();
+ foreach($suite as $testcase)
+ $cases[] = "'".addslashes(htmlspecialchars(serialize($testcase['trace'])))."'";
+ $contents .= implode(",\n", $cases)."];\n\n";
+ }
+ return $contents;
+ }
+
+ protected function renderFooter()
+ {
+ $trace = '';//$this->getJsTraceInfo();
+ $contents = <<<EOD
+ </tbody>
+ </table>
+ <script type="text/javascript">
+ /*<![CDATA[*/
+ $trace
+ /*]]>*/
+ </script>
+</body>
+</html>
+EOD;
+ return $contents;
+ }
+}
+
+class SeleniumTestCaseWriter
+{
+ protected $case;
+ protected $tests;
+
+ function __construct($case, $tests)
+ {
+ $this->case = $case;
+ $this->tests = $tests;
+ }
+
+ protected function renderHeader()
+ {
+ $contents = <<<EOD
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>{$this->case}</title>
+ <meta content="text/html; charset=UTF-8" http-equiv="content-type">
+</head>
+<body>
+<table cellpadding="1" cellspacing="1" border="1" id=TABLE1>
+ <tbody>
+ <tr>
+ <td rowspan="1" colspan="3"><strong>{$this->case}</strong></td>
+ </tr>
+EOD;
+ return $contents;
+ }
+
+ public function render()
+ {
+ echo $this->renderHeader();
+ foreach($this->tests as $test)
+ {
+ $t = $test['test'];
+ if($t[0] == "open")
+ $t[1] = "<a href=\"{$t[1]}\" target=\"_blank\">{$t[1]}</a>";
+ echo "<tr>\n";
+ echo "<td>{$t[0]}</td>\n";
+ echo "<td>{$t[1]}</td>\n";
+ echo "<td>{$t[2]}</td>\n";
+ echo "</tr>\n";
+ }
+ echo $this->renderFooter();
+ }
+
+ protected function renderFooter()
+ {
+ $contents = <<<EOD
+ </tbody>
+</table>
+</body>
+</html>
+EOD;
+ return $contents;
+ }
+}
+
+class SeleniumTestRunnerServer
+{
+ protected $cases = array();
+ protected $trace = array();
+ protected $name;
+ protected $runner;
+
+ public function __construct($int, $runner)
+ {
+ $this->runner = $runner;
+ $this->initialize($int);
+ }
+
+ protected function initialize($int)
+ {
+ foreach($int->getTests() as $command)
+ {
+ $case = $command[5];
+ $this->cases[$case][] =
+ array('test' => $command[2], 'trace' => $command[4]);
+ if(is_null($this->name))
+ $this->name = $command[6];
+ }
+ }
+
+ function serve()
+ {
+ if($this->isTestSuiteRequest())
+ {
+ $testSuite = new SeleniumTestSuiteWriter($this->cases,
+ $this->name, $this->runner);
+ $testSuite->render();
+ }
+ else if($this->isTestCaseRequest())
+ {
+ if(($case = $this->getTestCaseRequest()) !== false)
+ {
+
+ $testCase = new SeleniumTestCaseWriter($case, $this->getTestCase());
+ $testCase->render();
+ }
+ }
+ else
+ {
+ $this->runner->render();
+ }
+ }
+
+ protected function isTestSuiteRequest()
+ {
+ return isset($_GET['testSuites']);
+ }
+
+ protected function isTestCaseRequest()
+ {
+ return isset($_GET['case']);
+ }
+
+ public function isClientRequest()
+ {
+ return !$this->isTestSuiteRequest() && !$this->isTestCaseRequest();
+ }
+
+ protected function getTestCaseRequest()
+ {
+ $case = $_GET['case'];
+ if(isset($this->cases[$case]))
+ return $case;
+ else return false;
+ }
+
+ protected function getTestCase()
+ {
+ $case = $_GET['case'];
+ if(isset($this->cases[$case]))
+ return $this->cases[$case];
+ else
+ return array();
+ }
+}
+
+
+class SeleniumTestCase extends UnitTestCase
+{
+ protected $selenium;
+ protected $Page;
+
+ function __construct()
+ {
+ $server = SimpleSeleniumProxyServer::getInstance();
+ if(!is_null($server))
+ $this->selenium = $server->proxy();
+ parent::__construct();
+ }
+
+ function getPage($class)
+ {
+ $info = new ReflectionClass($class);
+ return Prado::getApplication()->getTestPage($info->getFileName());
+ }
+
+ function __call($func, $args)
+ {
+ if(count($args) == 0)
+ return $this->selenium->{$func}();
+ else if (count($args) == 1)
+ return $this->selenium->{$func}($args[0]);
+ else if (count($args) == 2)
+ return $this->selenium->{$func}($args[0], $args[1]);
+ }
+}
+
+?> \ No newline at end of file
diff --git a/tests/test_tools/selenium/prado-functional-test.js b/tests/test_tools/selenium/prado-functional-test.js
new file mode 100644
index 00000000..306f6a74
--- /dev/null
+++ b/tests/test_tools/selenium/prado-functional-test.js
@@ -0,0 +1,247 @@
+
+/**
+ * Override selenium implementation.
+ */
+Selenium.prototype.getAttribute = function(target) {
+ return this.page().findAttribute(target);
+};
+
+
+/**
+ * Override selenium implementation.
+ */
+Selenium.prototype.isVisible = function(locator) {
+ var element;
+ element = this.page().findElement(locator);
+
+ if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
+ var visibility = element.style["visibility"];
+ else
+ var visibility = this.findEffectiveStyleProperty(element, "visibility");
+
+ var _isDisplayed = this._isDisplayed(element);
+ return (visibility != "hidden" && _isDisplayed);
+};
+
+
+/**
+ * Override selenium implementation.
+ */
+Selenium.prototype._isDisplayed = function(element) {
+ if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
+ var display = element.style["display"];
+ else
+ var display = this.findEffectiveStyleProperty(element, "display");
+ if (display == "none") return false;
+ if (element.parentNode.style) {
+ return this._isDisplayed(element.parentNode);
+ }
+ return true;
+};
+
+Selenium.prototype.assertEmptySelection = function(selectLocator, optionLocator)
+{
+ /**
+ * Verifies that the selected option of a drop-down satisfies the optionSpecifier.
+ *
+ * <p>See the select command for more information about option locators.</p>
+ *
+ * @param selectLocator an <a href="#locators">element locator</a> identifying a drop-down menu
+ * @param optionLocator an option locator, typically just an option label (e.g. "John Smith")
+ */
+ var element = this.page().findElement(selectLocator);
+ var locator = this.optionLocatorFactory.fromLocatorString(optionLocator);
+ return element.selectedIndex == -1;
+}
+
+function runNextTest() {
+ if (!runAllTests)
+ return;
+
+ suiteTable = getIframeDocument(getSuiteFrame()).getElementsByTagName("table")[0];
+
+ // Do not change the row color of the first row
+ if (currentRowInSuite > 0) {
+ // Provide test-status feedback
+ if (testFailed) {
+ setCellColor(suiteTable.rows, currentRowInSuite, 0, failColor);
+ } else {
+ setCellColor(suiteTable.rows, currentRowInSuite, 0, passColor);
+ }
+
+ // Set the results from the previous test run
+ setResultsData(suiteTable, currentRowInSuite);
+ }
+
+ currentRowInSuite++;
+
+ // If we are done with all of the tests, set the title bar as pass or fail
+ if (currentRowInSuite >= suiteTable.rows.length) {
+ if (suiteFailed) {
+ setCellColor(suiteTable.rows, 0, 0, failColor);
+ } else {
+ setCellColor(suiteTable.rows, 0, 0, passColor);
+ }
+
+ LOG.warn("next? ", "warn");
+ // If this is an automated run (i.e., build script), then submit
+ // the test results by posting to a form
+
+ postTestResults(suiteFailed, suiteTable);
+ }
+
+ else {
+ // Make the current row blue
+ setCellColor(suiteTable.rows, currentRowInSuite, 0, workingColor);
+
+ testLink = suiteTable.rows[currentRowInSuite].cells[0].getElementsByTagName("a")[0];
+ testLink.focus();
+
+ var testFrame = getTestFrame();
+ addLoadListener(testFrame, startTest);
+
+ selenium.browserbot.setIFrameLocation(testFrame, testLink.href);
+ }
+}
+
+// Post the results to a servlet, CGI-script, etc. The URL of the
+// results-handler defaults to "/postResults", but an alternative location
+// can be specified by providing a "resultsUrl" query parameter.
+//
+// Parameters passed to the results-handler are:
+// result: passed/failed depending on whether the suite passed or failed
+// totalTime: the total running time in seconds for the suite.
+//
+// numTestPasses: the total number of tests which passed.
+// numTestFailures: the total number of tests which failed.
+//
+// numCommandPasses: the total number of commands which passed.
+// numCommandFailures: the total number of commands which failed.
+// numCommandErrors: the total number of commands which errored.
+//
+// suite: the suite table, including the hidden column of test results
+// testTable.1 to testTable.N: the individual test tables
+//
+function postTestResults(suiteFailed, suiteTable) {
+
+ form = document.createElement("form");
+ document.body.appendChild(form);
+
+ form.id = "resultsForm";
+ form.method="post";
+ form.target="myiframe";
+
+ var resultsUrl = post_results_to;
+ if (!resultsUrl) {
+ resultsUrl = "./results.php";
+ }
+
+ var actionAndParameters = resultsUrl.split('?',2);
+ form.action = actionAndParameters[0];
+ LOG.warn(form.action)
+ var resultsUrlQueryString = actionAndParameters[1];
+
+ form.createHiddenField = function(name, value) {
+ input = document.createElement("input");
+ input.type = "hidden";
+ input.name = name;
+ input.value = value;
+ this.appendChild(input);
+ };
+
+ if (resultsUrlQueryString) {
+ var clauses = resultsUrlQueryString.split('&');
+ for (var i = 0; i < clauses.length; i++) {
+ var keyValuePair = clauses[i].split('=',2);
+ var key = unescape(keyValuePair[0]);
+ var value = unescape(keyValuePair[1]);
+ form.createHiddenField(key, value);
+ }
+ }
+
+ form.createHiddenField("result", suiteFailed == true ? "failed" : "passed");
+
+ form.createHiddenField("totalTime", Math.floor((currentTime - startTime) / 1000));
+ form.createHiddenField("numTestPasses", numTestPasses);
+ form.createHiddenField("numTestFailures", numTestFailures);
+ form.createHiddenField("numCommandPasses", numCommandPasses);
+ form.createHiddenField("numCommandFailures", numCommandFailures);
+ form.createHiddenField("numCommandErrors", numCommandErrors);
+
+ // Create an input for each test table. The inputs are named
+ // testTable.1, testTable.2, etc.
+ for (rowNum = 1; rowNum < suiteTable.rows.length;rowNum++) {
+ // If there is a second column, then add a new input
+ if (suiteTable.rows[rowNum].cells.length > 1) {
+ var resultCell = suiteTable.rows[rowNum].cells[1];
+ parse_resultCell(resultCell,rowNum,form);
+ //form.createHiddenField("tests[]", resultCell.innerHTML);
+ // remove the resultCell, so it's not included in the suite HTML
+ //resultCell.parentNode.removeChild(resultCell);
+ }
+ }
+
+ // Add HTML for the suite itself
+ //form.createHiddenField("suite", suiteTable.parentNode.innerHTML);
+
+ form.submit();
+ document.body.removeChild(form);
+}
+
+function parse_resultCell(resultCell,rowNum,form)
+{
+ var div = resultCell.childNodes[0];
+ var table;
+ for(var i = 0; i<div.childNodes.length; i++)
+ {
+ if(div.childNodes[i].nodeName.toLowerCase() == 'table')
+ table = div.childNodes[i];
+ }
+ //LOG.info(div.innerHTML);
+ var testname = table.rows[0].cells[0].firstChild.innerHTML;
+ var resultColor = get_color_status(table.rows[0]);
+
+ form.createHiddenField("tests["+rowNum+"][testcase]",testname);
+
+ //var trace = window.testSuiteFrame.prado_trace[testname];
+
+ for(var i = 1; i<table.rows.length; i++)
+ {
+ var msg = table.rows[i].getAttribute("title");
+ var result = get_color_status(table.rows[i]);
+ var action = table.rows[i].cells[0].innerHTML;
+ var target = table.rows[i].cells[1].innerHTML;
+ var param = table.rows[i].cells[2].innerHTML;
+ var id = "tests["+rowNum+"][commands]["+(i-1)+"]";
+ form.createHiddenField(id+"[command]", "|"+action+"|"+target+"|"+param+"|");
+ form.createHiddenField(id+"[result]", result);
+ form.createHiddenField(id+"[msg]", msg);
+ //form.createHiddenField(id+"[trace]", trace[i-1]);
+ }
+}
+
+function get_color_status(element)
+{
+ var color = element.getAttribute("bgcolor");
+ if(color == passColor) return "passed";
+ if(color == failColor) return "failed";
+ if(color == doneColor) return "done";
+ return "";
+}
+
+
+
+
+Selenium.prototype.assertHTMLPresent = function(expectedValue) {
+ var actualValue = this.page().currentDocument.body.innerHTML;
+ if(actualValue.indexOf(expectedValue) >= 0)
+ return;
+ Assert.fail("Unable to find '"+(expectedValue.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "\""))+"' in document.body");
+};
+
+Selenium.prototype.assertHTMLNotPresent = function(expectedValue) {
+ var actualValue = this.page().currentDocument.body.innerHTML;
+ if(actualValue.indexOf(expectedValue) < 0)
+ return;
+ Assert.fail("'"+(expectedValue.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "\""))+"' was found in document.body");
+}; \ No newline at end of file
diff --git a/tests/test_tools/simpletest/CHANGELOG b/tests/test_tools/simpletest/CHANGELOG
new file mode 100755
index 00000000..961ce208
--- /dev/null
+++ b/tests/test_tools/simpletest/CHANGELOG
@@ -0,0 +1,6 @@
+June 7, 2005, by Qiang Xue (qiang.xue@gmail.com)
+------------------------------------------------
+- changed all class memeber declarations from 'var $varname' to 'private $varname'.
+- removed all reference usages, including creating new objects, returning and passing objects.
+- modified expectation.php line 106 from 'function test($compare, &$nasty=false) {' to 'function test($compare) {'.
+- added HtmlReporterWithCoverage.php \ No newline at end of file
diff --git a/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
new file mode 100755
index 00000000..99c3be2d
--- /dev/null
+++ b/tests/test_tools/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE
@@ -0,0 +1,201 @@
+Simple Test interface changes
+=============================
+Because the SimpleTest tool set is still evolving it is likely that tests
+written with earlier versions will fail with the newest ones. The most
+dramatic changes are in the alpha releases. Here is a list of possible
+problems...
+
+No HTML when matching page elements
+-----------------------------------
+This behaviour has been switched to using plain text as if it
+were seen by the user of the browser. This means that HTML tags
+are suppressed, entities are converted and whitespace is
+normalised. This should make it easier to match items in forms.
+Also images are replaced with their "alt" text so that they
+can be matched as well.
+
+No method SimpleRunner::_getTestCase()
+--------------------------------------
+This was made public as getTestCase() in 1.0RC2.
+
+No method restartSession()
+--------------------------
+This was renamed to restart() in the WebTestCase, SimpleBrowser
+and the underlying SimpleUserAgent in 1.0RC2. Because it was
+undocumented anyway, no attempt was made at backward
+compatibility.
+
+My custom test case ignored by tally()
+--------------------------------------
+The _assertTrue method has had it's signature changed due to a bug
+in the PHP 5.0.1 release. You must now use getTest() from within
+that method to get the test case.
+
+Broken code extending SimpleRunner
+----------------------------------
+This was replaced with SimpleScorer so that I could use the runner
+name in another class. This happened in RC1 development and there
+is no easy backward compatibility fix. The solution is simply to
+extend SimpleScorer instead.
+
+Missing method getBaseCookieValue()
+-----------------------------------
+This was renamed getCurrentCookieValue() in RC1.
+
+Missing files from the SimpleTest suite
+---------------------------------------
+Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant
+to point at the SimpleTest folder location before any of the toolset
+was loaded. This is no longer documented as it is now unnecessary
+for later versions. If you are using an earlier version you may
+need this constant. Consult the documentation that was bundled with
+the release that you are using or upgrade to Beta6 or later.
+
+No method SimpleBrowser::getCurrentUrl()
+--------------------------------------
+This is replaced with the more versatile showRequest() for
+debugging. It only existed in this context for version Beta5.
+Later versions will have SimpleBrowser::getHistory() for tracking
+paths through pages. It is renamed as getUrl() since 1.0RC1.
+
+No method Stub::setStubBaseClass()
+----------------------------------
+This method has finally been removed in 1.0RC1. Use
+SimpleTestOptions::setStubBaseClass() instead.
+
+No class CommandLineReporter
+----------------------------
+This was renamed to TextReporter in Beta3 and the deprecated version
+was removed in 1.0RC1.
+
+No method requireReturn()
+-------------------------
+This was deprecated in Beta3 and is now removed.
+
+No method expectCookie()
+------------------------
+This method was abruptly removed in Beta4 so as to simplify the internals
+until another mechanism can replace it. As a workaround it is necessary
+to assert that the cookie has changed by setting it before the page
+fetch and then assert the desired value.
+
+No method clickSubmitByFormId()
+-------------------------------
+This method had an incorrect name as no button was involved. It was
+renamed to submitByFormId() in Beta4 and the old version deprecated.
+Now removed.
+
+No method paintStart() or paintEnd()
+------------------------------------
+You should only get this error if you have subclassed the lower level
+reporting and test runner machinery. These methods have been broken
+down into events for test methods, events for test cases and events
+for group tests. The new methods are...
+
+paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart()
+paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd()
+
+This change was made in Beta3, ironically to make it easier to subclass
+the inner machinery. Simply duplicating the code you had in the previous
+methods should provide a temporary fix.
+
+No class TestDisplay
+--------------------
+This has been folded into SimpleReporter in Beta3 and is now deprecated.
+It was removed in RC1.
+
+No method WebTestCase::fetch()
+------------------------------
+This was renamed get() in Alpha8. It is removed in Beta3.
+
+No method submit()
+------------------
+This has been renamed clickSubmit() in Beta1. The old method was
+removed in Beta2.
+
+No method clearHistory()
+------------------------
+This method is deprecated in Beta2 and removed in RC1.
+
+No method getCallCount()
+------------------------
+This method has been deprecated since Beta1 and has now been
+removed. There are now more ways to set expectations on counts
+and so this method should be unecessery. Removed in RC1.
+
+Cannot find file *
+------------------
+The following public name changes have occoured...
+
+simple_html_test.php --> reporter.php
+simple_mock.php --> mock_objects.php
+simple_unit.php --> unit_tester.php
+simple_web.php --> web_tester.php
+
+The old names were deprecated in Alpha8 and removed in Beta1.
+
+No method attachObserver()
+--------------------------
+Prior to the Alpha8 release the old internal observer pattern was
+gutted and replaced with a visitor. This is to trade flexibility of
+test case expansion against the ease of writing user interfaces.
+
+Code such as...
+
+$test = &new MyTestCase();
+$test->attachObserver(new TestHtmlDisplay());
+$test->run();
+
+...should be rewritten as...
+
+$test = &new MyTestCase();
+$test->run(new HtmlReporter());
+
+If you previously attached multiple observers then the workaround
+is to run the tests twice, once with each, until they can be combined.
+For one observer the old method is simulated in Alpha 8, but is
+removed in Beta1.
+
+No class TestHtmlDisplay
+------------------------
+This class has been renamed to HtmlReporter in Alpha8. It is supported,
+but deprecated in Beta1 and removed in Beta2. If you have subclassed
+the display for your own design, then you will have to extend this
+class (HtmlReporter) instead.
+
+If you have accessed the event queue by overriding the notify() method
+then I am afraid you are in big trouble :(. The reporter is now
+carried around the test suite by the runner classes and the methods
+called directly. In the unlikely event that this is a problem and
+you don't want to upgrade the test tool then simplest is to write your
+own runner class and invoke the tests with...
+
+$test->accept(new MyRunner(new MyReporter()));
+
+...rather than the run method. This should be easier to extend
+anyway and gives much more control. Even this method is overhauled
+in Beta3 where the runner class can be set within the test case. Really
+the best thing to do is to upgrade to this version as whatever you were
+trying to achieve before should now be very much easier.
+
+Missing set options method
+--------------------------
+All test suite options are now in one class called SimpleTestOptions.
+This means that options are set differently...
+
+GroupTest::ignore() --> SimpleTestOptions::ignore()
+Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass()
+
+These changed in Alpha8 and the old versions are now removed in RC1.
+
+No method setExpected*()
+------------------------
+The mock expectations changed their names in Alpha4 and the old names
+ceased to be supported in Alpha8. The changes are...
+
+setExpectedArguments() --> expectArguments()
+setExpectedArgumentsSequence() --> expectArgumentsAt()
+setExpectedCallCount() --> expectCallCount()
+setMaximumCallCount() --> expectMaximumCallCount()
+
+The parameters remained the same.
diff --git a/tests/test_tools/simpletest/HtmlReporterWithCoverage.php b/tests/test_tools/simpletest/HtmlReporterWithCoverage.php
new file mode 100644
index 00000000..abd10076
--- /dev/null
+++ b/tests/test_tools/simpletest/HtmlReporterWithCoverage.php
@@ -0,0 +1,268 @@
+<?php
+
+if (!defined('T_ML_COMMENT'))
+ define('T_ML_COMMENT', T_COMMENT);
+else
+ define('T_DOC_COMMENT', T_ML_COMMENT);
+
+class HtmlReporterWithCoverage extends HtmlReporter
+{
+ protected $coverage = array();
+
+ protected $painter;
+
+ protected $base_dir;
+
+ function __construct($painter = 'index.php', $base_dir)
+ {
+ $this->painter = $painter;
+ $this->base_dir = $base_dir;
+ }
+
+ function paintHeader($test_name, $charset="UTF-8")
+ {
+ $this->sendNoCacheHeaders();
+ header('Content-Type: text/html; Charset='.$charset);
+ print "<html>\n<head>\n<title>$test_name</title>\n";
+ print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset={$charset}\"/>";
+ print "<style type=\"text/css\">\n";
+ print $this->_getCss() . "\n";
+ print "</style>\n";
+ print "</head>\n<body>\n";
+ print "<h1>$test_name</h1>\n";
+ flush();
+
+ if (extension_loaded('xdebug'))
+ xdebug_start_code_coverage(XDEBUG_CC_UNUSED);
+
+ }
+
+ /**
+ *
+ */
+ function _getCss()
+ {
+ $contents = parent::_getCss()."\n ";
+ $contents .= '
+ .bar { float: left; display: inline; border: 1px solid #eee; width: 300px; white-space: nowrap;}
+ .percentage { float: left; background-color: #eef; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; font-size: 0.65em; padding: 5px; margin-right: }
+ .coverage {margin: 0.4em; }
+ .coverage a {
+ padding-left: 0.5em;
+ }
+ .coverage:after {
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
+ visibility: hidden;
+ }
+ .coverage {display: inline-block;}
+ /* Hides from IE-mac \*/
+ * html .coverage {height: 1%;}
+ .coverage {display: block;}
+ /* End hide from IE-mac */
+ ';
+ Return $contents;
+ }
+
+ function paintFooter($test_name)
+ {
+ if (extension_loaded('xdebug'))
+ {
+ $this->coverage = xdebug_get_code_coverage();
+ xdebug_stop_code_coverage();
+ }
+
+ $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green");
+ print "<div style=\"";
+ print "padding: 8px; margin-top: 1em; background-color: $colour; color: white;";
+ print "\">";
+ print $this->getTestCaseProgress() . "/" . $this->getTestCaseCount();
+ print " test cases complete:\n";
+ print "<strong>" . $this->getPassCount() . "</strong> passes, ";
+ print "<strong>" . $this->getFailCount() . "</strong> fails and ";
+ print "<strong>" . $this->getExceptionCount() . "</strong> exceptions.";
+ print "</div>\n";
+ $this->paintCoverage();
+ print "</body>\n</html>\n";
+ }
+
+ function paintCoverage()
+ {
+ $dir = dirname(__FILE__);
+ if(count($this->coverage) > 0)
+ print '<h2>Code Coverage</h2>';
+
+
+ ksort($this->coverage);
+
+ $details = array();
+ foreach($this->coverage as $file => $coverage)
+ {
+ if(is_int(strpos($file, $dir)) == false
+ && is_int(strpos($file, 'simpletest')) == false
+ && is_int(strpos($file, $this->base_dir)))
+ {
+ $total = HTMLCoverageReport::codelines($file);
+ $executed = count($coverage);
+ $percentage = sprintf('%01d',$executed/$total*100);
+ $width = $percentage * 3;
+ $filename = str_replace($this->base_dir, '',$file);
+ $link = $this->constructURL($filename, $coverage);
+
+ $detail['total'] = $total;
+ $detail['executed'] = $executed;
+ $detail['width'] = $width;
+ $detail['filename'] = $filename;
+ $detail['link'] = $link;
+ $details[$percentage][] = $detail;
+ }
+ }
+ krsort($details);
+ foreach($details as $percentage => $files)
+ {
+ foreach($files as $detail)
+ {
+ $total = $detail['total'];
+ $executed = $detail['executed'];
+ $width = $detail['width'];
+ $filename = $detail['filename'];
+ $link = $detail['link'];
+
+ print "<div class=\"coverage\">";
+ print "<span class=\"bar\">";
+ print "<span class=\"percentage\" style=\"width:{$width}px\">";
+ print "$executed/$total\n";
+ print "$percentage%</span></span>\n";
+ print "<a href=\"{$link}\">{$filename}</a>\n";
+ print "</div>\n";
+ }
+ }
+ }
+
+ function constructURL($file, $coverage)
+ {
+ $file = rawurlencode($file);
+ $lines = implode(',', array_keys($coverage));
+ return $this->painter.'?file='.$file.'&amp;lines='.$lines;
+ }
+}
+
+
+class HTMLCoverageReport extends HtmlReporter
+{
+ protected $file;
+ protected $lines;
+ protected $name;
+
+ function __construct($file, $name, $lines)
+ {
+ $this->file = $file;
+ $this->lines = $lines;
+ $this->name = $name;
+ }
+
+ function show()
+ {
+ $this->paintHeader($this->name);
+
+ $contents = file($this->file);
+ foreach($contents as $count => $line)
+ {
+ $num = ($count+1);
+ $line = preg_replace("/\\n|\\r/",'',$line);
+ $line = htmlspecialchars($line);
+ $line = str_replace(' ','&nbsp;',$line);
+ $line = str_replace("\t",'&nbsp;&nbsp;&nbsp;&nbsp;',$line);
+ if(in_array($count+1, $this->lines))
+ echo "<div class=\"highlight\"><tt>$num $line</tt></div>\n";
+ else
+ echo "<tt>$num $line</tt><br />\n";
+ }
+
+ $this->paintFooter();
+ }
+
+ function paintHeader($file, $charset="UTF-8")
+ {
+ $total = $this->codelines($this->file);
+ $executed = count($this->lines);
+ $percentage = sprintf('%01.2f',$executed/$total*100);
+
+ $this->sendNoCacheHeaders();
+ header('Content-Type: text/html Charset='.$charset);
+ print "<html>\n<head>\n<title>Code Coverage: $file</title>\n";
+ print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset={$charset}\"/>";
+ print "<style type=\"text/css\">\n";
+ print $this->_getCss() . "\n";
+ print ".highlight { background-color: #eef; } \n";
+ print ".filename { margin-bottom: 2em; } \n";
+ print "</style>\n";
+ print "</head>\n<body>\n";
+ print "<h1>Code Coverage</h1>\n";
+ print "<div class=\"filename\"><strong>$file</strong></div>";
+ print "<div class=\"filename\"><tt>&nbsp;&nbsp;&nbsp;&nbsp;Total code lines: {$total} <br /> Total lines executed: {$executed} ({$percentage}%)</tt></div>";
+ flush();
+ }
+
+ function paintFooter($test_name)
+ {
+ print "</body>\n</html>\n";
+ }
+
+ static function codelines($file)
+ {
+ $source = file_get_contents($file);
+ $tokens = @token_get_all($source);
+
+ $lines = '';
+
+ foreach ($tokens as $token)
+ {
+ if (is_string($token))
+ {
+ // simple 1-character token
+ $lines .= $token;
+ }
+ else
+ {
+ // token array
+ list($id, $text) = $token;
+
+ switch ($id)
+ {
+ case T_COMMENT:
+ case T_ML_COMMENT: // we've defined this
+ case T_DOC_COMMENT: // and this
+ // no action on comments
+ break;
+
+ default:
+ // anything else -> output "as is"
+ //echo $text;
+ $lines .= $text;
+ break;
+ }
+ }
+ }
+
+ $lines = preg_replace('/\\n\s*$/m',"",$lines);
+ $codelines = explode("\n",$lines);
+ $count = 0;
+ $patterns[] = '^\s*{\s*$';
+ $patterns[] = '<\?';
+ $patterns[] = '^\s*(private|protected|public)\s+\$';
+ $pattern = '/'.implode('|', $patterns).'/';
+ foreach($codelines as $line)
+ {
+ if(!preg_match($pattern, $line))
+ $count++;
+ }
+ return $count;
+ //var_dump($codelines);
+ //return count($codelines);
+ }
+}
+
+?>
diff --git a/tests/test_tools/simpletest/LICENSE b/tests/test_tools/simpletest/LICENSE
new file mode 100755
index 00000000..93acab79
--- /dev/null
+++ b/tests/test_tools/simpletest/LICENSE
@@ -0,0 +1,49 @@
+The Open Group Test Suite License
+
+Preamble
+
+The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications.
+
+Testing is essential for proper development and maintenance of standards-based products.
+
+For buyers: adequate conformance testing leads to reduced integration costs and protection of investments in applications, software and people.
+
+For software developers: conformance testing of platforms and middleware greatly reduces the cost of developing and maintaining multi-platform application software.
+
+For suppliers: In-depth testing increases customer satisfaction and keeps development and support costs in check. API conformance is highly measurable and suppliers who claim it must be able to substantiate that claim.
+
+As such, since these are benchmark measures of conformance, we feel the integrity of test tools is of importance. In order to preserve the integrity of the existing conformance modes of this test package and to permit recipients of modified versions of this package to run the original test modes, this license requires that the original test modes be preserved.
+
+If you find a bug in one of the standards mode test cases, please let us know so we can feed this back into the original, and also raise any specification issues with the appropriate bodies (for example the POSIX committees).
+
+Definitions:
+
+ * "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification.
+ * "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder.
+ * "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package.
+ * "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.)
+* "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it.
+
+1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers.
+
+2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version.
+
+3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least the following:
+
+rename any non-standard executables and testcases so the names do not conflict with standard executables and testcases, which must also be provided, and provide a separate manual page for each non-standard executable and testcase that clearly documents how it differs from the Standard Version.
+
+4. You may distribute the programs of this Package in object code or executable form, provided that you do at least the following:
+
+accompany any non-standard executables and testcases with their corresponding Standard Version executables and testcases, giving the non-standard executables and testcases non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version.
+
+5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own.
+
+6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package.
+
+7.Subroutines supplied by you and linked into this Package shall not be considered part of this Package.
+
+8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission.
+
+9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+
+The End
diff --git a/tests/test_tools/simpletest/README b/tests/test_tools/simpletest/README
new file mode 100755
index 00000000..50fa4aaa
--- /dev/null
+++ b/tests/test_tools/simpletest/README
@@ -0,0 +1,110 @@
+SimpleTest
+==========
+You probably got this package from...
+http://sourceforge.net/projects/simpletest/
+
+If there is no licence agreement with this package please download
+a version from the location above. You must read and accept that
+licence to use this software. The file is titled simply LICENSE.
+
+What is it? It's a framework for unit testing, web site testing and
+mock objects for PHP 4.2.0+.
+
+If you have used JUnit you will find this PHP unit testing version very
+similar. Also included is a mock objects and server stubs generator.
+The stubs can have return values set for different arguments, can have
+sequences set also by arguments and can return items by reference.
+The mocks inherit all of this functionality and can also have
+expectations set, again in sequences and for different arguments.
+
+A web tester similar in concept to JWebUnit is also included. There is no
+JavaScript or tables support, but forms, authentication, cookies and
+frames are handled.
+
+You are not tied to just using SimpleTest, though. The mocks and stubs
+will work with other test frameworks and SimpleTest can use other
+framework's (PHPUnit, PEAR::PhpUnit) test cases as it's own. The
+web browser part of the web tester can also be used independently either
+in other testers or as part of a scripting solution.
+
+You can see a release schedule at http://www.lastcraft.com/overview.php
+which is also copied to the documentation folder with this release.
+A full PHPDocumenter API documentation exists at
+http://simpletest.sourceforge.net/.
+
+The user interface is minimal
+in the extreme, but a lot of information flows from the test suite.
+After version 1.0 we will release a better web UI, but we are leaving XUL
+and GTk versions to volunteers as everybody has their own opinion
+on a good GUI, and we don't want to discourage development by shipping
+one with the toolkit.
+
+You are looking at a first full release. The unit tests for SimpleTest
+itself can be run here...
+
+simpletest/test/unit_tests.php
+
+And tests involving live network connections as well are here...
+
+simpletest/test/all_tests.php
+
+The full tests will typically overrun the 8Mb limit usually allowed
+to a PHP process. A workaround is to run the tests on the command
+with a custom php.ini file if you do not have access to your server
+version.
+
+You will have to edit the all_tests.php file if you are accesssing
+the internet through a proxy server. See the comments in all_tests.php
+for instructions.
+
+The full tests read some test data from the LastCraft site. If the site
+is down or has been modified for a later version then you will get
+spurious errors. A unit_tests.php failure on the other hand would be
+very serious. As far as we know we haven't yet managed to check in any
+test failures so please correct us if you find one.
+
+Even if all of the tests run please verify that your existing test suites
+also function as expected. If they don't see the file...
+
+HELP_MY_TESTS_DONT_WORK_ANYMORE
+
+This contains information on interface changes. It also points out
+deprecated interfaces so you should read this even if all of
+your current tests appear to run.
+
+There is a documentation folder which contains the core reference information
+in English and French, although this information is fairly basic.
+You can find a tutorial on http://www.lastcraft.com/first_test_tutorial.php
+to get you started and this material will eventually become included
+with the project documentation. A French translation exists at
+http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires.
+
+If you download and use and possibly even extend this tool, please let us
+know. Any feedback, even bad, is always welcome and we will work to get
+your suggestions into the version one release. Ideally please send your
+comments to...
+
+simpletest-support@lists.sourceforge.net
+
+...so that others can read them too. We usually try to respond within 48
+hours.
+
+There is no change log as yet except at Sourceforge. You can visit the
+release notes to see the completed TODO list after each cycle and also the
+status of any bugs, but if the bug is recent then it will be fixed in CVS only.
+The CVS check-ins always have all the tests passing and so CVS snapshots should
+be pretty usable, although the code may not look so good internally.
+
+Oh, yes. It is called "Simple" because it should be simple to
+use. We intend to add a complete set of tools for a test first
+and "test as you code" type of development. "Simple" does not
+mean "Lite" in this context.
+
+Thanks to everyone who has sent comments and offered suggestions. They
+really are invaluable, but sadly you are too many to mention in full.
+Thanks to all on the advanced PHP forum on SitePoint, especially Harry
+Feucks. Early adopters are always an inspiration.
+
+yours Marcus Baker, Jason Sweat and Perrick Penet.
+--
+marcus@lastcraft.com
diff --git a/tests/test_tools/simpletest/VERSION b/tests/test_tools/simpletest/VERSION
new file mode 100755
index 00000000..d3827e75
--- /dev/null
+++ b/tests/test_tools/simpletest/VERSION
@@ -0,0 +1 @@
+1.0
diff --git a/tests/test_tools/simpletest/authentication.php b/tests/test_tools/simpletest/authentication.php
new file mode 100644
index 00000000..7b6ed4ba
--- /dev/null
+++ b/tests/test_tools/simpletest/authentication.php
@@ -0,0 +1,219 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: authentication.php,v 1.9 2004/09/19 17:24:11 lastcraft Exp $
+ */
+ /**
+ * include http class
+ */
+ require_once(dirname(__FILE__) . '/http.php');
+
+ /**
+ * Represents a single security realm's identity.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleRealm {
+ protected $_type;
+ protected $_root;
+ protected $_username;
+ protected $_password;
+
+ /**
+ * Starts with the initial entry directory.
+ * @param string $type Authentication type for this
+ * realm. Only Basic authentication
+ * is currently supported.
+ * @param SimpleUrl $url Somewhere in realm.
+ * @access public
+ */
+ function SimpleRealm($type, $url) {
+ $this->_type = $type;
+ $this->_root = $url->getBasePath();
+ $this->_username = false;
+ $this->_password = false;
+ }
+
+ /**
+ * Adds another location to the realm.
+ * @param SimpleUrl $url Somewhere in realm.
+ * @access public
+ */
+ function stretch($url) {
+ $this->_root = $this->_getCommonPath($this->_root, $url->getPath());
+ }
+
+ /**
+ * Finds the common starting path.
+ * @param string $first Path to compare.
+ * @param string $second Path to compare.
+ * @return string Common directories.
+ * @access private
+ */
+ function _getCommonPath($first, $second) {
+ $first = explode('/', $first);
+ $second = explode('/', $second);
+ for ($i = 0; $i < min(count($first), count($second)); $i++) {
+ if ($first[$i] != $second[$i]) {
+ return implode('/', array_slice($first, 0, $i)) . '/';
+ }
+ }
+ return implode('/', $first) . '/';
+ }
+
+ /**
+ * Sets the identity to try within this realm.
+ * @param string $username Username in authentication dialog.
+ * @param string $username Password in authentication dialog.
+ * @access public
+ */
+ function setIdentity($username, $password) {
+ $this->_username = $username;
+ $this->_password = $password;
+ }
+
+ /**
+ * Accessor for current identity.
+ * @return string Last succesful username.
+ * @access public
+ */
+ function getUsername() {
+ return $this->_username;
+ }
+
+ /**
+ * Accessor for current identity.
+ * @return string Last succesful password.
+ * @access public
+ */
+ function getPassword() {
+ return $this->_password;
+ }
+
+ /**
+ * Test to see if the URL is within the directory
+ * tree of the realm.
+ * @param SimpleUrl $url URL to test.
+ * @return boolean True if subpath.
+ * @access public
+ */
+ function isWithin($url) {
+ return (strpos($url->getBasePath(), $this->_root) === 0);
+ }
+ }
+
+ /**
+ * Manages security realms.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleAuthenticator {
+ protected $_realms;
+
+ /**
+ * Clears the realms.
+ * @access public
+ */
+ function SimpleAuthenticator() {
+ $this->restartSession();
+ }
+
+ /**
+ * Starts with no realms set up.
+ * @access public
+ */
+ function restartSession() {
+ $this->_realms = array();
+ }
+
+ /**
+ * Adds a new realm centered the current URL.
+ * Browsers vary wildly on their behaviour in this
+ * regard. Mozilla ignores the realm and presents
+ * only when challenged, wasting bandwidth. IE
+ * just carries on presenting until a new challenge
+ * occours. SimpleTest tries to follow the spirit of
+ * the original standards committee and treats the
+ * base URL as the root of a file tree shaped realm.
+ * @param SimpleUrl $url Base of realm.
+ * @param string $type Authentication type for this
+ * realm. Only Basic authentication
+ * is currently supported.
+ * @param string $realm Name of realm.
+ * @access public
+ */
+ function addRealm($url, $type, $realm) {
+ $this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url);
+ }
+
+ /**
+ * Sets the current identity to be presented
+ * against that realm.
+ * @param string $host Server hosting realm.
+ * @param string $realm Name of realm.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @access public
+ */
+ function setIdentityForRealm($host, $realm, $username, $password) {
+ if (isset($this->_realms[$host][$realm])) {
+ $this->_realms[$host][$realm]->setIdentity($username, $password);
+ }
+ }
+
+ /**
+ * Finds the name of the realm by comparing URLs.
+ * @param SimpleUrl $url URL to test.
+ * @return SimpleRealm Name of realm.
+ * @access private
+ */
+ function _findRealmFromUrl($url) {
+ if (! isset($this->_realms[$url->getHost()])) {
+ return false;
+ }
+ foreach ($this->_realms[$url->getHost()] as $name => $realm) {
+ if ($realm->isWithin($url)) {
+ return $realm;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Presents the appropriate headers for this location.
+ * @param SimpleHttpRequest $request Request to modify.
+ * @param SimpleUrl $url Base of realm.
+ * @access public
+ */
+ function addHeaders($request, $url) {
+ if ($url->getUsername() && $url->getPassword()) {
+ $username = $url->getUsername();
+ $password = $url->getPassword();
+ } elseif ($realm = $this->_findRealmFromUrl($url)) {
+ $username = $realm->getUsername();
+ $password = $realm->getPassword();
+ } else {
+ return;
+ }
+ $this->addBasicHeaders($request, $username, $password);
+ }
+
+ /**
+ * Presents the appropriate headers for this
+ * location for basic authentication.
+ * @param SimpleHttpRequest $request Request to modify.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @access public
+ * @static
+ */
+ function addBasicHeaders($request, $username, $password) {
+ if ($username && $password) {
+ $request->addHeaderLine(
+ 'Authorization: Basic ' . base64_encode("$username:$password"));
+ }
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/browser.php b/tests/test_tools/simpletest/browser.php
new file mode 100644
index 00000000..06e1b8d7
--- /dev/null
+++ b/tests/test_tools/simpletest/browser.php
@@ -0,0 +1,1016 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: browser.php,v 1.141 2005/02/22 02:39:21 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/http.php');
+ require_once(dirname(__FILE__) . '/encoding.php');
+ require_once(dirname(__FILE__) . '/page.php');
+ require_once(dirname(__FILE__) . '/frames.php');
+ require_once(dirname(__FILE__) . '/user_agent.php');
+ /**#@-*/
+
+ define('DEFAULT_MAX_NESTED_FRAMES', 3);
+
+ /**
+ * Browser history list.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleBrowserHistory {
+ protected $_sequence;
+ protected $_position;
+
+ /**
+ * Starts empty.
+ * @access public
+ */
+ function SimpleBrowserHistory() {
+ $this->_sequence = array();
+ $this->_position = -1;
+ }
+
+ /**
+ * Test for no entries yet.
+ * @return boolean True if empty.
+ * @access private
+ */
+ function _isEmpty() {
+ return ($this->_position == -1);
+ }
+
+ /**
+ * Test for being at the beginning.
+ * @return boolean True if first.
+ * @access private
+ */
+ function _atBeginning() {
+ return ($this->_position == 0) && ! $this->_isEmpty();
+ }
+
+ /**
+ * Test for being at the last entry.
+ * @return boolean True if last.
+ * @access private
+ */
+ function _atEnd() {
+ return ($this->_position + 1 >= count($this->_sequence)) && ! $this->_isEmpty();
+ }
+
+ /**
+ * Adds a successfully fetched page to the history.
+ * @param string $method GET or POST.
+ * @param SimpleUrl $url URL of fetch.
+ * @param SimpleFormEncoding $parameters Any post data with the fetch.
+ * @access public
+ */
+ function recordEntry($method, $url, $parameters) {
+ $this->_dropFuture();
+ array_push(
+ $this->_sequence,
+ array('method' => $method, 'url' => $url, 'parameters' => $parameters));
+ $this->_position++;
+ }
+
+ /**
+ * Last fetching method for current history
+ * position.
+ * @return string GET or POST for this point in
+ * the history.
+ * @access public
+ */
+ function getMethod() {
+ if ($this->_isEmpty()) {
+ return false;
+ }
+ return $this->_sequence[$this->_position]['method'];
+ }
+
+ /**
+ * Last fully qualified URL for current history
+ * position.
+ * @return SimpleUrl URL for this position.
+ * @access public
+ */
+ function getUrl() {
+ if ($this->_isEmpty()) {
+ return false;
+ }
+ return $this->_sequence[$this->_position]['url'];
+ }
+
+ /**
+ * Parameters of last fetch from current history
+ * position.
+ * @return SimpleFormEncoding Post parameters.
+ * @access public
+ */
+ function getParameters() {
+ if ($this->_isEmpty()) {
+ return false;
+ }
+ return $this->_sequence[$this->_position]['parameters'];
+ }
+
+ /**
+ * Step back one place in the history. Stops at
+ * the first page.
+ * @return boolean True if any previous entries.
+ * @access public
+ */
+ function back() {
+ if ($this->_isEmpty() || $this->_atBeginning()) {
+ return false;
+ }
+ $this->_position--;
+ return true;
+ }
+
+ /**
+ * Step forward one place. If already at the
+ * latest entry then nothing will happen.
+ * @return boolean True if any future entries.
+ * @access public
+ */
+ function forward() {
+ if ($this->_isEmpty() || $this->_atEnd()) {
+ return false;
+ }
+ $this->_position++;
+ return true;
+ }
+
+ /**
+ * Ditches all future entries beyond the current
+ * point.
+ * @access private
+ */
+ function _dropFuture() {
+ if ($this->_isEmpty()) {
+ return;
+ }
+ while (! $this->_atEnd()) {
+ array_pop($this->_sequence);
+ }
+ }
+ }
+
+ /**
+ * Simulated web browser. This is an aggregate of
+ * the user agent, the HTML parsing, request history
+ * and the last header set.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleBrowser {
+ protected $_user_agent;
+ protected $_page;
+ protected $_history;
+ protected $_ignore_frames;
+ protected $_maximum_nested_frames;
+
+ /**
+ * Starts with a fresh browser with no
+ * cookie or any other state information. The
+ * exception is that a default proxy will be
+ * set up if specified in the options.
+ * @access public
+ */
+ function SimpleBrowser() {
+ $this->_user_agent = $this->_createUserAgent();
+ $this->_user_agent->useProxy(
+ SimpleTestOptions::getDefaultProxy(),
+ SimpleTestOptions::getDefaultProxyUsername(),
+ SimpleTestOptions::getDefaultProxyPassword());
+ $this->_page = new SimplePage();
+ $this->_history = $this->_createHistory();
+ $this->_ignore_frames = false;
+ $this->_maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES;
+ }
+
+ /**
+ * Creates the underlying user agent.
+ * @return SimpleFetcher Content fetcher.
+ * @access protected
+ */
+ function _createUserAgent() {
+ return new SimpleUserAgent();
+ }
+
+ /**
+ * Creates a new empty history list.
+ * @return SimpleBrowserHistory New list.
+ * @access protected
+ */
+ function _createHistory() {
+ return new SimpleBrowserHistory();
+ }
+
+ /**
+ * Disables frames support. Frames will not be fetched
+ * and the frameset page will be used instead.
+ * @access public
+ */
+ function ignoreFrames() {
+ $this->_ignore_frames = true;
+ }
+
+ /**
+ * Enables frames support. Frames will be fetched from
+ * now on.
+ * @access public
+ */
+ function useFrames() {
+ $this->_ignore_frames = false;
+ }
+
+ /**
+ * Parses the raw content into a page. Will load further
+ * frame pages unless frames are disabled.
+ * @param SimpleHttpResponse $response Response from fetch.
+ * @param integer $depth Nested frameset depth.
+ * @return SimplePage Parsed HTML.
+ * @access protected
+ */
+ function _parse($response, $depth = 0) {
+ $builder = new SimplePageBuilder();
+ $page = $builder->parse($response);
+ if ($this->_ignore_frames || ! $page->hasFrames() || ($depth > $this->_maximum_nested_frames)) {
+ return $page;
+ }
+ $frameset = new SimpleFrameset($page);
+ foreach ($page->getFrameset() as $key => $url) {
+ $frame = $this->_fetch('GET', $url, array(), $depth + 1);
+ $frameset->addFrame($frame, $key);
+ }
+ return $frameset;
+ }
+
+ /**
+ * Fetches a page.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @param integer $depth Nested frameset depth protection.
+ * @return SimplePage Parsed page.
+ * @access private
+ */
+ function _fetch($method, $url, $parameters, $depth = 0) {
+ $response = $this->_user_agent->fetchResponse($method, $url, $parameters);
+ if ($response->isError()) {
+ return new SimplePage($response);
+ }
+ return $this->_parse($response, $depth);
+ }
+
+ /**
+ * Fetches a page or a single frame if that is the current
+ * focus.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ function _load($method, $url, $parameters = false) {
+ $frame = $url->getTarget();
+ if (! $frame || ! $this->_page->hasFrames() || (strtolower($frame) == '_top')) {
+ return $this->_loadPage($method, $url, $parameters);
+ }
+ return $this->_loadFrame(array($frame), $method, $url, $parameters);
+ }
+
+ /**
+ * Fetches a page and makes it the current page/frame.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ function _loadPage($method, $url, $parameters = false) {
+ $this->_page = $this->_fetch(strtoupper($method), $url, $parameters);
+ $this->_history->recordEntry(
+ $this->_page->getMethod(),
+ $this->_page->getUrl(),
+ $this->_page->getRequestData());
+ return $this->_page->getRaw();
+ }
+
+ /**
+ * Fetches a frame into the existing frameset replacing the
+ * original.
+ * @param array $frames List of names to drill down.
+ * @param string $method GET or POST.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param SimpleFormEncoding $parameters POST parameters.
+ * @return string Raw content of page.
+ * @access private
+ */
+ function _loadFrame($frames, $method, $url, $parameters = false) {
+ $page = $this->_fetch(strtoupper($method), $url, $parameters);
+ $this->_page->setFrame($frames, $page);
+ }
+
+ /**
+ * Removes expired and temporary cookies as if
+ * the browser was closed and re-opened.
+ * @param string/integer $date Time when session restarted.
+ * If omitted then all persistent
+ * cookies are kept.
+ * @access public
+ */
+ function restart($date = false) {
+ $this->_user_agent->restart($date);
+ }
+
+ /**
+ * Adds a header to every fetch.
+ * @param string $header Header line to add to every
+ * request until cleared.
+ * @access public
+ */
+ function addHeader($header) {
+ $this->_user_agent->addHeader($header);
+ }
+
+ /**
+ * Ages the cookies by the specified time.
+ * @param integer $interval Amount in seconds.
+ * @access public
+ */
+ function ageCookies($interval) {
+ $this->_user_agent->ageCookies($interval);
+ }
+
+ /**
+ * Sets an additional cookie. If a cookie has
+ * the same name and path it is replaced.
+ * @param string $name Cookie key.
+ * @param string $value Value of cookie.
+ * @param string $host Host upon which the cookie is valid.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date.
+ * @access public
+ */
+ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
+ $this->_user_agent->setCookie($name, $value, $host, $path, $expiry);
+ }
+
+ /**
+ * Reads the most specific cookie value from the
+ * browser cookies.
+ * @param string $host Host to search.
+ * @param string $path Applicable path.
+ * @param string $name Name of cookie to read.
+ * @return string False if not present, else the
+ * value as a string.
+ * @access public
+ */
+ function getCookieValue($host, $path, $name) {
+ return $this->_user_agent->getCookieValue($host, $path, $name);
+ }
+
+ /**
+ * Reads the current cookies for the current URL.
+ * @param string $name Key of cookie to find.
+ * @return string Null if there is no current URL, false
+ * if the cookie is not set.
+ * @access public
+ */
+ function getCurrentCookieValue($name) {
+ return $this->_user_agent->getBaseCookieValue($name, $this->_page->getUrl());
+ }
+
+ /**
+ * Sets the maximum number of redirects before
+ * a page will be loaded anyway.
+ * @param integer $max Most hops allowed.
+ * @access public
+ */
+ function setMaximumRedirects($max) {
+ $this->_user_agent->setMaximumRedirects($max);
+ }
+
+ /**
+ * Sets the maximum number of nesting of framed pages
+ * within a framed page to prevent loops.
+ * @param integer $max Highest depth allowed.
+ * @access public
+ */
+ function setMaximumNestedFrames($max) {
+ $this->_maximum_nested_frames = $max;
+ }
+
+ /**
+ * Sets the socket timeout for opening a connection.
+ * @param integer $timeout Maximum time in seconds.
+ * @access public
+ */
+ function setConnectionTimeout($timeout) {
+ $this->_user_agent->setConnectionTimeout($timeout);
+ }
+
+ /**
+ * Sets proxy to use on all requests for when
+ * testing from behind a firewall. Set URL
+ * to false to disable.
+ * @param string $proxy Proxy URL.
+ * @param string $username Proxy username for authentication.
+ * @param string $password Proxy password for authentication.
+ * @access public
+ */
+ function useProxy($proxy, $username = false, $password = false) {
+ $this->_user_agent->useProxy($proxy, $username, $password);
+ }
+
+ /**
+ * Fetches the page content with a HEAD request.
+ * Will affect cookies, but will not change the base URL.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param hash/SimpleFormEncoding $parameters Additional parameters for
+ * HEAD request.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function head($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if (is_array($parameters)) {
+ $parameters = new SimpleFormEncoding($parameters);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ $response = $this->_user_agent->fetchResponse(
+ 'HEAD',
+ $url,
+ $parameters);
+ return ! $response->isError();
+ }
+
+ /**
+ * Fetches the page content with a simple GET request.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param hash/SimpleFormEncoding $parameters Additional parameters for
+ * GET request.
+ * @return string Content of page or false.
+ * @access public
+ */
+ function get($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if (is_array($parameters)) {
+ $parameters = new SimpleFormEncoding($parameters);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ return $this->_load('GET', $url, $parameters);
+ }
+
+ /**
+ * Fetches the page content with a POST request.
+ * @param string/SimpleUrl $url Target to fetch as string.
+ * @param hash/SimpleFormEncoding $parameters POST parameters.
+ * @return string Content of page.
+ * @access public
+ */
+ function post($url, $parameters = false) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ if (is_array($parameters)) {
+ $parameters = new SimpleFormEncoding($parameters);
+ }
+ if ($this->getUrl()) {
+ $url = $url->makeAbsolute($this->getUrl());
+ }
+ return $this->_load('POST', $url, $parameters);
+ }
+
+ /**
+ * Equivalent to hitting the retry button on the
+ * browser. Will attempt to repeat the page fetch. If
+ * there is no history to repeat it will give false.
+ * @return string/boolean Content if fetch succeeded
+ * else false.
+ * @access public
+ */
+ function retry() {
+ $frames = $this->_page->getFrameFocus();
+ if (count($frames) > 0) {
+ $this->_loadFrame(
+ $frames,
+ $this->_page->getMethod(),
+ $this->_page->getUrl(),
+ $this->_page->getRequestData());
+ return $this->_page->getRaw();
+ }
+ if ($method = $this->_history->getMethod()) {
+ $this->_page = $this->_fetch(
+ $method,
+ $this->_history->getUrl(),
+ $this->_history->getParameters());
+ return $this->_page->getRaw();
+ }
+ return false;
+ }
+
+ /**
+ * Equivalent to hitting the back button on the
+ * browser. The browser history is unchanged on
+ * failure.
+ * @return boolean True if history entry and
+ * fetch succeeded
+ * @access public
+ */
+ function back() {
+ if (! $this->_history->back()) {
+ return false;
+ }
+ $content = $this->retry();
+ if (! $content) {
+ $this->_history->forward();
+ }
+ return $content;
+ }
+
+ /**
+ * Equivalent to hitting the forward button on the
+ * browser. The browser history is unchanged on
+ * failure.
+ * @return boolean True if history entry and
+ * fetch succeeded
+ * @access public
+ */
+ function forward() {
+ if (! $this->_history->forward()) {
+ return false;
+ }
+ $content = $this->retry();
+ if (! $content) {
+ $this->_history->back();
+ }
+ return $content;
+ }
+
+ /**
+ * Retries a request after setting the authentication
+ * for the current realm.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @return boolean True if successful fetch. Note
+ * that authentication may still have
+ * failed.
+ * @access public
+ */
+ function authenticate($username, $password) {
+ if (! $this->_page->getRealm()) {
+ return false;
+ }
+ $url = $this->_page->getUrl();
+ if (! $url) {
+ return false;
+ }
+ $this->_user_agent->setIdentity(
+ $url->getHost(),
+ $this->_page->getRealm(),
+ $username,
+ $password);
+ return $this->retry();
+ }
+
+ /**
+ * Accessor for a breakdown of the frameset.
+ * @return array Hash tree of frames by name
+ * or index if no name.
+ * @access public
+ */
+ function getFrames() {
+ return $this->_page->getFrames();
+ }
+
+ /**
+ * Accessor for current frame focus. Will be
+ * false if no frame has focus.
+ * @return integer/string/boolean Label if any, otherwise
+ * the position in the frameset
+ * or false if none.
+ * @access public
+ */
+ function getFrameFocus() {
+ return $this->_page->getFrameFocus();
+ }
+
+ /**
+ * Sets the focus by index. The integer index starts from 1.
+ * @param integer $choice Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocusByIndex($choice) {
+ return $this->_page->setFrameFocusByIndex($choice);
+ }
+
+ /**
+ * Sets the focus by name.
+ * @param string $name Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocus($name) {
+ return $this->_page->setFrameFocus($name);
+ }
+
+ /**
+ * Clears the frame focus. All frames will be searched
+ * for content.
+ * @access public
+ */
+ function clearFrameFocus() {
+ return $this->_page->clearFrameFocus();
+ }
+
+ /**
+ * Accessor for last error.
+ * @return string Error from last response.
+ * @access public
+ */
+ function getTransportError() {
+ return $this->_page->getTransportError();
+ }
+
+ /**
+ * Accessor for current MIME type.
+ * @return string MIME type as string; e.g. 'text/html'
+ * @access public
+ */
+ function getMimeType() {
+ return $this->_page->getMimeType();
+ }
+
+ /**
+ * Accessor for last response code.
+ * @return integer Last HTTP response code received.
+ * @access public
+ */
+ function getResponseCode() {
+ return $this->_page->getResponseCode();
+ }
+
+ /**
+ * Accessor for last Authentication type. Only valid
+ * straight after a challenge (401).
+ * @return string Description of challenge type.
+ * @access public
+ */
+ function getAuthentication() {
+ return $this->_page->getAuthentication();
+ }
+
+ /**
+ * Accessor for last Authentication realm. Only valid
+ * straight after a challenge (401).
+ * @return string Name of security realm.
+ * @access public
+ */
+ function getRealm() {
+ return $this->_page->getRealm();
+ }
+
+ /**
+ * Accessor for current URL of page or frame if
+ * focused.
+ * @return string Location of current page or frame as
+ * a string.
+ */
+ function getUrl() {
+ $url = $this->_page->getUrl();
+ return $url ? $url->asString() : false;
+ }
+
+ /**
+ * Accessor for raw bytes sent down the wire.
+ * @return string Original text sent.
+ * @access public
+ */
+ function getRequest() {
+ return $this->_page->getRequest();
+ }
+
+ /**
+ * Accessor for raw header information.
+ * @return string Header block.
+ * @access public
+ */
+ function getHeaders() {
+ return $this->_page->getHeaders();
+ }
+
+ /**
+ * Accessor for raw page information.
+ * @return string Original text content of web page.
+ * @access public
+ */
+ function getContent() {
+ return $this->_page->getRaw();
+ }
+
+ /**
+ * Accessor for plain text version of the page.
+ * @return string Normalised text representation.
+ * @access public
+ */
+ function getContentAsText() {
+ return $this->_page->getText();
+ }
+
+ /**
+ * Accessor for parsed title.
+ * @return string Title or false if no title is present.
+ * @access public
+ */
+ function getTitle() {
+ return $this->_page->getTitle();
+ }
+
+ /**
+ * Accessor for a list of all fixed links in current page.
+ * @return array List of urls with scheme of
+ * http or https and hostname.
+ * @access public
+ */
+ function getAbsoluteUrls() {
+ return $this->_page->getAbsoluteUrls();
+ }
+
+ /**
+ * Accessor for a list of all relative links.
+ * @return array List of urls without hostname.
+ * @access public
+ */
+ function getRelativeUrls() {
+ return $this->_page->getRelativeUrls();
+ }
+
+ /**
+ * Sets all form fields with that name.
+ * @param string $name Name of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($name, $value) {
+ return $this->_page->setField($name, $value);
+ }
+
+ /**
+ * Sets all form fields with that id attribute.
+ * @param string/integer $id Id of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setFieldById($id, $value) {
+ return $this->_page->setFieldById($id, $value);
+ }
+
+ /**
+ * Accessor for a form element value within the page.
+ * Finds the first match.
+ * @param string $name Field name.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($name) {
+ return $this->_page->getField($name);
+ }
+
+ /**
+ * Accessor for a form element value within the page.
+ * @param string/integer $id Id of field in forms.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getFieldById($id) {
+ return $this->_page->getFieldById($id);
+ }
+
+ /**
+ * Clicks the submit button by label. The owning
+ * form will be submitted by this.
+ * @param string $label Button label. An unlabeled
+ * button can be triggered by 'Submit'.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickSubmit($label = 'Submit', $additional = false) {
+ if (! ($form = $this->_page->getFormBySubmitLabel($label))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitButtonByLabel($label, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit button by name attribute. The owning
+ * form will be submitted by this.
+ * @param string $name Button name.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickSubmitByName($name, $additional = false) {
+ if (! ($form = $this->_page->getFormBySubmitName($name))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitButtonByName($name, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit button by ID attribute of the button
+ * itself. The owning form will be submitted by this.
+ * @param string $id Button ID.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickSubmitById($id, $additional = false) {
+ if (! ($form = $this->_page->getFormBySubmitId($id))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitButtonById($id, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit image by some kind of label. Usually
+ * the alt tag or the nearest equivalent. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param string $label ID attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickImage($label, $x = 1, $y = 1, $additional = false) {
+ if (! ($form = $this->_page->getFormByImageLabel($label))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitImageByLabel($label, $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit image by the name. Usually
+ * the alt tag or the nearest equivalent. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param string $name Name attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
+ if (! ($form = $this->_page->getFormByImageName($name))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitImageByName($name, $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Clicks the submit image by ID attribute. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param integer/string $id ID attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form data.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickImageById($id, $x = 1, $y = 1, $additional = false) {
+ if (! ($form = $this->_page->getFormByImageId($id))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submitImageById($id, $x, $y, $additional));
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Submits a form by the ID.
+ * @param string $id The form ID. No submit button value
+ * will be sent.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function submitFormById($id) {
+ if (! ($form = $this->_page->getFormById($id))) {
+ return false;
+ }
+ $success = $this->_load(
+ $form->getMethod(),
+ $form->getAction(),
+ $form->submit());
+ return ($success ? $this->getContent() : $success);
+ }
+
+ /**
+ * Follows a link by label. Will click the first link
+ * found with this link text by default, or a later
+ * one if an index is given. The match ignores case and
+ * white space issues.
+ * @param string $label Text between the anchor tags.
+ * @param integer $index Link position counting from zero.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickLink($label, $index = 0) {
+ $urls = $this->_page->getUrlsByLabel($label);
+ if (count($urls) == 0) {
+ return false;
+ }
+ if (count($urls) < $index + 1) {
+ return false;
+ }
+ $this->_load('GET', $urls[$index]);
+ return $this->getContent();
+ }
+
+ /**
+ * Tests to see if a link is present by label.
+ * @param string $label Text of value attribute.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function isLink($label) {
+ return (count($this->_page->getUrlsByLabel($label)) > 0);
+ }
+
+ /**
+ * Follows a link by id attribute.
+ * @param string $id ID attribute value.
+ * @return string/boolean Page on success.
+ * @access public
+ */
+ function clickLinkById($id) {
+ if (! ($url = $this->_page->getUrlById($id))) {
+ return false;
+ }
+ $this->_load('GET', $url);
+ return $this->getContent();
+ }
+
+ /**
+ * Tests to see if a link is present by ID attribute.
+ * @param string $id Text of id attribute.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function isLinkById($id) {
+ return (boolean)$this->_page->getUrlById($id);
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/docs/en/authentication_documentation.html b/tests/test_tools/simpletest/docs/en/authentication_documentation.html
new file mode 100755
index 00000000..0623023c
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/authentication_documentation.html
@@ -0,0 +1,320 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest documentation for testing log-in and authentication</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Authentication</span>
+</li>
+<li>
+<a href="browser_documentation.html">Scriptable browser</a>
+</li>
+</ul>
+</div>
+</div>
+<h1>Authentication documentation</h1>
+<div class="content">
+
+ <p>
+ One of the trickiest, and yet most important, areas
+ of testing web sites is the security.
+ Testing these schemes is one of the core goals of
+ the SimpleTest web tester.
+ </p>
+
+ <p>
+<a class="target" name="basic">
+<h2>Basic HTTP authentication</h2>
+</a>
+</p>
+ <p>
+ If you fetch a page protected by basic authentication then
+ rather than receiving content, you will instead get a 401
+ header.
+ We can illustrate this with this test...
+<pre>
+class AuthenticationTest extends WebTestCase {<strong>
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');
+ $this-&gt;showHeaders();
+ }</strong>
+}
+</pre>
+ This allows us to see the challenge header...
+ <div class="demo">
+ <h1>File test</h1>
+<pre 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>
+ We are trying to get away from visual inspection though, and so SimpleTest
+ allows to make automated assertions against the challenge.
+ Here is a thorough test of our header...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function test401Header() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
+ $this-&gt;assertAuthentication('Basic');
+ $this-&gt;assertResponse(401);
+ $this-&gt;assertRealm('SimpleTest basic authentication');</strong>
+ }
+}
+</pre>
+ Any one of these tests would normally do on it's own depending
+ on the amount of detail you want to see.
+ </p>
+ <p>
+ Most of the time we are not interested in testing the
+ authentication itself, but want to get past it to test
+ the pages underneath.
+ As soon as the challenge has been issued we can reply with
+ an authentication response...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function testAuthentication() {
+ $this-&gt;get('http://www.lastcraft.com/protected/');<strong>
+ $this-&gt;authenticate('Me', 'Secret');</strong>
+ $this-&gt;assertTitle(...);
+ }
+}
+</pre>
+ The username and password will now be sent with every
+ subsequent request to that directory and subdirectories.
+ You will have to authenticate again if you step outside
+ the authenticated directory, but SimpleTest is smart enough
+ to merge subdirectories into a common realm.
+ </p>
+ <p>
+ You can shortcut this step further by encoding the log in
+ details straight into the URL...
+<pre>
+class AuthenticationTest extends WebTestCase {
+ function testCanReadAuthenticatedPages() {
+ $this-&gt;get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
+ $this-&gt;assertTitle(...);
+ }
+}
+</pre>
+ If your username or password has special characters, then you
+ will have to URL encode them or the request will not be parsed
+ correctly.
+ Also this header will not be sent on subsequent requests if
+ you request a page with a fully qualified URL.
+ If you navigate with relative URLs though, the authentication
+ information will be preserved.
+ </p>
+ <p>
+ Only basic authentication is currently supported and this is
+ only really secure in tandem with HTTPS connections.
+ This is usually enough to protect test server from prying eyes,
+ however.
+ Digest authentication and NTLM authentication may be added
+ in the future.
+ </p>
+
+ <p>
+<a class="target" name="cookies">
+<h2>Cookies</h2>
+</a>
+</p>
+ <p>
+ Basic authentication doesn't give enough control over the
+ user interface for web developers.
+ More likely this functionality will be coded directly into
+ the web architecture using cookies and complicated timeouts.
+ </p>
+ <p>
+ Starting with a simple log-in form...
+<pre>
+&lt;form&gt;
+ Username:
+ &lt;input type="text" name="u" value="" /&gt;&lt;br /&gt;
+ Password:
+ &lt;input type="password" name="p" value="" /&gt;&lt;br /&gt;
+ &lt;input type="submit" value="Log in" /&gt;
+&lt;/form&gt;
+</pre>
+ Which looks like...
+ </p>
+ <p>
+ <form class="demo">
+ Username:
+ <input type="text" name="u" value="">
+<br>
+ Password:
+ <input type="password" name="p" value="">
+<br>
+ <input type="submit" value="Log in">
+ </form>
+ </p>
+ <p>
+ Let's suppose that in fetching this page a cookie has been
+ set with a session ID.
+ We are not going to fill the form in yet, just test that
+ we are tracking the user.
+ Here is the test...
+<pre>
+class LogInTest extends WebTestCase {
+ function testSessionCookieSetBeforeForm() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $this-&gt;assertCookie('SID');</strong>
+ }
+}
+</pre>
+ All we are doing is confirming that the cookie is set.
+ As the value is likely to be rather cryptic it's not
+ really worth testing this.
+ </p>
+ <p>
+ The rest of the test would be the same as any other form,
+ but we might want to confirm that we still have the same
+ cookie after log-in as before we entered.
+ We wouldn't want to lose track of this after all.
+ Here is a possible test for this...
+<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>
+ This confirms that the session identifier is maintained
+ afer log-in.
+ </p>
+ <p>
+ We could even attempt to spoof our own system by setting
+ arbitrary cookies to gain access...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testSessionCookieSameAfterLogIn() {
+ $this-&gt;get('http://www.my-site.com/login.php');<strong>
+ $this-&gt;setCookie('SID', 'Some other session');
+ $this-&gt;get('http://www.my-site.com/restricted.php');</strong>
+ $this-&gt;assertWantedPattern('/Access denied/');
+ }
+}
+</pre>
+ Is your site protected from this attack?
+ </p>
+
+ <p>
+<a class="target" name="session">
+<h2>Browser sessions</h2>
+</a>
+</p>
+ <p>
+ If you are testing an authentication system a critical piece
+ of behaviour is what happens when a user logs back in.
+ We would like to simulate closing and reopening a browser...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testLoseAuthenticationAfterBrowserClose() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;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>
+ The <span class="new_code">WebTestCase::restart()</span> method will
+ preserve cookies that have unexpired timeouts, but throw away
+ those that are temporary or expired.
+ You can optionally specify the time and date that the restart
+ happened.
+ </p>
+ <p>
+ Expiring cookies can be a problem.
+ After all, if you have a cookie that expires after an hour,
+ you don't want to stall the test for an hour while the
+ cookie passes it's timeout.
+ </p>
+ <p>
+ To push the cookies over the hour limit you can age them
+ before you restart the session...
+<pre>
+class LogInTest extends WebTestCase {
+ ...
+ function testLoseAuthenticationAfterOneHour() {
+ $this-&gt;get('http://www.my-site.com/login.php');
+ $this-&gt;setField('u', 'Me');
+ $this-&gt;setField('p', 'Secret');
+ $this-&gt;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>
+ After the restart it will appear that cookies are an
+ hour older and any that pass their expiry will have
+ disappeared.
+ </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/en/browser_documentation.html b/tests/test_tools/simpletest/docs/en/browser_documentation.html
new file mode 100755
index 00000000..ef54aaea
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/browser_documentation.html
@@ -0,0 +1,386 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest documentation for the scriptable web browser component</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Scriptable browser</span>
+</li>
+</ul>
+</div>
+</div>
+<h1>PHP Scriptable Web Browser</h1>
+<div class="content">
+
+ <p>
+ SimpleTest's web browser component can be used not just
+ outside of the <span class="new_code">WebTestCase</span> class, but also
+ independently of the SimpleTest framework itself.
+ </p>
+
+ <p>
+<a class="target" name="scripting">
+<h2>The Scriptable Browser</h2>
+</a>
+</p>
+ <p>
+ You can use the web browser in PHP scripts to confirm
+ services are up and running, or to extract information
+ from them at a regular basis.
+ For example, here is a small script to extract the current number of
+ open PHP 5 bugs from the <a href="http://www.php.net/">PHP web site</a>...
+<pre>
+<strong>&lt;?php
+ require_once('simpletest/browser.php');
+
+ $browser = &amp;new SimpleBrowser();
+ $browser-&gt;get('http://php.net/');
+ $browser-&gt;clickLink('reporting bugs');
+ $browser-&gt;clickLink('statistics');
+ $page = $browser-&gt;clickLink('PHP 5 bugs only');
+ preg_match('/status=Open.*?by=Any.*?(\d+)&lt;\/a&gt;/', $page, $matches);
+ print $matches[1];
+?&gt;</strong>
+</pre>
+ There are simpler methods to do this particular example in PHP
+ of course.
+ For example you can just use the PHP <span class="new_code">file()</span>
+ command against what here is a pretty fixed page.
+ However, using the web browser for scripts allows authentication,
+ correct handling of cookies, automatic loading of frames, redirects,
+ form submission and the ability to examine the page headers.
+ Such methods are fragile against a site that is constantly
+ evolving and you would want a more direct way of accessing
+ data in a permanent set up, but for simple tasks this can provide
+ a very rapid solution.
+ </p>
+ <p>
+ All of the navigation methods used in the
+ <a href="web_tester_documentation.html">WebTestCase</a>
+ are present in the <span class="new_code">SimpleBrowser</span> class, but
+ the assertions are replaced with simpler accessors.
+ Here is a full list of the page navigation methods...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">addHeader($header)</span></td><td>Adds a header to every fetch</td>
+</tr>
+ <tr>
+<td><span class="new_code">useProxy($proxy, $username, $password)</span></td><td>Use this proxy from now on</td>
+</tr>
+ <tr>
+<td><span class="new_code">head($url, $parameters)</span></td><td>Perform a HEAD request</td>
+</tr>
+ <tr>
+<td><span class="new_code">get($url, $parameters)</span></td><td>Fetch a page with GET</td>
+</tr>
+ <tr>
+<td><span class="new_code">post($url, $parameters)</span></td><td>Fetch a page with POST</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLink($label)</span></td><td>Follows a link by label</td>
+</tr>
+ <tr>
+<td><span class="new_code">isLink($label)</span></td><td>See if a link is present by label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLinkById($id)</span></td><td>Follows a link by attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">isLinkById($id)</span></td><td>See if a link is present by attribut</td>
+</tr>
+ <tr>
+<td><span class="new_code">getUrl()</span></td><td>Current URL of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getTitle()</span></td><td>Page title</td>
+</tr>
+ <tr>
+<td><span class="new_code">getContent()</span></td><td>Raw page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getContentAsText()</span></td><td>HTML removed except for alt text</td>
+</tr>
+ <tr>
+<td><span class="new_code">retry()</span></td><td>Repeat the last request</td>
+</tr>
+ <tr>
+<td><span class="new_code">back()</span></td><td>Use the browser back button</td>
+</tr>
+ <tr>
+<td><span class="new_code">forward()</span></td><td>Use the browser forward button</td>
+</tr>
+ <tr>
+<td><span class="new_code">authenticate($username, $password)</span></td><td>Retry page or frame after a 401 response</td>
+</tr>
+ <tr>
+<td><span class="new_code">restart($date)</span></td><td>Restarts the browser for a new session</td>
+</tr>
+ <tr>
+<td><span class="new_code">ageCookies($interval)</span></td><td>Ages the cookies by the specified time</td>
+</tr>
+ <tr>
+<td><span class="new_code">setCookie($name, $value)</span></td><td>Sets an additional cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCookieValue($host, $path, $name)</span></td><td>Reads the most specific cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCurrentCookieValue($name)</span></td><td>Reads cookie for the current context</td>
+</tr>
+ </tbody>
+</table>
+ The methods <span class="new_code">SimpleBrowser::useProxy()</span> and
+ <span class="new_code">SimpleBrowser::addHeader()</span> are special.
+ Once called they continue to apply to all subsequent fetches.
+ </p>
+ <p>
+ Navigating forms is similar to the
+ <a href="form_testing_documentation.html">WebTestCase form navigation</a>...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">setField($name, $value)</span></td><td>Sets all form fields with that name</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFieldById($id, $value)</span></td><td>Sets all form fields with that id</td>
+</tr>
+ <tr>
+<td><span class="new_code">getField($name)</span></td><td>Accessor for a form element value</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFieldById($id)</span></td><td>Accessor for a form element value</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmit($label)</span></td><td>Submits form by button label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitByName($name)</span></td><td>Submits form by button attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitById($id)</span></td><td>Submits form by button attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImage($label, $x, $y)</span></td><td>Clicks the image by alt text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageByName($name, $x, $y)</span></td><td>Clicks the image by attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageById($id, $x, $y)</span></td><td>Clicks the image by attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">submitFormById($id)</span></td><td>Submits by the form tag attribute</td>
+</tr>
+ </tbody>
+</table>
+ At the moment there aren't any methods to list available forms
+ and fields.
+ This will probably be added to later versions of SimpleTest.
+ </p>
+ <p>
+ Within a page, individual frames can be selected.
+ If no selection is made then all the frames are merged together
+ in one large conceptual page.
+ The content of the current page will be a concatenation of all of the
+ frames in the order that they were specified in the "frameset"
+ tags.
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">getFrames()</span></td><td>A dump of the current frame structure</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFrameFocus()</span></td><td>Current frame label or index</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocusByIndex($choice)</span></td><td>Select a frame numbered from 1</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocus($name)</span></td><td>Select frame by label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clearFrameFocus()</span></td><td>Treat all the frames as a single page</td>
+</tr>
+ </tbody>
+</table>
+ When focused on a single frame, the content will come from
+ that frame only.
+ This includes links to click and forms to submit.
+ </p>
+
+ <p>
+<a class="target" name="debug">
+<h2>What went wrong?</h2>
+</a>
+</p>
+ <p>
+ All of this functionality is great when we actually manage to fetch pages,
+ but that doesn't always happen.
+ To help figure out what went wrong, the browser has some methods to
+ aid in debugging...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">setConnectionTimeout($timeout)</span></td><td>Close the socket on overrun</td>
+</tr>
+ <tr>
+<td><span class="new_code">getRequest()</span></td><td>Raw request header of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getHeaders()</span></td><td>Raw response header of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getTransportError()</span></td><td>Any socket level errors in the last fetch</td>
+</tr>
+ <tr>
+<td><span class="new_code">getResponseCode()</span></td><td>HTTP response of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getMimeType()</span></td><td>Mime type of page or frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">getAuthentication()</span></td><td>Authentication type in 401 challenge header</td>
+</tr>
+ <tr>
+<td><span class="new_code">getRealm()</span></td><td>Authentication realm in 401 challenge header</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumRedirects($max)</span></td><td>Number of redirects before page is loaded anyway</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumNestedFrames($max)</span></td><td>Protection against recursive framesets</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreFrames()</span></td><td>Disables frames support</td>
+</tr>
+ <tr>
+<td><span class="new_code">useFrames()</span></td><td>Enables frames support</td>
+</tr>
+ </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
+ to every subsequent request.
+ The other methods are frames aware.
+ This means that if you have an individual frame that is not
+ loading, navigate to it using <span class="new_code">SimpleBrowser::setFrameFocus()</span>
+ and you can then use <span class="new_code">SimpleBrowser::getRequest()</span>, etc to
+ see what happened.
+ </p>
+
+ <p>
+<a class="target" name="unit">
+<h2>Complex unit tests with multiple browsers</h2>
+</a>
+</p>
+ <p>
+ Anything that could be done in a
+ <a href="web_tester_documentation.html">WebTestCase</a> can
+ now be done in a <a href="unit_tester_documentation.html">UnitTestCase</a>.
+ This means that we can freely mix domain object testing with the
+ web interface...
+<pre>
+<strong>
+class TestOfRegistration extends UnitTestCase {
+ function testNewUserAddedToAuthenticator() {</strong>
+ $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');
+ <strong>
+ $authenticator = &amp;new Authenticator();
+ $member = &amp;$authenticator-&gt;findByEmail('me@here');
+ $this-&gt;assertEqual($member-&gt;getPassword(), 'Secret');
+ }
+}</strong>
+</pre>
+ While this may be a useful temporary expediency, I am not a fan
+ of this type of testing.
+ The testing has cut across application layers, make it twice as
+ likely it will need refactoring when the code changes.
+ </p>
+ <p>
+ A more useful case of where using the browser directly can be helpful
+ is where the <span class="new_code">WebTestCase</span> cannot cope.
+ An example is where two browsers are needed at the same time.
+ </p>
+ <p>
+ For example, say we want to disallow multiple simultaneous
+ usage of a site with the same username.
+ This test case will do the job...
+<pre>
+class TestOfSecurity extends UnitTestCase {
+ function testNoMultipleLoginsFromSameUser() {<strong>
+ $first = &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');</strong>
+ }
+}
+</pre>
+ You can also use the <span class="new_code">SimpleBrowser</span> class
+ directly when you want to write test cases using a different
+ test tool than SimpleTest.
+ </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/en/docs.css b/tests/test_tools/simpletest/docs/en/docs.css
new file mode 100755
index 00000000..93226cd7
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/docs.css
@@ -0,0 +1,84 @@
+body {
+ padding-left: 3%;
+ padding-right: 3%;
+}
+pre {
+ font-family: courier;
+ font-size: 80%;
+ border: 1px solid;
+ background-color: #cccccc;
+ padding: 5px;
+ margin-left: 5%;
+ margin-right: 8%;
+}
+.code, .new_code, pre.new_code {
+ font-weight: bold;
+}
+div.copyright {
+ font-size: 80%;
+ color: gray;
+}
+div.copyright a {
+ color: gray;
+}
+ul.api {
+ padding-left: 0em;
+ padding-right: 25%;
+}
+ul.api li {
+ margin-top: 0.2em;
+ margin-bottom: 0.2em;
+ list-style: none;
+ text-indent: -3em;
+ padding-left: 3em;
+}
+div.demo {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: white;
+}
+div.demo span.fail {
+ color: red;
+}
+div.demo span.pass {
+ color: green;
+}
+div.demo h1 {
+ font-size: 12pt;
+ text-align: left;
+ font-weight: bold;
+}
+table {
+ border: 2px outset;
+ border-color: gray;
+ background-color: white;
+ margin: 5px;
+ margin-left: 5%;
+ margin-right: 5%;
+}
+td {
+ font-size: 80%;
+}
+.shell {
+ color: white;
+}
+pre.shell {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: black;
+}
+form.demo {
+ background-color: lightgray;
+ border: 4px outset;
+ border-color: lightgray;
+ padding: 10px;
+ margin-right: 40%;
+}
diff --git a/tests/test_tools/simpletest/docs/en/expectation_documentation.html b/tests/test_tools/simpletest/docs/en/expectation_documentation.html
new file mode 100755
index 00000000..0165988c
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/expectation_documentation.html
@@ -0,0 +1,356 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Extending the SimpleTest unit tester with additional expectation classes
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Expectations</span>
+</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>Expectation documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="mock">
+<h2>More control over mock objects</h2>
+</a>
+</p>
+ <p>
+ The default behaviour of the
+ <a href="mock_objects_documentation.html">mock objects</a>
+ in
+ <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a>
+ is either an identical match on the argument or to allow any argument at all.
+ For almost all tests this is sufficient.
+ Sometimes, though, you want to weaken a test case.
+ </p>
+ <p>
+ One place where a test can be too tightly coupled is with
+ text matching.
+ Suppose we have a component that outputs a helpful error
+ message when something goes wrong.
+ You want to test that the correct error was sent, but the actual
+ text may be rather long.
+ If you test for the text exactly, then every time the exact wording
+ of the message changes, you will have to go back and edit the test suite.
+ </p>
+ <p>
+ For example, suppose we have a news service that has failed
+ to connect to its remote source.
+<pre>
+<strong>class NewsService {
+ ...
+ function publish(&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>
+ Here it is sending its content to a
+ <span class="new_code">Writer</span> class.
+ We could test this behaviour with a
+ <span class="new_code">MockWriter</span> like so...
+<pre>
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {<strong>
+ $writer = &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>
+ This is a good example of a brittle test.
+ If we decide to add additional instructions, such as
+ suggesting an alternative news source, we will break
+ our tests even though no underlying functionality
+ has been altered.
+ </p>
+ <p>
+ To get around this, we would like to do a regular expression
+ test rather than an exact match.
+ We can actually do this with...
+<pre>
+class TestOfNewsService extends UnitTestCase {
+ ...
+ function testConnectionFailure() {
+ $writer = &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>
+ Instead of passing in the expected parameter to the
+ <span class="new_code">MockWriter</span> we pass an
+ expectation class called
+ <span class="new_code">WantedPatternExpectation</span>.
+ The mock object is smart enough to recognise this as special
+ and to treat it differently.
+ Rather than simply comparing the incoming argument to this
+ object, it uses the expectation object itself to
+ perform the test.
+ </p>
+ <p>
+ The <span class="new_code">WantedPatternExpectation</span> takes
+ the regular expression to match in its constructor.
+ Whenever a comparison is made by the <span class="new_code">MockWriter</span>
+ against this expectation class, it will do a
+ <span class="new_code">preg_match()</span> with this pattern.
+ With our test case above, as long as "cannot connect"
+ appears in the text of the string, the mock will issue a pass
+ to the unit tester.
+ The rest of the text does not matter.
+ </p>
+ <p>
+ The possible expectation classes are...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">EqualExpectation</span></td><td>An equality, rather than the stronger identity comparison</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotEqualExpectation</span></td><td>An inequality comparison</td>
+</tr>
+ <tr>
+<td><span class="new_code">IndenticalExpectation</span></td><td>The default mock object check which must match exactly</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotIndenticalExpectation</span></td><td>Inverts the mock object logic</td>
+</tr>
+ <tr>
+<td><span class="new_code">WantedPatternExpectation</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>
+</tr>
+ <tr>
+<td><span class="new_code">IsAExpectation</span></td><td>Checks the type or class name only</td>
+</tr>
+ <tr>
+<td><span class="new_code">NotAExpectation</span></td><td>Opposite of the <span class="new_code">IsAExpectation</span></td>
+</tr>
+ <tr>
+<td><span class="new_code">MethodExistsExpectation</span></td><td>Checks a method is available on an object</td>
+</tr>
+ </tbody>
+</table>
+ Most take the expected value in the constructor.
+ The exceptions are the pattern matchers, which take a regular expression,
+ and the <span class="new_code">IsAExpectation</span> and <span class="new_code">NotAExpectation</span> which takes a type
+ or class name as a string.
+ </p>
+
+ <p>
+<a class="target" name="behaviour">
+<h2>Using expectations to control stubs</h2>
+</a>
+</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>.
+ 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
+ only if it receives a valid session object.
+ We can do this as follows...
+<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>
+ We have set the default stub behaviour to return false when
+ <span class="new_code">isAllowed</span> is called.
+ When we call the method with a single parameter that
+ is a <span class="new_code">Session</span> object, it will return true.
+ We have also added a second parameter as a message.
+ This will be displayed as part of the mock object
+ failure message if this expectation is the cause of
+ a failure.
+ </p>
+ <p>
+ This kind of sophistication is rarely useful, but is included for
+ completeness.
+ </p>
+
+ <p>
+<a class="target" name="extending">
+<h2>Creating your own expectations</h2>
+</a>
+</p>
+ <p>
+ The expectation classes have a very simple structure.
+ So simple that it is easy to create your own versions for
+ commonly used test logic.
+ </p>
+ <p>
+ As an example here is the creation of a class to test for
+ valid IP addresses.
+ In order to work correctly with the stubs and mocks the new
+ expectation class should extend
+ <span class="new_code">SimpleExpectation</span>...
+<pre>
+<strong>class ValidIp extends SimpleExpectation {
+
+ function test($ip) {
+ return (ip2long($ip) != -1);
+ }
+
+ function testMessage($ip) {
+ return "Address [$ip] should be a valid IP address";
+ }
+}</strong>
+</pre>
+ There are only two methods to implement.
+ The <span class="new_code">test()</span> method should
+ evaluate to true if the expectation is to pass, and
+ false otherwise.
+ The <span class="new_code">testMessage()</span> method
+ should simply return some helpful text explaining the test
+ that was carried out.
+ </p>
+ <p>
+ This class can now be used in place of the earlier expectation
+ classes.
+ </p>
+
+ <p>
+<a class="target" name="unit">
+<h2>Under the bonnet of the unit tester</h2>
+</a>
+</p>
+ <p>
+ The <a href="http://sourceforge.net/projects/simpletest/">SimpleTest unit testing framework</a>
+ also uses the expectation classes internally for the
+ <a href="unit_test_documentation.html">UnitTestCase class</a>.
+ We can also take advantage of these mechanisms to reuse our
+ homebrew expectation classes within the test suites directly.
+ </p>
+ <p>
+ The most crude way of doing this is to use the
+ <span class="new_code">SimpleTest::assertExpectation()</span> method to
+ test against it directly...
+<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>
+ This is a little untidy compared with our usual
+ <span class="new_code">assert...()</span> syntax.
+ </p>
+ <p>
+ For such a simple case we would normally create a
+ separate assertion method on our test case rather
+ than bother using the expectation class.
+ If we pretend that our expectation is a little more
+ complicated for a moment, so that we want to reuse it,
+ we get...
+<pre>
+class TestOfNetworking extends UnitTestCase {
+ ...<strong>
+ function assertValidIp($ip, $message = '%s') {
+ $this-&gt;assertExpectation(new ValidIp(), $ip, $message);
+ }</strong>
+
+ function testGetValidIp() {
+ $server = &amp;new Server();<strong>
+ $this-&gt;assertValidIp(
+ $server-&gt;getIp(),
+ 'Server IP address-&gt;%s');</strong>
+ }
+}
+</pre>
+ It is unlikely we would ever need this degree of control
+ over the testing machinery.
+ It is rare to need the expectations for more than pattern
+ matching.
+ Also, complex expectation classes could make the tests
+ harder to read and debug.
+ These mechanisms are really of most use to authors of systems
+ that will extend the test framework to create their own tool set.
+ </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/en/form_testing_documentation.html b/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
new file mode 100755
index 00000000..b1e15b3d
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/form_testing_documentation.html
@@ -0,0 +1,277 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Simple Test documentation for testing HTML forms</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Testing forms</span>
+</li>
+<li>
+<a href="authentication_documentation.html">Authentication</a>
+</li>
+<li>
+<a href="browser_documentation.html">Scriptable browser</a>
+</li>
+</ul>
+</div>
+</div>
+<h1>Form testing documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="submit">
+<h2>Submitting a simple form</h2>
+</a>
+</p>
+ <p>
+ When a page is fetched by the <span class="new_code">WebTestCase</span>
+ using <span class="new_code">get()</span> or
+ <span class="new_code">post()</span> the page content is
+ automatically parsed.
+ This results in any form controls that are inside &lt;form&gt; tags
+ being available from within the test case.
+ For example, if we have this snippet of HTML...
+<pre>
+&lt;form&gt;
+ &lt;input type="text" name="a" value="A default" /&gt;
+ &lt;input type="submit" value="Go" /&gt;
+&lt;/form&gt;
+</pre>
+ Which looks like this...
+ </p>
+ <p>
+ <form class="demo">
+ <input type="text" name="a" value="A default">
+ <input type="submit" value="Go">
+ </form>
+ </p>
+ <p>
+ We can navigate to this code, via the
+ <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>
+ site, with the following test...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ <strong>
+ function testDefaultValue() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('a', 'A default');
+ }</strong>
+}
+</pre>
+ Immediately after loading the page all of the HTML controls are set at
+ their default values just as they would appear in the web browser.
+ The assertion tests that a HTML widget exists in the page with the
+ name "a" and that it is currently set to the value
+ "A default"
+ </p>
+ <p>
+ We could submit the form straight away, but first we'll change
+ the value of the text field and only then submit it...
+<pre>
+class SimpleFormTests extends WebTestCase {
+
+ function testDefaultValue() {
+ $this-&gt;get('http://www.my-site.com/');
+ $this-&gt;assertField('a', 'A default');<strong>
+ $this-&gt;setField('a', 'New value');
+ $this-&gt;clickSubmit('Go');</strong>
+ }
+}
+</pre>
+ Because we didn't specify a method attribute on the form tag, and
+ didn't specify an action either, the test case will follow
+ the usual browser behaviour of submitting the form data as a <em>GET</em>
+ request back to the same location.
+ SimpleTest tries to emulate typical browser behaviour as much as possible,
+ rather than attempting to catch missing attributes on tags.
+ This is because the target of the testing framework is the PHP application
+ logic, not syntax or other errors in the HTML code.
+ For HTML errors, other tools such as
+ <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> should be used.
+ </p>
+ <p>
+ If a field is not present in any form, or if an option is unavailable,
+ then <span class="new_code">WebTestCase::setField()</span> will return
+ <span class="new_code">false</span>.
+ For example, suppose we wish to verify that a "Superuser"
+ option is not present in this form...
+<pre>
+&lt;strong&gt;Select type of user to add:&lt;/strong&gt;
+&lt;select name="type"&gt;
+ &lt;option&gt;Subscriber&lt;/option&gt;
+ &lt;option&gt;Author&lt;/option&gt;
+ &lt;option&gt;Administrator&lt;/option&gt;
+&lt;/select&gt;
+</pre>
+ Which looks like...
+ </p>
+ <p>
+ <form class="demo">
+ <strong>Select type of user to add:</strong>
+ <select name="type">
+ <option>Subscriber</option>
+ <option>Author</option>
+ <option>Administrator</option>
+ </select>
+ </form>
+ </p>
+ <p>
+ The following test will confirm it...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...
+ function testNoSuperuserChoiceAvailable() {<strong>
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertFalse($this-&gt;setField('type', 'Superuser'));</strong>
+ }
+}
+</pre>
+ The selection will not be changed on a failure to set
+ a widget value.
+ </p>
+ <p>
+ Here is the full list of widgets currently supported...
+ <ul>
+ <li>Text fields, including hidden and password fields.</li>
+ <li>Submit buttons including the button tag, although not yet reset buttons</li>
+ <li>Text area. This includes text wrapping behaviour.</li>
+ <li>Checkboxes, including multiple checkboxes in the same form.</li>
+ <li>Drop down selections, including multiple selects.</li>
+ <li>Radio buttons.</li>
+ <li>Images.</li>
+ </ul>
+ </p>
+ <p>
+ Although most standard HTML widgets are catered for by <em>SimpleTest</em>'s
+ built in parser, it is unlikely that JavaScript will be implemented
+ anytime soon.
+ </p>
+
+ <p>
+<a class="target" name="multiple">
+<h2>Fields with multiple values</h2>
+</a>
+</p>
+ <p>
+ SimpleTest can cope with two types of multivalue controls: Multiple
+ selection drop downs, and multiple checkboxes with the same name
+ within a form.
+ The multivalue nature of these means that setting and testing
+ are slightly different.
+ Using checkboxes as an example...
+<pre>
+&lt;form class="demo"&gt;
+ &lt;strong&gt;Create privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="c" checked&gt;&lt;br&gt;
+ &lt;strong&gt;Retrieve privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="r" checked&gt;&lt;br&gt;
+ &lt;strong&gt;Update privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="u" checked&gt;&lt;br&gt;
+ &lt;strong&gt;Destroy privileges allowed:&lt;/strong&gt;
+ &lt;input type="checkbox" name="crud" value="d" checked&gt;&lt;br&gt;
+ &lt;input type="submit" value="Enable Privileges"&gt;
+&lt;/form&gt;
+</pre>
+ Which renders as...
+ </p>
+ <p>
+ <form class="demo">
+ <strong>Create privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="c" checked>
+<br>
+ <strong>Retrieve privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="r" checked>
+<br>
+ <strong>Update privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="u" checked>
+<br>
+ <strong>Destroy privileges allowed:</strong>
+ <input type="checkbox" name="crud" value="d" checked>
+<br>
+ <input type="submit" value="Enable Privileges">
+ </form>
+ </p>
+ <p>
+ If we wish to disable all but the retrieval privileges and
+ submit this information we can do it like this...
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...<strong>
+ function testDisableNastyPrivileges() {
+ $this-&gt;get('http://www.lastcraft.com/form_testing_documentation.php');
+ $this-&gt;assertField('crud', array('c', 'r', 'u', 'd'));
+ $this-&gt;setField('crud', array('r'));
+ $this-&gt;clickSubmit('Enable Privileges');
+ }</strong>
+}
+</pre>
+ Instead of setting the field to a single value, we give it a list
+ of values.
+ We do the same when testing expected values.
+ We can then write other test code to confirm the effect of this, perhaps
+ by logging in as that user and attempting an update.
+ </p>
+ <p>
+ <a class="target" name="raw">
+<h2>Raw posting</h2>
+</a>
+ </p>
+ <p>
+ If you want to test a form handler, but have not yet written
+ or do not have access to the form itself, you can create a
+ form submission by hand.
+<pre>
+class SimpleFormTests extends WebTestCase {
+ ...<strong>
+ function testAttemptedHack() {
+ $this-&gt;post(
+ 'http://www.my-site.com/add_user.php',
+ array('type' =&gt; 'superuser'));
+ $this-&gt;assertNoUnwantedPattern('/user created/i');
+ }</strong>
+}
+</pre>
+ By adding data to the <span class="new_code">WebTestCase::post()</span>
+ method, we are attempting to fetch the page as a form submission.
+ </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/en/group_test_documentation.html b/tests/test_tools/simpletest/docs/en/group_test_documentation.html
new file mode 100755
index 00000000..adbc66ef
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/group_test_documentation.html
@@ -0,0 +1,357 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP group test documentation</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>
+<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>
+<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>Group Test documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="group">
+<h2>Grouping tests</h2>
+</a>
+</p>
+ <p>
+ To run test cases as part of a group the test cases should really
+ be placed in files without the runner code...
+<pre>
+<strong>&lt;?php
+ require_once('../classes/io.php');
+
+ class FileTester extends UnitTestCase {
+ ...
+ }
+
+ class SocketTester extends UnitTestCase {
+ ...
+ }
+?&gt;</strong>
+</pre>
+ As many cases as needed can appear in a single file.
+ They should include any code they need, such as the library
+ being tested, but none of the simple test libraries.
+ </p>
+ <p>
+ If you have extended any test cases, you can include them
+ as well.
+<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>
+ The <span class="new_code">FileTester</span> class does
+ not contain any actual tests, but is a base class for other
+ test cases.
+ For this reason we use the
+ <span class="new_code">SimpleTestOptions::ignore()</span> directive
+ to tell the upcoming group test to ignore it.
+ This directive can appear anywhere in the file and works
+ when a whole file of test cases is loaded (see below).
+ We will call this sample <em>file_test.php</em>.
+ </p>
+ <p>
+ Next we create a group test file, called say <em>group_test.php</em>.
+ You will think of a better name I am sure.
+ We will add the test file using a safe method...
+<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>
+ This instantiates the test case before the test suite is
+ run.
+ This could get a little expensive with a large number of test
+ cases, so another method is provided that will only
+ instantiate the class when it is needed...
+<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>
+ The problem with this method is that for every test case
+ that we add we will have
+ to <span class="new_code">require_once()</span> the test code
+ file and manually instantiate each and every test case.
+ We can save a lot of typing with...
+<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>
+ What happens here is that the <span class="new_code">GroupTest</span>
+ class has done the <span class="new_code">require_once()</span>
+ for us.
+ It then checks to see if any new test case classes
+ have been created by the new file and automatically adds
+ them to the group test.
+ Now all we have to do is add each new file.
+ </p>
+ <p>
+ There are two things that could go wrong and which require care...
+ <ol>
+ <li>
+ The file could already have been parsed by PHP and so no
+ new classes will have been added. You should make
+ sure that the test cases are only included in this file
+ and no others.
+ </li>
+ <li>
+ New test case extension classes that get included will be
+ placed in the group test and run also.
+ You will need to add a <span class="new_code">SimpleTestOptions::ignore()</span>
+ directive for these classes or make sure that they are included
+ before the <span class="new_code">GroupTest::addTestFile()</span>
+ line.
+ </li>
+ </ol>
+ </p>
+
+ <p>
+<a class="target" name="higher">
+<h2>Higher groupings</h2>
+</a>
+</p>
+ <p>
+ The above method places all of the test cases into one large group.
+ For larger projects though this may not be flexible enough; you
+ may want to group the tests in all sorts of ways.
+ </p>
+ <p>
+ To get a more flexible group test we can subclass
+ <span class="new_code">GroupTest</span> and then instantiate it as needed...
+<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>
+ This effectively names the test in the constructor and then
+ adds our test cases and a single group below.
+ Of course we can add more than one group at this point.
+ We can now invoke the tests from a separate runner file...
+<pre>
+&lt;?php
+ require_once('file_group_test.php');
+ <strong>
+ $test = &amp;new FileGroupTest();
+ $test-&gt;run(new HtmlReporter());</strong>
+?&gt;
+</pre>
+ ...or we can group them into even larger group tests...
+<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>
+ If we still wish to run the original group test and we
+ don't want all of these little runner files, we can
+ put the test runner code around guard bars when we create
+ each group.
+<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>
+ This approach requires the guard to be set when including
+ the group test file, but this is still less hassle than
+ lots of separate runner files.
+ You include the same guard on the top level tests to make sure
+ that <span class="new_code">run()</span> will run once only
+ from the top level script that has been invoked.
+<pre>
+&lt;?php<strong>
+ define('RUNNER', true);</strong>
+ 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>
+ As with the normal test cases, a <span class="new_code">GroupTest</span> can
+ be loaded with the <span class="new_code">GroupTest::addTestFile()</span> method.
+<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="legacy">
+<h2>Integrating legacy test cases</h2>
+</a>
+</p>
+ <p>
+ If you already have unit tests for your code or are extending external
+ classes that have tests, it is unlikely that all of the test cases
+ are in SimpleTest format.
+ Fortunately it is possible to incorporate test cases from other
+ unit testers directly into SimpleTest group tests.
+ </p>
+ <p>
+ Say we have the following
+ <a href="http://sourceforge.net/projects/phpunit">PhpUnit</a>
+ test case in the file <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>
+ The group test can recognise this as long as we include
+ the appropriate adapter class before we add the test
+ file...
+<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>
+ There are only two adapters, the other is for the
+ <a href="http://pear.php.net/manual/en/package.php.phpunit.php">PEAR</a>
+ 1.0 unit tester...
+<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>
+ The PEAR test cases can be freely mixed with SimpleTest
+ ones even in the same test file,
+ but you cannot use SimpleTest assertions in the legacy
+ test case versions.
+ This is done as a check that you are not accidently making
+ your test cases completely dependent on SimpleTest.
+ You may want to do a PEAR release of your library for example
+ which would mean shipping it with valid PEAR::PhpUnit test
+ cases.
+ </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/en/index.html b/tests/test_tools/simpletest/docs/en/index.html
new file mode 100755
index 00000000..04797272
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/index.html
@@ -0,0 +1,467 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Download the Simple Test testing framework -
+ Unit tests and mock objects for PHP
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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 for PHP</h1>
+<div class="content">
+
+
+ <p>
+ The following assumes that you are familiar with the concept
+ of unit testing as well as the PHP web development language.
+ It is a guide for the impatient new user of
+ <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>.
+ For fuller documentation, especially if you are new
+ to unit testing see the ongoing
+ <a href="unit_test_documentation.html">documentation</a>, and for
+ example test cases see the
+ <a href="http://www.lastcraft.com/first_test_tutorial.php">unit testing tutorial</a>.
+ </p>
+
+ <p>
+<a class="target" name="unit">
+<h2>Using the tester quickly</h2>
+</a>
+</p>
+ <p>
+ Amongst software testing tools, a unit tester is the one
+ closest to the developer.
+ In the context of agile development the test code sits right
+ next to the source code as both are written simultaneously.
+ In this context SimpleTest aims to be a complete PHP developer
+ test solution and is called "Simple" because it
+ should be easy to use and extend.
+ It wasn't a good choice of name really.
+ It includes all of the typical functions you would expect from
+ <a href="http://www.junit.org/">JUnit</a> and the
+ <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>
+ ports, but also adds
+ <a href="http://www.mockobjects.com">mock objects</a>.
+ It has some <a href="http://sourceforge.net/projects/jwebunit/">JWebUnit</a>
+ functionality as well.
+ This includes web page navigation, cookie testing and form submission.
+ </p>
+ <p>
+ The quickest way to demonstrate is with an example.
+ </p>
+ <p>
+ Let us suppose we are testing a simple file logging class called
+ <span class="new_code">Log</span> in <em>classes/log.php</em>.
+ We start by creating a test script which we will call
+ <em>tests/log_test.php</em> and populate it as follows...
+<pre>
+<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
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+require_once('../classes/log.php');
+<strong>
+class TestOfLogging extends UnitTestCase {
+}</strong>
+?&gt;
+</pre>
+ 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
+ takes the file name to write to in the constructor and we have
+ a temporary folder in which to place this file...
+<pre>
+&lt;?php
+require_once('simpletest/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>
+ When a test case runs it will search for any method that
+ starts with the string <span class="new_code">test</span>
+ and execute that method.
+ We would normally have more than one test method of course.
+ Assertions within the test methods trigger messages to the
+ test framework which displays the result immediately.
+ This immediate response is important, not just in the event
+ of the code causing a crash, but also so that
+ <span class="new_code">print</span> statements can display
+ their content right next to the test case concerned.
+ </p>
+ <p>
+ To see these results we have to actually run the tests.
+ If this is the only test case we wish to run we can achieve
+ it with...
+<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>
+ On failure the display looks like this...
+ <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>
+ ...and if it passes like this...
+ <div class="demo">
+ <h1>testoflogging</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>2</strong> passes and <strong>0</strong> fails.</div>
+ </div>
+ And if you get this...
+ <div class="demo">
+ <b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
+ </div>
+ it means you're missing the <em>classes/Log.php</em> file that could look like...
+<pre>
+&lt;?php
+class Log {
+
+ function Log($file_path) {
+ }
+
+ function message() {
+ }
+}
+?&gt;;
+</pre>
+ </p>
+
+ <p>
+<a class="target" name="group">
+<h2>Building group tests</h2>
+</a>
+</p>
+ <p>
+ It is unlikely in a real application that we will only ever run
+ one test case.
+ This means that we need a way of grouping cases into a test
+ script that can, if need be, run every test in the application.
+ </p>
+ <p>
+ Our first step is to strip the includes and to undo our
+ previous hack...
+<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>
+ Next we create a new file called <em>tests/all_tests.php</em>
+ and insert the following code...
+<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>
+ The method <span class="new_code">GroupTest::addTestFile()</span>
+ will include the test case file and read any new classes created
+ that are descended from <span class="new_code">SimpleTestCase</span>, of which
+ <span class="new_code">UnitTestCase</span> is one example.
+ Just the class names are stored for now, so that the test runner
+ can instantiate the class when it works its way
+ through your test suite.
+ </p>
+ <p>
+ For this to work properly the test case file should not blindly include
+ any other test case extensions that do not actually run tests.
+ This could result in extra test cases being counted during the test
+ run.
+ Hardly a major problem, but to avoid this inconvenience simply add
+ a <span class="new_code">SimpleTestOptions::ignore()</span> directive
+ somewhere in the test case file.
+ Also the test case file should not have been included
+ elsewhere or no cases will be added to this group test.
+ This would be a more serious error as if the test case classes are
+ already loaded by PHP the <span class="new_code">GroupTest::addTestFile()</span>
+ method will not detect them.
+ </p>
+ <p>
+ To display the results it is necessary only to invoke
+ <em>tests/all_tests.php</em> from the web server.
+ </p>
+
+ <p>
+<a class="target" name="mock">
+<h2>Using mock objects</h2>
+</a>
+</p>
+ <p>
+ Let's move further into the future.
+ </p>
+ <p>
+ Assume that our logging class is tested and completed.
+ Assume also that we are testing another class that is
+ required to write log messages, say a
+ <span class="new_code">SessionPool</span>.
+ We want to test a method that will probably end up looking
+ like this...
+<pre>
+<strong>
+class SessionPool {
+ ...
+ function logIn($username) {
+ ...
+ $this-&gt;_log-&gt;message("User $username logged in.");
+ ...
+ }
+ ...
+}
+</strong>
+</pre>
+ In the spirit of reuse we are using our
+ <span class="new_code">Log</span> class.
+ A conventional test case might look like this...
+<pre>
+<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>
+ This test case design is not all bad, but it could be improved.
+ We are spending time fiddling with log files which are
+ not part of our test. Worse, we have created close ties
+ with the <span class="new_code">Log</span> class and
+ this test.
+ What if we don't use files any more, but use ths
+ <em>syslog</em> library instead?
+ Did you notice the extra carriage return in the message?
+ Was that added by the logger?
+ What if it also added a time stamp or other data?
+ </p>
+ <p>
+ The only part that we really want to test is that a particular
+ message was sent to the logger.
+ We reduce coupling if we can pass in a fake logging class
+ that simply records the message calls for testing, but
+ takes no action.
+ It would have to look exactly like our original though.
+ </p>
+ <p>
+ If the fake object doesn't write to a file then we save on deleting
+ the file before and after each test. We could save even more
+ test code if the fake object would kindly run the assertion for us.
+ <p>
+ </p>
+ Too good to be true?
+ Luckily we can create such an object easily...
+<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>
+ 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
+ <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
+ resulting pass or fail event to the test display.
+ Wildcards can be included here too so as to prevent tests
+ becoming too specific.
+ </p>
+ <p>
+ The mock objects in the SimpleTest suite can have arbitrary
+ return values set, sequences of returns, return values
+ selected according to the incoming arguments, sequences of
+ parameter expectations and limits on the number of times
+ a method is to be invoked.
+ </p>
+ <p>
+ For this test to run the mock objects library must have been
+ included in the test suite, say in <em>all_tests.php</em>.
+ </p>
+
+ <p>
+<a class="target" name="web">
+<h2>Web page testing</h2>
+</a>
+</p>
+ <p>
+ One of the requirements of web sites is that they produce web
+ pages.
+ If you are building a project top-down and you want to fully
+ integrate testing along the way then you will want a way of
+ automatically navigating a site and examining output for
+ correctness.
+ This is the job of a web tester.
+ </p>
+ <p>
+ The web testing in SimpleTest is fairly primitive, there is
+ no JavaScript for example.
+ To give an idea here is a trivial example where a home
+ page is fetched, from which we navigate to an "about"
+ page and then test some client determined content.
+<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>
+ With this code as an acceptance test you can ensure that
+ the content always meets the specifications of both the
+ developers and the other project stakeholders.
+ </p>
+ <p>
+ <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/en/mock_objects_documentation.html b/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html
new file mode 100755
index 00000000..2f8a1f90
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/mock_objects_documentation.html
@@ -0,0 +1,713 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP mock objects documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Mock objects</span>
+</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>Mock objects documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="what">
+<h2>What are mock objects?</h2>
+</a>
+</p>
+ <p>
+ Mock objects have two roles during a test case: actor and critic.
+ </p>
+ <p>
+ The actor behaviour is to simulate objects that are difficult to
+ set up or time consuming to set up for a test.
+ The classic example is a database connection.
+ Setting up a test database at the start of each test would slow
+ testing to a crawl and would require the installation of the
+ database engine and test data on the test machine.
+ If we can simulate the connection and return data of our
+ choosing we not only win on the pragmatics of testing, but can
+ also feed our code spurious data to see how it responds.
+ We can simulate databases being down or other extremes
+ without having to create a broken database for real.
+ In other words, we get greater control of the test environment.
+ </p>
+ <p>
+ If mock objects only behaved as actors they would simply be
+ known as <a href="server_stubs_documentation.html">server stubs</a>.
+ </p>
+ <p>
+ However, the mock objects not only play a part (by supplying chosen
+ return values on demand) they are also sensitive to the
+ messages sent to them (via expectations).
+ By setting expected parameters for a method call they act
+ as a guard that the calls upon them are made correctly.
+ If expectations are not met they save us the effort of
+ writing a failed test assertion by performing that duty on our
+ behalf.
+ In the case of an imaginary database connection they can
+ test that the query, say SQL, was correctly formed by
+ the object that is using the connection.
+ Set them up with fairly tight expectations and you will
+ hardly need manual assertions at all.
+ </p>
+
+ <p>
+<a class="target" name="creation">
+<h2>Creating mock objects</h2>
+</a>
+</p>
+ <p>
+ In the same way that we create server stubs, all we need is an
+ existing class, say a database connection that looks like this...
+<pre>
+<strong>class DatabaseConnection {
+ function DatabaseConnection() {
+ }
+
+ function query() {
+ }
+
+ function selectQuery() {
+ }
+}</strong>
+</pre>
+ The class does not need to have been implemented yet.
+ To create a mock version of the class we need to include the
+ mock object library and run the generator...
+<pre>
+<strong>require_once('simpletest/unit_tester.php');
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+
+Mock::generate('DatabaseConnection');</strong>
+</pre>
+ This generates a clone class called
+ <span class="new_code">MockDatabaseConnection</span>.
+ We can now create instances of the new class within
+ our test case...
+<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>
+ Unlike the generated stubs the mock constructor needs a reference
+ to the test case so that it can dispatch passes and failures while
+ checking its expectations.
+ This means that mock objects can only be used within test cases.
+ Despite this their extra power means that stubs are hardly ever used
+ if mocks are available.
+ </p>
+ <p>
+ <a class="target" name="stub">
+<h2>Mocks as actors</h2>
+</a>
+ </p>
+ <p>
+ 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...
+<pre>
+<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 also add extra methods to the mock when generating it
+ and choose our own class name...
+<pre>
+<strong>Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));</strong>
+</pre>
+ Here the mock will behave as if the <span class="new_code">setOptions()</span>
+ existed in the original class.
+ This is handy if a class has used the PHP <span class="new_code">overload()</span>
+ mechanism to add dynamic methods.
+ 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...
+<pre>
+class Iterator {
+ function Iterator() {
+ }
+
+ function next() {
+ }
+}
+</pre>
+ Again, assuming that this iterator only returns text until it
+ reaches the end, when it returns false, we can simulate it
+ with...
+<pre>
+Mock::generate('Iterator');
+
+class IteratorTest extends UnitTestCase() {
+
+ function testASequence() {<strong>
+ $iterator = &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>
+ When <span class="new_code">next()</span> is called on the
+ mock iterator it will first return "First string",
+ on the second call "Second string" will be returned
+ and on any other call <span class="new_code">false</span> will
+ be returned.
+ The sequenced return values take precedence over the constant
+ return value.
+ The constant one is a kind of default if you like.
+ </p>
+ <p>
+ A repeat of the stubbed information holder with name/value pairs...
+<pre>
+class Configuration {
+ function Configuration() {
+ }
+
+ function getValue($key) {
+ }
+}
+</pre>
+ This is a classic situation for using mock objects as
+ actual configuration will vary from machine to machine,
+ hardly helping the reliability of our tests if we use it
+ directly.
+ The problem though is that all the data comes through the
+ <span class="new_code">getValue()</span> method and yet
+ we want different results for different keys.
+ Luckily the mocks have a filter system...
+<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>
+ The extra parameter is a list of arguments to attempt
+ to match.
+ In this case we are trying to match only one argument which
+ is the look up key.
+ Now when the mock object has the
+ <span class="new_code">getValue()</span> method invoked
+ like this...
+<pre>
+$config-&gt;getValue('db_user')
+</pre>
+ ...it will return "admin".
+ It finds this by attempting to match the calling arguments
+ to its list of returns one after another until
+ a complete match is found.
+ </p>
+ <p>
+ 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...
+<pre>
+class Thing {
+}
+
+class Vector {
+ function Vector() {
+ }
+
+ function get($index) {
+ }
+}
+</pre>
+ In this case you can set a reference into the mock's
+ return list...
+<pre>
+$thing = new Thing();<strong>
+$vector = &amp;new MockVector($this);
+$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.
+ </p>
+
+ <p>
+<a class="target" name="expectations">
+<h2>Mocks as critics</h2>
+</a>
+</p>
+ <p>
+ Although the server stubs approach insulates your tests from
+ real world disruption, it is only half the benefit.
+ You can have the class under test receiving the required
+ messages, but is your new class sending correct ones?
+ Testing this can get messy without a mock objects library.
+ </p>
+ <p>
+ By way of example, suppose we have a
+ <span class="new_code">SessionPool</span> class that we
+ want to add logging to.
+ Rather than grow the original class into something more
+ complicated, we want to add this behaviour with a decorator (GOF).
+ The <span class="new_code">SessionPool</span> code currently looks
+ like this...
+<pre>
+<strong>class SessionPool {
+ function SessionPool() {
+ ...
+ }
+
+ function &amp;findSession($cookie) {
+ ...
+ }
+ ...
+}
+
+class Session {
+ ...
+}</strong>
+&lt;/php&gt;
+ While our logging code looks like this...
+&lt;php&gt;<strong>
+class Log {
+ function Log() {
+ ...
+ }
+
+ function message() {
+ ...
+ }
+}
+
+class LoggingSessionPool {
+ function LoggingSessionPool(&amp;$session_pool, &amp;$log) {
+ ...
+ }
+
+ function &amp;findSession(\$cookie) {
+ ...
+ }
+ ...
+}</strong>
+</pre>
+ Out of all of this, the only class we want to test here
+ is the <span class="new_code">LoggingSessionPool</span>.
+ In particular we would like to check that the
+ <span class="new_code">findSession()</span> method is
+ called with the correct session ID in the cookie and that
+ it sent the message "Starting session $cookie"
+ to the logger.
+ </p>
+ <p>
+ Despite the fact that we are testing only a few lines of
+ production code, here is what we would have to do in a
+ conventional test case:
+ <ol>
+ <li>Create a log object.</li>
+ <li>Set a directory to place the log file.</li>
+ <li>Set the directory permissions so we can write the log.</li>
+ <li>Create a <span class="new_code">SessionPool</span> object.</li>
+ <li>Hand start a session, which probably does lot's of things.</li>
+ <li>Invoke <span class="new_code">findSession()</span>.</li>
+ <li>Read the new Session ID (hope there is an accessor!).</li>
+ <li>Raise a test assertion to confirm that the ID matches the cookie.</li>
+ <li>Read the last line of the log file.</li>
+ <li>Pattern match out the extra logging timestamps, etc.</li>
+ <li>Assert that the session message is contained in the text.</li>
+ </ol>
+ It is hardly surprising that developers hate writing tests
+ when they are this much drudgery.
+ To make things worse, every time the logging format changes or
+ the method of creating new sessions changes, we have to rewrite
+ parts of this test even though this test does not officially
+ test those parts of the system.
+ We are creating headaches for the writers of these other classes.
+ </p>
+ <p>
+ Instead, here is the complete test method using mock object magic...
+<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>
+ We start by creating a dummy session.
+ We don't have to be too fussy about this as the check
+ for which session we want is done elsewhere.
+ We only need to check that it was the same one that came
+ from the session pool.
+ </p>
+ <p>
+ <span class="new_code">findSession()</span> is a factory
+ method the simulation of which is described <a href="#stub">above</a>.
+ The point of departure comes with the first
+ <span class="new_code">expectOnce()</span> call.
+ This line states that whenever
+ <span class="new_code">findSession()</span> is invoked on the
+ mock, it will test the incoming arguments.
+ If it receives the single argument of a string "abc"
+ then a test pass is sent to the unit tester, otherwise a fail is
+ generated.
+ This was the part where we checked that the right session was asked for.
+ The argument list follows the same format as the one for setting
+ return values.
+ You can have wildcards and sequences and the order of
+ evaluation is the same.
+ </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
+ once only with the argument "Starting session abc".
+ By testing the calling arguments, rather than the logger output,
+ we insulate the test from any display changes in the logger.
+ </p>
+ <p>
+ We start to run our tests when we create the new
+ <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
+ strict.
+ If it still seems rather daunting there is a lot less of it
+ than if we tried this without mocks and this particular test,
+ interactions rather than output, is always more work to set
+ up.
+ More often you will be testing more complex situations without
+ needing this level or precision.
+ Also some of this can be refactored into a test case
+ <span class="new_code">setUp()</span> method.
+ </p>
+ <p>
+ Here is the full list of expectations you can set on a mock object
+ in <a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>...
+ <table>
+<thead>
+ <tr>
+<th>Expectation</th><th>Needs <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">No</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectArgumentsAt($timing, $method, $args)</span></td>
+ <td style="text-align: center">No</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectCallCount($method, $count)</span></td>
+ <td style="text-align: center">Yes</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectMaximumCallCount($method, $count)</span></td>
+ <td style="text-align: center">No</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectMinimumCallCount($method, $count)</span></td>
+ <td style="text-align: center">Yes</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectNever($method)</span></td>
+ <td style="text-align: center">No</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectOnce($method, $args)</span></td>
+ <td style="text-align: center">Yes</td>
+ </tr>
+ <tr>
+ <td><span class="new_code">expectAtLeastOnce($method, $args)</span></td>
+ <td style="text-align: center">Yes</td>
+ </tr>
+ </tbody>
+</table>
+ Where the parameters are...
+ <dl>
+ <dt class="new_code">$method</dt>
+ <dd>The method name, as a string, to apply the condition to.</dd>
+ <dt class="new_code">$args</dt>
+ <dd>
+ The arguments as a list. Wildcards can be included in the same
+ manner as for <span class="new_code">setReturn()</span>.
+ This argument is optional for <span class="new_code">expectOnce()</span>
+ and <span class="new_code">expectAtLeastOnce()</span>.
+ </dd>
+ <dt class="new_code">$timing</dt>
+ <dd>
+ The only point in time to test the condition.
+ The first call starts at zero.
+ </dd>
+ <dt class="new_code">$count</dt>
+ <dd>The number of calls expected.</dd>
+ </dl>
+ The method <span class="new_code">expectMaximumCallCount()</span>
+ is slightly different in that it will only ever generate a failure.
+ It is silent if the limit is never reached.
+ </p>
+ <p>
+ Like the assertions within test cases, all of the expectations
+ can take a message override as an extra parameter.
+ Also the original failure message can be embedded in the output
+ as "%s".
+ </p>
+
+ <p>
+<a class="target" name="approaches">
+<h2>Other approaches</h2>
+</a>
+</p>
+ <p>
+ There are three approaches to creating mocks including the one
+ that SimpleTest employs.
+ Coding them by hand using a base class, generating them to
+ a file and dynamically generating them on the fly.
+ </p>
+ <p>
+ Mock objects generated with <a href="simple_test.html">SimpleTest</a>
+ are dynamic.
+ They are created at run time in memory, using
+ <span class="new_code">eval()</span>, rather than written
+ out to a file.
+ This makes the mocks easy to create, a one liner,
+ especially compared with hand
+ crafting them in a parallel class hierarchy.
+ The problem is that the behaviour is usually set up in the tests
+ themselves.
+ If the original objects change the mock versions
+ that the tests rely on can get out of sync.
+ This can happen with the parallel hierarchy approach as well,
+ but is far more quickly detected.
+ </p>
+ <p>
+ The solution, of course, is to add some real integration
+ tests.
+ You don't need very many and the convenience gained
+ from the mocks more than outweighs the small amount of
+ extra testing.
+ You cannot trust code that was only tested with mocks.
+ </p>
+ <p>
+ If you are still determined to build static libraries of mocks
+ because you want to simulate very specific behaviour, you can
+ achieve the same effect using the SimpleTest class generator.
+ In your library file, say <em>mocks/connection.php</em> for a
+ database connection, create a mock and inherit to override
+ special methods or add presets...
+<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>
+ The generate call tells the class generator to create
+ a class called <span class="new_code">BasicMockConnection</span>
+ rather than the usual <span class="new_code">MockConnection</span>.
+ We then inherit from this to get our version of
+ <span class="new_code">MockConnection</span>.
+ By intercepting in this way we can add behaviour, here setting
+ the default value of <span class="new_code">query()</span> to be false.
+ By using the default name we make sure that the mock class
+ generator will not recreate a different one when invoked elsewhere in the
+ tests.
+ It never creates a class if it already exists.
+ As long as the above file is included first then all tests
+ that generated <span class="new_code">MockConnection</span> should
+ now be using our one instead.
+ If we don't get the order right and the mock library
+ creates one first then the class creation will simply fail.
+ </p>
+ <p>
+ Use this trick if you find you have a lot of common mock behaviour
+ or you are getting frequent integration problems at later
+ stages of testing.
+ </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
+ </div>
+</body>
+</html>
diff --git a/tests/test_tools/simpletest/docs/en/overview.html b/tests/test_tools/simpletest/docs/en/overview.html
new file mode 100755
index 00000000..d4965de3
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/overview.html
@@ -0,0 +1,422 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>
+ Overview and feature list for the SimpleTest PHP unit tester and web tester
+ </title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<h2>
+<a href="index.html">SimpleTest</a>
+</h2>
+<ul>
+<li>
+<span class="chosen">Overview</span>
+</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>Overview of SimpleTest</h1>
+<div class="content">
+ <p>
+<a class="target" name="summary">
+<h2>What is SimpleTest?</h2>
+</a>
+</p>
+ <p>
+ The heart of SimpleTest is a testing framework built around
+ test case classes.
+ These are written as extensions of base test case classes,
+ each extended with methods that actually contain test code.
+ Top level test scripts then invoke the <span class="new_code">run()</span>
+ methods on every one of these test cases in order.
+ Each test method is written to invoke various assertions that
+ the developer expects to be true such as
+ <span class="new_code">assertEqual()</span>.
+ If the expectation is correct, then a successful result is dispatched to the
+ observing test reporter, but any failure triggers an alert
+ and a description of the mismatch.
+ </p>
+ <p>
+ A <a href="unit_test_documentation.html">test case</a> looks like this...
+<pre>
+&lt;?php
+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>
+}
+?&gt;
+</pre>
+ </p>
+ <p>
+ These tools are designed for the developer.
+ Tests are written in the PHP language itself more or less
+ as the application itself is built.
+ The advantage of using PHP itself as the testing language is that
+ there are no new languages to learn, testing can start straight away,
+ and the developer can test any part of the code.
+ Basically, all parts that can be accessed by the application code can also be
+ accessed by the test code if they are in the same language.
+ </p>
+ <p>
+ The simplest type of test case is the
+ <a href="unit_tester_documentation.html">UnitTestCase</a>.
+ This class of test case includes standard tests for equality,
+ references and pattern matching.
+ All these test the typical expectations of what you would
+ expect the result of a function or method to be.
+ This is by far the most common type of test in the daily
+ routine of development, making up about 95% of test cases.
+ </p>
+ <p>
+ The top level task of a web application though is not to
+ produce correct output from its methods and objects, but
+ to generate web pages.
+ The <a href="web_tester_documentation.html">WebTestCase</a> class tests web
+ pages.
+ It simulates a web browser requesting a page, complete with
+ cookies, proxies, secure connections, authentication, forms, frames and most
+ navigation elements.
+ With this type of test case, the developer can assert that
+ information is present in the page and that forms and
+ sessions are handled correctly.
+ </p>
+ <p>
+ A <a href="web_tester_documentation.html">WebTestCase</a> looks like this...
+<pre>
+&lt;?php
+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>
+}
+?&gt;
+</pre>
+ </p>
+
+ <p>
+<a class="target" name="features">
+<h2>Feature list</h2>
+</a>
+</p>
+ <p>
+ The following is a very rough outline of past and future features
+ and their expected point of release.
+ I am afraid it is liable to change without warning as meeting the
+ milestones rather depends on time available.
+ 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".
+ <table>
+<thead>
+ <tr>
+<th>Feature</th><th>Description</th><th>Release</th>
+</tr>
+ </thead>
+<tbody>
+<tr>
+ <td>Unit test case</td>
+ <td>Core test case class and assertions</td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Html display</td>
+ <td>Simplest possible display</td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Autoloading of test cases</td>
+ <td>
+ Reading a file with test cases and loading them into a
+ group test automatically
+ </td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Mock objects code generator</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>
+ </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>
+ </tr>
+ <tr>
+ <td>Partial mocks</td>
+ <td>
+ Mocking parts of a class for testing less than a class
+ or for complex simulations
+ </td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Web cookie handling</td>
+ <td>Correct handling of cookies when fetching pages</td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Following redirects</td>
+ <td>Page fetching automatically follows 300 redirects</td>
+ <td style="color: green;">Done</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>
+ </tr>
+ <tr>
+ <td>Command line interface</td>
+ <td>Test display without the need of a web browser</td>
+ <td style="color: green;">Done</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>
+ </tr>
+ <tr>
+ <td>XML output and parsing</td>
+ <td>
+ Allows multi host testing and the integration of acceptance
+ testing extensions
+ </td>
+ <td style="color: green;">Done</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>
+ Exposure of lower level web browser interface for more
+ detailed test cases
+ </td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>HTTP authentication</td>
+ <td>
+ 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>
+ </tr>
+ <tr>
+ <td>SSL support</td>
+ <td>Can connect to https: pages</td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Proxy support</td>
+ <td>Can connect via. common proxies</td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Frames support</td>
+ <td>Handling of frames in web test cases</td>
+ <td style="color: green;">Done</td>
+ </tr>
+ <tr>
+ <td>Improved display</td>
+ <td>Better web GUI with tree display of test cases</td>
+ <td style="color: red;">1.1</td>
+ </tr>
+ <tr>
+ <td>Localisation</td>
+ <td>Messages abstracted and code generated from XML</td>
+ <td style="color: red;">1.1</td>
+ </tr>
+ <tr>
+ <td>File upload testing</td>
+ <td>Can simulate the input type file tag</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 style="color: red;">2.0</td>
+ </tr>
+ <tr>
+ <td>Testing exceptions</td>
+ <td>Similar to testing PHP errors</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 style="color: red;">2.0</td>
+ </tr>
+ </tbody>
+</table>
+ PHP5 migraton will start straight after the version 1.1 series,
+ whereupon PHP4 will no longer be supported.
+ SimpleTest is currently compatible with PHP5, but will not
+ make use of all of the new features until version 2.
+ </p>
+
+ <p>
+<a class="target" name="resources">
+<h2>Web resources for testing</h2>
+</a>
+</p>
+ <p>
+ Process is at least as important as tools.
+ The type of process that makes the heaviest use of a developer's
+ testing tool is of course
+ <a href="http://www.extremeprogramming.org/">Extreme Programming</a>.
+ This is one of the
+ <a href="http://www.agilealliance.com/articles/index">Agile Methodologies</a>
+ which combine various practices to "flatten the cost curve" of software development.
+ More extreme still is <a href="http://www.testdriven.com/modules/news/">Test Driven Development</a>,
+ where you very strictly adhere to the rule of no coding until you have a test.
+ If you're more of a planner or believe that experience trumps evolution,
+ you may prefer the
+ <a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a> approach.
+ I haven't tried it, but even I can see that you will need test tools (see figure 9).
+ </p>
+ <p>
+ Most unit testers clone <a href="http://www.junit.org/">JUnit</a> to some degree,
+ as far as the interface at least. There is a wealth of information on the
+ JUnit site including the
+ <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a>
+ which contains plenty of general advice on testing.
+ Once you get bitten by the bug you will certainly appreciate the phrase
+ <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">test infected</a>
+ coined by Eric Gamma.
+ If you are still reviewing which unit tester to use the main choices
+ are <a href="http://phpunit.sourceforge.net/">PHPUnit</a>
+ and <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>.
+ They currently lack a lot of features found in
+ <a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>, but the PEAR
+ version at least has been upgraded for PHP5 and is recommended if you are porting
+ 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>
+ is very Java focused, but still worth a read.
+ As a new technology there are plenty of discussions and debate on how to use mocks,
+ often on Wikis such as
+ <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://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
+ 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>,
+ <a href="http://htmlunit.sourceforge.net/">HTMLUnit</a>
+ 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.
+ As SimpleTest does not support JavaScript you would probably
+ have to look at these tools anyway if you have highly dynamic
+ pages.
+ </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/en/partial_mocks_documentation.html b/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html
new file mode 100755
index 00000000..20749415
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/partial_mocks_documentation.html
@@ -0,0 +1,426 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP partial mocks documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Partial mocks</span>
+</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>Partial mock objects documentation</h1>
+<div class="content">
+
+ <p>
+ A partial mock is simply a pattern to alleviate a specific problem
+ in testing with mock objects,
+ that of getting mock objects into tight corners.
+ It's quite a limited tool and possibly not even a good idea.
+ It is included with SimpleTest because I have found it useful
+ on more than one occasion and has saved a lot of work at that point.
+ </p>
+
+ <p>
+<a class="target" name="inject">
+<h2>The mock injection problem</h2>
+</a>
+</p>
+ <p>
+ When one object uses another it is very simple to just pass a mock
+ version in already set up with its expectations.
+ Things are rather tricker if one object creates another and the
+ creator is the one you want to test.
+ This means that the created object should be mocked, but we can
+ hardly tell our class under test to create a mock instead.
+ The tested class doesn't even know it is running inside a test
+ after all.
+ </p>
+ <p>
+ For example, suppose we are building a telnet client and it
+ needs to create a network socket to pass its messages.
+ The connection method might look something like...
+<pre>
+<strong>&lt;?php
+ require_once('socket.php');
+
+ class Telnet {
+ ...
+ function &amp;connect($ip, $port, $username, $password) {
+ $socket = &amp;new Socket($ip, $port);
+ $socket-&gt;read( ... );
+ ...
+ }
+ }
+?&gt;</strong>
+</pre>
+ We would really like to have a mock object version of the socket
+ here, what can we do?
+ </p>
+ <p>
+ The first solution is to pass the socket in as a parameter,
+ forcing the creation up a level.
+ Having the client handle this is actually a very good approach
+ if you can manage it and should lead to factoring the creation from
+ the doing.
+ In fact, this is one way in which testing with mock objects actually
+ forces you to code more tightly focused solutions.
+ They improve your programming.
+ </p>
+ <p>
+ Here this would be...
+<pre>
+&lt;?php
+ require_once('socket.php');
+
+ class Telnet {
+ ...
+ <strong>function &amp;connect(&amp;$socket, $username, $password) {
+ $socket-&gt;read( ... );
+ ...
+ }</strong>
+ }
+?&gt;
+</pre>
+ This means that the test code is typical for a test involving
+ mock objects.
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = &amp;new MockSocket($this);
+ ...
+ $telnet = &amp;new Telnet();
+ $telnet-&gt;connect($socket, 'Me', 'Secret');
+ ...</strong>
+ }
+}
+</pre>
+ It is pretty obvious though that one level is all you can go.
+ You would hardly want your top level application creating
+ every low level file, socket and database connection ever
+ needed.
+ It wouldn't know the constructor parameters anyway.
+ </p>
+ <p>
+ The next simplest compromise is to have the created object passed
+ in as an optional parameter...
+<pre>
+&lt;?php
+ require_once('socket.php');
+
+ class Telnet {
+ ...<strong>
+ function &amp;connect($ip, $port, $username, $password, $socket = false) {
+ if (!$socket) {
+ $socket = &amp;new Socket($ip, $port);
+ }
+ $socket-&gt;read( ... );</strong>
+ ...
+ return $socket;
+ }
+ }
+?&gt;
+</pre>
+ For a quick solution this is usually good enough.
+ The test now looks almost the same as if the parameter
+ was formally passed...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = &amp;new MockSocket($this);
+ ...
+ $telnet = &amp;new Telnet();
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret', &amp;$socket);
+ ...</strong>
+ }
+}
+</pre>
+ The problem with this approach is its untidiness.
+ There is test code in the main class and parameters passed
+ in the test case that are never used.
+ This is a quick and dirty approach, but nevertheless effective
+ in most situations.
+ </p>
+ <p>
+ The next method is to pass in a factory object to do the creation...
+<pre>
+&lt;?php
+ require_once('socket.php');
+
+ class Telnet {<strong>
+ function Telnet(&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>
+ This is probably the most highly factored answer as creation
+ is now moved into a small specialist class.
+ The networking factory can now be tested separately, but mocked
+ easily when we are testing the telnet class...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = &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>
+ The downside is that we are adding a lot more classes to the
+ library.
+ Also we are passing a lot of factories around which will
+ make the code a little less intuitive.
+ The most flexible solution, but the most complex.
+ </p>
+ <p>
+ Is there a middle ground?
+ </p>
+
+ <p>
+<a class="target" name="creation">
+<h2>Protected factory method</h2>
+</a>
+</p>
+ <p>
+ There is a way we can circumvent the problem without creating
+ any new application classes, but it involves creating a subclass
+ when we do the actual testing.
+ Firstly we move the socket creation into its own method...
+<pre>
+&lt;?php
+ require_once('socket.php');
+
+ class Telnet {
+ ...
+ function &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>
+ This is the only change we make to the application code.
+ </p>
+ <p>
+ For the test case we have to create a subclass so that
+ we can intercept the socket creation...
+<pre>
+<strong>class TelnetTestVersion extends Telnet {
+ var $_mock;
+
+ function TelnetTestVersion(&amp;$mock) {
+ $this-&gt;_mock = &amp;$mock;
+ $this-&gt;Telnet();
+ }
+
+ function &amp;_createSocket() {
+ return $this-&gt;_mock;
+ }
+}</strong>
+</pre>
+ Here I have passed the mock in the constructor, but a
+ setter would have done just as well.
+ Note that the mock was set into the object variable
+ before the constructor was chained.
+ This is necessary in case the constructor calls
+ <span class="new_code">connect()</span>.
+ Otherwise it could get a null value from
+ <span class="new_code">_createSocket()</span>.
+ </p>
+ <p>
+ After the completion of all of this extra work the
+ actual test case is fairly easy.
+ We just test our new class instead...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = &amp;new MockSocket($this);
+ ...
+ $telnet = &amp;new TelnetTestVersion($socket);
+ $telnet-&gt;connect('127.0.0.1', 21, 'Me', 'Secret');
+ ...</strong>
+ }
+}
+</pre>
+ The new class is very simple of course.
+ It just sets up a return value, rather like a mock.
+ It would be nice if it also checked the incoming parameters
+ as well.
+ Just like a mock.
+ It seems we are likely to do this often, can
+ we automate the subclass creation?
+ </p>
+
+ <p>
+<a class="target" name="partial">
+<h2>A partial mock</h2>
+</a>
+</p>
+ <p>
+ Of course the answer is "yes" or I would have stopped writing
+ this by now!
+ The previous test case was a lot of work, but we can
+ generate the subclass using a similar approach to the mock objects.
+ </p>
+ <p>
+ Here is the partial mock version of the test...
+<pre>
+<strong>Mock::generatePartial(
+ 'Telnet',
+ 'TelnetTestVersion',
+ array('_createSocket'));</strong>
+
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {<strong>
+ $socket = &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>
+ The partial mock is a subclass of the original with
+ selected methods "knocked out" with test
+ versions.
+ The <span class="new_code">generatePartial()</span> call
+ takes three parameters: the class to be subclassed,
+ the new test class name and a list of methods to mock.
+ </p>
+ <p>
+ Instantiating the resulting objects is slightly tricky.
+ The only constructor parameter of a partial mock is
+ the unit tester reference.
+ As with the normal mock objects this is needed for sending
+ test results in response to checked expectations.
+ </p>
+ <p>
+ The original constructor is not run yet.
+ This is necessary in case the constructor is going to
+ make use of the as yet unset mocked methods.
+ We set any return values at this point and then run the
+ constructor with its normal parameters.
+ This three step construction of "new", followed
+ by setting up the methods, followed by running the constructor
+ proper is what distinguishes the partial mock code.
+ </p>
+ <p>
+ Apart from construction, all of the mocked methods have
+ the same features as mock objects and all of the unmocked
+ methods behave as before.
+ We can set expectations very easily...
+<pre>
+class TelnetTest extends UnitTestCase {
+ ...
+ function testConnection() {
+ $socket = &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="less">
+<h2>Testing less than a class</h2>
+</a>
+</p>
+ <p>
+ The mocked out methods don't have to be factory methods,
+ they could be any sort of method.
+ In this way partial mocks allow us to take control of any part of
+ a class except the constructor.
+ We could even go as far as to mock every method
+ except one we actually want to test.
+ </p>
+ <p>
+ This last situation is all rather hypothetical, as I haven't
+ tried it.
+ I am open to the possibility, but a little worried that
+ forcing object granularity may be better for the code quality.
+ I personally use partial mocks as a way of overriding creation
+ or for occasional testing of the TemplateMethod pattern.
+ </p>
+ <p>
+ It's all going to come down to the coding standards of your
+ project to decide which mechanism you use.
+ </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/en/reporter_documentation.html b/tests/test_tools/simpletest/docs/en/reporter_documentation.html
new file mode 100755
index 00000000..44be8b1e
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/reporter_documentation.html
@@ -0,0 +1,515 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP test runner and display documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Reporting</span>
+</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>Test reporter documentation</h1>
+<div class="content">
+
+ <p>
+ SimpleTest pretty much follows the MVC pattern
+ (Model-View-Controller).
+ The reporter classes are the view and the model is your
+ test cases and their hiearchy.
+ The controller is mostly hidden from the user of
+ SimpleTest unless you want to change how the test cases
+ are actually run, in which case it is possible to
+ override the runner objects from within the test case.
+ As usual with MVC, the controller is mostly undefined
+ and there are other places to control the test run.
+ </p>
+
+ <p>
+<a class="target" name="html">
+<h2>Reporting results in HTML</h2>
+</a>
+</p>
+ <p>
+ The default test display is minimal in the extreme.
+ It reports success and failure with the conventional red and
+ green bars and shows a breadcrumb trail of test groups
+ for every failed assertion.
+ Here's a fail...
+ <div class="demo">
+ <h1>File test</h1>
+ <span class="fail">Fail</span>: createnewfile-&gt;True assertion failed.<br>
+ <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
+ <strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ And here all tests passed...
+ <div class="demo">
+ <h1>File test</h1>
+ <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
+ <strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
+ </div>
+ The good news is that there are several points in the display
+ hiearchy for subclassing.
+ </p>
+ <p>
+ For web page based displays there is the
+ <span class="new_code">HtmlReporter</span> class with the following
+ signature...
+<pre>
+class HtmlReporter extends SimpleReporter {
+ public 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>
+ Here is what some of these methods mean. First the display methods
+ that you will probably want to override...
+ <ul class="api">
+ <li>
+ <span class="new_code">HtmlReporter(string $encoding)</span>
+<br>
+ is the constructor.
+ Note that the unit test sets up the link to the display
+ rather than the other way around.
+ The display is a mostly passive receiver of test events.
+ This allows easy adaption of the display for other test
+ systems beside unit tests, such as monitoring servers.
+ The encoding is the character encoding you wish to
+ display the test output in.
+ In order to correctly render debug output when
+ using the web tester, this should match the encoding
+ of the site you are trying to test.
+ The available character set strings are described in
+ the PHP <a href="http://www.php.net/manual/en/function.htmlentities.php">html_entities()</a>
+ function.
+ </li>
+ <li>
+ <span class="new_code">void paintHeader(string $test_name)</span>
+<br>
+ is called once at the very start of the test when the first
+ start event arrives.
+ The first start event is usually delivered by the top level group
+ test and so this is where <span class="new_code">$test_name</span>
+ comes from.
+ It paints the page titles, CSS, body tag, etc.
+ It returns nothing (<span class="new_code">void</span>).
+ </li>
+ <li>
+ <span class="new_code">void paintFooter(string $test_name)</span>
+<br>
+ Called at the very end of the test to close any tags opened
+ by the page header.
+ By default it also displays the red/green bar and the final
+ count of results.
+ Actually the end of the test happens when a test end event
+ comes in with the same name as the one that started it all
+ at the same level.
+ The tests nest you see.
+ Closing the last test finishes the display.
+ </li>
+ <li>
+ <span class="new_code">void paintMethodStart(string $test_name)</span>
+<br>
+ is called at the start of each test method.
+ The name normally comes from method name.
+ The other test start events behave the same way except
+ that the group test one tells the reporter how large
+ it is in number of held test cases.
+ This is so that the reporter can display a progress bar
+ as the runner churns through the test cases.
+ </li>
+ <li>
+ <span class="new_code">void paintMethodEnd(string $test_name)</span>
+<br>
+ backs out of the test started with the same name.
+ </li>
+ <li>
+ <span class="new_code">void paintFail(string $message)</span>
+<br>
+ paints a failure.
+ By default it just displays the word fail, a breadcrumbs trail
+ showing the current test nesting and the message issued by
+ the assertion.
+ </li>
+ <li>
+ <span class="new_code">void paintPass(string $message)</span>
+<br>
+ by default does nothing.
+ </li>
+ <li>
+ <span class="new_code">string _getCss()</span>
+<br>
+ Returns the CSS styles as a string for the page header
+ method.
+ Additional styles have to be appended here if you are
+ not overriding the page header.
+ You will want to use this method in an overriden page header
+ if you want to include the original CSS.
+ </li>
+ </ul>
+ There are also some accessors to get information on the current
+ state of the test suite.
+ Use these to enrich the display...
+ <ul class="api">
+ <li>
+ <span class="new_code">array getTestList()</span>
+<br>
+ is the first convenience method for subclasses.
+ Lists the current nesting of the tests as a list
+ of test names.
+ The first, most deeply nested test, is first in the
+ list and the current test method will be last.
+ </li>
+ <li>
+ <span class="new_code">integer getPassCount()</span>
+<br>
+ returns the number of passes chalked up so far.
+ Needed for the display at the end.
+ </li>
+ <li>
+ <span class="new_code">integer getFailCount()</span>
+<br>
+ is likewise the number of fails so far.
+ </li>
+ <li>
+ <span class="new_code">integer getExceptionCount()</span>
+<br>
+ is likewise the number of errors so far.
+ </li>
+ <li>
+ <span class="new_code">integer getTestCaseCount()</span>
+<br>
+ is the total number of test cases in the test run.
+ This includes the grouping tests themselves.
+ </li>
+ <li>
+ <span class="new_code">integer getTestCaseProgress()</span>
+<br>
+ is the number of test cases completed so far.
+ </li>
+ </ul>
+ One simple modification is to get the HtmlReporter to display
+ the passes as well as the failures and errors...
+<pre>
+<strong>class 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>
+ One method that was glossed over was the <span class="new_code">makeDry()</span>
+ method.
+ If you run this method, with no parameters, on the reporter
+ before the test suite is run no actual test methods
+ will be called.
+ You will still get the events of entering and leaving the
+ test methods and test cases, but no passes or failures etc,
+ because the test code will not actually be executed.
+ </p>
+ <p>
+ The reason for this is to allow for more sophistcated
+ GUI displays that allow the selection of individual test
+ cases.
+ In order to build a list of possible tests they need a
+ report on the test structure for drawing, say a tree view
+ of the test suite.
+ With a reporter set to dry run that just sends drawing events
+ this is easily accomplished.
+ </p>
+
+ <p>
+<a class="target" name="other">
+<h2>Extending the reporter</h2>
+</a>
+</p>
+ <p>
+ Rather than simply modifying the existing display, you might want to
+ produce a whole new HTML look, or even generate text or XML.
+ Rather than override every method in
+ <span class="new_code">HtmlReporter</span> we can take one
+ step up the class hiearchy to <span class="new_code">SimpleReporter</span>
+ in the <em>simple_test.php</em> source file.
+ </p>
+ <p>
+ A do nothing display, a blank canvas for your own creation, would
+ be...
+<pre>
+<strong>require_once('simpletest/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>
+ No output would come from this class until you add it.
+ </p>
+
+ <p>
+<a class="target" name="cli">
+<h2>The command line reporter</h2>
+</a>
+</p>
+ <p>
+ SimpleTest also ships with a minimal command line reporter.
+ The interface mimics JUnit to some extent, but paints the
+ failure messages as they arrive.
+ To use the command line reporter simply substitute it
+ for the HTML version...
+<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>
+ Then invoke the test suite from the command line...
+<pre class="shell">
+php file_test.php
+</pre>
+ You will need the command line version of PHP installed
+ of course.
+ A passing test suite looks like this...
+<pre class="shell">
+File test
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+</pre>
+ A failure triggers a display like this...
+<pre class="shell">
+File test
+1) True assertion failed.
+ in createnewfile
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+</pre>
+ </p>
+ <p>
+ One of the main reasons for using a command line driven
+ test suite is of using the tester as part of some automated
+ process.
+ To function properly in shell scripts the test script should
+ return a non-zero exit code on failure.
+ If a test suite fails the value <span class="new_code">false</span>
+ is returned from the <span class="new_code">SimpleTest::run()</span>
+ method.
+ We can use that result to exit the script with the desired return
+ code...
+<pre>
+&lt;?php
+ require_once('simpletest/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>
+ Of course we don't really want to create two test scripts,
+ a command line one and a web browser one, for each test suite.
+ The command line reporter includes a method to sniff out the
+ run time environment...
+<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>
+ This is the form used within SimpleTest itself.
+ </p>
+
+ <p>
+<a class="target" name="xml">
+<h2>Remote testing</h2>
+</a>
+</p>
+ <p>
+ SimpleTest ships with an <span class="new_code">XmlReporter</span> class
+ used for internal communication.
+ When run the output looks like...
+<pre class="shell">
+&lt;?xml version="1.0"?&gt;
+&lt;run&gt;
+ &lt;group size="4"&gt;
+ &lt;name&gt;Remote tests&lt;/name&gt;
+ &lt;group size="4"&gt;
+ &lt;name&gt;Visual test with 48 passes, 48 fails and 4 exceptions&lt;/name&gt;
+ &lt;case&gt;
+ &lt;name&gt;testofunittestcaseoutput&lt;/name&gt;
+ &lt;test&gt;
+ &lt;name&gt;testofresults&lt;/name&gt;
+ &lt;pass&gt;This assertion passed&lt;/pass&gt;
+ &lt;fail&gt;This assertion failed&lt;/fail&gt;
+ &lt;/test&gt;
+ &lt;test&gt;
+ ...
+ &lt;/test&gt;
+ &lt;/case&gt;
+ &lt;/group&gt;
+ &lt;/group&gt;
+&lt;/run&gt;
+</pre>
+ You can make use of this format with the parser
+ supplied as part of SimpleTest itself.
+ This is called <span class="new_code">SimpleTestXmlParser</span> and
+ resides in <em>xml.php</em> within the SimpleTest package...
+<pre>
+&lt;?php
+ require_once('simpletest/xml.php');
+
+ ...
+ $parser = &amp;new SimpleTestXmlParser(new HtmlReporter());
+ $parser-&gt;parse($test_output);
+?&gt;
+</pre>
+ The <span class="new_code">$test_output</span> should be the XML format
+ from the XML reporter, and could come from say a command
+ line run of a test case.
+ The parser sends events to the reporter just like any
+ other test run.
+ There are some odd occasions where this is actually useful.
+ </p>
+ <p>
+ A problem with large test suites is thet they can exhaust
+ the default 8Mb memory limit on a PHP process.
+ By having the test groups output in XML and run in
+ separate processes, the output can be reparsed to
+ aggregate the results into a much smaller footprint top level
+ test.
+ </p>
+ <p>
+ Because the XML output can come from anywhere, this opens
+ up the possibility of aggregating test runs from remote
+ servers.
+ A test case already exists to do this within the SimpleTest
+ framework, but it is currently experimental...
+<pre>
+&lt;?php
+ <strong>require_once('../remote.php');</strong>
+ require_once('../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>
+ The <span class="new_code">RemoteTestCase</span> takes the actual location
+ of the test runner, basically a web page in XML format.
+ It also takes the URL of a reporter set to do a dry run.
+ This is so that progress can be reported upward correctly.
+ The <span class="new_code">RemoteTestCase</span> can be added to test suites
+ just like any other group 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/en/server_stubs_documentation.html b/tests/test_tools/simpletest/docs/en/server_stubs_documentation.html
new file mode 100755
index 00000000..4b18bb0b
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/server_stubs_documentation.html
@@ -0,0 +1,388 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP server stubs documentation</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>
+<span class="chosen">Server stubs</span>
+</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>Server stubs documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="what">
+<h2>What are server stubs?</h2>
+</a>
+</p>
+ <p>
+ This was originally a pattern named by Robert Binder (Testing
+ object-oriented systems: models, patterns, and tools,
+ Addison-Wesley) in 1999.
+ A server stub is a simulation of an object or component.
+ It should exactly replace a component in a system for test
+ or prototyping purposes, but remain lightweight.
+ This allows tests to run more quickly, or if the simulated
+ class has not been written, to run at all.
+ </p>
+
+ <p>
+<a class="target" name="creation">
+<h2>Creating server stubs</h2>
+</a>
+</p>
+ <p>
+ All we need is an existing class, say a database connection
+ that looks like this...
+<pre>
+<strong>class DatabaseConnection {
+ function DatabaseConnection() {
+ }
+
+ function query() {
+ }
+
+ function selectQuery() {
+ }
+}</strong>
+</pre>
+ The class does not need to have been implemented yet.
+ To create a stub version of the class we need to include the
+ server stub library and run the generator...
+<pre>
+<strong>require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+Stub::generate('DatabaseConnection');</strong>
+</pre>
+ This generates a clone class called
+ <span class="new_code">StubDatabaseConnection</span>.
+ We can now create instances of the new class within
+ our prototype script...
+<pre>
+require_once('simpletest/mock_objects.php');
+require_once('database_connection.php');
+Stub::generate('DatabaseConnection');
+<strong>
+$connection = new StubDatabaseConnection();
+</strong>
+</pre>
+ The stub 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.
+ 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>
+</pre>
+ Now every time we call
+ <span class="new_code">$connection-&gt;query()</span> we get
+ the result of 37.
+ We can set the return value to anything, say a hash of
+ imaginary database results or a list of persistent objects.
+ Parameters are irrelevant here, we always get the same
+ values back each time once they have been set up this way.
+ That may not sound like a convincing replica of a
+ database connection, but for the half a dozen lines of
+ a test method it is usually all you need.
+ </p>
+
+ <p>
+<a class="target" name="patterns">
+<h2>Simulation patterns</h2>
+</a>
+</p>
+ <p>
+ Things aren't always that simple though.
+ One common problem is iterators, where constantly returning
+ the same value could cause an endless loop in the object
+ being tested.
+ For these we need to set up sequences of values.
+ Let's say we have a simple iterator that looks like this...
+<pre>
+class Iterator {
+ function Iterator() {
+ }
+
+ function next() {
+ }
+}
+</pre>
+ This is about the simplest iterator you could have.
+ Assuming that this iterator only returns text until it
+ reaches the end, when it returns false, we can simulate it
+ with...
+<pre>
+<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>
+ When <span class="new_code">next()</span> is called on the
+ stub iterator it will first return "First string",
+ on the second call "Second string" will be returned
+ and on any other call <span class="new_code">false</span> will
+ be returned.
+ The sequenced return values take precedence over the constant
+ return value.
+ The constant one is a kind of default if you like.
+ </p>
+ <p>
+ Another tricky situation is an overloaded
+ <span class="new_code">get()</span> operation.
+ An example of this is an information holder with name/value pairs.
+ Say we have a configuration class like...
+<pre>
+class Configuration {
+ function Configuration() {
+ }
+
+ function getValue($key) {
+ }
+}
+</pre>
+ This is a classic situation for using stub objects as
+ actual configuration will vary from machine to machine,
+ hardly helping the reliability of our tests if we use it
+ directly.
+ The problem though is that all the data comes through the
+ <span class="new_code">getValue()</span> method and yet
+ we want different results for different keys.
+ Luckily the stubs have a filter system...
+<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>
+ The extra parameter is a list of arguments to attempt
+ to match.
+ In this case we are trying to match only one argument which
+ is the look up key.
+ Now when the server stub has the
+ <span class="new_code">getValue()</span> method invoked
+ like this...
+<pre>
+$config-&gt;getValue('db_user');
+</pre>
+ ...it will return "admin".
+ It finds this by attempting to match the calling arguments
+ to its list of returns one after another until
+ a complete match is found.
+ </p>
+ <p>
+ You can set a default argument argument like so...
+<pre>
+<strong>
+$config-&gt;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 stub rather than just a copy.
+ The PHP copy semantics force us to use a different method
+ for this.
+ You might be simulating a container for example...
+<pre>
+class Thing {
+}
+
+class Vector {
+ function Vector() {
+ }
+
+ function get($index) {
+ }
+}
+</pre>
+ In this case you can set a reference into the stub's
+ return list...
+<pre>
+Stub::generate('Vector');
+
+$thing = new Thing();<strong>
+$vector = &amp;new StubVector();
+$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.
+ </p>
+ <p>
+ These three factors, timing, parameters and whether to copy,
+ can be combined orthogonally.
+ For example...
+<pre>
+$complex = &amp;new StubComplexThing();
+$stuff = 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 stubbed using the mechanics above.
+ </p>
+ <p>
+ Here's how...
+<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>
+ 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>
+<a class="target" name="options">
+<h2>Stub creation options</h2>
+</a>
+</p>
+ <p>
+ There are some additional options when creating stubs.
+ At the generation stage we can change the class name...
+<pre>
+<strong>Stub::generate('Iterator', 'MyStubIterator');
+$iterator = &amp;new MyStubIterator();
+</strong>
+</pre>
+ This is not very useful in itself as there would be no difference
+ in this class and the default except for the name.
+ However we can also add additional methods not found in the
+ original interface...
+<pre>
+class Iterator {
+}
+<strong>Stub::generate('Iterator', 'PrototypeIterator', array('next', 'isError'));
+$iterator = &amp;new PrototypeIterator();
+$iterator-&gt;setReturnValue('next', 0);
+</strong>
+</pre>
+ The <span class="new_code">next()</span> and
+ <span class="new_code">isError()</span> methods can now have
+ return values set just as if they existed in the original class.
+ </p>
+ <p>
+ One other esoteric way of customising the stubs is to change
+ the default wildcard used for parameter matching.
+<pre>
+<strong>Stub::generate('Connection');
+$iterator = &amp;new StubConnection('wild');
+$iterator-&gt;setReturnValue('query', array('id' =&gt; 33), array('wild'));
+</strong>
+</pre>
+ The only reason to do this is if you genuinely wanted to test
+ against the literal string "*" and didn't want it
+ interpreted as "any".
+ </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/en/unit_test_documentation.html b/tests/test_tools/simpletest/docs/en/unit_test_documentation.html
new file mode 100755
index 00000000..6aa8d8a7
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/unit_test_documentation.html
@@ -0,0 +1,387 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>SimpleTest for PHP regression test documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<h2>
+<a href="index.html">SimpleTest</a>
+</h2>
+<ul>
+<li>
+<a href="overview.html">Overview</a>
+</li>
+<li>
+<span class="chosen">Unit tester</span>
+</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>PHP Unit Test documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="unit">
+<h2>Unit test cases</h2>
+</a>
+</p>
+ <p>
+ The core system is a regression testing framework built around
+ test cases.
+ A sample test case looks like this...
+<pre>
+<strong>class FileTestCase extends UnitTestCase {
+}</strong>
+</pre>
+ If no test name is supplied when chaining the constructor then
+ the class name will be taken instead.
+ This will be the name displayed in the test results.
+ </p>
+ <p>
+ Actual tests are added as methods in the test case whose names
+ by default start with the string "test" and
+ when the test case is invoked all such methods are run in
+ the order that PHP introspection finds them.
+ As many test methods can be added as needed.
+ For example...
+<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>
+ The constructor is optional and usually omitted.
+ Without a name, the class name is taken as the name of the test case.
+ </p>
+ <p>
+ Our only test method at the moment is <span class="new_code">testCreation()</span>
+ where we check that a file has been created by our
+ <span class="new_code">Writer</span> object.
+ We could have put the <span class="new_code">unlink()</span>
+ code into this method as well, but by placing it in
+ <span class="new_code">setUp()</span> and
+ <span class="new_code">tearDown()</span> we can use it with
+ other test methods that we add.
+ </p>
+ <p>
+ The <span class="new_code">setUp()</span> method is run
+ just before each and every test method.
+ <span class="new_code">tearDown()</span> is run just after
+ each and every test method.
+ </p>
+ <p>
+ You can place some test case set up into the constructor to
+ be run once for all the methods in the test case, but
+ you risk test inteference that way.
+ This way is slightly slower, but it is safer.
+ Note that if you come from a JUnit background this will not
+ be the behaviour you are used to.
+ JUnit surprisingly reinstantiates the test case for each test
+ method to prevent such interference.
+ SimpleTest requires the end user to use <span class="new_code">setUp()</span>, but
+ supplies additional hooks for library writers.
+ </p>
+ <p>
+ The means of reporting test results (see below) are by a
+ visiting display class
+ that is notified by various <span class="new_code">assert...()</span>
+ methods.
+ Here is the full list for the <span class="new_code">UnitTestCase</span>
+ class, the default for SimpleTest...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">assertTrue($x)</span></td><td>Fail if $x is false</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertFalse($x)</span></td><td>Fail if $x is true</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNull($x)</span></td><td>Fail if $x is set</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotNull($x)</span></td><td>Fail if $x not set</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertIsA($x, $t)</span></td><td>Fail if $x is not the class or type $t</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotA($x, $t)</span></td><td>Fail if $x is of the class or type $t</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertEqual($x, $y)</span></td><td>Fail if $x == $y is false</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotEqual($x, $y)</span></td><td>Fail if $x == $y is true</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertIdentical($x, $y)</span></td><td>Fail if $x == $y is false or a type mismatch</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNotIdentical($x, $y)</span></td><td>Fail if $x == $y is true and types match</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertReference($x, $y)</span></td><td>Fail unless $x and $y are the same variable</td>
+</tr>
+ <tr>
+<td><span class="new_code">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>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoUnwantedPattern($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>
+</tr>
+ <tr>
+<td><span class="new_code">assertErrorPattern($p)</span></td><td>Fail unless the error matches the regex $p</td>
+</tr>
+ </tbody>
+</table>
+ All assertion methods can take an optional description to
+ label the displayed result with.
+ If omitted a default message is sent instead which is usually
+ sufficient.
+ This default message can still be embedded in your own message
+ if you include "%s" within the string.
+ All the assertions return true on a pass or false on failure.
+ </p>
+ <p>
+ Some examples...
+<pre>
+<strong>$variable = null;
+$this-&gt;assertNull($variable, 'Should be cleared');</strong>
+</pre>
+ ...will pass and normally show no message.
+ If you have
+ <a href="http://www.lastcraft.com/display_subclass_tutorial.php">set up the tester to display passes</a>
+ as well then the message will be displayed as is.
+<pre>
+<strong>$this-&gt;assertIdentical(0, false, 'Zero is not false [%s]');</strong>
+</pre>
+ This will fail as it performs a type
+ check as well as a comparison between the two values.
+ The "%s" part is replaced by the default
+ error message that would have been shown if we had not
+ supplied our own.
+ This also allows us to nest test messages.
+<pre>
+<strong>$a = 1;
+$b = $a;
+$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>
+</pre>
+ This will pass as using a case insensitive match the string
+ <span class="new_code">hello</span> is contained in <span class="new_code">Hello world</span>.
+<pre>
+<strong>trigger_error('Disaster');
+trigger_error('Catastrophe');
+$this-&gt;assertError();
+$this-&gt;assertError('Catastrophe');
+$this-&gt;assertNoErrors();</strong>
+</pre>
+ This one takes some explanation as in fact they all pass!
+ </p>
+ <p>
+ PHP errors in SimpleTest are trapped and placed in a queue.
+ Here the first error check catches the "Disaster"
+ message without checking the text and passes.
+ This removes the error from the queue.
+ The next error check tests not only the existence of the error,
+ but also the text which here matches so another pass.
+ With the queue now empty the last test will pass as well.
+ If any unchecked errors are left at the end of a test method then
+ an exception will be reported in the test.
+ Note that SimpleTest cannot catch compile time PHP errors.
+ </p>
+ <p>
+ The test cases also have some convenience methods for debugging
+ code or extending the suite...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">setUp()</span></td><td>Runs this before each test method</td>
+</tr>
+ <tr>
+<td><span class="new_code">tearDown()</span></td><td>Runs this after each test method</td>
+</tr>
+ <tr>
+<td><span class="new_code">pass()</span></td><td>Sends a test pass</td>
+</tr>
+ <tr>
+<td><span class="new_code">fail()</span></td><td>Sends a test failure</td>
+</tr>
+ <tr>
+<td><span class="new_code">error()</span></td><td>Sends an exception event</td>
+</tr>
+ <tr>
+<td><span class="new_code">sendMessage()</span></td><td>Sends a status message to those displays that support it</td>
+</tr>
+ <tr>
+<td><span class="new_code">signal($type, $payload)</span></td><td>Sends a user defined message to the test reporter</td>
+</tr>
+ <tr>
+<td><span class="new_code">dump($var)</span></td><td>Does a formatted <span class="new_code">print_r()</span> for quick and dirty debugging</td>
+</tr>
+ <tr>
+<td><span class="new_code">swallowErrors()</span></td><td>Clears the error queue</td>
+</tr>
+ </tbody>
+</table>
+ </p>
+
+ <p>
+<a class="target" name="extending_unit">
+<h2>Extending test cases</h2>
+</a>
+</p>
+ <p>
+ Of course additional test methods can be added to create
+ specific types of test case too so as to extend 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>
+ Here the SimpleTest library is held in a folder called
+ <em>simpletest</em> that is local.
+ Substitute your own path for this.
+ </p>
+ <p>
+ This new case can be now be inherited just like
+ a normal test case...
+<pre>
+class FileTestCase extends <strong>FileTester</strong> {
+
+ function setUp() {
+ @unlink('../temp/test.txt');
+ }
+
+ function tearDown() {
+ @unlink('../temp/test.txt');
+ }
+
+ function testCreation() {
+ $writer = &amp;new FileWriter('../temp/test.txt');
+ $writer-&gt;write('Hello');<strong>
+ $this-&gt;assertFileExists('../temp/test.txt');</strong>
+ }
+}
+</pre>
+ </p>
+ <p>
+ If you want a test case that does not have all of the
+ <span class="new_code">UnitTestCase</span> assertions,
+ only your own and <span class="new_code">assertTrue()</span>,
+ you need to extend the <span class="new_code">SimpleTestCase</span>
+ class instead.
+ It is found in <em>simple_test.php</em> rather than
+ <em>unit_tester.php</em>.
+ See <a href="group_test_documentation.html">later</a> if you
+ want to incorporate other unit tester's
+ test cases in your test suites.
+ </p>
+
+ <p>
+<a class="target" name="running_unit">
+<h2>Running a single test case</h2>
+</a>
+</p>
+ <p>
+ You won't often run single test cases except when bashing
+ away at a module that is having difficulty and you don't
+ want to upset the main test suite.
+ Here is the scaffolding needed to run the a lone test case...
+<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>
+ This script will run as is, but will output zero passes
+ and zero failures until test methods are added.
+ </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/en/web_tester_documentation.html b/tests/test_tools/simpletest/docs/en/web_tester_documentation.html
new file mode 100755
index 00000000..51f604be
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/en/web_tester_documentation.html
@@ -0,0 +1,508 @@
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Simple Test for PHP web script testing documentation</title>
+<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
+</head>
+<body>
+<div class="menu_back">
+<div class="menu">
+<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>
+<span class="chosen">Web tester</span>
+</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>Web tester documentation</h1>
+<div class="content">
+ <p>
+<a class="target" name="fetch">
+<h2>Fetching a page</h2>
+</a>
+</p>
+ <p>
+ Testing classes is all very well, but PHP is predominately
+ a language for creating functionality within web pages.
+ How do we test the front end presentation role of our PHP
+ applications?
+ Well the web pages are just text, so we should be able to
+ examine them just like any other test data.
+ </p>
+ <p>
+ This leads to a tricky issue.
+ If we test at too low a level, testing for matching tags
+ in the page with pattern matching for example, our tests will
+ be brittle.
+ The slightest change in layout could break a large number of
+ tests.
+ If we test at too high a level, say using mock versions of a
+ template engine, then we lose the ability to automate some classes
+ of test.
+ For example, the interaction of forms and navigation will
+ have to be tested manually.
+ These types of test are extremely repetitive and error prone.
+ </p>
+ <p>
+ SimpleTest includes a special form of test case for the testing
+ of web page actions.
+ The <span class="new_code">WebTestCase</span> includes facilities
+ for navigation, content and cookie checks and form handling.
+ Usage of these test cases is similar to the
+ <a href="unit_tester_documentation.html">UnitTestCase</a>...
+<pre>
+<strong>class TestOfLastcraft extends WebTestCase {
+}</strong>
+</pre>
+ Here we are about to test the
+ <a href="http://www/lastcraft.com/">Last Craft</a> site itself.
+ If this test case is in a file called <em>lastcraft_test.php</em>
+ then it can be loaded in a runner script just like unit tests...
+<pre>
+&lt;?php<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>
+ I am using the text reporter here to more clearly
+ distinguish the web content from the test output.
+ </p>
+ <p>
+ Nothing is being tested yet.
+ We can fetch the home page by using the
+ <span class="new_code">get()</span> method...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+ <strong>
+ function testHomepage() {
+ $this-&gt;assertTrue($this-&gt;get('http://www.lastcraft.com/'));
+ }</strong>
+}
+</pre>
+ The <span class="new_code">get()</span> method will
+ return true only if page content was successfully
+ loaded.
+ It is a simple, but crude way to check that a web page
+ was actually delivered by the web server.
+ However that content may be a 404 response and yet
+ our <span class="new_code">get()</span> method will still return true.
+ </p>
+ <p>
+ Assuming that the web server for the Last Craft site is up
+ (sadly not always the case), we should see...
+<pre class="shell">
+Web site tests
+OK
+Test cases run: 1/1, Failures: 0, Exceptions: 0
+</pre>
+ All we have really checked is that any kind of page was
+ returned.
+ We don't yet know if it was the right one.
+ </p>
+
+ <p>
+<a class="target" name="content">
+<h2>Testing page content</h2>
+</a>
+</p>
+ <p>
+ To confirm that the page we think we are on is actually the
+ page we are on, we need to verify the page content.
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {<strong>
+ $this-&gt;get('http://www.lastcraft.com/');
+ $this-&gt;assertWantedPattern('/why the last craft/i');</strong>
+ }
+}
+</pre>
+ The page from the last fetch is held in a buffer in
+ the test case, so there is no need to refer to it directly.
+ The pattern match is always made against the buffer.
+ </p>
+ <p>
+ Here is the list of possible content assertions...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">assertTitle($title)</span></td><td>Pass if title is an exact match</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertWantedPattern($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>
+</tr>
+ <tr>
+<td><span class="new_code">assertWantedText($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>
+</tr>
+ <tr>
+<td><span class="new_code">assertLink($label)</span></td><td>Pass if a link with this text is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoLink($label)</span></td><td>Pass if no link with this text is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertLinkById($id)</span></td><td>Pass if a link with this id attribute is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoLinkById($id)</span></td><td>Pass if no link with this id attribute is present</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertField($name, $value)</span></td><td>Pass if an input tag with this name has this value</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertFieldById($id, $value)</span></td><td>Pass if an input tag with this id has this value</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertResponse($codes)</span></td><td>Pass if HTTP response matches this list</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertMime($types)</span></td><td>Pass if MIME type is in this list</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertAuthentication($protocol)</span></td><td>Pass if the current challenge is this protocol</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoAuthentication()</span></td><td>Pass if there is no current challenge</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertRealm($name)</span></td><td>Pass if the current challenge realm matches</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertHeader($header, $content)</span></td><td>Pass if a header was fetched matching this value</td>
+</tr>
+ <tr>
+<td><span class="new_code">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>
+</tr>
+ <tr>
+<td><span class="new_code">assertCookie($name, $value)</span></td><td>Pass if there is currently a matching cookie</td>
+</tr>
+ <tr>
+<td><span class="new_code">assertNoCookie($name)</span></td><td>Pass if there is currently no cookie of this name</td>
+</tr>
+ </tbody>
+</table>
+ As usual with the SimpleTest assertions, they all return
+ false on failure and true on pass.
+ They also allow an optional test message and you can embed
+ the original test message inside using "%s" inside
+ your custom message.
+ </p>
+ <p>
+ So now we could instead test against the title tag with...
+<pre>
+<strong>$this-&gt;assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');</strong>
+</pre>
+ As well as the simple HTML content checks we can check
+ that the MIME type is in a list of allowed types with...
+<pre>
+<strong>$this-&gt;assertMime(array('text/plain', 'text/html'));</strong>
+</pre>
+ More interesting is checking the HTTP response code.
+ Like the MIME type, we can assert that the response code
+ is in a list of allowed values...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testRedirects() {
+ $this-&gt;get('http://www.lastcraft.com/test/redirect.php');
+ $this-&gt;assertResponse(200);&lt;/strong&gt;
+ }
+}
+</pre>
+ Here we are checking that the fetch is successful by
+ allowing only a 200 HTTP response.
+ This test will pass, but it is not actually correct to do so.
+ There is no page, instead the server issues a redirect.
+ The <span class="new_code">WebTestCase</span> will
+ automatically follow up to three such redirects.
+ The tests are more robust this way and we are usually
+ interested in the interaction with the pages rather
+ than their delivery.
+ If the redirects are of interest then this ability must
+ be disabled...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {<strong>
+ $this-&gt;setMaximumRedirects(0);</strong>
+ $this-&gt;get('http://www.lastcraft.com/test/redirect.php');
+ $this-&gt;assertResponse(200);
+ }
+}
+</pre>
+ The assertion now fails as expected...
+<pre class="shell">
+Web site tests
+1) Expecting response in [200] got [302]
+ in testhomepage
+ in testoflastcraft
+ in lastcraft_test.php
+FAILURES!!!
+Test cases run: 1/1, Failures: 1, Exceptions: 0
+</pre>
+ We can modify the test to correctly assert redirects with...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+
+ function testHomepage() {
+ $this-&gt;setMaximumRedirects(0);
+ $this-&gt;get('http://www.lastcraft.com/test/redirect.php');
+ $this-&gt;assertResponse(<strong>array(301, 302, 303, 307)</strong>);
+ }
+}
+</pre>
+ This now passes.
+ </p>
+
+ <p>
+<a class="target" name="navigation">
+<h2>Navigating a web site</h2>
+</a>
+</p>
+ <p>
+ Users don't often navigate sites by typing in URLs, but by
+ clicking links and buttons.
+ Here we confirm that the contact details can be reached
+ from the home page...
+<pre>
+class TestOfLastcraft extends WebTestCase {
+ ...
+ function testContact() {
+ $this-&gt;get('http://www.lastcraft.com/');<strong>
+ $this-&gt;clickLink('About');
+ $this-&gt;assertTitle('About Last Craft');</strong>
+ }
+}
+</pre>
+ The parameter is the text of the link.
+ </p>
+ <p>
+ If the target is a button rather than an anchor tag, then
+ <span class="new_code">clickSubmit()</span> should be used
+ with the button title...
+<pre>
+<strong>$this-&gt;clickSubmit('Go!');</strong>
+</pre>
+ </p>
+ <p>
+ The list of navigation methods is...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">getUrl()</span></td><td>The current location</td>
+</tr>
+ <tr>
+<td><span class="new_code">get($url, $parameters)</span></td><td>Send a GET request with these parameters</td>
+</tr>
+ <tr>
+<td><span class="new_code">post($url, $parameters)</span></td><td>Send a POST request with these parameters</td>
+</tr>
+ <tr>
+<td><span class="new_code">head($url, $parameters)</span></td><td>Send a HEAD request without replacing the page content</td>
+</tr>
+ <tr>
+<td><span class="new_code">retry()</span></td><td>Reload the last request</td>
+</tr>
+ <tr>
+<td><span class="new_code">back()</span></td><td>Like the browser back button</td>
+</tr>
+ <tr>
+<td><span class="new_code">forward()</span></td><td>Like the browser forward button</td>
+</tr>
+ <tr>
+<td><span class="new_code">authenticate($name, $password)</span></td><td>Retry after a challenge</td>
+</tr>
+ <tr>
+<td><span class="new_code">restart()</span></td><td>Restarts the browser as if a new session</td>
+</tr>
+ <tr>
+<td><span class="new_code">getCookie($name)</span></td><td>Gets the cookie value for the current context</td>
+</tr>
+ <tr>
+<td><span class="new_code">ageCookies($interval)</span></td><td>Ages current cookies prior to a restart</td>
+</tr>
+ <tr>
+<td><span class="new_code">clearFrameFocus()</span></td><td>Go back to treating all frames as one page</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmit($label)</span></td><td>Click the first button with this label</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitByName($name)</span></td><td>Click the button with this name attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickSubmitById($id)</span></td><td>Click the button with this ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImage($label, $x, $y)</span></td><td>Click an input tag of type image by title or alt text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageByName($name, $x, $y)</span></td><td>Click an input tag of type image by name</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickImageById($id, $x, $y)</span></td><td>Click an input tag of type image by ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">submitFormById($id)</span></td><td>Submit a form without the submit value</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLink($label, $index)</span></td><td>Click an anchor by the visible label text</td>
+</tr>
+ <tr>
+<td><span class="new_code">clickLinkById($id)</span></td><td>Click an anchor by the ID attribute</td>
+</tr>
+ <tr>
+<td><span class="new_code">getFrameFocus()</span></td><td>The name of the currently selected frame</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocusByIndex($choice)</span></td><td>Focus on a frame counting from 1</td>
+</tr>
+ <tr>
+<td><span class="new_code">setFrameFocus($name)</span></td><td>Focus on a frame by name</td>
+</tr>
+ </tbody>
+</table>
+ </p>
+ <p>
+ The parameters in the <span class="new_code">get()</span>, <span class="new_code">post()</span> or
+ <span class="new_code">head()</span> methods are optional.
+ The HTTP HEAD fetch does not change the browser context, only loads
+ cookies.
+ This can be useful for when an image or stylesheet sets a cookie
+ for crafty robot blocking.
+ </p>
+ <p>
+ The <span class="new_code">retry()</span>, <span class="new_code">back()</span> and
+ <span class="new_code">forward()</span> commands work as they would on
+ your web browser.
+ They use the history to retry pages.
+ This can be handy for checking the effect of hitting the
+ back button on your forms.
+ </p>
+ <p>
+ The frame methods need a little explanation.
+ By default a framed page is treated just like any other.
+ Content will be searced for throughout the entire frameset,
+ so clicking a link will work no matter which frame
+ the anchor tag is in.
+ You can override this behaviour by focusing on a single
+ frame.
+ If you do that, all searches and actions will apply to that
+ frame alone, such as authentication and retries.
+ If a link or button is not in a focused frame then it cannot
+ be clicked.
+ </p>
+ <p>
+ Testing navigation on fixed pages only tells you when you
+ have broken an entire script.
+ For highly dynamic pages, such as for bulletin boards, this can
+ be crucial for verifying the correctness of the application.
+ For most applications though, the really tricky logic is usually in
+ the handling of forms and sessions.
+ Fortunately SimpleTest includes
+ <a href="form_testing_documentation.html">tools for testing web forms</a>
+ as well.
+ </p>
+
+ <p>
+<a class="target" name="request">
+<h2>Modifying the request</h2>
+</a>
+</p>
+ <p>
+ Although SimpleTest does not have the goal of testing networking
+ problems, it does include some methods to modify and debug
+ the requests it makes.
+ Here is another method list...
+ <table>
+<tbody>
+ <tr>
+<td><span class="new_code">getTransportError()</span></td><td>The last socket error</td>
+</tr>
+ <tr>
+<td><span class="new_code">showRequest()</span></td><td>Dump the outgoing request</td>
+</tr>
+ <tr>
+<td><span class="new_code">showHeaders()</span></td><td>Dump the incoming headers</td>
+</tr>
+ <tr>
+<td><span class="new_code">showSource()</span></td><td>Dump the raw HTML page content</td>
+</tr>
+ <tr>
+<td><span class="new_code">ignoreFrames()</span></td><td>Do not load framesets</td>
+</tr>
+ <tr>
+<td><span class="new_code">setCookie($name, $value)</span></td><td>Set a cookie from now on</td>
+</tr>
+ <tr>
+<td><span class="new_code">addHeader($header)</span></td><td>Always add this header to the request</td>
+</tr>
+ <tr>
+<td><span class="new_code">setMaximumRedirects($max)</span></td><td>Stop after this many redirects</td>
+</tr>
+ <tr>
+<td><span class="new_code">setConnectionTimeout($timeout)</span></td><td>Kill the connection after this time between bytes</td>
+</tr>
+ <tr>
+<td><span class="new_code">useProxy($proxy, $name, $password)</span></td><td>Make requests via this proxy URL</td>
+</tr>
+ </tbody>
+</table>
+ These methods are principally for debugging.
+ </p>
+
+ </div>
+<div class="copyright">
+ Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
+ </div>
+</body>
+</html>
diff --git a/tests/test_tools/simpletest/docs/fr/authentication_documentation.html b/tests/test_tools/simpletest/docs/fr/authentication_documentation.html
new file mode 100755
index 00000000..08cc2349
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/authentication_documentation.html
@@ -0,0 +1,264 @@
+<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
new file mode 100755
index 00000000..fa8ad1b6
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/browser_documentation.html
@@ -0,0 +1,329 @@
+<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
new file mode 100755
index 00000000..93226cd7
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/docs.css
@@ -0,0 +1,84 @@
+body {
+ padding-left: 3%;
+ padding-right: 3%;
+}
+pre {
+ font-family: courier;
+ font-size: 80%;
+ border: 1px solid;
+ background-color: #cccccc;
+ padding: 5px;
+ margin-left: 5%;
+ margin-right: 8%;
+}
+.code, .new_code, pre.new_code {
+ font-weight: bold;
+}
+div.copyright {
+ font-size: 80%;
+ color: gray;
+}
+div.copyright a {
+ color: gray;
+}
+ul.api {
+ padding-left: 0em;
+ padding-right: 25%;
+}
+ul.api li {
+ margin-top: 0.2em;
+ margin-bottom: 0.2em;
+ list-style: none;
+ text-indent: -3em;
+ padding-left: 3em;
+}
+div.demo {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: white;
+}
+div.demo span.fail {
+ color: red;
+}
+div.demo span.pass {
+ color: green;
+}
+div.demo h1 {
+ font-size: 12pt;
+ text-align: left;
+ font-weight: bold;
+}
+table {
+ border: 2px outset;
+ border-color: gray;
+ background-color: white;
+ margin: 5px;
+ margin-left: 5%;
+ margin-right: 5%;
+}
+td {
+ font-size: 80%;
+}
+.shell {
+ color: white;
+}
+pre.shell {
+ border: 4px ridge;
+ border-color: gray;
+ padding: 10px;
+ margin: 5px;
+ margin-left: 20px;
+ margin-right: 40px;
+ background-color: black;
+}
+form.demo {
+ background-color: lightgray;
+ border: 4px outset;
+ border-color: lightgray;
+ padding: 10px;
+ margin-right: 40%;
+}
diff --git a/tests/test_tools/simpletest/docs/fr/expectation_documentation.html b/tests/test_tools/simpletest/docs/fr/expectation_documentation.html
new file mode 100755
index 00000000..ab9ef606
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/expectation_documentation.html
@@ -0,0 +1,263 @@
+<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
new file mode 100755
index 00000000..f9f5d0df
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/form_testing_documentation.html
@@ -0,0 +1,235 @@
+<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
new file mode 100755
index 00000000..662f868e
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/group_test_documentation.html
@@ -0,0 +1,288 @@
+<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
new file mode 100755
index 00000000..f4b2ad93
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/index.html
@@ -0,0 +1,343 @@
+<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
new file mode 100755
index 00000000..0ce48bc9
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/mock_objects_documentation.html
@@ -0,0 +1,492 @@
+<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
new file mode 100755
index 00000000..b6965753
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/overview.html
@@ -0,0 +1,294 @@
+<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
new file mode 100755
index 00000000..4098ab45
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/partial_mocks_documentation.html
@@ -0,0 +1,333 @@
+<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
new file mode 100755
index 00000000..4f927781
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/reporter_documentation.html
@@ -0,0 +1,386 @@
+<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
new file mode 100755
index 00000000..59085795
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/server_stubs_documentation.html
@@ -0,0 +1,279 @@
+<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
new file mode 100755
index 00000000..3dcfeca5
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/unit_test_documentation.html
@@ -0,0 +1,306 @@
+<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
new file mode 100755
index 00000000..86044e5e
--- /dev/null
+++ b/tests/test_tools/simpletest/docs/fr/web_tester_documentation.html
@@ -0,0 +1,397 @@
+<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
new file mode 100644
index 00000000..f54140ca
--- /dev/null
+++ b/tests/test_tools/simpletest/dumper.php
@@ -0,0 +1,380 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: dumper.php,v 1.22 2005/02/05 04:51:17 lastcraft Exp $
+ */
+ /**
+ * does type matter
+ */
+ define('TYPE_MATTERS', true);
+
+ /**
+ * Displays variables as text and does diffs.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleDumper {
+
+ /**
+ * Renders a variable in a shorter form than print_r().
+ * @param mixed $value Variable to render as a string.
+ * @return string Human readable string form.
+ * @access public
+ */
+ function describeValue($value) {
+ $type = $this->getType($value);
+ switch($type) {
+ case "Null":
+ return "NULL";
+ case "Boolean":
+ return "Boolean: " . ($value ? "true" : "false");
+ case "Array":
+ return "Array: " . count($value) . " items";
+ case "Object":
+ return "Object: of " . get_class($value);
+ case "String":
+ return "String: " . $this->clipString($value, 100);
+ default:
+ return "$type: $value";
+ }
+ return "Unknown";
+ }
+
+ /**
+ * Gets the string representation of a type.
+ * @param mixed $value Variable to check against.
+ * @return string Type.
+ * @access public
+ */
+ function getType($value) {
+ if (! isset($value)) {
+ return "Null";
+ } elseif (is_bool($value)) {
+ return "Boolean";
+ } elseif (is_string($value)) {
+ return "String";
+ } elseif (is_integer($value)) {
+ return "Integer";
+ } elseif (is_float($value)) {
+ return "Float";
+ } elseif (is_array($value)) {
+ return "Array";
+ } elseif (is_resource($value)) {
+ return "Resource";
+ } elseif (is_object($value)) {
+ return "Object";
+ }
+ return "Unknown";
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two variables. Uses a
+ * dynamic call.
+ * @param mixed $first First variable.
+ * @param mixed $second Value to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Description of difference.
+ * @access public
+ */
+ function describeDifference($first, $second, $identical = false) {
+ if ($identical) {
+ if (! $this->_isTypeMatch($first, $second)) {
+ return "with type mismatch as [" . $this->describeValue($first) .
+ "] does not match [" . $this->describeValue($second) . "]";
+ }
+ }
+ $type = $this->getType($first);
+ if ($type == "Unknown") {
+ return "with unknown type";
+ }
+ $method = '_describe' . $type . 'Difference';
+ return $this->$method($first, $second, $identical);
+ }
+
+ /**
+ * Tests to see if types match.
+ * @param mixed $first First variable.
+ * @param mixed $second Value to compare with.
+ * @return boolean True if matches.
+ * @access private
+ */
+ function _isTypeMatch($first, $second) {
+ return ($this->getType($first) == $this->getType($second));
+ }
+
+ /**
+ * Clips a string to a maximum length.
+ * @param string $value String to truncate.
+ * @param integer $size Minimum string size to show.
+ * @param integer $position Centre of string section.
+ * @return string Shortened version.
+ * @access public
+ */
+ function clipString($value, $size, $position = 0) {
+ $length = strlen($value);
+ if ($length <= $size) {
+ return $value;
+ }
+ $position = min($position, $length);
+ $start = ($size/2 > $position ? 0 : $position - $size/2);
+ if ($start + $size > $length) {
+ $start = $length - $size;
+ }
+ $value = substr($value, $start, $size);
+ return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : "");
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two variables. The minimal
+ * version.
+ * @param null $first First value.
+ * @param mixed $second Value to compare with.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeGenericDifference($first, $second) {
+ return "as [" . $this->describeValue($first) .
+ "] does not match [" .
+ $this->describeValue($second) . "]";
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a null and another variable.
+ * @param null $first First null.
+ * @param mixed $second Null to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeNullDifference($first, $second, $identical) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a boolean and another variable.
+ * @param boolean $first First boolean.
+ * @param mixed $second Boolean to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeBooleanDifference($first, $second, $identical) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a string and another variable.
+ * @param string $first First string.
+ * @param mixed $second String to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeStringDifference($first, $second, $identical) {
+ if (is_object($second) || is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ $position = $this->_stringDiffersAt($first, $second);
+ $message = "at character $position";
+ $message .= " with [" .
+ $this->clipString($first, 100, $position) . "] and [" .
+ $this->clipString($second, 100, $position) . "]";
+ return $message;
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between an integer and another variable.
+ * @param integer $first First number.
+ * @param mixed $second Number to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeIntegerDifference($first, $second, $identical) {
+ if (is_object($second) || is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ return "because [" . $this->describeValue($first) .
+ "] differs from [" .
+ $this->describeValue($second) . "] by " .
+ abs($first - $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two floating point numbers.
+ * @param float $first First float.
+ * @param mixed $second Float to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeFloatDifference($first, $second, $identical) {
+ if (is_object($second) || is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ return "because " . $this->describeValue($first) .
+ "] differs from [" .
+ $this->describeValue($second) . "]";
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two arrays.
+ * @param array $first First array.
+ * @param mixed $second Array to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeArrayDifference($first, $second, $identical) {
+ if (! is_array($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ if (! $this->_isMatchingKeys($first, $second, $identical)) {
+ return "as key list [" .
+ implode(", ", array_keys($first)) . "] does not match key list [" .
+ implode(", ", array_keys($second)) . "]";
+ }
+ foreach (array_keys($first) as $key) {
+ if ($identical && ($first[$key] === $second[$key])) {
+ continue;
+ }
+ if (! $identical && ($first[$key] == $second[$key])) {
+ continue;
+ }
+ return "with member [$key] " . $this->describeDifference(
+ $first[$key],
+ $second[$key],
+ $identical);
+ }
+ return "";
+ }
+
+ /**
+ * Compares two arrays to see if their key lists match.
+ * For an identical match, the ordering and types of the keys
+ * is significant.
+ * @param array $first First array.
+ * @param array $second Array to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return boolean True if matching.
+ * @access private
+ */
+ function _isMatchingKeys($first, $second, $identical) {
+ $first_keys = array_keys($first);
+ $second_keys = array_keys($second);
+ if ($identical) {
+ return ($first_keys === $second_keys);
+ }
+ sort($first_keys);
+ sort($second_keys);
+ return ($first_keys == $second_keys);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between a resource and another variable.
+ * @param resource $first First resource.
+ * @param mixed $second Resource to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeResourceDifference($first, $second, $identical) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+
+ /**
+ * Creates a human readable description of the
+ * difference between two objects.
+ * @param object $first First object.
+ * @param mixed $second Object to compare with.
+ * @param boolean $identical If true then type anomolies count.
+ * @return string Human readable description.
+ * @access private
+ */
+ function _describeObjectDifference($first, $second, $identical) {
+ if (! is_object($second)) {
+ return $this->_describeGenericDifference($first, $second);
+ }
+ return $this->_describeArrayDifference(
+ get_object_vars($first),
+ get_object_vars($second),
+ $identical);
+ }
+
+ /**
+ * Find the first character position that differs
+ * in two strings by binary chop.
+ * @param string $first First string.
+ * @param string $second String to compare with.
+ * @return integer Position of first differing
+ * character.
+ * @access private
+ */
+ function _stringDiffersAt($first, $second) {
+ if (! $first || ! $second) {
+ return 0;
+ }
+ if (strlen($first) < strlen($second)) {
+ list($first, $second) = array($second, $first);
+ }
+ $position = 0;
+ $step = strlen($first);
+ while ($step > 1) {
+ $step = (integer)(($step + 1)/2);
+ if (strncmp($first, $second, $position + $step) == 0) {
+ $position += $step;
+ }
+ }
+ return $position;
+ }
+
+ /**
+ * Sends a formatted dump of a variable to a string.
+ * @param mixed $variable Variable to display.
+ * @return string Output from print_r().
+ * @access public
+ * @static
+ */
+ function dump($variable) {
+ ob_start();
+ print_r($variable);
+ $formatted = ob_get_contents();
+ ob_end_clean();
+ return $formatted;
+ }
+
+ /**
+ * Extracts the last assertion that was not within
+ * Simpletest itself. The name must start with "assert".
+ * @param array $stack List of stack frames.
+ * @param string $format String formatting.
+ * @param string $prefix Prefix of method to search for.
+ * @access public
+ * @static
+ */
+ function getFormattedAssertionLine($stack, $format = '%d', $prefix = 'assert') {
+ foreach ($stack as $frame) {
+ if (isset($frame['file']) && strpos($frame['file'], 'simpletest') !== false) { // dirname() is a bit slow.
+ if (substr(dirname($frame['file']), -10) == 'simpletest') {
+ continue;
+ }
+ }
+ if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) {
+ return sprintf($format, $frame['line']);
+ }
+ }
+ return '';
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/encoding.php b/tests/test_tools/simpletest/encoding.php
new file mode 100644
index 00000000..62ca2a1b
--- /dev/null
+++ b/tests/test_tools/simpletest/encoding.php
@@ -0,0 +1,156 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: encoding.php,v 1.6 2005/01/02 23:43:23 lastcraft Exp $
+ */
+
+ /**
+ * Bundle of GET/POST parameters. Can include
+ * repeated parameters.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleFormEncoding {
+ protected $_request;
+ protected $_x;
+ protected $_y;
+
+ /**
+ * Starts empty.
+ * @param array $query/SimpleQueryString Hash of parameters.
+ * Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function SimpleFormEncoding($query = false) {
+ if (! $query) {
+ $query = array();
+ }
+ $this->_request = array();
+ $this->setCoordinates();
+ $this->merge($query);
+ }
+
+ /**
+ * Adds a parameter to the query.
+ * @param string $key Key to add value to.
+ * @param string/array $value New data.
+ * @access public
+ */
+ function add($key, $value) {
+ if ($value === false) {
+ return;
+ }
+ if (! isset($this->_request[$key])) {
+ $this->_request[$key] = array();
+ }
+ if (is_array($value)) {
+ foreach ($value as $item) {
+ $this->_request[$key][] = $item;
+ }
+ } else {
+ $this->_request[$key][] = $value;
+ }
+ }
+
+ /**
+ * Adds a set of parameters to this query.
+ * @param array/SimpleQueryString $query Multiple values are
+ * as lists on a single key.
+ * @access public
+ */
+ function merge($query) {
+ if (is_object($query)) {
+ foreach ($query->getKeys() as $key) {
+ $this->add($key, $query->getValue($key));
+ }
+ if ($query->getX() !== false) {
+ $this->setCoordinates($query->getX(), $query->getY());
+ }
+ } elseif (is_array($query)) {
+ foreach ($query as $key => $value) {
+ $this->add($key, $value);
+ }
+ }
+ }
+
+ /**
+ * Sets image coordinates. Set to false to clear
+ * them.
+ * @param integer $x Horizontal position.
+ * @param integer $y Vertical position.
+ * @access public
+ */
+ function setCoordinates($x = false, $y = false) {
+ if (($x === false) || ($y === false)) {
+ $this->_x = $this->_y = false;
+ return;
+ }
+ $this->_x = (integer)$x;
+ $this->_y = (integer)$y;
+ }
+
+ /**
+ * Accessor for horizontal image coordinate.
+ * @return integer X value.
+ * @access public
+ */
+ function getX() {
+ return $this->_x;
+ }
+
+ /**
+ * Accessor for vertical image coordinate.
+ * @return integer Y value.
+ * @access public
+ */
+ function getY() {
+ return $this->_y;
+ }
+
+ /**
+ * Accessor for single value.
+ * @return string/array False if missing, string
+ * if present and array if
+ * multiple entries.
+ * @access public
+ */
+ function getValue($key) {
+ if (! isset($this->_request[$key])) {
+ return false;
+ } elseif (count($this->_request[$key]) == 1) {
+ return $this->_request[$key][0];
+ } else {
+ return $this->_request[$key];
+ }
+ }
+
+ /**
+ * Accessor for key list.
+ * @return array List of keys present.
+ * @access public
+ */
+ function getKeys() {
+ return array_keys($this->_request);
+ }
+
+ /**
+ * Renders the query string as a URL encoded
+ * request part.
+ * @return string Part of URL.
+ * @access public
+ */
+ function asString() {
+ $statements = array();
+ foreach ($this->_request as $key => $values) {
+ foreach ($values as $value) {
+ $statements[] = "$key=" . urlencode($value);
+ }
+ }
+ $coords = ($this->_x !== false) ? '?' . $this->_x . ',' . $this->_y : '';
+ return implode('&', $statements) . $coords;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/errors.php b/tests/test_tools/simpletest/errors.php
new file mode 100644
index 00000000..70c6c338
--- /dev/null
+++ b/tests/test_tools/simpletest/errors.php
@@ -0,0 +1,141 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: errors.php,v 1.13 2005/01/08 03:48:39 lastcraft Exp $
+ */
+ /** @ignore - PHP5 compatibility fix. */
+ if (! defined('E_STRICT')) {
+ define('E_STRICT', 2048);
+ }
+
+ /**
+ * Singleton error queue used to record trapped
+ * errors.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleErrorQueue {
+ protected $_queue;
+
+ /**
+ * Starts with an empty queue.
+ * @access public
+ */
+ function SimpleErrorQueue() {
+ $this->clear();
+ }
+
+ /**
+ * Adds an error to the front of the queue.
+ * @param $severity PHP error code.
+ * @param $message Text of error.
+ * @param $filename File error occoured in.
+ * @param $line Line number of error.
+ * @param $super_globals Hash of PHP super global arrays.
+ * @access public
+ */
+ function add($severity, $message, $filename, $line, $super_globals) {
+ array_push(
+ $this->_queue,
+ array($severity, $message, $filename, $line, $super_globals));
+ }
+
+ /**
+ * Pulls the earliest error from the queue.
+ * @return False if none, or a list of error
+ * information. Elements are: severity
+ * as the PHP error code, the error message,
+ * the file with the error, the line number
+ * and a list of PHP super global arrays.
+ * @access public
+ */
+ function extract() {
+ if (count($this->_queue)) {
+ return array_shift($this->_queue);
+ }
+ return false;
+ }
+
+ /**
+ * Discards the contents of the error queue.
+ * @access public
+ */
+ function clear() {
+ $this->_queue = array();
+ }
+
+ /**
+ * Tests to see if the queue is empty.
+ * @return True if empty.
+ */
+ function isEmpty() {
+ return (count($this->_queue) == 0);
+ }
+
+ /**
+ * Global access to a single error queue.
+ * @return Global error queue object.
+ * @access public
+ * @static
+ */
+ static function instance() {
+ static $queue = false;
+ if (! $queue) {
+ $queue = new SimpleErrorQueue();
+ }
+ return $queue;
+ }
+
+ /**
+ * Converst an error code into it's string
+ * representation.
+ * @param $severity PHP integer error code.
+ * @return String version of error code.
+ * @access public
+ * @static
+ */
+ static function getSeverityAsString($severity) {
+ static $map = array(
+ E_STRICT => 'E_STRICT',
+ E_ERROR => 'E_ERROR',
+ E_WARNING => 'E_WARNING',
+ E_PARSE => 'E_PARSE',
+ E_NOTICE => 'E_NOTICE',
+ E_CORE_ERROR => 'E_CORE_ERROR',
+ E_CORE_WARNING => 'E_CORE_WARNING',
+ E_COMPILE_ERROR => 'E_COMPILE_ERROR',
+ E_COMPILE_WARNING => 'E_COMPILE_WARNING',
+ E_USER_ERROR => 'E_USER_ERROR',
+ E_USER_WARNING => 'E_USER_WARNING',
+ E_USER_NOTICE => 'E_USER_NOTICE');
+ return $map[$severity];
+ }
+ }
+
+ /**
+ * Error handler that simply stashes any errors into the global
+ * error queue. Simulates the existing behaviour with respect to
+ * logging errors, but this feature may be removed in future.
+ * @param $severity PHP error code.
+ * @param $message Text of error.
+ * @param $filename File error occoured in.
+ * @param $line Line number of error.
+ * @param $super_globals Hash of PHP super global arrays.
+ * @static
+ * @access public
+ */
+ function simpleTestErrorHandler($severity, $message, $filename, $line, $super_globals) {
+ if ($severity = $severity & error_reporting()) {
+ restore_error_handler();
+ if (ini_get('log_errors')) {
+ $label = SimpleErrorQueue::getSeverityAsString($severity);
+ error_log("$label: $message in $filename on line $line");
+ }
+ $queue = SimpleErrorQueue::instance();
+ $queue->add($severity, $message, $filename, $line, $super_globals);
+ set_error_handler('simpleTestErrorHandler');
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/expectation.php b/tests/test_tools/simpletest/expectation.php
new file mode 100644
index 00000000..355963b4
--- /dev/null
+++ b/tests/test_tools/simpletest/expectation.php
@@ -0,0 +1,568 @@
+<?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 $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/dumper.php');
+ require_once(dirname(__FILE__) . '/options.php');
+ /**#@-*/
+
+ /**
+ * Assertion that can display failure information.
+ * Also includes various helper methods.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @abstract
+ */
+ class SimpleExpectation {
+ protected $_dumper;
+ protected $_message;
+
+ /**
+ * Creates a dumper for displaying values and sets
+ * the test message.
+ * @param string $message Customised message on failure.
+ */
+ function SimpleExpectation($message = '%s') {
+ $this->_dumper = new SimpleDumper();
+ $this->_message = $message;
+ }
+
+ /**
+ * Tests the expectation. True if correct.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ * @abstract
+ */
+ function test($compare) {
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ * @abstract
+ */
+ function testMessage($compare) {
+ }
+
+ /**
+ * Overlays the generated message onto the stored user
+ * message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function overlayMessage($compare) {
+ return sprintf($this->_message, $this->testMessage($compare));
+ }
+
+ /**
+ * Accessor for the dumper.
+ * @return SimpleDumper Current value dumper.
+ * @access protected
+ */
+ function _getDumper() {
+ return $this->_dumper;
+ }
+ }
+
+ /**
+ * Test for equality.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class EqualExpectation extends SimpleExpectation {
+ protected $_value;
+
+ /**
+ * Sets the value to compare against.
+ * @param mixed $value Test value to match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function EqualExpectation($value, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_value = $value;
+ }
+
+ /**
+ * Tests the expectation. True if it matches the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (($this->_value == $compare) && ($compare == $this->_value));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return "Equal expectation [" . $this->_dumper->describeValue($this->_value) . "]";
+ } else {
+ return "Equal expectation fails " .
+ $this->_dumper->describeDifference($this->_value, $compare);
+ }
+ }
+
+ /**
+ * Accessor for comparison value.
+ * @return mixed Held value to compare with.
+ * @access protected
+ */
+ function _getValue() {
+ return $this->_value;
+ }
+ }
+
+ /**
+ * Test for inequality.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NotEqualExpectation extends EqualExpectation {
+
+ /**
+ * Sets the value to compare against.
+ * @param mixed $value Test value to match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function NotEqualExpectation($value, $message = '%s') {
+ $this->EqualExpectation($value, $message);
+ }
+
+ /**
+ * Tests the expectation. True if it differs from the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ if ($this->test($compare)) {
+ return "Not equal expectation passes " .
+ $dumper->describeDifference($this->_getValue(), $compare);
+ } else {
+ return "Not equal expectation fails [" .
+ $dumper->describeValue($this->_getValue()) .
+ "] matches";
+ }
+ }
+ }
+
+ /**
+ * Test for identity.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class IdenticalExpectation extends EqualExpectation {
+
+ /**
+ * Sets the value to compare against.
+ * @param mixed $value Test value to match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function IdenticalExpectation($value, $message = '%s') {
+ $this->EqualExpectation($value, $message);
+ }
+
+ /**
+ * Tests the expectation. True if it exactly
+ * matches the held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return SimpleTestCompatibility::isIdentical($this->_getValue(), $compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ if ($this->test($compare)) {
+ return "Identical expectation [" . $dumper->describeValue($this->_getValue()) . "]";
+ } else {
+ return "Identical expectation [" . $dumper->describeValue($this->_getValue()) .
+ "] fails with [" .
+ $dumper->describeValue($compare) . "] " .
+ $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS);
+ }
+ }
+ }
+
+ /**
+ * Test for non-identity.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NotIdenticalExpectation extends IdenticalExpectation {
+
+ /**
+ * Sets the value to compare against.
+ * @param mixed $value Test value to match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function NotIdenticalExpectation($value, $message = '%s') {
+ $this->IdenticalExpectation($value, $message);
+ }
+
+ /**
+ * Tests the expectation. True if it differs from the
+ * held value.
+ * @param mixed $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ if ($this->test($compare)) {
+ return "Not identical expectation passes " .
+ $dumper->describeDifference($this->_getValue(), $compare, TYPE_MATTERS);
+ } else {
+ return "Not identical expectation [" . $dumper->describeValue($this->_getValue()) . "] matches";
+ }
+ }
+ }
+
+ /**
+ * Test for a pattern using Perl regex rules.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class WantedPatternExpectation extends SimpleExpectation {
+ protected $_pattern;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $pattern Pattern to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function WantedPatternExpectation($pattern, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_pattern = $pattern;
+ }
+
+ /**
+ * Accessor for the pattern.
+ * @return string Perl regex as string.
+ * @access protected
+ */
+ function _getPattern() {
+ return $this->_pattern;
+ }
+
+ /**
+ * Tests the expectation. True if the Perl regex
+ * matches the comparison value.
+ * @param string $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (boolean)preg_match($this->_getPattern(), $compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return $this->_describePatternMatch($this->_getPattern(), $compare);
+ } else {
+ $dumper = $this->_getDumper();
+ return "Pattern [" . $this->_getPattern() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ }
+ }
+
+ /**
+ * Describes a pattern match including the string
+ * found and it's position.
+ * @param string $pattern Regex to match against.
+ * @param string $subject Subject to search.
+ * @access protected
+ */
+ function _describePatternMatch($pattern, $subject) {
+ preg_match($pattern, $subject, $matches);
+ $position = strpos($subject, $matches[0]);
+ $dumper = $this->_getDumper();
+ return "Pattern [$pattern] detected at character [$position] in [" .
+ $dumper->describeValue($subject) . "] as [" .
+ $matches[0] . "] in region [" .
+ $dumper->clipString($subject, 100, $position) . "]";
+ }
+ }
+
+ /**
+ * Fail if a pattern is detected within the
+ * comparison.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class UnwantedPatternExpectation extends WantedPatternExpectation {
+
+ /**
+ * Sets the reject pattern
+ * @param string $pattern Pattern to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function UnwantedPatternExpectation($pattern, $message = '%s') {
+ $this->WantedPatternExpectation($pattern, $message);
+ }
+
+ /**
+ * Tests the expectation. False if the Perl regex
+ * matches the comparison value.
+ * @param string $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param string $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ $dumper = $this->_getDumper();
+ return "Pattern [" . $this->_getPattern() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ } else {
+ return $this->_describePatternMatch($this->_getPattern(), $compare);
+ }
+ }
+ }
+
+ /**
+ * Tests either type or class name if it's an object.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class IsAExpectation extends SimpleExpectation {
+ protected $_type;
+
+ /**
+ * Sets the type to compare with.
+ * @param string $type Type or class name.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function IsAExpectation($type, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_type = $type;
+ }
+
+ /**
+ * Accessor for type to check against.
+ * @return string Type or class name.
+ * @access protected
+ */
+ function _getType() {
+ return $this->_type;
+ }
+
+ /**
+ * Tests the expectation. True if the type or
+ * class matches the string value.
+ * @param string $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ if (is_object($compare)) {
+ return SimpleTestCompatibility::isA($compare, $this->_type);
+ } else {
+ return (strtolower(gettype($compare)) == $this->_canonicalType($this->_type));
+ }
+ }
+
+ /**
+ * Coerces type name into a gettype() match.
+ * @param string $type User type.
+ * @return string Simpler type.
+ * @access private
+ */
+ function _canonicalType($type) {
+ $type = strtolower($type);
+ $map = array(
+ 'bool' => 'boolean',
+ 'float' => 'double',
+ 'real' => 'double',
+ 'int' => 'integer');
+ if (isset($map[$type])) {
+ $type = $map[$type];
+ }
+ return $type;
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ return "Value [" . $dumper->describeValue($compare) .
+ "] should be type [" . $this->_type . "]";
+ }
+ }
+
+ /**
+ * Tests either type or class name if it's an object.
+ * Will succeed if the type does not match.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NotAExpectation extends IsAExpectation {
+ protected $_type;
+
+ /**
+ * Sets the type to compare with.
+ * @param string $type Type or class name.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function NotAExpectation($type, $message = '%s') {
+ $this->IsAExpectation($type, $message);
+ }
+
+ /**
+ * Tests the expectation. False if the type or
+ * class matches the string value.
+ * @param string $compare Comparison value.
+ * @return boolean True if different.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ return "Value [" . $dumper->describeValue($compare) .
+ "] should not be type [" . $this->_getType() . "]";
+ }
+ }
+
+ /**
+ * Tests for existance of a method in an object
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class MethodExistsExpectation extends SimpleExpectation {
+ protected $_method;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $method Method to check.
+ * @param string $message Customised message on failure.
+ * @access public
+ * @return void
+ */
+ function MethodExistsExpectation($method, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_method = $method;
+ }
+
+ /**
+ * Tests the expectation. True if the method exists in the test object.
+ * @param string $compare Comparison method name.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (boolean)(is_object($compare) && method_exists($compare, $this->_method));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ if (! is_object($compare)) {
+ return 'No method on non-object [' . $dumper->describeValue($compare) . ']';
+ }
+ $method = $this->_method;
+ return "Object [" . $dumper->describeValue($compare) .
+ "] should contain method [$method]";
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/extensions/pear_test_case.php b/tests/test_tools/simpletest/extensions/pear_test_case.php
new file mode 100755
index 00000000..51727345
--- /dev/null
+++ b/tests/test_tools/simpletest/extensions/pear_test_case.php
@@ -0,0 +1,199 @@
+<?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
new file mode 100755
index 00000000..a0954d8b
--- /dev/null
+++ b/tests/test_tools/simpletest/extensions/phpunit_test_case.php
@@ -0,0 +1,108 @@
+<?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
new file mode 100644
index 00000000..89b4948a
--- /dev/null
+++ b/tests/test_tools/simpletest/form.php
@@ -0,0 +1,619 @@
+<?php
+ /**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: form.php,v 1.16 2005/02/22 02:17:04 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 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
+ */
+ class SimpleForm {
+ protected $_method;
+ protected $_action;
+ protected $_default_target;
+ protected $_id;
+ protected $_buttons;
+ protected $_images;
+ protected $_widgets;
+ protected $_radios;
+ protected $_checkboxes;
+
+ /**
+ * Starts with no held controls/widgets.
+ * @param SimpleTag $tag Form tag to read.
+ * @param SimpleUrl $url Location of holding page.
+ */
+ function SimpleForm($tag, $url) {
+ $this->_method = $tag->getAttribute('method');
+ $this->_action = $this->_createAction($tag->getAttribute('action'), $url);
+ $this->_default_target = false;
+ $this->_id = $tag->getAttribute('id');
+ $this->_buttons = array();
+ $this->_images = array();
+ $this->_widgets = array();
+ $this->_radios = array();
+ $this->_checkboxes = array();
+ }
+
+ /**
+ * Sets the frame target within a frameset.
+ * @param string $frame Name of frame.
+ * @access public
+ */
+ function setDefaultTarget($frame) {
+ $this->_default_target = $frame;
+ }
+
+ /**
+ * Accessor for form action.
+ * @return string Either get or post.
+ * @access public
+ */
+ function getMethod() {
+ return ($this->_method ? strtolower($this->_method) : 'get');
+ }
+
+ /**
+ * Combined action attribute with current location
+ * to get an absolute form target.
+ * @param string $action Action attribute from form tag.
+ * @param SimpleUrl $base Page location.
+ * @return SimpleUrl Absolute form target.
+ */
+ function _createAction($action, $base) {
+ if ($action === false) {
+ return $base;
+ }
+ if ($action === true) {
+ $url = new SimpleUrl('');
+ } else {
+ $url = new SimpleUrl($action);
+ }
+ return $url->makeAbsolute($base);
+ }
+
+ /**
+ * Absolute URL of the target.
+ * @return SimpleUrl URL target.
+ * @access public
+ */
+ function getAction() {
+ $url = $this->_action;
+ if ($this->_default_target && ! $url->getTarget()) {
+ $url->setTarget($this->_default_target);
+ }
+ return $url;
+ }
+
+ /**
+ * ID field of form for unique identification.
+ * @return string Unique tag ID.
+ * @access public
+ */
+ function getId() {
+ return $this->_id;
+ }
+
+ /**
+ * Adds a tag contents to the form.
+ * @param SimpleWidget $tag Input tag to add.
+ * @access public
+ */
+ function addWidget($tag) {
+ if (strtolower($tag->getAttribute('type')) == 'submit') {
+ $this->_buttons[] = $tag;
+ } elseif (strtolower($tag->getAttribute('type')) == 'image') {
+ $this->_images[] = $tag;
+ } elseif ($tag->getName()) {
+ $this->_setWidget($tag);
+ }
+ }
+
+ /**
+ * Sets the widget into the form, grouping radio
+ * buttons if any.
+ * @param SimpleWidget $tag Incoming form control.
+ * @access private
+ */
+ function _setWidget($tag) {
+ if (strtolower($tag->getAttribute('type')) == 'radio') {
+ $this->_addRadioButton($tag);
+ } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') {
+ $this->_addCheckbox($tag);
+ } else {
+ $this->_widgets[] = $tag;
+ }
+ }
+
+ /**
+ * Adds a radio button, building a group if necessary.
+ * @param SimpleRadioButtonTag $tag Incoming form control.
+ * @access private
+ */
+ function _addRadioButton($tag) {
+ if (! isset($this->_radios[$tag->getName()])) {
+ $this->_widgets[] = new SimpleRadioGroup();
+ $this->_radios[$tag->getName()] = count($this->_widgets) - 1;
+ }
+ $this->_widgets[$this->_radios[$tag->getName()]]->addWidget($tag);
+ }
+
+ /**
+ * Adds a checkbox, making it a group on a repeated name.
+ * @param SimpleCheckboxTag $tag Incoming form control.
+ * @access private
+ */
+ function _addCheckbox($tag) {
+ if (! isset($this->_checkboxes[$tag->getName()])) {
+ $this->_widgets[] = $tag;
+ $this->_checkboxes[$tag->getName()] = count($this->_widgets) - 1;
+ } else {
+ $index = $this->_checkboxes[$tag->getName()];
+ if (! SimpleTestCompatibility::isA($this->_widgets[$index], 'SimpleCheckboxGroup')) {
+ $previous = $this->_widgets[$index];
+ $this->_widgets[$index] = new SimpleCheckboxGroup();
+ $this->_widgets[$index]->addWidget($previous);
+ }
+ $this->_widgets[$index]->addWidget($tag);
+ }
+ }
+
+ /**
+ * Extracts current value from form.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @return string/array Value(s) as string or null
+ * if not set.
+ * @access public
+ */
+ function _getValueBySelector($selector) {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($selector->isMatch($this->_widgets[$i])) {
+ return $this->_widgets[$i]->getValue();
+ }
+ }
+ foreach ($this->_buttons as $button) {
+ if ($selector->isMatch($button)) {
+ return $button->getValue();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Extracts current value from form.
+ * @param string $name Keyed by widget name.
+ * @return string/array Value(s) or null
+ * if not set.
+ * @access public
+ */
+ function getValue($name) {
+ return $this->_getValueBySelector(new SimpleNameSelector($name));
+ }
+
+ /**
+ * Extracts current value from form by the ID.
+ * @param string/integer $id Keyed by widget ID attribute.
+ * @return string/array Value(s) or null
+ * if not set.
+ * @access public
+ */
+ function getValueById($id) {
+ return $this->_getValueBySelector(new SimpleIdSelector($id));
+ }
+
+ /**
+ * Sets a widget value within the form.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @param string $value Value to input into the widget.
+ * @return boolean True if value is legal, false
+ * otherwise. If the field is not
+ * present, nothing will be set.
+ * @access public
+ */
+ function _setFieldBySelector($selector, $value) {
+ $success = false;
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($selector->isMatch($this->_widgets[$i])) {
+ if ($this->_widgets[$i]->setValue($value)) {
+ $success = true;
+ }
+ }
+ }
+ return $success;
+ }
+
+ /**
+ * Sets a widget value within the form.
+ * @param string $name Name of widget tag.
+ * @param string $value Value to input into the widget.
+ * @return boolean True if value is legal, false
+ * otherwise. If the field is not
+ * present, nothing will be set.
+ * @access public
+ */
+ function setField($name, $value) {
+ return $this->_setFieldBySelector(new SimpleNameSelector($name), $value);
+ }
+
+ /**
+ * Sets a widget value within the form by using the ID.
+ * @param string/integer $id Name of widget tag.
+ * @param string $value Value to input into the widget.
+ * @return boolean True if value is legal, false
+ * otherwise. If the field is not
+ * present, nothing will be set.
+ * @access public
+ */
+ function setFieldById($id, $value) {
+ return $this->_setFieldBySelector(new SimpleIdSelector($id), $value);
+ }
+
+ /**
+ * Creates the encoding for the current values in the
+ * form.
+ * @return SimpleFormEncoding Request to submit.
+ * @access private
+ */
+ function _getEncoding() {
+ $encoding = new SimpleFormEncoding();
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ $encoding->add(
+ $this->_widgets[$i]->getName(),
+ $this->_widgets[$i]->getValue());
+ }
+ return $encoding;
+ }
+
+ /**
+ * Test to see if a form has a submit button.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @return boolean True if present.
+ * @access private
+ */
+ function _hasSubmitBySelector($selector) {
+ foreach ($this->_buttons as $button) {
+ if ($selector->isMatch($button)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Test to see if a form has a submit button with this
+ * name attribute.
+ * @param string $name Name to look for.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasSubmitName($name) {
+ return $this->_hasSubmitBySelector(new SimpleNameSelector($name));
+ }
+
+ /**
+ * Test to see if a form has a submit button with this
+ * value attribute.
+ * @param string $label Button label to search for.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasSubmitLabel($label) {
+ return $this->_hasSubmitBySelector(new SimpleLabelSelector($label));
+ }
+
+ /**
+ * Test to see if a form has a submit button with this
+ * ID attribute.
+ * @param string $id Button ID attribute to search for.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasSubmitId($id) {
+ return $this->_hasSubmitBySelector(new SimpleIdSelector($id));
+ }
+
+ /**
+ * Test to see if a form has an image control.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @return boolean True if present.
+ * @access public
+ */
+ function _hasImageBySelector($selector) {
+ foreach ($this->_images as $image) {
+ if ($selector->isMatch($image)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Test to see if a form has a submit button with this
+ * name attribute.
+ * @param string $label Button alt attribute to search for
+ * or nearest equivalent.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasImageLabel($label) {
+ return $this->_hasImageBySelector(new SimpleLabelSelector($label));
+ }
+
+ /**
+ * Test to see if a form has a submittable image with this
+ * field name.
+ * @param string $name Image name to search for.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasImageName($name) {
+ return $this->_hasImageBySelector(new SimpleNameSelector($name));
+ }
+
+ /**
+ * Test to see if a form has a submittable image with this
+ * ID attribute.
+ * @param string $id Button ID attribute to search for.
+ * @return boolean True if present.
+ * @access public
+ */
+ function hasImageId($id) {
+ return $this->_hasImageBySelector(new SimpleIdSelector($id));
+ }
+
+ /**
+ * Gets the submit values for a selected button.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button
+ * in the form.
+ * @access public
+ */
+ function _submitButtonBySelector($selector, $additional) {
+ foreach ($this->_buttons as $button) {
+ if ($selector->isMatch($button)) {
+ $encoding = $this->_getEncoding();
+ $encoding->merge($button->getSubmitValues());
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the submit values for a named button.
+ * @param string $name Button label to search for.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitButtonByName($name, $additional = false) {
+ return $this->_submitButtonBySelector(
+ new SimpleNameSelector($name),
+ $additional);
+ }
+
+ /**
+ * Gets the submit values for a named button.
+ * @param string $label Button label to search for.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitButtonByLabel($label, $additional = false) {
+ return $this->_submitButtonBySelector(
+ new SimpleLabelSelector($label),
+ $additional);
+ }
+
+ /**
+ * Gets the submit values for a button identified by the ID.
+ * @param string $id Button ID attribute to search for.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitButtonById($id, $additional = false) {
+ return $this->_submitButtonBySelector(
+ new SimpleIdSelector($id),
+ $additional);
+ }
+
+ /**
+ * Gets the submit values for an image.
+ * @param SimpleSelector $selector Criteria to apply.
+ * @param integer $x X-coordinate of click.
+ * @param integer $y Y-coordinate of click.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function _submitImageBySelector($selector, $x, $y, $additional) {
+ foreach ($this->_images as $image) {
+ if ($selector->isMatch($image)) {
+ $encoding = $this->_getEncoding();
+ $encoding->merge($image->getSubmitValues($x, $y));
+ if ($additional) {
+ $encoding->merge($additional);
+ }
+ return $encoding;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the submit values for an image identified by the alt
+ * tag or nearest equivalent.
+ * @param string $label Button label to search for.
+ * @param integer $x X-coordinate of click.
+ * @param integer $y Y-coordinate of click.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitImageByLabel($label, $x, $y, $additional = false) {
+ return $this->_submitImageBySelector(
+ new SimpleLabelSelector($label),
+ $x,
+ $y,
+ $additional);
+ }
+
+ /**
+ * Gets the submit values for an image identified by the ID.
+ * @param string $name Image name to search for.
+ * @param integer $x X-coordinate of click.
+ * @param integer $y Y-coordinate of click.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitImageByName($name, $x, $y, $additional = false) {
+ return $this->_submitImageBySelector(
+ new SimpleNameSelector($name),
+ $x,
+ $y,
+ $additional);
+ }
+
+ /**
+ * Gets the submit values for an image identified by the ID.
+ * @param string/integer $id Button ID attribute to search for.
+ * @param integer $x X-coordinate of click.
+ * @param integer $y Y-coordinate of click.
+ * @param hash $additional Additional data for the form.
+ * @return SimpleEncoding Submitted values or false
+ * if there is no such button in the
+ * form.
+ * @access public
+ */
+ function submitImageById($id, $x, $y, $additional = false) {
+ return $this->_submitImageBySelector(
+ new SimpleIdSelector($id),
+ $x,
+ $y,
+ $additional);
+ }
+
+ /**
+ * Simply submits the form without the submit button
+ * value. Used when there is only one button or it
+ * is unimportant.
+ * @return hash Submitted values.
+ * @access public
+ */
+ function submit() {
+ return $this->_getEncoding();
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/frames.php b/tests/test_tools/simpletest/frames.php
new file mode 100644
index 00000000..75951476
--- /dev/null
+++ b/tests/test_tools/simpletest/frames.php
@@ -0,0 +1,673 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: frames.php,v 1.29 2004/11/30 05:33:56 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/page.php');
+ require_once(dirname(__FILE__) . '/user_agent.php');
+ /**#@-*/
+
+ /**
+ * A composite page. Wraps a frameset page and
+ * adds subframes. The original page will be
+ * mostly ignored. Implements the SimplePage
+ * interface so as to be interchangeable.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleFrameset {
+ protected $_frameset;
+ protected $_frames;
+ protected $_focus;
+ protected $_names;
+
+ /**
+ * Stashes the frameset page. Will make use of the
+ * browser to fetch the sub frames recursively.
+ * @param SimplePage $page Frameset page.
+ */
+ function SimpleFrameset($page) {
+ $this->_frameset = $page;
+ $this->_frames = array();
+ $this->_focus = false;
+ $this->_names = array();
+ }
+
+ /**
+ * Adds a parsed page to the frameset.
+ * @param SimplePage $page Frame page.
+ * @param string $name Name of frame in frameset.
+ * @access public
+ */
+ function addFrame($page, $name = false) {
+ $this->_frames[] = $page;
+ if ($name) {
+ $this->_names[$name] = count($this->_frames) - 1;
+ }
+ }
+
+ /**
+ * Replaces existing frame with another. If the
+ * frame is nested, then the call is passed down
+ * one level.
+ * @param array $path Path of frame in frameset.
+ * @param SimplePage $page Frame source.
+ * @access public
+ */
+ function setFrame($path, $page) {
+ $name = array_shift($path);
+ if (isset($this->_names[$name])) {
+ $index = $this->_names[$name];
+ } else {
+ $index = $name - 1;
+ }
+ if (count($path) == 0) {
+ $this->_frames[$index] = $page;
+ return;
+ }
+ $this->_frames[$index]->setFrame($path, $page);
+ }
+
+ /**
+ * Accessor for current frame focus. Will be
+ * false if no frame has focus. Will have the nested
+ * frame focus if any.
+ * @return array Labels or indexes of nested frames.
+ * @access public
+ */
+ function getFrameFocus() {
+ if ($this->_focus === false) {
+ return array();
+ }
+ return array_merge(
+ array($this->_getPublicNameFromIndex($this->_focus)),
+ $this->_frames[$this->_focus]->getFrameFocus());
+ }
+
+ /**
+ * Turns an internal array index into the frames list
+ * into a public name, or if none, then a one offset
+ * index.
+ * @param integer $subject Internal index.
+ * @return integer/string Public name.
+ * @access private
+ */
+ function _getPublicNameFromIndex($subject) {
+ foreach ($this->_names as $name => $index) {
+ if ($subject == $index) {
+ return $name;
+ }
+ }
+ return $subject + 1;
+ }
+
+ /**
+ * Sets the focus by index. The integer index starts from 1.
+ * If already focused and the target frame also has frames,
+ * then the nested frame will be focused.
+ * @param integer $choice Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocusByIndex($choice) {
+ if (is_integer($this->_focus)) {
+ if ($this->_frames[$this->_focus]->hasFrames()) {
+ return $this->_frames[$this->_focus]->setFrameFocusByIndex($choice);
+ }
+ }
+ if (($choice < 1) || ($choice > count($this->_frames))) {
+ return false;
+ }
+ $this->_focus = $choice - 1;
+ return true;
+ }
+
+ /**
+ * Sets the focus by name. If already focused and the
+ * target frame also has frames, then the nested frame
+ * will be focused.
+ * @param string $name Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocus($name) {
+ if (is_integer($this->_focus)) {
+ if ($this->_frames[$this->_focus]->hasFrames()) {
+ return $this->_frames[$this->_focus]->setFrameFocus($name);
+ }
+ }
+ if (in_array($name, array_keys($this->_names))) {
+ $this->_focus = $this->_names[$name];
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Clears the frame focus.
+ * @access public
+ */
+ function clearFrameFocus() {
+ $this->_focus = false;
+ $this->_clearNestedFramesFocus();
+ }
+
+ /**
+ * Clears the frame focus for any nested frames.
+ * @access private
+ */
+ function _clearNestedFramesFocus() {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $this->_frames[$i]->clearFrameFocus();
+ }
+ }
+
+ /**
+ * Test for the presence of a frameset.
+ * @return boolean Always true.
+ * @access public
+ */
+ function hasFrames() {
+ return true;
+ }
+
+ /**
+ * Accessor for frames information.
+ * @return array/string Recursive hash of frame URL strings.
+ * The key is either a numerical
+ * index or the name attribute.
+ * @access public
+ */
+ function getFrames() {
+ $report = array();
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $report[$this->_getPublicNameFromIndex($i)] =
+ $this->_frames[$i]->getFrames();
+ }
+ return $report;
+ }
+
+ /**
+ * Accessor for raw text of either all the pages or
+ * the frame in focus.
+ * @return string Raw unparsed content.
+ * @access public
+ */
+ function getRaw() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRaw();
+ }
+ $raw = '';
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $raw .= $this->_frames[$i]->getRaw();
+ }
+ return $raw;
+ }
+
+ /**
+ * Accessor for plain text of either all the pages or
+ * the frame in focus.
+ * @return string Plain text content.
+ * @access public
+ */
+ function getText() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getText();
+ }
+ $raw = '';
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $raw .= ' ' . $this->_frames[$i]->getText();
+ }
+ return trim($raw);
+ }
+
+ /**
+ * Accessor for last error.
+ * @return string Error from last response.
+ * @access public
+ */
+ function getTransportError() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getTransportError();
+ }
+ return $this->_frameset->getTransportError();
+ }
+
+ /**
+ * Request method used to fetch this frame.
+ * @return string GET, POST or HEAD.
+ * @access public
+ */
+ function getMethod() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getMethod();
+ }
+ return $this->_frameset->getMethod();
+ }
+
+ /**
+ * Original resource name.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getUrl() {
+ if (is_integer($this->_focus)) {
+ $url = $this->_frames[$this->_focus]->getUrl();
+ $url->setTarget($this->_getPublicNameFromIndex($this->_focus));
+ } else {
+ $url = $this->_frameset->getUrl();
+ }
+ return $url;
+ }
+
+ /**
+ * Original request data.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequestData() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRequestData();
+ }
+ return $this->_frameset->getRequestData();
+ }
+
+ /**
+ * Accessor for current MIME type.
+ * @return string MIME type as string; e.g. 'text/html'
+ * @access public
+ */
+ function getMimeType() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getMimeType();
+ }
+ return $this->_frameset->getMimeType();
+ }
+
+ /**
+ * Accessor for last response code.
+ * @return integer Last HTTP response code received.
+ * @access public
+ */
+ function getResponseCode() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getResponseCode();
+ }
+ return $this->_frameset->getResponseCode();
+ }
+
+ /**
+ * Accessor for last Authentication type. Only valid
+ * straight after a challenge (401).
+ * @return string Description of challenge type.
+ * @access public
+ */
+ function getAuthentication() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getAuthentication();
+ }
+ return $this->_frameset->getAuthentication();
+ }
+
+ /**
+ * Accessor for last Authentication realm. Only valid
+ * straight after a challenge (401).
+ * @return string Name of security realm.
+ * @access public
+ */
+ function getRealm() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRealm();
+ }
+ return $this->_frameset->getRealm();
+ }
+
+ /**
+ * Accessor for outgoing header information.
+ * @return string Header block.
+ * @access public
+ */
+ function getRequest() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRequest();
+ }
+ return $this->_frameset->getRequest();
+ }
+
+ /**
+ * Accessor for raw header information.
+ * @return string Header block.
+ * @access public
+ */
+ function getHeaders() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getHeaders();
+ }
+ return $this->_frameset->getHeaders();
+ }
+
+ /**
+ * Accessor for parsed title.
+ * @return string Title or false if no title is present.
+ * @access public
+ */
+ function getTitle() {
+ return $this->_frameset->getTitle();
+ }
+
+ /**
+ * Accessor for a list of all fixed links.
+ * @return array List of urls with scheme of
+ * http or https and hostname.
+ * @access public
+ */
+ function getAbsoluteUrls() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getAbsoluteUrls();
+ }
+ $urls = array();
+ foreach ($this->_frames as $frame) {
+ $urls = array_merge($urls, $frame->getAbsoluteUrls());
+ }
+ return array_values(array_unique($urls));
+ }
+
+ /**
+ * Accessor for a list of all relative links.
+ * @return array List of urls without hostname.
+ * @access public
+ */
+ function getRelativeUrls() {
+ if (is_integer($this->_focus)) {
+ return $this->_frames[$this->_focus]->getRelativeUrls();
+ }
+ $urls = array();
+ foreach ($this->_frames as $frame) {
+ $urls = array_merge($urls, $frame->getRelativeUrls());
+ }
+ return array_values(array_unique($urls));
+ }
+
+ /**
+ * Accessor for URLs by the link label. Label will match
+ * regardess of whitespace issues and case.
+ * @param string $label Text of link.
+ * @return array List of links with that label.
+ * @access public
+ */
+ function getUrlsByLabel($label) {
+ if (is_integer($this->_focus)) {
+ return $this->_tagUrlsWithFrame(
+ $this->_frames[$this->_focus]->getUrlsByLabel($label),
+ $this->_focus);
+ }
+ $urls = array();
+ foreach ($this->_frames as $index => $frame) {
+ $urls = array_merge(
+ $urls,
+ $this->_tagUrlsWithFrame(
+ $frame->getUrlsByLabel($label),
+ $index));
+ }
+ return $urls;
+ }
+
+ /**
+ * Accessor for a URL by the id attribute. If in a frameset
+ * then the first link found with that ID attribute is
+ * returned only. Focus on a frame if you want one from
+ * a specific part of the frameset.
+ * @param string $id Id attribute of link.
+ * @return string URL with that id.
+ * @access public
+ */
+ function getUrlById($id) {
+ foreach ($this->_frames as $index => $frame) {
+ if ($url = $frame->getUrlById($id)) {
+ if (! $url->gettarget()) {
+ $url->setTarget($this->_getPublicNameFromIndex($index));
+ }
+ return $url;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Attaches the intended frame index to a list of URLs.
+ * @param array $urls List of SimpleUrls.
+ * @param string $frame Name of frame or index.
+ * @return array List of tagged URLs.
+ * @access private
+ */
+ function _tagUrlsWithFrame($urls, $frame) {
+ $tagged = array();
+ foreach ($urls as $url) {
+ if (! $url->getTarget()) {
+ $url->setTarget($this->_getPublicNameFromIndex($frame));
+ }
+ $tagged[] = $url;
+ }
+ return $tagged;
+ }
+
+ /**
+ * Finds a held form by button label. Will only
+ * search correctly built forms. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $label Button label, default 'Submit'.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitLabel($label) {
+ return $this->_findForm('getFormBySubmitLabel', $label);
+ }
+
+ /**
+ * Finds a held form by button label. Will only
+ * search correctly built forms. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $name Button name attribute.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitName($name) {
+ return $this->_findForm('getFormBySubmitName', $name);
+ }
+
+ /**
+ * Finds a held form by button id. Will only
+ * search correctly built forms. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $id Button ID attribute.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitId($id) {
+ return $this->_findForm('getFormBySubmitId', $id);
+ }
+
+ /**
+ * Finds a held form by image label. Will only
+ * search correctly built forms. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $label Usually the alt attribute.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageLabel($label) {
+ return $this->_findForm('getFormByImageLabel', $label);
+ }
+
+ /**
+ * Finds a held form by image button id. Will only
+ * search correctly built forms. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $name Image name.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageName($name) {
+ return $this->_findForm('getFormByImageName', $name);
+ }
+
+ /**
+ * Finds a held form by image button id. Will only
+ * search correctly built forms. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $id Image ID attribute.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageId($id) {
+ return $this->_findForm('getFormByImageId', $id);
+ }
+
+ /**
+ * Finds a held form by the form ID. A way of
+ * identifying a specific form when we have control
+ * of the HTML code. The first form found
+ * either within the focused frame, or across frames,
+ * will be the one returned.
+ * @param string $id Form label.
+ * @return SimpleForm Form object containing the matching ID.
+ * @access public
+ */
+ function getFormById($id) {
+ return $this->_findForm('getFormById', $id);
+ }
+
+ /**
+ * General form finder. Will search all the frames or
+ * just the one in focus.
+ * @param string $method Method to use to find in a page.
+ * @param string $attribute Label, name or ID.
+ * @return SimpleForm Form object containing the matching ID.
+ * @access protected
+ */
+ function _findForm($method, $attribute) {
+ if (is_integer($this->_focus)) {
+ return $this->_findFormInFrame(
+ $this->_frames[$this->_focus],
+ $this->_focus,
+ $method,
+ $attribute);
+ }
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $form = $this->_findFormInFrame(
+ $this->_frames[$i],
+ $i,
+ $method,
+ $attribute);
+ if ($form) {
+ return $form;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a form in a page using a form finding method. Will
+ * also tag the form with the frame name it belongs in.
+ * @param SimplePage $page Page content of frame.
+ * @param integer $index Internal frame representation.
+ * @param string $method Method to use to find in a page.
+ * @param string $attribute Label, name or ID.
+ * @return SimpleForm Form object containing the matching ID.
+ * @access protected
+ */
+ function _findFormInFrame($page, $index, $method, $attribute) {
+ $form = $this->_frames[$index]->$method($attribute);
+ if (isset($form)) {
+ $form->setDefaultTarget($this->_getPublicNameFromIndex($index));
+ }
+ return $form;
+ }
+
+ /**
+ * Sets a field on each form in which the field is
+ * available.
+ * @param string $name Field name.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
+ * @access public
+ */
+ function setField($name, $value) {
+ if (is_integer($this->_focus)) {
+ $this->_frames[$this->_focus]->setField($name, $value);
+ } else {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $this->_frames[$i]->setField($name, $value);
+ }
+ }
+ }
+
+ /**
+ * Sets a field on the form in which the unique field is
+ * available.
+ * @param string/integer $id Field ID attribute.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
+ * @access public
+ */
+ function setFieldById($id, $value) {
+ if (is_integer($this->_focus)) {
+ $this->_frames[$this->_focus]->setFieldById($id, $value);
+ } else {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $this->_frames[$i]->setFieldById($id, $value);
+ }
+ }
+ }
+
+ /**
+ * Accessor for a form element value within a frameset.
+ * Finds the first match amongst the frames.
+ * @param string $name Field name.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($name) {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $value = $this->_frames[$i]->getField($name);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Accessor for a form element value within a page.
+ * Finds the first match.
+ * @param string/integer $id Field ID attribute.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getFieldById($id) {
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $value = $this->_frames[$i]->getFieldById($id);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/http.php b/tests/test_tools/simpletest/http.php
new file mode 100644
index 00000000..fa27de9c
--- /dev/null
+++ b/tests/test_tools/simpletest/http.php
@@ -0,0 +1,853 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: http.php,v 1.98 2005/02/02 23:25:23 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/socket.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
+ * @subpackage WebTester
+ */
+ class SimpleRoute {
+ protected $_url;
+
+ /**
+ * Sets the target URL.
+ * @param SimpleUrl $url URL as object.
+ * @access public
+ */
+ function SimpleRoute($url) {
+ $this->_url = $url;
+ }
+
+ /**
+ * Resource name.
+ * @return SimpleUrl Current url.
+ * @access protected
+ */
+ function getUrl() {
+ return $this->_url;
+ }
+
+ /**
+ * Creates the first line which is the actual request.
+ * @param string $method HTTP request method, usually GET.
+ * @return string Request line content.
+ * @access protected
+ */
+ function _getRequestLine($method) {
+ return $method . ' ' . $this->_url->getPath() .
+ $this->_url->getEncodedRequest() . ' HTTP/1.0';
+ }
+
+ /**
+ * Creates the host part of the request.
+ * @return string Host line content.
+ * @access protected
+ */
+ function _getHostLine() {
+ $line = 'Host: ' . $this->_url->getHost();
+ if ($this->_url->getPort()) {
+ $line .= ':' . $this->_url->getPort();
+ }
+ return $line;
+ }
+
+ /**
+ * Opens a socket to the route.
+ * @param string $method HTTP request method, usually GET.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleSocket New socket.
+ * @access public
+ */
+ function createConnection($method, $timeout) {
+ $default_port = ('https' == $this->_url->getScheme()) ? 443 : 80;
+ $socket = $this->_createSocket(
+ $this->_url->getScheme() ? $this->_url->getScheme() : 'http',
+ $this->_url->getHost(),
+ $this->_url->getPort() ? $this->_url->getPort() : $default_port,
+ $timeout);
+ if (! $socket->isError()) {
+ $socket->write($this->_getRequestLine($method) . "\r\n");
+ $socket->write($this->_getHostLine() . "\r\n");
+ $socket->write("Connection: close\r\n");
+ }
+ return $socket;
+ }
+
+ /**
+ * Factory for socket.
+ * @param string $scheme Protocol to use.
+ * @param string $host Hostname to connect to.
+ * @param integer $port Remote port.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleSocket/SimpleSecureSocket New socket.
+ * @access protected
+ */
+ function _createSocket($scheme, $host, $port, $timeout) {
+ if (in_array($scheme, array('https'))) {
+ return new SimpleSecureSocket($host, $port, $timeout);
+ }
+ return new SimpleSocket($host, $port, $timeout);
+ }
+ }
+
+ /**
+ * Creates HTTP headers for the end point of
+ * a HTTP request via a proxy server.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleProxyRoute extends SimpleRoute {
+ protected $_proxy;
+ protected $_username;
+ protected $_password;
+
+ /**
+ * Stashes the proxy address.
+ * @param SimpleUrl $url URL as object.
+ * @param string $proxy Proxy URL.
+ * @param string $username Username for autentication.
+ * @param string $password Password for autentication.
+ * @access public
+ */
+ function SimpleProxyRoute($url, $proxy, $username = false, $password = false) {
+ $this->SimpleRoute($url);
+ $this->_proxy = $proxy;
+ $this->_username = $username;
+ $this->_password = $password;
+ }
+
+ /**
+ * Creates the first line which is the actual request.
+ * @param string $method HTTP request method, usually GET.
+ * @param SimpleUrl $url URL as object.
+ * @return string Request line content.
+ * @access protected
+ */
+ function _getRequestLine($method) {
+ $url = $this->getUrl();
+ $scheme = $url->getScheme() ? $url->getScheme() : 'http';
+ $port = $url->getPort() ? ':' . $url->getPort() : '';
+ return $method . ' ' . $scheme . '://' . $url->getHost() . $port .
+ $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0';
+ }
+
+ /**
+ * Creates the host part of the request.
+ * @param SimpleUrl $url URL as object.
+ * @return string Host line content.
+ * @access protected
+ */
+ function _getHostLine() {
+ $host = 'Host: ' . $this->_proxy->getHost();
+ $port = $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080;
+ return "$host:$port";
+ }
+
+ /**
+ * Opens a socket to the route.
+ * @param string $method HTTP request method, usually GET.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleSocket New socket.
+ * @access public
+ */
+ function createConnection($method, $timeout) {
+ $socket = $this->_createSocket(
+ $this->_proxy->getScheme() ? $this->_proxy->getScheme() : 'http',
+ $this->_proxy->getHost(),
+ $this->_proxy->getPort() ? $this->_proxy->getPort() : 8080,
+ $timeout);
+ if (! $socket->isError()) {
+ $socket->write($this->_getRequestLine($method) . "\r\n");
+ $socket->write($this->_getHostLine() . "\r\n");
+ if ($this->_username && $this->_password) {
+ $socket->write('Proxy-Authorization: Basic ' .
+ base64_encode($this->_username . ':' . $this->_password) .
+ "\r\n");
+ }
+ $socket->write("Connection: close\r\n");
+ }
+ return $socket;
+ }
+ }
+
+ /**
+ * HTTP request for a web page. Factory for
+ * HttpResponse object.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHttpRequest {
+ protected $_route;
+ protected $_method;
+ protected $_encoding;
+ protected $_headers;
+ protected $_cookies;
+
+ /**
+ * Saves the URL ready for fetching.
+ * @param SimpleRoute $route Request route.
+ * @param string $method HTTP request method,
+ * usually GET.
+ * @param SimpleFormEncoding $encoding Content to send with
+ * request or false.
+ * @access public
+ */
+ function SimpleHttpRequest($route, $method, $encoding = false) {
+ $this->_route = $route;
+ $this->_method = $method;
+ $this->_encoding = $encoding;
+ $this->_headers = array();
+ $this->_cookies = array();
+ }
+
+ /**
+ * Fetches the content and parses the headers.
+ * @param integer $timeout Connection timeout.
+ * @return SimpleHttpResponse A response which may only have
+ * an error.
+ * @access public
+ */
+ function fetch($timeout) {
+ $socket = $this->_route->createConnection($this->_method, $timeout);
+ if ($socket->isError()) {
+ return $this->_createResponse($socket);
+ }
+ $this->_dispatchRequest($socket, $this->_method, $this->_encoding);
+ return $this->_createResponse($socket);
+ }
+
+ /**
+ * Sends the headers.
+ * @param SimpleSocket $socket Open socket.
+ * @param string $method HTTP request method,
+ * usually GET.
+ * @param SimpleFormEncoding $encoding Content to send with request.
+ * @access private
+ */
+ function _dispatchRequest($socket, $method, $encoding) {
+ if ($encoding || ($method == 'POST')) {
+ $socket->write("Content-Length: " . $this->_getContentLength($encoding) . "\r\n");
+ $socket->write("Content-Type: application/x-www-form-urlencoded\r\n");
+ }
+ foreach ($this->_headers as $header_line) {
+ $socket->write($header_line . "\r\n");
+ }
+ if (count($this->_cookies) > 0) {
+ $socket->write("Cookie: " . $this->_marshallCookies($this->_cookies) . "\r\n");
+ }
+ $socket->write("\r\n");
+ if ($encoding) {
+ $socket->write($encoding->asString());
+ }
+ }
+
+ /**
+ * Calculates the length of the encoded content.
+ * @param SimpleFormEncoding $encoding Content to send with
+ * request or false.
+ */
+ function _getContentLength($encoding) {
+ if (! $encoding) {
+ return 0;
+ }
+ return (integer)strlen($encoding->asString());
+ }
+
+ /**
+ * Adds a header line to the request.
+ * @param string $header_line Text of header line.
+ * @access public
+ */
+ function addHeaderLine($header_line) {
+ $this->_headers[] = $header_line;
+ }
+
+ /**
+ * Adds a cookie to the request.
+ * @param SimpleCookie $cookie Additional cookie.
+ * @access public
+ */
+ function setCookie($cookie) {
+ $this->_cookies[] = $cookie;
+ }
+
+ /**
+ * Serialises the cookie hash ready for
+ * transmission.
+ * @param hash $cookies Parsed cookies.
+ * @return array Cookies in header form.
+ * @access private
+ */
+ function _marshallCookies($cookies) {
+ $cookie_pairs = array();
+ foreach ($cookies as $cookie) {
+ $cookie_pairs[] = $cookie->getName() . "=" . $cookie->getValue();
+ }
+ return implode(";", $cookie_pairs);
+ }
+
+ /**
+ * Wraps the socket in a response parser.
+ * @param SimpleSocket $socket Responding socket.
+ * @return SimpleHttpResponse Parsed response object.
+ * @access protected
+ */
+ function _createResponse($socket) {
+ return new SimpleHttpResponse(
+ $socket,
+ $this->_method,
+ $this->_route->getUrl(),
+ $this->_encoding);
+ }
+ }
+
+ /**
+ * Collection of header lines in the response.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHttpHeaders {
+ protected $_raw_headers;
+ protected $_response_code;
+ protected $_http_version;
+ protected $_mime_type;
+ protected $_location;
+ protected $_cookies;
+ protected $_authentication;
+ protected $_realm;
+
+ /**
+ * Parses the incoming header block.
+ * @param string $headers Header block.
+ * @access public
+ */
+ function SimpleHttpHeaders($headers) {
+ $this->_raw_headers = $headers;
+ $this->_response_code = false;
+ $this->_http_version = false;
+ $this->_mime_type = '';
+ $this->_location = false;
+ $this->_cookies = array();
+ $this->_authentication = false;
+ $this->_realm = false;
+ foreach (split("\r\n", $headers) as $header_line) {
+ $this->_parseHeaderLine($header_line);
+ }
+ }
+
+ /**
+ * Accessor for parsed HTTP protocol version.
+ * @return integer HTTP error code.
+ * @access public
+ */
+ function getHttpVersion() {
+ return $this->_http_version;
+ }
+
+ /**
+ * Accessor for raw header block.
+ * @return string All headers as raw string.
+ * @access public
+ */
+ function getRaw() {
+ return $this->_raw_headers;
+ }
+
+ /**
+ * Accessor for parsed HTTP error code.
+ * @return integer HTTP error code.
+ * @access public
+ */
+ function getResponseCode() {
+ return (integer)$this->_response_code;
+ }
+
+ /**
+ * Returns the redirected URL or false if
+ * no redirection.
+ * @return string URL or false for none.
+ * @access public
+ */
+ function getLocation() {
+ return $this->_location;
+ }
+
+ /**
+ * Test to see if the response is a valid redirect.
+ * @return boolean True if valid redirect.
+ * @access public
+ */
+ function isRedirect() {
+ return in_array($this->_response_code, array(301, 302, 303, 307)) &&
+ (boolean)$this->getLocation();
+ }
+
+ /**
+ * Test to see if the response is an authentication
+ * challenge.
+ * @return boolean True if challenge.
+ * @access public
+ */
+ function isChallenge() {
+ return ($this->_response_code == 401) &&
+ (boolean)$this->_authentication &&
+ (boolean)$this->_realm;
+ }
+
+ /**
+ * Accessor for MIME type header information.
+ * @return string MIME type.
+ * @access public
+ */
+ function getMimeType() {
+ return $this->_mime_type;
+ }
+
+ /**
+ * Accessor for authentication type.
+ * @return string Type.
+ * @access public
+ */
+ function getAuthentication() {
+ return $this->_authentication;
+ }
+
+ /**
+ * Accessor for security realm.
+ * @return string Realm.
+ * @access public
+ */
+ function getRealm() {
+ return $this->_realm;
+ }
+
+ /**
+ * Accessor for any new cookies.
+ * @return array List of new cookies.
+ * @access public
+ */
+ function getNewCookies() {
+ return $this->_cookies;
+ }
+
+ /**
+ * Called on each header line to accumulate the held
+ * data within the class.
+ * @param string $header_line One line of header.
+ * @access protected
+ */
+ function _parseHeaderLine($header_line) {
+ if (preg_match('/HTTP\/(\d+\.\d+)\s+(.*?)\s/i', $header_line, $matches)) {
+ $this->_http_version = $matches[1];
+ $this->_response_code = $matches[2];
+ }
+ if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) {
+ $this->_mime_type = trim($matches[1]);
+ }
+ if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) {
+ $this->_location = trim($matches[1]);
+ }
+ if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) {
+ $this->_cookies[] = $this->_parseCookie($matches[1]);
+ }
+ if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) {
+ $this->_authentication = $matches[1];
+ $this->_realm = trim($matches[2]);
+ }
+ }
+
+ /**
+ * Parse the Set-cookie content.
+ * @param string $cookie_line Text after "Set-cookie:"
+ * @return SimpleCookie New cookie object.
+ * @access private
+ */
+ function _parseCookie($cookie_line) {
+ $parts = split(";", $cookie_line);
+ $cookie = array();
+ preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie);
+ foreach ($parts as $part) {
+ if (preg_match('/\s*(.*?)\s*=(.*)/', $part, $matches)) {
+ $cookie[$matches[1]] = trim($matches[2]);
+ }
+ }
+ return new SimpleCookie(
+ $cookie[1],
+ trim($cookie[2]),
+ isset($cookie["path"]) ? $cookie["path"] : "",
+ isset($cookie["expires"]) ? $cookie["expires"] : false);
+ }
+ }
+
+ /**
+ * Basic HTTP response.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleHttpResponse extends SimpleStickyError {
+ protected $_method;
+ protected $_url;
+ protected $_request_data;
+ protected $_sent;
+ protected $_content;
+ protected $_headers;
+
+ /**
+ * Constructor. Reads and parses the incoming
+ * content and headers.
+ * @param SimpleSocket $socket Network connection to fetch
+ * response text from.
+ * @param string $method HTTP request method.
+ * @param SimpleUrl $url Resource name.
+ * @param mixed $request_data Record of content sent.
+ * @access public
+ */
+ function SimpleHttpResponse($socket, $method, $url, $request_data = '') {
+ $this->SimpleStickyError();
+ $this->_method = $method;
+ $this->_url = $url;
+ $this->_request_data = $request_data;
+ $this->_sent = $socket->getSent();
+ $this->_content = false;
+ $raw = $this->_readAll($socket);
+ if ($socket->isError()) {
+ $this->_setError('Error reading socket [' . $socket->getError() . ']');
+ return;
+ }
+ $this->_parse($raw);
+ }
+
+ /**
+ * Splits up the headers and the rest of the content.
+ * @param string $raw Content to parse.
+ * @access private
+ */
+ function _parse($raw) {
+ if (! $raw) {
+ $this->_setError('Nothing fetched');
+ $this->_headers = new SimpleHttpHeaders('');
+ } elseif (! strstr($raw, "\r\n\r\n")) {
+ $this->_setError('Could not parse headers');
+ $this->_headers = new SimpleHttpHeaders($raw);
+ } else {
+ list($headers, $this->_content) = split("\r\n\r\n", $raw, 2);
+ $this->_headers = new SimpleHttpHeaders($headers);
+ }
+ }
+
+ /**
+ * Original request method.
+ * @return string GET, POST or HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return $this->_method;
+ }
+
+ /**
+ * Resource name.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getUrl() {
+ return $this->_url;
+ }
+
+ /**
+ * Original request data.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequestData() {
+ return $this->_request_data;
+ }
+
+ /**
+ * Raw request that was sent down the wire.
+ * @return string Bytes actually sent.
+ * @access public
+ */
+ function getSent() {
+ return $this->_sent;
+ }
+
+ /**
+ * Accessor for the content after the last
+ * header line.
+ * @return string All content.
+ * @access public
+ */
+ function getContent() {
+ return $this->_content;
+ }
+
+ /**
+ * Accessor for header block. The response is the
+ * combination of this and the content.
+ * @return SimpleHeaders Wrapped header block.
+ * @access public
+ */
+ function getHeaders() {
+ return $this->_headers;
+ }
+
+ /**
+ * Accessor for any new cookies.
+ * @return array List of new cookies.
+ * @access public
+ */
+ function getNewCookies() {
+ return $this->_headers->getNewCookies();
+ }
+
+ /**
+ * Reads the whole of the socket output into a
+ * single string.
+ * @param SimpleSocket $socket Unread socket.
+ * @return string Raw output if successful
+ * else false.
+ * @access private
+ */
+ function _readAll($socket) {
+ $all = '';
+ while (! $this->_isLastPacket($next = $socket->read())) {
+ $all .= $next;
+ }
+ return $all;
+ }
+
+ /**
+ * Test to see if the packet from the socket is the
+ * last one.
+ * @param string $packet Chunk to interpret.
+ * @return boolean True if empty or EOF.
+ * @access private
+ */
+ function _isLastPacket($packet) {
+ if (is_string($packet)) {
+ return $packet === '';
+ }
+ return ! $packet;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/mock_objects.php b/tests/test_tools/simpletest/mock_objects.php
new file mode 100644
index 00000000..d39eb84e
--- /dev/null
+++ b/tests/test_tools/simpletest/mock_objects.php
@@ -0,0 +1,1323 @@
+<?php
+ /**
+ * 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 $
+ */
+
+ /**#@+
+ * include SimpleTest files
+ */
+ require_once(dirname(__FILE__) . '/expectation.php');
+ require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/dumper.php');
+ /**#@-*/
+
+ /**
+ * Default character simpletest will substitute for any value
+ */
+ define('MOCK_WILDCARD', '*');
+
+ /**
+ * A wildcard expectation always matches.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class WildcardExpectation extends SimpleExpectation {
+
+ /**
+ * Chains constructor only.
+ * @access public
+ */
+ function WildcardExpectation() {
+ $this->SimpleExpectation();
+ }
+
+ /**
+ * Tests the expectation. Always true.
+ * @param mixed $compare Ignored.
+ * @return boolean True.
+ * @access public
+ */
+ function test($compare) {
+ return true;
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ return 'Wildcard always matches [' . $dumper->describeValue($compare) . ']';
+ }
+ }
+
+ /**
+ * Parameter comparison assertion.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class ParametersExpectation extends SimpleExpectation {
+ protected $_expected;
+
+ /**
+ * Sets the expected parameter list.
+ * @param array $parameters Array of parameters including
+ * those that are wildcarded.
+ * If the value is not an array
+ * then it is considered to match any.
+ * @param mixed $wildcard Any parameter matching this
+ * will always match.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function ParametersExpectation($expected = false, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_expected = $expected;
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param array $parameters Comparison values.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($parameters) {
+ if (! is_array($this->_expected)) {
+ return true;
+ }
+ if (count($this->_expected) != count($parameters)) {
+ return false;
+ }
+ for ($i = 0; $i < count($this->_expected); $i++) {
+ if (! $this->_testParameter($parameters[$i], $this->_expected[$i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests an individual parameter.
+ * @param mixed $parameter Value to test.
+ * @param mixed $expected Comparison value.
+ * @return boolean True if expectation
+ * fulfilled.
+ * @access private
+ */
+ function _testParameter($parameter, $expected) {
+ $comparison = $this->_coerceToExpectation($expected);
+ return $comparison->test($parameter);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param array $comparison Incoming parameter list.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($parameters) {
+ if ($this->test($parameters)) {
+ return "Expectation of " . count($this->_expected) .
+ " arguments of [" . $this->_renderArguments($this->_expected) .
+ "] is correct";
+ } else {
+ return $this->_describeDifference($this->_expected, $parameters);
+ }
+ }
+
+ /**
+ * Message to display if expectation differs from
+ * the parameters actually received.
+ * @param array $expected Expected parameters as list.
+ * @param array $parameters Actual parameters received.
+ * @return string Description of difference.
+ * @access private
+ */
+ function _describeDifference($expected, $parameters) {
+ if (count($expected) != count($parameters)) {
+ return "Expected " . count($expected) .
+ " arguments of [" . $this->_renderArguments($expected) .
+ "] but got " . count($parameters) .
+ " arguments of [" . $this->_renderArguments($parameters) . "]";
+ }
+ $messages = array();
+ for ($i = 0; $i < count($expected); $i++) {
+ $comparison = $this->_coerceToExpectation($expected[$i]);
+ if (! $comparison->test($parameters[$i])) {
+ $messages[] = "parameter " . ($i + 1) . " with [" .
+ $comparison->overlayMessage($parameters[$i]) . "]";
+ }
+ }
+ return "Parameter expectation differs at " . implode(" and ", $messages);
+ }
+
+ /**
+ * Creates an identical expectation if the
+ * object/value is not already some type
+ * of expectation.
+ * @param mixed $expected Expected value.
+ * @return SimpleExpectation Expectation object.
+ * @access private
+ */
+ function _coerceToExpectation($expected) {
+ if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) {
+ return $expected;
+ }
+ return new IdenticalExpectation($expected);
+ }
+
+ /**
+ * Renders the argument list as a string for
+ * messages.
+ * @param array $args Incoming arguments.
+ * @return string Simple description of type and value.
+ * @access private
+ */
+ function _renderArguments($args) {
+ $descriptions = array();
+ if (is_array($args)) {
+ foreach ($args as $arg) {
+ $dumper = new SimpleDumper();
+ $descriptions[] = $dumper->describeValue($arg);
+ }
+ }
+ return implode(', ', $descriptions);
+ }
+ }
+
+ /**
+ * Confirms that the number of calls on a method is as expected.
+ */
+ class CallCountExpectation extends SimpleExpectation {
+ protected $_method;
+ protected $_count;
+
+ /**
+ * Stashes the method and expected count for later
+ * reporting.
+ * @param string $method Name of method to confirm against.
+ * @param integer $count Expected number of calls.
+ * @param string $message Custom error message.
+ */
+ function CallCountExpectation($method, $count, $message = '%s') {
+ $this->_method = $method;
+ $this->_count = $count;
+ $this->SimpleExpectation($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if expected.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_count == $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ * @access public
+ */
+ function testMessage($compare) {
+ return 'Expected call count for [' . $this->_method .
+ '] was [' . $this->_count .
+ '] got [' . $compare . ']';
+ }
+ }
+
+ /**
+ * Confirms that the number of calls on a method is as expected.
+ */
+ class MinimumCallCountExpectation extends SimpleExpectation {
+ protected $_method;
+ protected $_count;
+
+ /**
+ * Stashes the method and expected count for later
+ * reporting.
+ * @param string $method Name of method to confirm against.
+ * @param integer $count Minimum number of calls.
+ * @param string $message Custom error message.
+ */
+ function MinimumCallCountExpectation($method, $count, $message = '%s') {
+ $this->_method = $method;
+ $this->_count = $count;
+ $this->SimpleExpectation($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if enough.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_count <= $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ * @access public
+ */
+ function testMessage($compare) {
+ return 'Minimum call count for [' . $this->_method .
+ '] was [' . $this->_count .
+ '] got [' . $compare . ']';
+ }
+ }
+
+ /**
+ * Confirms that the number of calls on a method is as expected.
+ */
+ class MaximumCallCountExpectation extends SimpleExpectation {
+ protected $_method;
+ protected $_count;
+
+ /**
+ * Stashes the method and expected count for later
+ * reporting.
+ * @param string $method Name of method to confirm against.
+ * @param integer $count Minimum number of calls.
+ * @param string $message Custom error message.
+ */
+ function MaximumCallCountExpectation($method, $count, $message = '%s') {
+ $this->_method = $method;
+ $this->_count = $count;
+ $this->SimpleExpectation($message);
+ }
+
+ /**
+ * Tests the assertion. True if correct.
+ * @param integer $compare Measured call count.
+ * @return boolean True if not over.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_count >= $compare);
+ }
+
+ /**
+ * Reports the comparison.
+ * @param integer $compare Measured call count.
+ * @return string Message to show.
+ * @access public
+ */
+ function testMessage($compare) {
+ return 'Maximum call count for [' . $this->_method .
+ '] was [' . $this->_count .
+ '] got [' . $compare . ']';
+ }
+ }
+
+ /**
+ * Retrieves values and references by searching the
+ * parameter lists until a match is found.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class CallMap {
+ protected $_map;
+
+ /**
+ * Creates an empty call map.
+ * @access public
+ */
+ function CallMap() {
+ $this->_map = array();
+ }
+
+ /**
+ * Stashes a value against a method call.
+ * @param array $parameters Arguments including wildcards.
+ * @param mixed $value Value copied into the map.
+ * @access public
+ */
+ function addValue($parameters, $value) {
+ $this->addReference($parameters, $value);
+ }
+
+ /**
+ * Stashes a reference against a method call.
+ * @param array $parameters Array of arguments (including wildcards).
+ * @param mixed $reference Array reference placed in the map.
+ * @access public
+ */
+ function addReference($parameters, $reference) {
+ $place = count($this->_map);
+ $this->_map[$place] = array();
+ $this->_map[$place]["params"] = new ParametersExpectation($parameters);
+ $this->_map[$place]["content"] = $reference;
+ }
+
+ /**
+ * Searches the call list for a matching parameter
+ * set. Returned by reference.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return object Object held in the first matching
+ * slot, otherwise null.
+ * @access public
+ */
+ function findFirstMatch($parameters) {
+ $slot = $this->_findFirstSlot($parameters);
+ if (!isset($slot)) {
+ return null;
+ }
+ return $slot["content"];
+ }
+
+ /**
+ * Searches the call list for a matching parameter
+ * set. True if successful.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return boolean True if a match is present.
+ * @access public
+ */
+ function isMatch($parameters) {
+ return ($this->_findFirstSlot($parameters) != null);
+ }
+
+ /**
+ * Searches the map for a matching item.
+ * @param array $parameters Parameters to search by
+ * without wildcards.
+ * @return array Reference to slot or null.
+ * @access private
+ */
+ function _findFirstSlot($parameters) {
+ $count = count($this->_map);
+ for ($i = 0; $i < $count; $i++) {
+ if ($this->_map[$i]["params"]->test($parameters)) {
+ return $this->_map[$i];
+ }
+ }
+ return null;
+ }
+ }
+
+ /**
+ * An empty collection of methods that can have their
+ * return values set. Used for prototyping.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class SimpleStub {
+ protected $_wildcard;
+ protected $_is_strict;
+ protected $_returns;
+ protected $_return_sequence;
+ protected $_call_counts;
+
+ /**
+ * Sets up the wildcard and everything else empty.
+ * @param mixed $wildcard Parameter matching wildcard.
+ * @param boolean $is_strict Enables method name checks.
+ * @access public
+ */
+ function SimpleStub($wildcard, $is_strict = true) {
+ $this->_wildcard = $wildcard;
+ $this->_is_strict = $is_strict;
+ $this->_returns = array();
+ $this->_return_sequence = array();
+ $this->_call_counts = array();
+ }
+
+ /**
+ * Replaces wildcard matches with wildcard
+ * expectations in the argument list.
+ * @param array $args Raw argument list.
+ * @return array Argument list with
+ * expectations.
+ * @access private
+ */
+ function _replaceWildcards($args) {
+ if ($args === false) {
+ return false;
+ }
+ for ($i = 0; $i < count($args); $i++) {
+ if ($args[$i] === $this->_wildcard) {
+ $args[$i] = new WildcardExpectation();
+ }
+ }
+ return $args;
+ }
+
+ /**
+ * Returns the expected value for the method name.
+ * @param string $method Name of method to simulate.
+ * @param array $args Arguments as an array.
+ * @return mixed Stored return.
+ * @access private
+ */
+ function _invoke($method, $args) {
+ $method = strtolower($method);
+ $step = $this->getCallCount($method);
+ $this->_addCall($method, $args);
+ return $this->_getReturn($method, $args, $step);
+ }
+
+ /**
+ * Triggers a PHP error if the method is not part
+ * of this object.
+ * @param string $method Name of method.
+ * @param string $task Description of task attempt.
+ * @access protected
+ */
+ function _dieOnNoMethod($method, $task) {
+ if ($this->_is_strict && !method_exists($this, $method)) {
+ trigger_error(
+ "Cannot $task as no ${method}() in class " . get_class($this),
+ E_USER_ERROR);
+ }
+ }
+
+ /**
+ * Adds one to the call count of a method.
+ * @param string $method Method called.
+ * @param array $args Arguments as an array.
+ * @access protected
+ */
+ function _addCall($method, $args) {
+ if (!isset($this->_call_counts[$method])) {
+ $this->_call_counts[$method] = 0;
+ }
+ $this->_call_counts[$method]++;
+ }
+
+ /**
+ * Fetches the call count of a method so far.
+ * @param string $method Method name called.
+ * @return Number of calls so far.
+ * @access public
+ */
+ function getCallCount($method) {
+ $this->_dieOnNoMethod($method, "get call count");
+ $method = strtolower($method);
+ if (! isset($this->_call_counts[$method])) {
+ return 0;
+ }
+ return $this->_call_counts[$method];
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by value for all calls to this method.
+ * @param string $method Method name.
+ * @param mixed $value Result of call passed by value.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnValue($method, $value, $args = false) {
+ $this->_dieOnNoMethod($method, "set return value");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_returns[$method])) {
+ $this->_returns[$method] = new CallMap();
+ }
+ $this->_returns[$method]->addValue($args, $value);
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by value only when the required call count
+ * is reached.
+ * @param integer $timing Number of calls in the future
+ * to which the result applies. If
+ * not set then all calls will return
+ * the value.
+ * @param string $method Method name.
+ * @param mixed $value Result of call passed by value.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnValueAt($timing, $method, $value, $args = false) {
+ $this->_dieOnNoMethod($method, "set return value sequence");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_return_sequence[$method])) {
+ $this->_return_sequence[$method] = array();
+ }
+ if (! isset($this->_return_sequence[$method][$timing])) {
+ $this->_return_sequence[$method][$timing] = new CallMap();
+ }
+ $this->_return_sequence[$method][$timing]->addValue($args, $value);
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by reference for all calls.
+ * @param string $method Method name.
+ * @param mixed $reference Result of the call will be this object.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnReference($method, $reference, $args = false) {
+ $this->_dieOnNoMethod($method, "set return reference");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_returns[$method])) {
+ $this->_returns[$method] = new CallMap();
+ }
+ $this->_returns[$method]->addReference($args, $reference);
+ }
+
+ /**
+ * Sets a return for a parameter list that will
+ * be passed by value only when the required call count
+ * is reached.
+ * @param integer $timing Number of calls in the future
+ * to which the result applies. If
+ * not set then all calls will return
+ * the value.
+ * @param string $method Method name.
+ * @param mixed $reference Result of the call will be this object.
+ * @param array $args List of parameters to match
+ * including wildcards.
+ * @access public
+ */
+ function setReturnReferenceAt($timing, $method, $reference, $args = false) {
+ $this->_dieOnNoMethod($method, "set return reference sequence");
+ $args = $this->_replaceWildcards($args);
+ $method = strtolower($method);
+ if (! isset($this->_return_sequence[$method])) {
+ $this->_return_sequence[$method] = array();
+ }
+ if (! isset($this->_return_sequence[$method][$timing])) {
+ $this->_return_sequence[$method][$timing] = new CallMap();
+ }
+ $this->_return_sequence[$method][$timing]->addReference($args, $reference);
+ }
+
+ /**
+ * Finds the return value matching the incoming
+ * arguments. If there is no matching value found
+ * then an error is triggered.
+ * @param string $method Method name.
+ * @param array $args Calling arguments.
+ * @param integer $step Current position in the
+ * call history.
+ * @return mixed Stored return.
+ * @access protected
+ */
+ function _getReturn($method, $args, $step) {
+ if (isset($this->_return_sequence[$method][$step])) {
+ if ($this->_return_sequence[$method][$step]->isMatch($args)) {
+ return $this->_return_sequence[$method][$step]->findFirstMatch($args);
+ }
+ }
+ if (isset($this->_returns[$method])) {
+ return $this->_returns[$method]->findFirstMatch($args);
+ }
+ return null;
+ }
+ }
+
+ /**
+ * An empty collection of methods that can have their
+ * return values set and expectations made of the
+ * calls upon them. The mock will assert the
+ * expectations against it's attached test case in
+ * addition to the server stub behaviour.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class SimpleMock extends SimpleStub {
+ protected $_test;
+ protected $_expected_counts;
+ protected $_max_counts;
+ protected $_expected_args;
+ protected $_expected_args_at;
+
+ /**
+ * Creates an empty return list and expectation list.
+ * All call counts are set to zero.
+ * @param SimpleTestCase $test Test case to test expectations in.
+ * @param mixed $wildcard Parameter matching wildcard.
+ * @param boolean $is_strict Enables method name checks on
+ * expectations.
+ * @access public
+ */
+ function SimpleMock($test, $wildcard, $is_strict = true) {
+ $this->SimpleStub($wildcard, $is_strict);
+ if (! $test) {
+ trigger_error('No unit tester for mock object', E_USER_ERROR);
+ return;
+ }
+ $this->_test = SimpleMock::registerTest($test);
+ $this->_expected_counts = array();
+ $this->_max_counts = array();
+ $this->_expected_args = array();
+ $this->_expected_args_at = array();
+ }
+
+ /**
+ * Accessor for attached unit test so that when
+ * subclassed, new expectations can be added easily.
+ * @return SimpleTestCase Unit test passed in constructor.
+ * @access public
+ */
+ function getTest() {
+ return $this->_test;
+ }
+
+ /**
+ * Die if bad arguments array is passed
+ * @param mixed $args The arguments value to be checked.
+ * @param string $task Description of task attempt.
+ * @return boolean Valid arguments
+ * @access private
+ */
+ function _checkArgumentsIsArray($args, $task) {
+ if (! is_array($args)) {
+ trigger_error(
+ "Cannot $task as \$args parameter is not an array",
+ E_USER_ERROR);
+ }
+ }
+
+ /**
+ * Sets up an expected call with a set of
+ * expected parameters in that call. All
+ * calls will be compared to these expectations
+ * regardless of when the call is made.
+ * @param string $method Method call to test.
+ * @param array $args Expected parameters for the call
+ * including wildcards.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectArguments($method, $args, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set expected arguments');
+ $this->_checkArgumentsIsArray($args, 'set expected arguments');
+ $args = $this->_replaceWildcards($args);
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_args[strtolower($method)] =
+ new ParametersExpectation($args, $message);
+ }
+
+ /**
+ * Sets up an expected call with a set of
+ * expected parameters in that call. The
+ * expected call count will be adjusted if it
+ * is set too low to reach this call.
+ * @param integer $timing Number of calls in the future at
+ * which to test. Next call is 0.
+ * @param string $method Method call to test.
+ * @param array $args Expected parameters for the call
+ * including wildcards.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectArgumentsAt($timing, $method, $args, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set expected arguments at time');
+ $this->_checkArgumentsIsArray($args, 'set expected arguments at time');
+ $args = $this->_replaceWildcards($args);
+ if (! isset($this->_expected_args_at[$timing])) {
+ $this->_expected_args_at[$timing] = array();
+ }
+ $method = strtolower($method);
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_args_at[$timing][$method] =
+ new ParametersExpectation($args, $message);
+ }
+
+ /**
+ * Sets an expectation for the number of times
+ * a method will be called. The tally method
+ * is used to check this.
+ * @param string $method Method call to test.
+ * @param integer $count Number of times it should
+ * have been called at tally.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectCallCount($method, $count, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set expected call count');
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_counts[strtolower($method)] =
+ new CallCountExpectation($method, $count, $message);
+ }
+
+ /**
+ * Sets the number of times a method may be called
+ * before a test failure is triggered.
+ * @param string $method Method call to test.
+ * @param integer $count Most number of times it should
+ * have been called.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectMaximumCallCount($method, $count, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set maximum call count');
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_max_counts[strtolower($method)] =
+ new MaximumCallCountExpectation($method, $count, $message);
+ }
+
+ /**
+ * Sets the number of times to call a method to prevent
+ * a failure on the tally.
+ * @param string $method Method call to test.
+ * @param integer $count Least number of times it should
+ * have been called.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectMinimumCallCount($method, $count, $message = '%s') {
+ $this->_dieOnNoMethod($method, 'set minimum call count');
+ $message .= Mock::getExpectationLine(' at line [%d]');
+ $this->_expected_counts[strtolower($method)] =
+ new MinimumCallCountExpectation($method, $count, $message);
+ }
+
+ /**
+ * Convenience method for barring a method
+ * call.
+ * @param string $method Method call to ban.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectNever($method, $message = '%s') {
+ $this->expectMaximumCallCount($method, 0, $message);
+ }
+
+ /**
+ * Convenience method for a single method
+ * call.
+ * @param string $method Method call to track.
+ * @param array $args Expected argument list or
+ * false for any arguments.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectOnce($method, $args = false, $message = '%s') {
+ $this->expectCallCount($method, 1, $message);
+ if ($args !== false) {
+ $this->expectArguments($method, $args, $message);
+ }
+ }
+
+ /**
+ * Convenience method for requiring a method
+ * call.
+ * @param string $method Method call to track.
+ * @param array $args Expected argument list or
+ * false for any arguments.
+ * @param string $message Overridden message.
+ * @access public
+ */
+ function expectAtLeastOnce($method, $args = false, $message = '%s') {
+ $this->expectMinimumCallCount($method, 1, $message);
+ if ($args !== false) {
+ $this->expectArguments($method, $args, $message);
+ }
+ }
+
+ /**
+ * Totals up the call counts and triggers a test
+ * assertion if a test is present for expected
+ * call counts.
+ * This method must be called explicitly for the call
+ * count assertions to be triggered.
+ * @access public
+ */
+ function tally() {
+ foreach ($this->_expected_counts as $method => $expectation) {
+ $this->_assertTrue(
+ $expectation->test($this->getCallCount($method)),
+ $expectation->overlayMessage($this->getCallCount($method)));
+ }
+ foreach ($this->_max_counts as $method => $expectation) {
+ if ($expectation->test($this->getCallCount($method))) {
+ $this->_assertTrue(
+ true,
+ $expectation->overlayMessage($this->getCallCount($method)));
+ }
+ }
+ }
+
+ /**
+ * Returns the expected value for the method name
+ * and checks expectations. Will generate any
+ * test assertions as a result of expectations
+ * if there is a test present.
+ * @param string $method Name of method to simulate.
+ * @param array $args Arguments as an array.
+ * @return mixed Stored return.
+ * @access private
+ */
+ function _invoke($method, $args) {
+ $method = strtolower($method);
+ $step = $this->getCallCount($method);
+ $this->_addCall($method, $args);
+ $this->_checkExpectations($method, $args, $step);
+ return $this->_getReturn($method, $args, $step);
+ }
+
+ /**
+ * Tests the arguments against expectations.
+ * @param string $method Method to check.
+ * @param array $args Argument list to match.
+ * @param integer $timing The position of this call
+ * in the call history.
+ * @access private
+ */
+ function _checkExpectations($method, $args, $timing) {
+ if (isset($this->_max_counts[$method])) {
+ if (! $this->_max_counts[$method]->test($timing + 1)) {
+ $this->_assertTrue(
+ false,
+ $this->_max_counts[$method]->overlayMessage($timing + 1));
+ }
+ }
+ if (isset($this->_expected_args_at[$timing][$method])) {
+ $this->_assertTrue(
+ $this->_expected_args_at[$timing][$method]->test($args),
+ "Mock method [$method] at [$timing] -> " .
+ $this->_expected_args_at[$timing][$method]->overlayMessage($args));
+ } elseif (isset($this->_expected_args[$method])) {
+ $this->_assertTrue(
+ $this->_expected_args[$method]->test($args),
+ "Mock method [$method] -> " . $this->_expected_args[$method]->overlayMessage($args));
+ }
+ }
+
+ /**
+ * Triggers an assertion on the held test case.
+ * Should be overridden when using another test
+ * framework other than the SimpleTest one if the
+ * assertion method has a different name.
+ * @param boolean $assertion True will pass.
+ * @param string $message Message that will go with
+ * the test event.
+ * @access protected
+ */
+ function _assertTrue($assertion, $message) {
+ $test =SimpleMock::injectTest($this->_test);
+ $test->assertTrue($assertion, $message);
+ }
+
+ /**
+ * Stashes the test case for later recovery.
+ * @param SimpleTestCase $test Test case.
+ * @return string Key to find it again.
+ * @access public
+ * @static
+ */
+ function registerTest($test) {
+ $registry =SimpleMock::_getRegistry();
+ $registry[$class = get_class($test)] = $test;
+ return $class;
+ }
+
+ /**
+ * Resolves the dependency on the test case.
+ * @param string $class Key to look up test case in.
+ * @return SimpleTestCase Test case to send results to.
+ * @access public
+ * @static
+ */
+ function injectTest($key) {
+ $registry =SimpleMock::_getRegistry();
+ return $registry[$key];
+ }
+
+ /**
+ * Registry for test cases. The reason for this is
+ * to break the reference between the test cases and
+ * the mocks. It was leading to a fatal error due to
+ * recursive dependencies during comparisons. See
+ * http://bugs.php.net/bug.php?id=31449 for the PHP
+ * bug.
+ * @return array List of references.
+ * @access private
+ * @static
+ */
+ function _getRegistry() {
+ static $registry;
+ if (! isset($registry)) {
+ $registry = array();
+ }
+ return $registry;
+ }
+ }
+
+ /**
+ * Static methods only service class for code generation of
+ * server stubs.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class Stub {
+
+ /**
+ * Factory for server stub classes.
+ */
+ function Stub() {
+ trigger_error('Stub factory methods are class only.');
+ }
+
+ /**
+ * Clones a class' interface and creates a stub version
+ * that can have return values set.
+ * @param string $class Class to clone.
+ * @param string $stub_class New class name. Default is
+ * the old name with "Stub"
+ * prepended.
+ * @param array $methods Additional methods to add beyond
+ * those in the cloned class. Use this
+ * to emulate the dynamic addition of
+ * methods in the cloned class or when
+ * the class hasn't been written yet.
+ * @static
+ * @access public
+ */
+ function generate($class, $stub_class = false, $methods = false) {
+ if (! SimpleTestCompatibility::classExists($class)) {
+ return false;
+ }
+ if (! $stub_class) {
+ $stub_class = "Stub" . $class;
+ }
+ if (SimpleTestCompatibility::classExists($stub_class)) {
+ return false;
+ }
+ return eval(Stub::_createClassCode(
+ $class,
+ $stub_class,
+ $methods ? $methods : array()) . " return true;");
+ }
+
+ /**
+ * The new server stub class code in string form.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Additional methods.
+ * @static
+ * @access private
+ */
+ function _createClassCode($class, $stub_class, $methods) {
+ $stub_base = SimpleTestOptions::getStubBaseClass();
+ $code = "class $stub_class extends $stub_base {\n";
+ $code .= " function $stub_class(\$wildcard = MOCK_WILDCARD) {\n";
+ $code .= " \$this->$stub_base(\$wildcard);\n";
+ $code .= " }\n";
+ $code .= Stub::_createHandlerCode($class, $stub_base, $methods);
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * Creates code within a class to generate replaced
+ * methods. All methods call the _invoke() handler
+ * with the method name and the arguments in an
+ * array.
+ * @param string $class Class to clone.
+ * @param string $base Base mock/stub class with methods that
+ * cannot be cloned. Otherwise you
+ * would be stubbing the accessors used
+ * to set the stubs.
+ * @param array $methods Additional methods.
+ * @static
+ * @access private
+ */
+ function _createHandlerCode($class, $base, $methods) {
+ $code = "";
+ $methods = array_merge($methods, get_class_methods($class));
+ foreach ($methods as $method) {
+ if (Stub::_isSpecialMethod($method)) {
+ continue;
+ }
+ if (in_array($method, get_class_methods($base))) {
+ continue;
+ }
+ $code .= " function $method() {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " return \$this->_invoke(\"$method\", \$args);\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+
+ /**
+ * Tests to see if a special PHP method is about to
+ * be stubbed by mistake.
+ * @param string $method Method name.
+ * @return boolean True if special.
+ * @access private
+ * @static
+ */
+ function _isSpecialMethod($method) {
+ return in_array(
+ strtolower($method),
+ array('__construct', '__clone', '__get', '__set', '__call'));
+ }
+ }
+
+ /**
+ * Static methods only service class for code generation of
+ * mock objects.
+ * @package SimpleTest
+ * @subpackage MockObjects
+ */
+ class Mock {
+
+ /**
+ * Factory for mock object classes.
+ * @access public
+ */
+ function Mock() {
+ trigger_error("Mock factory methods are class only.");
+ }
+
+ /**
+ * Clones a class' interface and creates a mock version
+ * that can have return values and expectations set.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name. Default is
+ * the old name with "Mock"
+ * prepended.
+ * @param array $methods Additional methods to add beyond
+ * those in th cloned class. Use this
+ * to emulate the dynamic addition of
+ * methods in the cloned class or when
+ * the class hasn't been written yet.
+ * @static
+ * @access public
+ */
+ function generate($class, $mock_class = false, $methods = false) {
+ if (! SimpleTestCompatibility::classExists($class)) {
+ return false;
+ }
+ if (! $mock_class) {
+ $mock_class = "Mock" . $class;
+ }
+ if (SimpleTestCompatibility::classExists($mock_class)) {
+ return false;
+ }
+ return eval(Mock::_createClassCode(
+ $class,
+ $mock_class,
+ $methods ? $methods : array()) . " return true;");
+ }
+
+ /**
+ * Generates a version of a class with selected
+ * methods mocked only. Inherits the old class
+ * and chains the mock methods of an aggregated
+ * mock object.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Methods to be overridden
+ * with mock versions.
+ * @static
+ * @access public
+ */
+ function generatePartial($class, $mock_class, $methods) {
+ if (! SimpleTestCompatibility::classExists($class)) {
+ return false;
+ }
+ if (SimpleTestCompatibility::classExists($mock_class)) {
+ trigger_error("Partial mock class [$mock_class] already exists");
+ return false;
+ }
+ return eval(Mock::_extendClassCode($class, $mock_class, $methods));
+ }
+
+ /**
+ * The new mock class code as a string.
+ * @param string $class Class to clone.
+ * @param string $mock_class New class name.
+ * @param array $methods Additional methods.
+ * @return string Code for new mock class.
+ * @static
+ * @access private
+ */
+ function _createClassCode($class, $mock_class, $methods) {
+ $mock_base = SimpleTestOptions::getMockBaseClass();
+ $code = "class $mock_class extends $mock_base {\n";
+ $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
+ $code .= " \$this->$mock_base(\$test, \$wildcard);\n";
+ $code .= " }\n";
+ $code .= Stub::_createHandlerCode($class, $mock_base, $methods);
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * The extension class code as a string. The class
+ * composites a mock object and chains mocked methods
+ * to it.
+ * @param string $class Class to extend.
+ * @param string $mock_class New class name.
+ * @param array $methods Mocked methods.
+ * @return string Code for a new class.
+ * @static
+ * @access private
+ */
+ function _extendClassCode($class, $mock_class, $methods) {
+ $mock_base = SimpleTestOptions::getMockBaseClass();
+ $code = "class $mock_class extends $class {\n";
+ $code .= " var \$_mock;\n";
+ $code .= Mock::_addMethodList($methods);
+ $code .= "\n";
+ $code .= " function $mock_class(&\$test, \$wildcard = MOCK_WILDCARD) {\n";
+ $code .= " \$this->_mock = new $mock_base(\$test, \$wildcard, false);\n";
+ $code .= " }\n";
+ $code .= Mock::_chainMockReturns();
+ $code .= Mock::_chainMockExpectations();
+ $code .= Mock::_overrideMethods($methods);
+ $code .= SimpleTestOptions::getPartialMockCode();
+ $code .= "}\n";
+ return $code;
+ }
+
+ /**
+ * Creates a list of mocked methods for error checking.
+ * @param array $methods Mocked methods.
+ * @return string Code for a method list.
+ * @access private
+ */
+ function _addMethodList($methods) {
+ return " var \$_mocked_methods = array('" . implode("', '", $methods) . "');\n";
+ }
+
+ /**
+ * Creates code to abandon the expectation if not mocked.
+ * @param string $alias Parameter name of method name.
+ * @return string Code for bail out.
+ * @access private
+ */
+ function _bailOutIfNotMocked($alias) {
+ $code = " if (! in_array($alias, \$this->_mocked_methods)) {\n";
+ $code .= " trigger_error(\"Method [$alias] is not mocked\");\n";
+ $code .= " return;\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code for chaining to the composited
+ * mock object.
+ * @return string Code for mock set up.
+ * @access private
+ */
+ function _chainMockReturns() {
+ $code = " function setReturnValue(\$method, \$value, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnValue(\$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnReference(\$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code for chaining to an aggregated
+ * mock object.
+ * @return string Code for expectations.
+ * @access private
+ */
+ function _chainMockExpectations() {
+ $code = " function expectArguments(\$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectArguments(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectArgumentsAt(\$timing, \$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectArgumentsAt(\$timing, \$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectCallCount(\$method, \$count) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectCallCount(\$method, \$count);\n";
+ $code .= " }\n";
+ $code .= " function expectMaximumCallCount(\$method, \$count) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectMaximumCallCount(\$method, \$count);\n";
+ $code .= " }\n";
+ $code .= " function expectMinimumCallCount(\$method, \$count) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectMinimumCallCount(\$method, \$count);\n";
+ $code .= " }\n";
+ $code .= " function expectNever(\$method) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectNever(\$method);\n";
+ $code .= " }\n";
+ $code .= " function expectOnce(\$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectOnce(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function expectAtLeastOnce(\$method, \$args = false) {\n";
+ $code .= Mock::_bailOutIfNotMocked("\$method");
+ $code .= " \$this->_mock->expectAtLeastOnce(\$method, \$args);\n";
+ $code .= " }\n";
+ $code .= " function tally() {\n";
+ $code .= " \$this->_mock->tally();\n";
+ $code .= " }\n";
+ return $code;
+ }
+
+ /**
+ * Creates source code to override a list of methods
+ * with mock versions.
+ * @param array $methods Methods to be overridden
+ * with mock versions.
+ * @return string Code for overridden chains.
+ * @access private
+ */
+ function _overrideMethods($methods) {
+ $code = "";
+ foreach ($methods as $method) {
+ $code .= " function $method() {\n";
+ $code .= " \$args = func_get_args();\n";
+ $code .= " return \$this->_mock->_invoke(\"$method\", \$args);\n";
+ $code .= " }\n";
+ }
+ return $code;
+ }
+
+ /**
+ * Uses a stack trace to find the line of an assertion.
+ * @param string $format String formatting.
+ * @param array $stack Stack frames top most first. Only
+ * needed if not using the PHP
+ * backtrace function.
+ * @return string Line number of first expect*
+ * method embedded in format string.
+ * @access public
+ * @static
+ */
+ function getExpectationLine($format = '%d', $stack = false) {
+ if ($stack === false) {
+ $stack = SimpleTestCompatibility::getStackTrace();
+ }
+ return SimpleDumper::getFormattedAssertionLine($stack, $format, 'expect');
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/options.php b/tests/test_tools/simpletest/options.php
new file mode 100644
index 00000000..51ec5353
--- /dev/null
+++ b/tests/test_tools/simpletest/options.php
@@ -0,0 +1,366 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @version $Id: options.php,v 1.35 2005/02/04 03:48:52 lastcraft Exp $
+ */
+
+ /**
+ * Static global directives and options.
+ * @package SimpleTest
+ */
+ class SimpleTestOptions {
+
+ /**
+ * 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.
+ * @param string $class Add a class to ignore.
+ * @static
+ * @access public
+ */
+ function ignore($class) {
+ $registry =SimpleTestOptions::_getRegistry();
+ $registry['IgnoreList'][] = strtolower($class);
+ }
+
+ /**
+ * Test to see if a test case is in the ignore
+ * list.
+ * @param string $class Class name to test.
+ * @return boolean True if should not be run.
+ * @access public
+ * @static
+ */
+ function isIgnored($class) {
+ $registry =SimpleTestOptions::_getRegistry();
+ return in_array(strtolower($class), $registry['IgnoreList']);
+ }
+
+ /**
+ * The base class name is settable here. This is the
+ * class that a new stub will inherited from.
+ * To modify the generated stubs simply extend the
+ * SimpleStub class and set it's name
+ * with this method before any stubs are generated.
+ * @param string $stub_base Server stub class to use.
+ * @static
+ * @access public
+ */
+ function setStubBaseClass($stub_base) {
+ $registry =SimpleTestOptions::_getRegistry();
+ $registry['StubBaseClass'] = $stub_base;
+ }
+
+ /**
+ * Accessor for the currently set stub base class.
+ * @return string Class name to inherit from.
+ * @static
+ * @access public
+ */
+ function getStubBaseClass() {
+ $registry =SimpleTestOptions::_getRegistry();
+ return $registry['StubBaseClass'];
+ }
+
+ /**
+ * The base class name is settable here. This is the
+ * class that a new mock will inherited from.
+ * To modify the generated mocks simply extend the
+ * SimpleMock class and set it's name
+ * with this method before any mocks are generated.
+ * @param string $mock_base Mock base class to use.
+ * @static
+ * @access public
+ */
+ function setMockBaseClass($mock_base) {
+ $registry =SimpleTestOptions::_getRegistry();
+ $registry['MockBaseClass'] = $mock_base;
+ }
+
+ /**
+ * Accessor for the currently set mock base class.
+ * @return string Class name to inherit from.
+ * @static
+ * @access public
+ */
+ function getMockBaseClass() {
+ $registry =SimpleTestOptions::_getRegistry();
+ return $registry['MockBaseClass'];
+ }
+
+ /**
+ * Adds additional mock code.
+ * @param string $code Extra code that can be added
+ * to the partial mocks for
+ * extra functionality. Useful
+ * when a test tool has overridden
+ * the mock base classes.
+ * @access public
+ */
+ function addPartialMockCode($code = '') {
+ $registry =SimpleTestOptions::_getRegistry();
+ $registry['AdditionalPartialMockCode'] = $code;
+ }
+
+ /**
+ * Accessor for additional partial mock code.
+ * @return string Extra code.
+ * @access public
+ */
+ function getPartialMockCode() {
+ $registry =SimpleTestOptions::_getRegistry();
+ return $registry['AdditionalPartialMockCode'];
+ }
+
+ /**
+ * 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 =SimpleTestOptions::_getRegistry();
+ $registry['DefaultProxy'] = $proxy;
+ $registry['DefaultProxyUsername'] = $username;
+ $registry['DefaultProxyPassword'] = $password;
+ }
+
+ /**
+ * Accessor for default proxy host.
+ * @return string Proxy URL.
+ * @access public
+ */
+ function getDefaultProxy() {
+ $registry =SimpleTestOptions::_getRegistry();
+ return $registry['DefaultProxy'];
+ }
+
+ /**
+ * Accessor for default proxy username.
+ * @return string Proxy username for authentication.
+ * @access public
+ */
+ function getDefaultProxyUsername() {
+ $registry =SimpleTestOptions::_getRegistry();
+ return $registry['DefaultProxyUsername'];
+ }
+
+ /**
+ * Accessor for default proxy password.
+ * @return string Proxy password for authentication.
+ * @access public
+ */
+ function getDefaultProxyPassword() {
+ $registry =SimpleTestOptions::_getRegistry();
+ return $registry['DefaultProxyPassword'];
+ }
+
+ /**
+ * Accessor for global registry of options.
+ * @return hash All stored values.
+ * @access private
+ * @static
+ */
+ function _getRegistry() {
+ static $registry = false;
+ if (! $registry) {
+ $registry = SimpleTestOptions::_getDefaults();
+ }
+ return $registry;
+ }
+
+ /**
+ * Constant default values.
+ * @return hash All registry defaults.
+ * @access private
+ * @static
+ */
+ function _getDefaults() {
+ return array(
+ 'StubBaseClass' => 'SimpleStub',
+ 'MockBaseClass' => 'SimpleMock',
+ 'IgnoreList' => array(),
+ 'AdditionalPartialMockCode' => '',
+ 'DefaultProxy' => false,
+ 'DefaultProxyUsername' => false,
+ 'DefaultProxyPassword' => false);
+ }
+ }
+
+ /**
+ * Static methods for compatibility between different
+ * PHP versions.
+ * @package SimpleTest
+ */
+ class SimpleTestCompatibility {
+
+ /**
+ * Identity test. Drops back to equality + types for PHP5
+ * objects as the === operator counts as the
+ * stronger reference constraint.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access public
+ * @static
+ */
+ function isIdentical($first, $second) {
+ if ($first != $second) {
+ return false;
+ }
+ if (version_compare(phpversion(), '5') >= 0) {
+ return SimpleTestCompatibility::_isIdenticalType($first, $second);
+ }
+ return ($first === $second);
+ }
+
+ /**
+ * Recursive type test.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access private
+ * @static
+ */
+ function _isIdenticalType($first, $second) {
+ if (gettype($first) != gettype($second)) {
+ return false;
+ }
+ if (is_object($first) && is_object($second)) {
+ if (get_class($first) != get_class($second)) {
+ return false;
+ }
+ return SimpleTestCompatibility::_isArrayOfIdenticalTypes(
+ get_object_vars($first),
+ get_object_vars($second));
+ }
+ if (is_array($first) && is_array($second)) {
+ return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second);
+ }
+ return true;
+ }
+
+ /**
+ * Recursive type test for each element of an array.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access private
+ * @static
+ */
+ function _isArrayOfIdenticalTypes($first, $second) {
+ if (array_keys($first) != array_keys($second)) {
+ return false;
+ }
+ foreach (array_keys($first) as $key) {
+ $is_identical = SimpleTestCompatibility::_isIdenticalType(
+ $first[$key],
+ $second[$key]);
+ if (! $is_identical) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Test for two variables being aliases.
+ * @param mixed $first Test subject.
+ * @param mixed $second Comparison object.
+ * @access public
+ * @static
+ */
+ function isReference($first, $second) {
+ if (version_compare(phpversion(), '5', '>=')
+ && is_object($first)) {
+ return ($first === $second);
+ }
+ $temp = $first;
+ $first = uniqid("test");
+ $is_ref = ($first === $second);
+ $first = $temp;
+ return $is_ref;
+ }
+
+ /**
+ * Test to see if an object is a member of a
+ * class hiearchy.
+ * @param object $object Object to test.
+ * @param string $class Root name of hiearchy.
+ * @access public
+ * @static
+ */
+ function isA($object, $class) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ if (! class_exists($class, false)) {
+ return false;
+ }
+ eval("\$is_a = \$object instanceof $class;");
+ return $is_a;
+ }
+ if (function_exists('is_a')) {
+ return is_a($object, $class);
+ }
+ return ((strtolower($class) == get_class($object))
+ or (is_subclass_of($object, $class)));
+ }
+
+ /**
+ * Autoload safe version of class_exists().
+ * @param string $class Name of class to look for.
+ * @return boolean True if class is defined.
+ * @access public
+ * @static
+ */
+ function classExists($class) {
+ if (version_compare(phpversion(), '5') >= 0) {
+ return class_exists($class, false);
+ } else {
+ return class_exists($class);
+ }
+ }
+
+ /**
+ * Sets a socket timeout for each chunk.
+ * @param resource $handle Socket handle.
+ * @param integer $timeout Limit in seconds.
+ * @access public
+ * @static
+ */
+ function setTimeout($handle, $timeout) {
+ if (function_exists('stream_set_timeout')) {
+ stream_set_timeout($handle, $timeout, 0);
+ } elseif (function_exists('socket_set_timeout')) {
+ socket_set_timeout($handle, $timeout, 0);
+ } elseif (function_exists('set_socket_timeout')) {
+ set_socket_timeout($handle, $timeout, 0);
+ }
+ }
+
+ /**
+ * Gets the current stack trace topmost first.
+ * @return array List of stack frames.
+ * @access public
+ * @static
+ */
+ function getStackTrace() {
+ if (function_exists('debug_backtrace')) {
+ return array_reverse(debug_backtrace());
+ }
+ return array();
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/page.php b/tests/test_tools/simpletest/page.php
new file mode 100644
index 00000000..843dedf5
--- /dev/null
+++ b/tests/test_tools/simpletest/page.php
@@ -0,0 +1,961 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: page.php,v 1.105 2005/02/04 05:32:16 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/http.php');
+ require_once(dirname(__FILE__) . '/parser.php');
+ require_once(dirname(__FILE__) . '/tag.php');
+ require_once(dirname(__FILE__) . '/form.php');
+ /**#@-*/
+
+ /**
+ * SAX event handler. Maintains a list of
+ * open tags and dispatches them as they close.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimplePageBuilder extends SimpleSaxListener {
+ protected $_tags;
+ protected $_page;
+
+ /**
+ * Sets the builder up empty.
+ * @access public
+ */
+ function SimplePageBuilder() {
+ $this->SimpleSaxListener();
+ }
+
+ /**
+ * Reads the raw content and send events
+ * into the page to be built.
+ * @param $response SimpleHttpResponse Fetched response.
+ * @return SimplePage Newly parsed page.
+ * @access public
+ */
+ function parse($response) {
+ $this->_tags = array();
+ $this->_page = $this->_createPage($response);
+ $parser = $this->_createParser($this);
+ $parser->parse($response->getContent());
+ $this->_page->acceptPageEnd();
+ return $this->_page;
+ }
+
+ /**
+ * Creates an empty page.
+ * @return SimplePage New unparsed page.
+ * @access protected
+ */
+ function _createPage($response) {
+ return new SimplePage($response);
+ }
+
+ /**
+ * Creates the parser used with the builder.
+ * @param $listener SimpleSaxListener Target of parser.
+ * @return SimpleSaxParser Parser to generate
+ * events for the builder.
+ * @access protected
+ */
+ function _createParser($listener) {
+ return new SimpleSaxParser($listener);
+ }
+
+ /**
+ * Make the keys lower case for case insensitive look-ups.
+ * @param hash $map Hash to convert.
+ * @return hash Unchanged values, but keys lower case.
+ * @access private
+ */
+ function _keysToLowerCase($map) {
+ $lower = array();
+ foreach ($map as $key => $value) {
+ $lower[strtolower($key)] = $value;
+ }
+ return $lower;
+ }
+
+ /**
+ * Start of element event. Opens a new tag.
+ * @param string $name Element name.
+ * @param hash $attributes Attributes without content
+ * are marked as true.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function startElement($name, $attributes) {
+ $tag = $this->_createTag($name, $this->_keysToLowerCase($attributes));
+ if ($name == 'form') {
+ $this->_page->acceptFormStart($tag);
+ return true;
+ }
+ if ($name == 'frameset') {
+ $this->_page->acceptFramesetStart($tag);
+ return true;
+ }
+ if ($name == 'frame') {
+ $this->_page->acceptFrame($tag);
+ return true;
+ }
+ if ($tag->expectEndTag()) {
+ $this->_openTag($tag);
+ return true;
+ }
+ $this->_page->acceptTag($tag);
+ return true;
+ }
+
+ /**
+ * End of element event.
+ * @param string $name Element name.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function endElement($name) {
+ if ($name == 'form') {
+ $this->_page->acceptFormEnd();
+ return true;
+ }
+ if ($name == 'frameset') {
+ $this->_page->acceptFramesetEnd();
+ return true;
+ }
+ if (isset($this->_tags[$name]) && (count($this->_tags[$name]) > 0)) {
+ $tag = array_pop($this->_tags[$name]);
+ $this->_addContentTagToOpenTags($tag);
+ $this->_page->acceptTag($tag);
+ return true;
+ }
+ return true;
+ }
+
+ /**
+ * Unparsed, but relevant data. The data is added
+ * to every open tag.
+ * @param string $text May include unparsed tags.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function addContent($text) {
+ foreach (array_keys($this->_tags) as $name) {
+ for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
+ $this->_tags[$name][$i]->addContent($text);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Parsed relevant data. The parsed tag is added
+ * to every open tag.
+ * @param SimpleTag $tag May include unparsed tags.
+ * @access private
+ */
+ function _addContentTagToOpenTags($tag) {
+ if ($tag->getTagName() != 'option') {
+ return;
+ }
+ foreach (array_keys($this->_tags) as $name) {
+ for ($i = 0, $count = count($this->_tags[$name]); $i < $count; $i++) {
+ $this->_tags[$name][$i]->addTag($tag);
+ }
+ }
+ }
+
+ /**
+ * Opens a tag for receiving content. Multiple tags
+ * will be receiving input at the same time.
+ * @param SimpleTag $tag New content tag.
+ * @access private
+ */
+ function _openTag($tag) {
+ $name = $tag->getTagName();
+ if (! in_array($name, array_keys($this->_tags))) {
+ $this->_tags[$name] = array();
+ }
+ array_push($this->_tags[$name], $tag);
+ }
+
+ /**
+ * Factory for the tag objects. Creates the
+ * appropriate tag object for the incoming tag name.
+ * @param string $name HTML tag name.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createTag($name, $attributes) {
+ if ($name == 'a') {
+ return new SimpleAnchorTag($attributes);
+ } elseif ($name == 'title') {
+ return new SimpleTitleTag($attributes);
+ } elseif ($name == 'input') {
+ return $this->_createInputTag($attributes);
+ } elseif ($name == 'button') {
+ return new SimpleButtonTag($attributes);
+ } elseif ($name == 'textarea') {
+ return new SimpleTextAreaTag($attributes);
+ } elseif ($name == 'select') {
+ return $this->_createSelectionTag($attributes);
+ } elseif ($name == 'option') {
+ return new SimpleOptionTag($attributes);
+ } elseif ($name == 'form') {
+ return new SimpleFormTag($attributes);
+ } elseif ($name == 'frame') {
+ return new SimpleFrameTag($attributes);
+ }
+ return new SimpleTag($name, $attributes);
+ }
+
+ /**
+ * Factory for selection fields.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createSelectionTag($attributes) {
+ if (isset($attributes['multiple'])) {
+ return new MultipleSelectionTag($attributes);
+ }
+ return new SimpleSelectionTag($attributes);
+ }
+
+ /**
+ * Factory for input tags.
+ * @param hash $attributes Element attributes.
+ * @return SimpleTag Tag object.
+ * @access protected
+ */
+ function _createInputTag($attributes) {
+ if (! isset($attributes['type'])) {
+ return new SimpleTextTag($attributes);
+ }
+ $type = strtolower($attributes['type']);
+ if ($type == 'submit') {
+ return new SimpleSubmitTag($attributes);
+ } elseif ($type == 'image') {
+ return new SimpleImageSubmitTag($attributes);
+ } elseif ($type == 'checkbox') {
+ return new SimpleCheckboxTag($attributes);
+ } elseif ($type == 'radio') {
+ return new SimpleRadioButtonTag($attributes);
+ } else {
+ return new SimpleTextTag($attributes);
+ }
+ }
+ }
+
+ /**
+ * A wrapper for a web page.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimplePage {
+ protected $_links;
+ protected $_title;
+ protected $_open_forms;
+ protected $_complete_forms;
+ protected $_frameset;
+ protected $_frames;
+ protected $_frameset_nesting_level;
+ protected $_transport_error;
+ protected $_raw;
+ protected $_text;
+ protected $_sent;
+ protected $_headers;
+ protected $_method;
+ protected $_url;
+ protected $_request_data;
+
+ /**
+ * Parses a page ready to access it's contents.
+ * @param SimpleHttpResponse $response Result of HTTP fetch.
+ * @access public
+ */
+ function SimplePage($response = false) {
+ $this->_links = array();
+ $this->_title = false;
+ $this->_open_forms = array();
+ $this->_complete_forms = array();
+ $this->_frameset = false;
+ $this->_frames = array();
+ $this->_frameset_nesting_level = 0;
+ $this->_text = false;
+ if ($response) {
+ $this->_extractResponse($response);
+ } else {
+ $this->_noResponse();
+ }
+ }
+
+ /**
+ * Extracts all of the response information.
+ * @param SimpleHttpResponse $response Response being parsed.
+ * @access private
+ */
+ function _extractResponse($response) {
+ $this->_transport_error = $response->getError();
+ $this->_raw = $response->getContent();
+ $this->_sent = $response->getSent();
+ $this->_headers = $response->getHeaders();
+ $this->_method = $response->getMethod();
+ $this->_url = $response->getUrl();
+ $this->_request_data = $response->getRequestData();
+ }
+
+ /**
+ * Sets up a missing response.
+ * @access private
+ */
+ function _noResponse() {
+ $this->_transport_error = 'No page fetched yet';
+ $this->_raw = false;
+ $this->_sent = false;
+ $this->_headers = false;
+ $this->_method = 'GET';
+ $this->_url = false;
+ $this->_request_data = false;
+ }
+
+ /**
+ * Original request as bytes sent down the wire.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequest() {
+ return $this->_sent;
+ }
+
+ /**
+ * Accessor for raw text of page.
+ * @return string Raw unparsed content.
+ * @access public
+ */
+ function getRaw() {
+ return $this->_raw;
+ }
+
+ /**
+ * Accessor for plain text of page as a text browser
+ * would see it.
+ * @return string Plain text of page.
+ * @access public
+ */
+ function getText() {
+ if (! $this->_text) {
+ $this->_text = SimpleSaxParser::normalise($this->_raw);
+ }
+ return $this->_text;
+ }
+
+ /**
+ * Accessor for raw headers of page.
+ * @return string Header block as text.
+ * @access public
+ */
+ function getHeaders() {
+ if ($this->_headers) {
+ return $this->_headers->getRaw();
+ }
+ return false;
+ }
+
+ /**
+ * Original request method.
+ * @return string GET, POST or HEAD.
+ * @access public
+ */
+ function getMethod() {
+ return $this->_method;
+ }
+
+ /**
+ * Original resource name.
+ * @return SimpleUrl Current url.
+ * @access public
+ */
+ function getUrl() {
+ return $this->_url;
+ }
+
+ /**
+ * Original request data.
+ * @return mixed Sent content.
+ * @access public
+ */
+ function getRequestData() {
+ return $this->_request_data;
+ }
+
+ /**
+ * Accessor for last error.
+ * @return string Error from last response.
+ * @access public
+ */
+ function getTransportError() {
+ return $this->_transport_error;
+ }
+
+ /**
+ * Accessor for current MIME type.
+ * @return string MIME type as string; e.g. 'text/html'
+ * @access public
+ */
+ function getMimeType() {
+ if ($this->_headers) {
+ return $this->_headers->getMimeType();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for HTTP response code.
+ * @return integer HTTP response code received.
+ * @access public
+ */
+ function getResponseCode() {
+ if ($this->_headers) {
+ return $this->_headers->getResponseCode();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for last Authentication type. Only valid
+ * straight after a challenge (401).
+ * @return string Description of challenge type.
+ * @access public
+ */
+ function getAuthentication() {
+ if ($this->_headers) {
+ return $this->_headers->getAuthentication();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for last Authentication realm. Only valid
+ * straight after a challenge (401).
+ * @return string Name of security realm.
+ * @access public
+ */
+ function getRealm() {
+ if ($this->_headers) {
+ return $this->_headers->getRealm();
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for current frame focus. Will be
+ * false as no frames.
+ * @return array Always empty.
+ * @access public
+ */
+ function getFrameFocus() {
+ return array();
+ }
+
+ /**
+ * Sets the focus by index. The integer index starts from 1.
+ * @param integer $choice Chosen frame.
+ * @return boolean Always false.
+ * @access public
+ */
+ function setFrameFocusByIndex($choice) {
+ return false;
+ }
+
+ /**
+ * Sets the focus by name. Always fails for a leaf page.
+ * @param string $name Chosen frame.
+ * @return boolean False as no frames.
+ * @access public
+ */
+ function setFrameFocus($name) {
+ return false;
+ }
+
+ /**
+ * Clears the frame focus. Does nothing for a leaf page.
+ * @access public
+ */
+ function clearFrameFocus() {
+ }
+
+ /**
+ * Adds a tag to the page.
+ * @param SimpleTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptTag($tag) {
+ if ($tag->getTagName() == "a") {
+ $this->_addLink($tag);
+ } elseif ($tag->getTagName() == "title") {
+ $this->_setTitle($tag);
+ } elseif ($this->_isFormElement($tag->getTagName())) {
+ for ($i = 0; $i < count($this->_open_forms); $i++) {
+ $this->_open_forms[$i]->addWidget($tag);
+ }
+ }
+ }
+
+ /**
+ * Tests to see if a tag is a possible form
+ * element.
+ * @param string $name HTML element name.
+ * @return boolean True if form element.
+ * @access private
+ */
+ function _isFormElement($name) {
+ return in_array($name, array('input', 'button', 'textarea', 'select'));
+ }
+
+ /**
+ * Opens a form. New widgets go here.
+ * @param SimpleFormTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptFormStart($tag) {
+ $this->_open_forms[] = new SimpleForm($tag, $this->getUrl());
+ }
+
+ /**
+ * Closes the most recently opened form.
+ * @access public
+ */
+ function acceptFormEnd() {
+ if (count($this->_open_forms)) {
+ $this->_complete_forms[] = array_pop($this->_open_forms);
+ }
+ }
+
+ /**
+ * Opens a frameset. A frameset may contain nested
+ * frameset tags.
+ * @param SimpleFramesetTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptFramesetStart($tag) {
+ if (! $this->_isLoadingFrames()) {
+ $this->_frameset = $tag;
+ }
+ $this->_frameset_nesting_level++;
+ }
+
+ /**
+ * Closes the most recently opened frameset.
+ * @access public
+ */
+ function acceptFramesetEnd() {
+ if ($this->_isLoadingFrames()) {
+ $this->_frameset_nesting_level--;
+ }
+ }
+
+ /**
+ * Takes a single frame tag and stashes it in
+ * the current frame set.
+ * @param SimpleFrameTag $tag Tag to accept.
+ * @access public
+ */
+ function acceptFrame($tag) {
+ if ($this->_isLoadingFrames()) {
+ if ($tag->getAttribute('src')) {
+ $this->_frames[] = $tag;
+ }
+ }
+ }
+
+ /**
+ * Test to see if in the middle of reading
+ * a frameset.
+ * @return boolean True if inframeset.
+ * @access private
+ */
+ function _isLoadingFrames() {
+ if (! $this->_frameset) {
+ return false;
+ }
+ return ($this->_frameset_nesting_level > 0);
+ }
+
+ /**
+ * Test to see if link is an absolute one.
+ * @param string $url Url to test.
+ * @return boolean True if absolute.
+ * @access protected
+ */
+ function _linkIsAbsolute($url) {
+ $parsed = new SimpleUrl($url);
+ return (boolean)($parsed->getScheme() && $parsed->getHost());
+ }
+
+ /**
+ * Adds a link to the page.
+ * @param SimpleAnchorTag $tag Link to accept.
+ * @access protected
+ */
+ function _addLink($tag) {
+ $this->_links[] = $tag;
+ }
+
+ /**
+ * Marker for end of complete page. Any work in
+ * progress can now be closed.
+ * @access public
+ */
+ function acceptPageEnd() {
+ while (count($this->_open_forms)) {
+ $this->_complete_forms[] = array_pop($this->_open_forms);
+ }
+ }
+
+ /**
+ * Test for the presence of a frameset.
+ * @return boolean True if frameset.
+ * @access public
+ */
+ function hasFrames() {
+ return (boolean)$this->_frameset;
+ }
+
+ /**
+ * Accessor for frame name and source URL for every frame that
+ * will need to be loaded. Immediate children only.
+ * @return boolean/array False if no frameset or
+ * otherwise a hash of frame URLs.
+ * The key is either a numerical
+ * base one index or the name attribute.
+ * @access public
+ */
+ function getFrameset() {
+ if (! $this->_frameset) {
+ return false;
+ }
+ $urls = array();
+ for ($i = 0; $i < count($this->_frames); $i++) {
+ $name = $this->_frames[$i]->getAttribute('name');
+ $url = new SimpleUrl($this->_frames[$i]->getAttribute('src'));
+ $urls[$name ? $name : $i + 1] = $url->makeAbsolute($this->getUrl());
+ }
+ return $urls;
+ }
+
+ /**
+ * Fetches a list of loaded frames.
+ * @return array/string Just the URL for a single page.
+ * @access public
+ */
+ function getFrames() {
+ $url = $this->getUrl();
+ return $url->asString();
+ }
+
+ /**
+ * Accessor for a list of all fixed links.
+ * @return array List of urls with scheme of
+ * http or https and hostname.
+ * @access public
+ */
+ function getAbsoluteUrls() {
+ $all = array();
+ foreach ($this->_links as $link) {
+ if ($this->_linkIsAbsolute($link->getHref())) {
+ $all[] = $link->getHref();
+ }
+ }
+ return $all;
+ }
+
+ /**
+ * Accessor for a list of all relative links.
+ * @return array List of urls without hostname.
+ * @access public
+ */
+ function getRelativeUrls() {
+ $all = array();
+ foreach ($this->_links as $link) {
+ if (! $this->_linkIsAbsolute($link->getHref())) {
+ $all[] = $link->getHref();
+ }
+ }
+ return $all;
+ }
+
+ /**
+ * Accessor for URLs by the link label. Label will match
+ * regardess of whitespace issues and case.
+ * @param string $label Text of link.
+ * @return array List of links with that label.
+ * @access public
+ */
+ function getUrlsByLabel($label) {
+ $matches = array();
+ foreach ($this->_links as $link) {
+ if ($link->getText() == $label) {
+ $matches[] = $this->_getUrlFromLink($link);
+ }
+ }
+ return $matches;
+ }
+
+ /**
+ * Accessor for a URL by the id attribute.
+ * @param string $id Id attribute of link.
+ * @return SimpleUrl URL with that id of false if none.
+ * @access public
+ */
+ function getUrlById($id) {
+ foreach ($this->_links as $link) {
+ if ($link->getAttribute('id') === (string)$id) {
+ return $this->_getUrlFromLink($link);
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Converts a link into a target URL.
+ * @param SimpleAnchor $link Parsed link.
+ * @return SimpleUrl URL with frame target if any.
+ * @access private
+ */
+ function _getUrlFromLink($link) {
+ $url = $this->_makeAbsolute($link->getHref());
+ if ($link->getAttribute('target')) {
+ $url->setTarget($link->getAttribute('target'));
+ }
+ return $url;
+ }
+
+ /**
+ * Expands expandomatic URLs into fully qualified
+ * URLs.
+ * @param SimpleUrl $url Relative URL.
+ * @return SimpleUrl Absolute URL.
+ * @access protected
+ */
+ function _makeAbsolute($url) {
+ if (! is_object($url)) {
+ $url = new SimpleUrl($url);
+ }
+ return $url->makeAbsolute($this->getUrl());
+ }
+
+ /**
+ * Sets the title tag contents.
+ * @param SimpleTitleTag $tag Title of page.
+ * @access protected
+ */
+ function _setTitle($tag) {
+ $this->_title = $tag;
+ }
+
+ /**
+ * Accessor for parsed title.
+ * @return string Title or false if no title is present.
+ * @access public
+ */
+ function getTitle() {
+ if ($this->_title) {
+ return $this->_title->getText();
+ }
+ return false;
+ }
+
+ /**
+ * Finds a held form by button label. Will only
+ * search correctly built forms.
+ * @param string $label Button label, default 'Submit'.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitLabel($label) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasSubmitLabel($label)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by button label. Will only
+ * search correctly built forms.
+ * @param string $name Button name attribute.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitName($name) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasSubmitName($name)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by button id. Will only
+ * search correctly built forms.
+ * @param string $id Button ID attribute.
+ * @return SimpleForm Form object containing the button.
+ * @access public
+ */
+ function getFormBySubmitId($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasSubmitId($id)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image label. Will only
+ * search correctly built forms.
+ * @param string $label Usually the alt attribute.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageLabel($label) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasImageLabel($label)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image button id. Will only
+ * search correctly built forms.
+ * @param string $name Image name.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageName($name) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasImageName($name)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by image button id. Will only
+ * search correctly built forms.
+ * @param string $id Image ID attribute.
+ * @return SimpleForm Form object containing the image.
+ * @access public
+ */
+ function getFormByImageId($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->hasImageId($id)) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a held form by the form ID. A way of
+ * identifying a specific form when we have control
+ * of the HTML code.
+ * @param string $id Form label.
+ * @return SimpleForm Form object containing the matching ID.
+ * @access public
+ */
+ function getFormById($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->getId() == $id) {
+ return $this->_complete_forms[$i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Sets a field on each form in which the field is
+ * available.
+ * @param string $name Field name.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
+ * @access public
+ */
+ function setField($name, $value) {
+ $is_set = false;
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->setField($name, $value)) {
+ $is_set = true;
+ }
+ }
+ return $is_set;
+ }
+
+ /**
+ * Sets a field on the form in which the unique field is
+ * available.
+ * @param string/integer $id Field ID attribute.
+ * @param string $value Value to set field to.
+ * @return boolean True if value is valid.
+ * @access public
+ */
+ function setFieldById($id, $value) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ if ($this->_complete_forms[$i]->setFieldById($id, $value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for a form element value within a page.
+ * Finds the first match.
+ * @param string $name Field name.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getField($name) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ $value = $this->_complete_forms[$i]->getValue($name);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Accessor for a form element value within a page.
+ * Finds the first match.
+ * @param string/integer $id Field ID attribute.
+ * @return string/boolean A string if the field is
+ * present, false if unchecked
+ * and null if missing.
+ * @access public
+ */
+ function getFieldById($id) {
+ for ($i = 0; $i < count($this->_complete_forms); $i++) {
+ $value = $this->_complete_forms[$i]->getValueById($id);
+ if (isset($value)) {
+ return $value;
+ }
+ }
+ return null;
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/parser.php b/tests/test_tools/simpletest/parser.php
new file mode 100644
index 00000000..7dc56a58
--- /dev/null
+++ b/tests/test_tools/simpletest/parser.php
@@ -0,0 +1,750 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage MockObjects
+ * @version $Id: parser.php,v 1.66 2005/02/06 04:03:27 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);
+ /**#@-*/
+
+ /**
+ * Compounded regular expression. Any of
+ * the contained patterns could match and
+ * when one does it's label is returned.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class ParallelRegex {
+ protected $_patterns;
+ protected $_labels;
+ protected $_regex;
+ protected $_case;
+
+ /**
+ * Constructor. Starts with no patterns.
+ * @param boolean $case True for case sensitive, false
+ * for insensitive.
+ * @access public
+ */
+ function ParallelRegex($case) {
+ $this->_case = $case;
+ $this->_patterns = array();
+ $this->_labels = array();
+ $this->_regex = null;
+ }
+
+ /**
+ * Adds a pattern with an optional label.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $label Label of regex to be returned
+ * on a match.
+ * @access public
+ */
+ function addPattern($pattern, $label = true) {
+ $count = count($this->_patterns);
+ $this->_patterns[$count] = $pattern;
+ $this->_labels[$count] = $label;
+ $this->_regex = null;
+ }
+
+ /**
+ * Attempts to match all patterns at once against
+ * a string.
+ * @param string $subject String to match against.
+ * @param string $match First matched portion of
+ * subject.
+ * @return boolean True on success.
+ * @access public
+ */
+ function match($subject, $match) {
+ if (count($this->_patterns) == 0) {
+ return false;
+ }
+ if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) {
+ $match = '';
+ return false;
+ }
+ $match = $matches[0];
+ for ($i = 1; $i < count($matches); $i++) {
+ if ($matches[$i]) {
+ return $this->_labels[$i - 1];
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Compounds the patterns into a single
+ * regular expression separated with the
+ * "or" operator. Caches the regex.
+ * Will automatically escape (, ) and / tokens.
+ * @param array $patterns List of patterns in order.
+ * @access private
+ */
+ function _getCompoundedRegex() {
+ if ($this->_regex == null) {
+ for ($i = 0, $count = count($this->_patterns); $i < $count; $i++) {
+ $this->_patterns[$i] = '(' . str_replace(
+ array('/', '(', ')'),
+ array('\/', '\(', '\)'),
+ $this->_patterns[$i]) . ')';
+ }
+ $this->_regex = "/" . implode("|", $this->_patterns) . "/" . $this->_getPerlMatchingFlags();
+ }
+ return $this->_regex;
+ }
+
+ /**
+ * Accessor for perl regex mode flags to use.
+ * @return string Perl regex flags.
+ * @access private
+ */
+ function _getPerlMatchingFlags() {
+ return ($this->_case ? "msS" : "msSi");
+ }
+ }
+
+ /**
+ * States for a stack machine.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleStateStack {
+ protected $_stack;
+
+ /**
+ * Constructor. Starts in named state.
+ * @param string $start Starting state name.
+ * @access public
+ */
+ function SimpleStateStack($start) {
+ $this->_stack = array($start);
+ }
+
+ /**
+ * Accessor for current state.
+ * @return string State.
+ * @access public
+ */
+ function getCurrent() {
+ return $this->_stack[count($this->_stack) - 1];
+ }
+
+ /**
+ * Adds a state to the stack and sets it
+ * to be the current state.
+ * @param string $state New state.
+ * @access public
+ */
+ function enter($state) {
+ array_push($this->_stack, $state);
+ }
+
+ /**
+ * Leaves the current state and reverts
+ * to the previous one.
+ * @return boolean False if we drop off
+ * the bottom of the list.
+ * @access public
+ */
+ function leave() {
+ if (count($this->_stack) == 1) {
+ return false;
+ }
+ array_pop($this->_stack);
+ return true;
+ }
+ }
+
+ /**
+ * Accepts text and breaks it into tokens.
+ * Some optimisation to make the sure the
+ * content is only scanned by the PHP regex
+ * parser once. Lexer modes must not start
+ * with leading underscores.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleLexer {
+ protected $_regexes;
+ protected $_parser;
+ protected $_mode;
+ protected $_mode_handlers;
+ protected $_case;
+
+ /**
+ * Sets up the lexer in case insensitive matching
+ * by default.
+ * @param SimpleSaxParser $parser Handling strategy by
+ * reference.
+ * @param string $start Starting handler.
+ * @param boolean $case True for case sensitive.
+ * @access public
+ */
+ function SimpleLexer($parser, $start = "accept", $case = false) {
+ $this->_case = $case;
+ $this->_regexes = array();
+ $this->_parser = $parser;
+ $this->_mode = new SimpleStateStack($start);
+ $this->_mode_handlers = array($start => $start);
+ }
+
+ /**
+ * Adds a token search pattern for a particular
+ * parsing mode. The pattern does not change the
+ * current mode.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Should only apply this
+ * pattern when dealing with
+ * this type of input.
+ * @access public
+ */
+ function addPattern($pattern, $mode = "accept") {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern);
+ if (! isset($this->_mode_handlers[$mode])) {
+ $this->_mode_handlers[$mode] = $mode;
+ }
+ }
+
+ /**
+ * Adds a pattern that will enter a new parsing
+ * mode. Useful for entering parenthesis, strings,
+ * tags, etc.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Should only apply this
+ * pattern when dealing with
+ * this type of input.
+ * @param string $new_mode Change parsing to this new
+ * nested mode.
+ * @access public
+ */
+ function addEntryPattern($pattern, $mode, $new_mode) {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern, $new_mode);
+ if (! isset($this->_mode_handlers[$new_mode])) {
+ $this->_mode_handlers[$new_mode] = $new_mode;
+ }
+ }
+
+ /**
+ * Adds a pattern that will exit the current mode
+ * and re-enter the previous one.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Mode to leave.
+ * @access public
+ */
+ function addExitPattern($pattern, $mode) {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern, "__exit");
+ if (! isset($this->_mode_handlers[$mode])) {
+ $this->_mode_handlers[$mode] = $mode;
+ }
+ }
+
+ /**
+ * Adds a pattern that has a special mode. Acts as an entry
+ * and exit pattern in one go, effectively calling a special
+ * parser handler for this token only.
+ * @param string $pattern Perl style regex, but ( and )
+ * lose the usual meaning.
+ * @param string $mode Should only apply this
+ * pattern when dealing with
+ * this type of input.
+ * @param string $special Use this mode for this one token.
+ * @access public
+ */
+ function addSpecialPattern($pattern, $mode, $special) {
+ if (! isset($this->_regexes[$mode])) {
+ $this->_regexes[$mode] = new ParallelRegex($this->_case);
+ }
+ $this->_regexes[$mode]->addPattern($pattern, "_$special");
+ if (! isset($this->_mode_handlers[$special])) {
+ $this->_mode_handlers[$special] = $special;
+ }
+ }
+
+ /**
+ * Adds a mapping from a mode to another handler.
+ * @param string $mode Mode to be remapped.
+ * @param string $handler New target handler.
+ * @access public
+ */
+ function mapHandler($mode, $handler) {
+ $this->_mode_handlers[$mode] = $handler;
+ }
+
+ /**
+ * Splits the page text into tokens. Will fail
+ * if the handlers report an error or if no
+ * content is consumed. If successful then each
+ * unparsed and parsed token invokes a call to the
+ * held listener.
+ * @param string $raw Raw HTML text.
+ * @return boolean True on success, else false.
+ * @access public
+ */
+ function parse($raw) {
+ if (! isset($this->_parser)) {
+ return false;
+ }
+ $length = strlen($raw);
+ while (is_array($parsed = $this->_reduce($raw))) {
+ list($raw, $unmatched, $matched, $mode) = $parsed;
+ if (! $this->_dispatchTokens($unmatched, $matched, $mode)) {
+ return false;
+ }
+ if ($raw === '') {
+ return true;
+ }
+ if (strlen($raw) == $length) {
+ return false;
+ }
+ $length = strlen($raw);
+ }
+ if (! $parsed) {
+ return false;
+ }
+ return $this->_invokeParser($raw, LEXER_UNMATCHED);
+ }
+
+ /**
+ * Sends the matched token and any leading unmatched
+ * text to the parser changing the lexer to a new
+ * mode if one is listed.
+ * @param string $unmatched Unmatched leading portion.
+ * @param string $matched Actual token match.
+ * @param string $mode Mode after match. A boolean
+ * false mode causes no change.
+ * @return boolean False if there was any error
+ * from the parser.
+ * @access private
+ */
+ function _dispatchTokens($unmatched, $matched, $mode = false) {
+ if (! $this->_invokeParser($unmatched, LEXER_UNMATCHED)) {
+ return false;
+ }
+ if (is_bool($mode)) {
+ return $this->_invokeParser($matched, LEXER_MATCHED);
+ }
+ if ($this->_isModeEnd($mode)) {
+ if (! $this->_invokeParser($matched, LEXER_EXIT)) {
+ return false;
+ }
+ return $this->_mode->leave();
+ }
+ if ($this->_isSpecialMode($mode)) {
+ $this->_mode->enter($this->_decodeSpecial($mode));
+ if (! $this->_invokeParser($matched, LEXER_SPECIAL)) {
+ return false;
+ }
+ return $this->_mode->leave();
+ }
+ $this->_mode->enter($mode);
+ return $this->_invokeParser($matched, LEXER_ENTER);
+ }
+
+ /**
+ * Tests to see if the new mode is actually to leave
+ * the current mode and pop an item from the matching
+ * mode stack.
+ * @param string $mode Mode to test.
+ * @return boolean True if this is the exit mode.
+ * @access private
+ */
+ function _isModeEnd($mode) {
+ return ($mode === "__exit");
+ }
+
+ /**
+ * Test to see if the mode is one where this mode
+ * is entered for this token only and automatically
+ * leaves immediately afterwoods.
+ * @param string $mode Mode to test.
+ * @return boolean True if this is the exit mode.
+ * @access private
+ */
+ function _isSpecialMode($mode) {
+ return (strncmp($mode, "_", 1) == 0);
+ }
+
+ /**
+ * Strips the magic underscore marking single token
+ * modes.
+ * @param string $mode Mode to decode.
+ * @return string Underlying mode name.
+ * @access private
+ */
+ function _decodeSpecial($mode) {
+ return substr($mode, 1);
+ }
+
+ /**
+ * Calls the parser method named after the current
+ * mode. Empty content will be ignored. The lexer
+ * has a parser handler for each mode in the lexer.
+ * @param string $content Text parsed.
+ * @param boolean $is_match Token is recognised rather
+ * than unparsed data.
+ * @access private
+ */
+ function _invokeParser($content, $is_match) {
+ if (($content === '') || ($content === false)) {
+ return true;
+ }
+ $handler = $this->_mode_handlers[$this->_mode->getCurrent()];
+ return $this->_parser->$handler($content, $is_match);
+ }
+
+ /**
+ * Tries to match a chunk of text and if successful
+ * removes the recognised chunk and any leading
+ * unparsed data. Empty strings will not be matched.
+ * @param string $raw The subject to parse. This is the
+ * content that will be eaten.
+ * @return array/boolean Three item list of unparsed
+ * content followed by the
+ * recognised token and finally the
+ * action the parser is to take.
+ * True if no match, false if there
+ * is a parsing error.
+ * @access private
+ */
+ function _reduce($raw) {
+ if ($action = $this->_regexes[$this->_mode->getCurrent()]->match($raw, $match)) {
+ $unparsed_character_count = strpos($raw, $match);
+ $unparsed = substr($raw, 0, $unparsed_character_count);
+ $raw = substr($raw, $unparsed_character_count + strlen($match));
+ return array($raw, $unparsed, $match, $action);
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Converts HTML tokens into selected SAX events.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleSaxParser {
+ protected $_lexer;
+ protected $_listener;
+ protected $_tag;
+ protected $_attributes;
+ protected $_current_attribute;
+
+ /**
+ * Sets the listener.
+ * @param SimpleSaxListener $listener SAX event handler.
+ * @access public
+ */
+ function SimpleSaxParser($listener) {
+ $this->_listener = $listener;
+ $this->_lexer = $this->createLexer($this);
+ $this->_tag = '';
+ $this->_attributes = array();
+ $this->_current_attribute = '';
+ }
+
+ /**
+ * Runs the content through the lexer which
+ * should call back to the acceptors.
+ * @param string $raw Page text to parse.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function parse($raw) {
+ return $this->_lexer->parse($raw);
+ }
+
+ /**
+ * Sets up the matching lexer. Starts in 'text' mode.
+ * @param SimpleSaxParser $parser Event generator, usually $self.
+ * @return SimpleLexer Lexer suitable for this parser.
+ * @access public
+ * @static
+ */
+ function createLexer($parser) {
+ $lexer = new SimpleLexer($parser, 'text');
+ $lexer->mapHandler('text', 'acceptTextToken');
+ SimpleSaxParser::_addSkipping($lexer);
+ foreach (SimpleSaxParser::_getParsedTags() as $tag) {
+ SimpleSaxParser::_addTag($lexer, $tag);
+ }
+ SimpleSaxParser::_addInTagTokens($lexer);
+ return $lexer;
+ }
+
+ /**
+ * List of parsed tags. Others are ignored.
+ * @return array List of searched for tags.
+ * @access private
+ */
+ function _getParsedTags() {
+ return array('a', 'title', 'form', 'input', 'button', 'textarea', 'select',
+ 'option', 'frameset', 'frame');
+ }
+
+ /**
+ * The lexer has to skip certain sections such
+ * as server code, client code and styles.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @access private
+ * @static
+ */
+ function _addSkipping($lexer) {
+ $lexer->mapHandler('css', 'ignore');
+ $lexer->addEntryPattern('<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');
+ }
+
+ /**
+ * 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');
+ }
+
+ /**
+ * Pattern matches to parse the inside of a tag
+ * including the attributes and their quoting.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @access private
+ * @static
+ */
+ function _addInTagTokens($lexer) {
+ $lexer->mapHandler('tag', 'acceptStartToken');
+ $lexer->addSpecialPattern('\s+', 'tag', 'ignore');
+ SimpleSaxParser::_addAttributeTokens($lexer);
+ $lexer->addExitPattern('>', 'tag');
+ }
+
+ /**
+ * Matches attributes that are either single quoted,
+ * double quoted or unquoted.
+ * @param SimpleLexer $lexer Lexer to add patterns to.
+ * @access private
+ * @static
+ */
+ function _addAttributeTokens($lexer) {
+ $lexer->mapHandler('dq_attribute', 'acceptAttributeToken');
+ $lexer->addEntryPattern('=\s*"', 'tag', 'dq_attribute');
+ $lexer->addPattern("\\\\\"", 'dq_attribute');
+ $lexer->addExitPattern('"', 'dq_attribute');
+ $lexer->mapHandler('sq_attribute', 'acceptAttributeToken');
+ $lexer->addEntryPattern("=\s*'", 'tag', 'sq_attribute');
+ $lexer->addPattern("\\\\'", 'sq_attribute');
+ $lexer->addExitPattern("'", 'sq_attribute');
+ $lexer->mapHandler('uq_attribute', 'acceptAttributeToken');
+ $lexer->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute');
+ }
+
+ /**
+ * Accepts a token from the tag mode. If the
+ * starting element completes then the element
+ * is dispatched and the current attributes
+ * set back to empty. The element or attribute
+ * name is converted to lower case.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptStartToken($token, $event) {
+ if ($event == LEXER_ENTER) {
+ $this->_tag = strtolower(substr($token, 1));
+ return true;
+ }
+ if ($event == LEXER_EXIT) {
+ $success = $this->_listener->startElement(
+ $this->_tag,
+ $this->_attributes);
+ $this->_tag = "";
+ $this->_attributes = array();
+ return $success;
+ }
+ if ($token != "=") {
+ $this->_current_attribute = strtolower(SimpleSaxParser::decodeHtml($token));
+ $this->_attributes[$this->_current_attribute] = "";
+ }
+ return true;
+ }
+
+ /**
+ * Accepts a token from the end tag mode.
+ * The element name is converted to lower case.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptEndToken($token, $event) {
+ if (! preg_match('/<\/(.*)>/', $token, $matches)) {
+ return false;
+ }
+ return $this->_listener->endElement(strtolower($matches[1]));
+ }
+
+ /**
+ * Part of the tag data.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptAttributeToken($token, $event) {
+ if ($event == LEXER_UNMATCHED) {
+ $this->_attributes[$this->_current_attribute] .=
+ SimpleSaxParser::decodeHtml($token);
+ }
+ if ($event == LEXER_SPECIAL) {
+ $this->_attributes[$this->_current_attribute] .=
+ preg_replace('/^=\s*/' , '', SimpleSaxParser::decodeHtml($token));
+ }
+ return true;
+ }
+
+ /**
+ * A character entity.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptEntityToken($token, $event) {
+ }
+
+ /**
+ * Character data between tags regarded as
+ * important.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function acceptTextToken($token, $event) {
+ return $this->_listener->addContent($token);
+ }
+
+ /**
+ * Incoming data to be ignored.
+ * @param string $token Incoming characters.
+ * @param integer $event Lexer event type.
+ * @return boolean False if parse error.
+ * @access public
+ */
+ function ignore($token, $event) {
+ return true;
+ }
+
+ /**
+ * Decodes any HTML entities.
+ * @param string $html Incoming HTML.
+ * @return string Outgoing plain text.
+ * @access public
+ * @static
+ */
+ function decodeHtml($html) {
+ static $translations;
+ if (! isset($translations)) {
+ $translations = array_flip(get_html_translation_table(HTML_ENTITIES));
+ }
+ return strtr($html, $translations);
+ }
+
+ /**
+ * Turns HTML into text browser visible text. Images
+ * are converted to their alt text and tags are supressed.
+ * Entities are converted to their visible representation.
+ * @param string $html HTML to convert.
+ * @return string Plain text.
+ * @access public
+ * @static
+ */
+ function normalise($html) {
+ $text = preg_replace('|<img.*?alt\s*=\s*"(.*?)".*?>|', ' \1 ', $html);
+ $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 = preg_replace('|\s+|', ' ', $text);
+ return trim($text);
+ }
+ }
+
+ /**
+ * SAX event handler.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @abstract
+ */
+ class SimpleSaxListener {
+
+ /**
+ * Sets the document to write to.
+ * @access public
+ */
+ function SimpleSaxListener() {
+ }
+
+ /**
+ * Start of element event.
+ * @param string $name Element name.
+ * @param hash $attributes Name value pairs.
+ * Attributes without content
+ * are marked as true.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function startElement($name, $attributes) {
+ }
+
+ /**
+ * End of element event.
+ * @param string $name Element name.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function endElement($name) {
+ }
+
+ /**
+ * Unparsed, but relevant data.
+ * @param string $text May include unparsed tags.
+ * @return boolean False on parse error.
+ * @access public
+ */
+ function addContent($text) {
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/remote.php b/tests/test_tools/simpletest/remote.php
new file mode 100644
index 00000000..5a5f2d32
--- /dev/null
+++ b/tests/test_tools/simpletest/remote.php
@@ -0,0 +1,115 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: remote.php,v 1.11 2004/08/04 22:09:39 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/browser.php');
+ require_once(dirname(__FILE__) . '/xml.php');
+ require_once(dirname(__FILE__) . '/simple_test.php');
+ /**#@-*/
+
+ /**
+ * Runs an XML formated test on a remote server.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class RemoteTestCase {
+ protected $_url;
+ protected $_dry_url;
+ protected $_size;
+
+ /**
+ * Sets the location of the remote test.
+ * @param string $url Test location.
+ * @param string $dry_url Location for dry run.
+ * @access public
+ */
+ function RemoteTestCase($url, $dry_url = false) {
+ $this->_url = $url;
+ $this->_dry_url = $dry_url ? $dry_url : $url;
+ $this->_size = false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_url;
+ }
+
+ /**
+ * Runs the top level test for this class. Currently
+ * reads the data as a single chunk. I'll fix this
+ * once I have added iteration to the browser.
+ * @param SimpleReporter $reporter Target of test results.
+ * @returns boolean True if no failures.
+ * @access public
+ */
+ function run($reporter) {
+ $browser = $this->_createBrowser();
+ $xml = $browser->get($this->_url);
+ if (! $xml) {
+ trigger_error('Cannot read remote test URL [' . $this->_url . ']');
+ return false;
+ }
+ $parser = $this->_createParser($reporter);
+ if (! $parser->parse($xml)) {
+ trigger_error('Cannot parse incoming XML from [' . $this->_url . ']');
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Creates a new web browser object for fetching
+ * the XML report.
+ * @return SimpleBrowser New browser.
+ * @access protected
+ */
+ function _createBrowser() {
+ return new SimpleBrowser();
+ }
+
+ /**
+ * Creates the XML parser.
+ * @param SimpleReporter $reporter Target of test results.
+ * @return SimpleTestXmlListener XML reader.
+ * @access protected
+ */
+ function _createParser($reporter) {
+ return new SimpleTestXmlParser($reporter);
+ }
+
+ /**
+ * Accessor for the number of subtests.
+ * @return integer Number of test cases.
+ * @access public
+ */
+ function getSize() {
+ if ($this->_size === false) {
+ $browser = $this->_createBrowser();
+ $xml = $browser->get($this->_dry_url);
+ if (! $xml) {
+ trigger_error('Cannot read remote test URL [' . $this->_dry_url . ']');
+ return false;
+ }
+ $reporter = new SimpleReporter();
+ $parser = $this->_createParser($reporter);
+ if (! $parser->parse($xml)) {
+ trigger_error('Cannot parse incoming XML from [' . $this->_dry_url . ']');
+ return false;
+ }
+ $this->_size = $reporter->getTestCaseCount();
+ }
+ return $this->_size;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/reporter.php b/tests/test_tools/simpletest/reporter.php
new file mode 100644
index 00000000..32125c9b
--- /dev/null
+++ b/tests/test_tools/simpletest/reporter.php
@@ -0,0 +1,241 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: reporter.php,v 1.33 2004/11/29 04:35:49 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/scorer.php');
+ /**#@-*/
+
+ /**
+ * Sample minimal test displayer. Generates only
+ * failure messages and a pass count.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class HtmlReporter extends SimpleReporter {
+ protected $_character_set;
+
+ /**
+ * Does nothing yet. The first output will
+ * be sent on the first test start. For use
+ * by a web browser.
+ * @access public
+ */
+ function HtmlReporter($character_set = 'ISO-8859-1') {
+ $this->SimpleReporter();
+ $this->_character_set = $character_set;
+ }
+
+ /**
+ * Paints the top of the web page setting the
+ * title to the name of the starting test.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintHeader($test_name) {
+ $this->sendNoCacheHeaders();
+ print "<html>\n<head>\n<title>$test_name</title>\n";
+ print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" .
+ $this->_character_set . "\">\n";
+ print "<style type=\"text/css\">\n";
+ print $this->_getCss() . "\n";
+ print "</style>\n";
+ print "</head>\n<body>\n";
+ print "<h1>$test_name</h1>\n";
+ flush();
+ }
+
+ /**
+ * Send the headers necessary to ensure the page is
+ * reloaded on every request. Otherwise you could be
+ * scratching your head over out of date test data.
+ * @access public
+ * @static
+ */
+ function sendNoCacheHeaders() {
+ if (! headers_sent()) {
+ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
+ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
+ header("Cache-Control: no-store, no-cache, must-revalidate");
+ header("Cache-Control: post-check=0, pre-check=0", false);
+ header("Pragma: no-cache");
+ }
+ }
+
+ /**
+ * Paints the CSS. Add additional styles here.
+ * @return string CSS code as text.
+ * @access protected
+ */
+ function _getCss() {
+ return ".fail { color: red; } pre { background-color: lightgray; }";
+ }
+
+ /**
+ * Paints the end of the test with a summary of
+ * the passes and failures.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintFooter($test_name) {
+ $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green");
+ print "<div style=\"";
+ print "padding: 8px; margin-top: 1em; background-color: $colour; color: white;";
+ print "\">";
+ print $this->getTestCaseProgress() . "/" . $this->getTestCaseCount();
+ print " test cases complete:\n";
+ print "<strong>" . $this->getPassCount() . "</strong> passes, ";
+ print "<strong>" . $this->getFailCount() . "</strong> fails and ";
+ print "<strong>" . $this->getExceptionCount() . "</strong> exceptions.";
+ print "</div>\n";
+ print "</body>\n</html>\n";
+ }
+
+ /**
+ * Paints the test failure with a breadcrumbs
+ * trail of the nesting test suites below the
+ * top level test.
+ * @param string $message Failure message displayed in
+ * the context of the other tests.
+ * @access public
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ print "<span class=\"fail\">Fail</span>: ";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print implode(" -&gt; ", $breadcrumb);
+ print " -&gt; " . $this->_htmlEntities($message) . "<br />\n";
+ }
+
+ /**
+ * Paints a PHP error or exception.
+ * @param string $message Message is ignored.
+ * @access public
+ * @abstract
+ */
+ function paintException($message) {
+ parent::paintException($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.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ print '<pre>' . $this->_htmlEntities($message) . '</pre>';
+ }
+
+ /**
+ * Character set adjusted entity conversion.
+ * @param string $message Plain text or Unicode message.
+ * @return string Browser readable message.
+ * @access protected
+ */
+ function _htmlEntities($message) {
+ return htmlentities($message, ENT_COMPAT, $this->_character_set);
+ }
+ }
+
+ /**
+ * Sample minimal test displayer. Generates only
+ * failure messages and a pass count. For command
+ * line use. I've tried to make it look like JUnit,
+ * but I wanted to output the errors as they arrived
+ * which meant dropping the dots.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class TextReporter extends SimpleReporter {
+
+ /**
+ * Does nothing yet. The first output will
+ * be sent on the first test start.
+ * @access public
+ */
+ function TextReporter() {
+ $this->SimpleReporter();
+ }
+
+ /**
+ * Paints the title only.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintHeader($test_name) {
+ if (! SimpleReporter::inCli()) {
+ header('Content-type: text/plain');
+ }
+ print "$test_name\n";
+ flush();
+ }
+
+ /**
+ * Paints the end of the test with a summary of
+ * the passes and failures.
+ * @param string $test_name Name class of test.
+ * @access public
+ */
+ function paintFooter($test_name) {
+ if ($this->getFailCount() + $this->getExceptionCount() == 0) {
+ print "OK\n";
+ } else {
+ print "FAILURES!!!\n";
+ }
+ print "Test cases run: " . $this->getTestCaseProgress() .
+ "/" . $this->getTestCaseCount() .
+ ", Passes: " . $this->getPassCount() .
+ ", Failures: " . $this->getFailCount() .
+ ", Exceptions: " . $this->getExceptionCount() . "\n";
+
+ }
+
+ /**
+ * Paints the test failure as a stack trace.
+ * @param string $message Failure message displayed in
+ * the context of the other tests.
+ * @access public
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ print $this->getFailCount() . ") $message\n";
+ $breadcrumb = $this->getTestList();
+ array_shift($breadcrumb);
+ print "\tin " . implode("\n\tin ", array_reverse($breadcrumb));
+ print "\n";
+ }
+
+ /**
+ * Paints a PHP error or exception.
+ * @param string $message Message is ignored.
+ * @access public
+ * @abstract
+ */
+ function paintException($message) {
+ parent::paintException($message);
+ print "Exception " . $this->getExceptionCount() . "!\n$message\n";
+ }
+
+ /**
+ * Paints formatted text such as dumped variables.
+ * @param string $message Text to show.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ print "$message\n";
+ flush();
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/runner.php b/tests/test_tools/simpletest/runner.php
new file mode 100644
index 00000000..411efe7e
--- /dev/null
+++ b/tests/test_tools/simpletest/runner.php
@@ -0,0 +1,300 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: runner.php,v 1.29 2005/01/11 04:03:46 lastcraft Exp $
+ */
+
+ /**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+ require_once(dirname(__FILE__) . '/errors.php');
+ require_once(dirname(__FILE__) . '/options.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;
+ }
+
+ /**
+ * Invokes a test method and buffered with setUp()
+ * and tearDown() calls.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $this->_test_case->setUp();
+ $this->_test_case->$method();
+ $this->_test_case->tearDown();
+ }
+ }
+
+ /**
+ * Do nothing decorator. Just passes the invocation
+ * straight through.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleInvokerDecorator {
+ protected $_invoker;
+
+ /**
+ * Stores the invoker to wrap.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function SimpleInvokerDecorator($invoker) {
+ $this->_invoker = $invoker;
+ }
+
+ /**
+ * Accessor for test case being run.
+ * @return SimpleTestCase Test case.
+ * @access public
+ */
+ function getTestCase() {
+ return $this->_invoker->getTestCase();
+ }
+
+ /**
+ * Invokes a test method and buffered with setUp()
+ * and tearDown() calls.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $this->_invoker->invoke($method);
+ }
+ }
+
+ /**
+ * Extension that traps errors into an error queue.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator {
+
+ /**
+ /**
+ * Stores the invoker to wrap.
+ * @param SimpleInvoker $invoker Test method runner.
+ */
+ function SimpleErrorTrappingInvoker($invoker) {
+ $this->SimpleInvokerDecorator($invoker);
+ }
+
+ /**
+ * Invokes a test method and dispatches any
+ * untrapped errors. Called back from
+ * the visiting runner.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ set_error_handler('simpleTestErrorHandler');
+ parent::invoke($method);
+ $queue = SimpleErrorQueue::instance();
+ while (list($severity, $message, $file, $line, $globals) = $queue->extract()) {
+ $test_case = $this->getTestCase();
+ $test_case->error($severity, $message, $file, $line, $globals);
+ }
+ restore_error_handler();
+ }
+ }
+
+ /**
+ * The standard runner. Will run every method starting
+ * with test Basically the
+ * Mediator pattern.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleRunner {
+ protected $_test_case;
+ protected $_scorer;
+
+ /**
+ * Takes in the test case and reporter to mediate between.
+ * @param SimpleTestCase $test_case Test case to run.
+ * @param SimpleScorer $scorer Reporter to receive events.
+ */
+ function SimpleRunner($test_case, $scorer) {
+ $this->_test_case = $test_case;
+ $this->_scorer = $scorer;
+ }
+
+ /**
+ * Accessor for test case being run.
+ * @return SimpleTestCase Test case.
+ * @access public
+ */
+ function getTestCase() {
+ return $this->_test_case;
+ }
+
+ /**
+ * Runs the test methods in the test case.
+ * @param SimpleTest $test_case Test case to run test on.
+ * @param string $method Name of test method.
+ * @access public
+ */
+ function run() {
+ $methods = get_class_methods(get_class($this->_test_case));
+ $invoker = $this->_test_case->createInvoker();
+ foreach ($methods as $method) {
+ if (! $this->_isTest($method)) {
+ continue;
+ }
+ if ($this->_isConstructor($method)) {
+ continue;
+ }
+ $this->_scorer->paintMethodStart($method);
+ if ($this->_scorer->shouldInvoke($this->_test_case->getLabel(), $method)) {
+ $invoker->invoke($method);
+ }
+ $this->_scorer->paintMethodEnd($method);
+ }
+ }
+
+ /**
+ * Tests to see if the method is the constructor and
+ * so should be ignored.
+ * @param string $method Method name to try.
+ * @return boolean True if constructor.
+ * @access protected
+ */
+ function _isConstructor($method) {
+ return SimpleTestCompatibility::isA(
+ $this->_test_case,
+ strtolower($method));
+ }
+
+ /**
+ * Tests to see if the method is a test that should
+ * be run. Currently any method that starts with 'test'
+ * is a candidate.
+ * @param string $method Method name to try.
+ * @return boolean True if test method.
+ * @access protected
+ */
+ function _isTest($method) {
+ return strtolower(substr($method, 0, 4)) == 'test';
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ $this->_scorer->paintMethodStart($test_name);
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ $this->_scorer->paintMethodEnd($test_name);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ $this->_scorer->paintPass($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ $this->_scorer->paintFail($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ $this->_scorer->paintError($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param Exception $exception Object thrown.
+ * @access public
+ */
+ function paintException($exception) {
+ $this->_scorer->paintException($exception);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ $this->_scorer->paintMessage($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ $this->_scorer->paintFormattedMessage($message);
+ }
+
+ /**
+ * Chains to the wrapped reporter.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @return boolean Should return false if this
+ * type of signal should fail the
+ * test suite.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ $this->_scorer->paintSignal($type, $payload);
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/scorer.php b/tests/test_tools/simpletest/scorer.php
new file mode 100644
index 00000000..6c321f8c
--- /dev/null
+++ b/tests/test_tools/simpletest/scorer.php
@@ -0,0 +1,378 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: scorer.php,v 1.4 2005/01/11 04:03:46 lastcraft Exp $
+ */
+
+ /**
+ * Can recieve test events and display them. Display
+ * is achieved by making display methods available
+ * and visiting the incoming event.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @abstract
+ */
+ class SimpleScorer {
+ protected $_passes;
+ protected $_fails;
+ protected $_exceptions;
+ protected $_is_dry_run;
+
+ /**
+ * Starts the test run with no results.
+ * @access public
+ */
+ function SimpleScorer() {
+ $this->_passes = 0;
+ $this->_fails = 0;
+ $this->_exceptions = 0;
+ $this->_is_dry_run = false;
+ }
+
+ /**
+ * Signals that the next evaluation will be a dry
+ * run. That is, the structure events will be
+ * recorded, but no tests will be run.
+ */
+ function makeDry($is_dry = true) {
+ $this->_is_dry_run = $is_dry;
+ }
+
+ /**
+ * The reporter has a veto on what should be run.
+ * @param string $test_case_name name of test case.
+ * @param string $method Name of test method.
+ * @access public
+ */
+ function shouldInvoke($test_case_name, $method) {
+ return ! $this->_is_dry_run;
+ }
+
+ /**
+ * Accessor for current status. Will be false
+ * if there have been any failures or exceptions.
+ * Used for command line tools.
+ * @return boolean True if no failures.
+ * @access public
+ */
+ function getStatus() {
+ if ($this->_exceptions + $this->_fails > 0) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test or other label.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test or other label.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ }
+
+ /**
+ * Increments the pass count.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ $this->_passes++;
+ }
+
+ /**
+ * Increments the fail count.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ $this->_fails++;
+ }
+
+ /**
+ * Deals with PHP 4 throwing an error.
+ * @param string $message Text of error formatted by
+ * the test case.
+ * @access public
+ */
+ function paintError($message) {
+ $this->paintException($message);
+ }
+
+ /**
+ * Deals with PHP 5 throwing an exception
+ * This isn't really implemented yet.
+ * @param Exception $exception Object thrown.
+ * @access public
+ */
+ function paintException($exception) {
+ $this->_exceptions++;
+ }
+
+ /**
+ * Accessor for the number of passes so far.
+ * @return integer Number of passes.
+ * @access public
+ */
+ function getPassCount() {
+ return $this->_passes;
+ }
+
+ /**
+ * Accessor for the number of fails so far.
+ * @return integer Number of fails.
+ * @access public
+ */
+ function getFailCount() {
+ return $this->_fails;
+ }
+
+ /**
+ * Accessor for the number of untrapped errors
+ * so far.
+ * @return integer Number of exceptions.
+ * @access public
+ */
+ function getExceptionCount() {
+ return $this->_exceptions;
+ }
+
+ /**
+ * Paints a simple supplementary message.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ }
+
+ /**
+ * Paints a formatted ASCII message such as a
+ * variable dump.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ }
+
+ /**
+ * By default just ignores user generated events.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ }
+ }
+
+ /**
+ * Recipient of generated test messages that can display
+ * page footers and headers. Also keeps track of the
+ * test nesting. This is the main base class on which
+ * to build the finished test (page based) displays.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleReporter extends SimpleScorer {
+ protected $_test_stack;
+ protected $_size;
+ protected $_progress;
+
+ /**
+ * Starts the display with no results in.
+ * @access public
+ */
+ function SimpleReporter() {
+ $this->SimpleScorer();
+ $this->_test_stack = array();
+ $this->_size = null;
+ $this->_progress = 0;
+ }
+
+ /**
+ * Paints the start of a group test. Will also paint
+ * the page header and footer if this is the
+ * first test. Will stash the size if the first
+ * start.
+ * @param string $test_name Name of test that is starting.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ if (! isset($this->_size)) {
+ $this->_size = $size;
+ }
+ if (count($this->_test_stack) == 0) {
+ $this->paintHeader($test_name);
+ }
+ $this->_test_stack[] = $test_name;
+ }
+
+ /**
+ * Paints the end of a group test. Will paint the page
+ * footer if the stack of tests has unwound.
+ * @param string $test_name Name of test that is ending.
+ * @param integer $progress Number of test cases ending.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ array_pop($this->_test_stack);
+ if (count($this->_test_stack) == 0) {
+ $this->paintFooter($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test case. Will also paint
+ * the page header and footer if this is the
+ * first test. Will stash the size if the first
+ * start.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ if (! isset($this->_size)) {
+ $this->_size = 1;
+ }
+ if (count($this->_test_stack) == 0) {
+ $this->paintHeader($test_name);
+ }
+ $this->_test_stack[] = $test_name;
+ }
+
+ /**
+ * Paints the end of a test case. Will paint the page
+ * footer if the stack of tests has unwound.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ $this->_progress++;
+ array_pop($this->_test_stack);
+ if (count($this->_test_stack) == 0) {
+ $this->paintFooter($test_name);
+ }
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ $this->_test_stack[] = $test_name;
+ }
+
+ /**
+ * Paints the end of a test method. Will paint the page
+ * footer if the stack of tests has unwound.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ array_pop($this->_test_stack);
+ }
+
+ /**
+ * Paints the test document header.
+ * @param string $test_name First test top level
+ * to start.
+ * @access public
+ * @abstract
+ */
+ function paintHeader($test_name) {
+ }
+
+ /**
+ * Paints the test document footer.
+ * @param string $test_name The top level test.
+ * @access public
+ * @abstract
+ */
+ function paintFooter($test_name) {
+ }
+
+ /**
+ * Accessor for internal test stack. For
+ * subclasses that need to see the whole test
+ * history for display purposes.
+ * @return array List of methods in nesting order.
+ * @access public
+ */
+ function getTestList() {
+ return $this->_test_stack;
+ }
+
+ /**
+ * Accessor for total test size in number
+ * of test cases. Null until the first
+ * test is started.
+ * @return integer Total number of cases at start.
+ * @access public
+ */
+ function getTestCaseCount() {
+ return $this->_size;
+ }
+
+ /**
+ * Accessor for the number of test cases
+ * completed so far.
+ * @return integer Number of ended cases.
+ * @access public
+ */
+ function getTestCaseProgress() {
+ return $this->_progress;
+ }
+
+ /**
+ * Static check for running in the comand line.
+ * @return boolean True if CLI.
+ * @access public
+ * @static
+ */
+ static function inCli() {
+ return php_sapi_name() == 'cli';
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/shell_tester.php b/tests/test_tools/simpletest/shell_tester.php
new file mode 100644
index 00000000..7bab8ce0
--- /dev/null
+++ b/tests/test_tools/simpletest/shell_tester.php
@@ -0,0 +1,271 @@
+<?php
+ /**
+ * 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 $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/simple_test.php');
+ /**#@-*/
+
+ /**
+ * Wrapper for exec() functionality.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleShell {
+ protected $_output;
+
+ /**
+ * Executes the shell comand and stashes the output.
+ * @access public
+ */
+ function SimpleShell() {
+ $this->_output = false;
+ }
+
+ /**
+ * Actually runs the command. Does not trap the
+ * error stream output as this need PHP 4.3+.
+ * @param string $command The actual command line
+ * to run.
+ * @return integer Exit code.
+ * @access public
+ */
+ function execute($command) {
+ $this->_output = false;
+ exec($command, $this->_output, $ret);
+ return $ret;
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return string Output as text.
+ * @access public
+ */
+ function getOutput() {
+ return implode("\n", $this->_output);
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return array Output as array of lines.
+ * @access public
+ */
+ function getOutputAsList() {
+ return $this->_output;
+ }
+ }
+
+ /**
+ * Test case for testing of command line scripts and
+ * utilities. Usually scripts taht are external to the
+ * PHP code, but support it in some way.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class ShellTestCase extends SimpleTestCase {
+ protected $_current_shell;
+ protected $_last_status;
+ protected $_last_command;
+
+ /**
+ * Creates an empty test case. Should be subclassed
+ * with test methods for a functional test case.
+ * @param string $label Name of test case. Will use
+ * the class name if none specified.
+ * @access public
+ */
+ function ShellTestCase($label = false) {
+ $this->SimpleTestCase($label);
+ $this->_current_shell = $this->_createShell();
+ $this->_last_status = false;
+ $this->_last_command = '';
+ }
+
+ /**
+ * Executes a command and buffers the results.
+ * @param string $command Command to run.
+ * @return boolean True if zero exit code.
+ * @access public
+ */
+ function execute($command) {
+ $shell = $this->_getShell();
+ $this->_last_status = $shell->execute($command);
+ $this->_last_command = $command;
+ return ($this->_last_status === 0);
+ }
+
+ /**
+ * Dumps the output of the last command.
+ * @access public
+ */
+ function dumpOutput() {
+ $this->dump($this->getOutput());
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return string Output as text.
+ * @access public
+ */
+ function getOutput() {
+ $shell = $this->_getShell();
+ return $shell->getOutput();
+ }
+
+ /**
+ * Accessor for the last output.
+ * @return array Output as array of lines.
+ * @access public
+ */
+ function getOutputAsList() {
+ $shell = $this->_getShell();
+ return $shell->getOutputAsList();
+ }
+
+ /**
+ * Tests the last status code from the shell.
+ * @param integer $status Expected status of last
+ * command.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertExitCode($status, $message = "%s") {
+ $message = sprintf($message, "Expected status code of [$status] from [" .
+ $this->_last_command . "], but got [" .
+ $this->_last_status . "]");
+ return $this->assertTrue($status === $this->_last_status, $message);
+ }
+
+ /**
+ * Attempt to exactly match the combined STDERR and
+ * STDOUT output.
+ * @param string $expected Expected output.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertOutput($expected, $message = "%s") {
+ $shell = $this->_getShell();
+ return $this->assertExpectation(
+ new EqualExpectation($expected),
+ $shell->getOutput(),
+ $message);
+ }
+
+ /**
+ * Scans the output for a Perl regex. If found
+ * anywhere it passes, else it fails.
+ * @param string $pattern Regex to search for.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertOutputPattern($pattern, $message = "%s") {
+ $shell = $this->_getShell();
+ return $this->assertExpectation(
+ new WantedPatternExpectation($pattern),
+ $shell->getOutput(),
+ $message);
+ }
+
+ /**
+ * If a Perl regex is found anywhere in the current
+ * output then a failure is generated, else a pass.
+ * @param string $pattern Regex to search for.
+ * @param $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoOutputPattern($pattern, $message = "%s") {
+ $shell = $this->_getShell();
+ return $this->assertExpectation(
+ new UnwantedPatternExpectation($pattern),
+ $shell->getOutput(),
+ $message);
+ }
+
+ /**
+ * File existence check.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFileExists($path, $message = "%s") {
+ $message = sprintf($message, "File [$path] should exist");
+ return $this->assertTrue(file_exists($path), $message);
+ }
+
+ /**
+ * File non-existence check.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFileNotExists($path, $message = "%s") {
+ $message = sprintf($message, "File [$path] should not exist");
+ return $this->assertFalse(file_exists($path), $message);
+ }
+
+ /**
+ * Scans a file for a Perl regex. If found
+ * anywhere it passes, else it fails.
+ * @param string $pattern Regex to search for.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFilePattern($pattern, $path, $message = "%s") {
+ $shell = $this->_getShell();
+ return $this->assertExpectation(
+ new WantedPatternExpectation($pattern),
+ implode('', file($path)),
+ $message);
+ }
+
+ /**
+ * If a Perl regex is found anywhere in the named
+ * file then a failure is generated, else a pass.
+ * @param string $pattern Regex to search for.
+ * @param string $path Full filename and path.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoFilePattern($pattern, $path, $message = "%s") {
+ $shell = $this->_getShell();
+ return $this->assertExpectation(
+ new UnwantedPatternExpectation($pattern),
+ implode('', file($path)),
+ $message);
+ }
+
+ /**
+ * Accessor for current shell. Used for testing the
+ * the tester itself.
+ * @return Shell Current shell.
+ * @access protected
+ */
+ function _getShell() {
+ return $this->_current_shell;
+ }
+
+ /**
+ * Factory for the shell to run the command on.
+ * @return Shell New shell object.
+ * @access protected
+ */
+ function _createShell() {
+ return new SimpleShell();
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/simple_test.php b/tests/test_tools/simpletest/simple_test.php
new file mode 100644
index 00000000..f2204f42
--- /dev/null
+++ b/tests/test_tools/simpletest/simple_test.php
@@ -0,0 +1,553 @@
+<?php
+ /**
+ * Base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: simple_test.php,v 1.89 2005/02/18 19:25:05 lastcraft Exp $
+ */
+
+ /**#@+
+ * Includes SimpleTest files and defined the root constant
+ * for dependent libraries.
+ */
+ require_once(dirname(__FILE__) . '/errors.php');
+ require_once(dirname(__FILE__) . '/options.php');
+ require_once(dirname(__FILE__) . '/runner.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__) . '/');
+ }
+ /**#@-*/
+
+ /**
+ * 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;
+ protected $_runner;
+
+ /**
+ * 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) {
+ $this->_label = $label ? $label : get_class($this);
+ $this->_runner = false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_label;
+ }
+
+ /**
+ * Used to invoke the single tests.
+ * @return SimpleInvoker Individual test runner.
+ * @access public
+ */
+ function createInvoker() {
+ return new SimpleErrorTrappingInvoker(new SimpleInvoker($this));
+ }
+
+ /**
+ * Can modify the incoming reporter so as to run
+ * the tests differently. This version simply
+ * passes it straight through.
+ * @param SimpleReporter $reporter Incoming observer.
+ * @return SimpleReporter
+ * @access protected
+ */
+ function _createRunner($reporter) {
+ return new SimpleRunner($this, $reporter);
+ }
+
+ /**
+ * Uses reflection to run every method within itself
+ * starting with the string "test" unless a method
+ * is specified.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintCaseStart($this->getLabel());
+ $this->_runner = $this->_createRunner($reporter);
+ $this->_runner->run();
+ $reporter->paintCaseEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Sets up unit test wide variables at the start
+ * of each test method. To be overridden in
+ * actual user test cases.
+ * @access public
+ */
+ function setUp() {
+ }
+
+ /**
+ * Clears the data set in the setUp() method call.
+ * To be overridden by the user in actual user test cases.
+ * @access public
+ */
+ function tearDown() {
+ }
+
+ /**
+ * Sends a pass event with a message.
+ * @param string $message Message to send.
+ * @access public
+ */
+ function pass($message = "Pass") {
+ $this->_runner->paintPass($message . $this->getAssertionLine(' at line [%d]'));
+ }
+
+ /**
+ * Sends a fail event with a message.
+ * @param string $message Message to send.
+ * @access public
+ */
+ function fail($message = "Fail") {
+ $this->_runner->paintFail($message . $this->getAssertionLine(' at line [%d]'));
+ }
+
+ /**
+ * Formats a PHP error and dispatches it to the
+ * runner.
+ * @param integer $severity PHP error code.
+ * @param string $message Text of error.
+ * @param string $file File error occoured in.
+ * @param integer $line Line number of error.
+ * @param hash $globals PHP super global arrays.
+ * @access public
+ */
+ function error($severity, $message, $file, $line, $globals) {
+ $severity = SimpleErrorQueue::getSeverityAsString($severity);
+ $this->_runner->paintError(
+ "Unexpected PHP error [$message] severity [$severity] in [$file] line [$line]");
+ }
+
+ /**
+ * Sends a user defined event to the test runner.
+ * This is for small scale extension where
+ * both the test case and either the runner or
+ * display are subclassed.
+ * @param string $type Type of event.
+ * @param mixed $payload Object or message to deliver.
+ * @access public
+ */
+ function signal($type, $payload) {
+ $this->_runner->paintSignal($type, $payload);
+ }
+
+ /**
+ * Cancels any outstanding errors.
+ * @access public
+ */
+ function swallowErrors() {
+ $queue = SimpleErrorQueue::instance();
+ $queue->clear();
+ }
+
+ /**
+ * Runs an expectation directly, for extending the
+ * tests with new expectation classes.
+ * @param SimpleExpectation $expectation Expectation subclass.
+ * @param mixed $test_value Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertExpectation($expectation, $test_value, $message = '%s') {
+ return $this->assertTrue(
+ $expectation->test($test_value),
+ sprintf($message, $expectation->overlayMessage($test_value)));
+ }
+
+ /**
+ * Called from within the test methods to register
+ * passes and failures.
+ * @param boolean $result Pass on true.
+ * @param string $message Message to display describing
+ * the test state.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertTrue($result, $message = false) {
+ if (! $message) {
+ $message = 'True assertion got ' . ($result ? 'True' : 'False');
+ }
+ if ($result) {
+ $this->pass($message);
+ return true;
+ } else {
+ $this->fail($message);
+ return false;
+ }
+ }
+
+ /**
+ * Will be true on false and vice versa. False
+ * is the PHP definition of false, so that null,
+ * empty strings, zero and an empty array all count
+ * as false.
+ * @param boolean $result Pass on false.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertFalse($result, $message = false) {
+ if (! $message) {
+ $message = 'False assertion got ' . ($result ? 'True' : 'False');
+ }
+ return $this->assertTrue(! $result, $message);
+ }
+
+ /**
+ * Uses a stack trace to find the line of an assertion.
+ * @param string $format String formatting.
+ * @param array $stack Stack frames top most first. Only
+ * needed if not using the PHP
+ * backtrace function.
+ * @return string Line number of first assert*
+ * method embedded in format string.
+ * @access public
+ */
+ function getAssertionLine($format = '%d', $stack = false) {
+ if ($stack === false) {
+ $stack = SimpleTestCompatibility::getStackTrace();
+ }
+ return SimpleDumper::getFormattedAssertionLine($stack, $format);
+ }
+
+ /**
+ * Sends a formatted dump of a variable to the
+ * test suite for those emergency debugging
+ * situations.
+ * @param mixed $variable Variable to display.
+ * @param string $message Message to display.
+ * @return mixed The original variable.
+ * @access public
+ */
+ function dump($variable, $message = false) {
+ $formatted = SimpleDumper::dump($variable);
+ if ($message) {
+ $formatted = $message . "\n" . $formatted;
+ }
+ $this->_runner->paintFormattedMessage($formatted);
+ return $variable;
+ }
+
+ /**
+ * Dispatches a text message straight to the
+ * test suite. Useful for status bar displays.
+ * @param string $message Message to show.
+ * @access public
+ */
+ function sendMessage($message) {
+ $this->_runner->PaintMessage($message);
+ }
+
+ /**
+ * Accessor for the number of subtests.
+ * @return integer Number of test cases.
+ * @access public
+ * @static
+ */
+ function getSize() {
+ return 1;
+ }
+ }
+
+ /**
+ * This is a composite test class for combining
+ * test cases and other RunnableTest classes into
+ * a group test.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class GroupTest {
+ protected $_label;
+ protected $_test_cases;
+ protected $_old_track_errors;
+ protected $_xdebug_is_enabled;
+
+ /**
+ * Sets the name of the test suite.
+ * @param string $label Name sent at the start and end
+ * of the test.
+ * @access public
+ */
+ function GroupTest($label) {
+ $this->_label = $label;
+ $this->_test_cases = array();
+ $this->_old_track_errors = ini_get('track_errors');
+ $this->_xdebug_is_enabled = function_exists('xdebug_is_enabled') ?
+ xdebug_is_enabled() : false;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_label;
+ }
+
+ /**
+ * Adds a test into the suite. Can be either a group
+ * test or some other unit test.
+ * @param SimpleTestCase $test_case Suite or individual test
+ * case implementing the
+ * runnable test interface.
+ * @access public
+ */
+ function addTestCase($test_case) {
+ $this->_test_cases[] = $test_case;
+ }
+
+ /**
+ * Adds a test into the suite by class name. The class will
+ * be instantiated as needed.
+ * @param SimpleTestCase $test_case Suite or individual test
+ * case implementing the
+ * runnable test interface.
+ * @access public
+ */
+ function addTestClass($class) {
+ $this->_test_cases[] = $class;
+ }
+
+ /**
+ * Builds a group test from a library of test cases.
+ * The new group is composed into this one.
+ * @param string $test_file File name of library with
+ * test case classes.
+ * @access public
+ */
+ function addTestFile($test_file) {
+ $existing_classes = get_declared_classes();
+ if ($error = $this->_requireWithError($test_file)) {
+ $this->addTestCase(new BadGroupTest($test_file, $error));
+ return;
+ }
+ $classes = $this->_selectRunnableTests($existing_classes, get_declared_classes());
+ if (count($classes) == 0) {
+ $this->addTestCase(new BadGroupTest($test_file, 'No new test cases'));
+ return;
+ }
+ $this->addTestCase($this->_createGroupFromClasses($test_file, $classes));
+ }
+
+ /**
+ * Requires a source file recording any syntax errors.
+ * @param string $file File name to require in.
+ * @return string/boolean An error message on failure or false
+ * if no errors.
+ * @access private
+ */
+ function _requireWithError($file) {
+ $this->_enableErrorReporting();
+ include($file);
+ $error = isset($php_errormsg) ? $php_errormsg : false;
+ $this->_disableErrorReporting();
+ $self_inflicted = array(
+ 'Assigning the return value of new by reference is deprecated',
+ 'var: Deprecated. Please use the public/private/protected modifiers');
+ if (in_array($error, $self_inflicted)) {
+ return false;
+ }
+ return $error;
+ }
+
+ /**
+ * Sets up detection of parse errors. Note that XDebug
+ * interferes with this and has to be disabled. This is
+ * to make sure the correct error code is returned
+ * from unattended scripts.
+ * @access private
+ */
+ function _enableErrorReporting() {
+ if ($this->_xdebug_is_enabled) {
+ xdebug_disable();
+ }
+ ini_set('track_errors', true);
+ }
+
+ /**
+ * Resets detection of parse errors to their old values.
+ * This is to make sure the correct error code is returned
+ * from unattended scripts.
+ * @access private
+ */
+ function _disableErrorReporting() {
+ ini_set('track_errors', $this->_old_track_errors);
+ if ($this->_xdebug_is_enabled) {
+ xdebug_enable();
+ }
+ }
+
+ /**
+ * Calculates the incoming test cases from a before
+ * and after list of loaded classes.
+ * @param array $existing_classes Classes before require().
+ * @param array $new_classes Classes after require().
+ * @return array New classes which are test
+ * cases that shouldn't be ignored.
+ * @access private
+ */
+ function _selectRunnableTests($existing_classes, $new_classes) {
+ $classes = array();
+ foreach ($new_classes as $class) {
+ if (in_array($class, $existing_classes)) {
+ continue;
+ }
+ if (! $this->_isTestCase($class)) {
+ continue;
+ }
+ $classes[] = $class;
+ }
+ return $classes;
+ }
+
+ /**
+ * Builds a group test from a class list.
+ * @param string $title Title of new group.
+ * @param array $classes Test classes.
+ * @return GroupTest Group loaded with the new
+ * test cases.
+ * @access private
+ */
+ function _createGroupFromClasses($title, $classes) {
+ $group = new GroupTest($title);
+ foreach ($classes as $class) {
+ if (SimpleTestOptions::isIgnored($class)) {
+ continue;
+ }
+ $group->addTestClass($class);
+ }
+ return $group;
+ }
+
+ /**
+ * Test to see if a class is derived from the
+ * TestCase class.
+ * @param string $class Class name.
+ * @access private
+ */
+ function _isTestCase($class) {
+ while ($class = get_parent_class($class)) {
+ $class = strtolower($class);
+ if ($class == "simpletestcase" || $class == "grouptest") {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Invokes run() on all of the held test cases, instantiating
+ * them if necessary.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintGroupStart($this->getLabel(), $this->getSize());
+ for ($i = 0, $count = count($this->_test_cases); $i < $count; $i++) {
+ if (is_string($this->_test_cases[$i])) {
+ $class = $this->_test_cases[$i];
+ $test = new $class();
+ $test->run($reporter);
+ } else {
+ $this->_test_cases[$i]->run($reporter);
+ }
+ }
+ $reporter->paintGroupEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Number of contained test cases.
+ * @return integer Total count of cases in the group.
+ * @access public
+ */
+ function getSize() {
+ $count = 0;
+ foreach ($this->_test_cases as $case) {
+ if (is_string($case)) {
+ $count++;
+ } else {
+ $count += $case->getSize();
+ }
+ }
+ return $count;
+ }
+ }
+
+ /**
+ * This is a failing group test for when a test suite hasn't
+ * loaded properly.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class BadGroupTest {
+ protected $_label;
+ protected $_error;
+
+ /**
+ * Sets the name of the test suite and error message.
+ * @param string $label Name sent at the start and end
+ * of the test.
+ * @access public
+ */
+ function BadGroupTest($label, $error) {
+ $this->_label = $label;
+ $this->_error = $error;
+ }
+
+ /**
+ * Accessor for the test name for subclasses.
+ * @return string Name of the test.
+ * @access public
+ */
+ function getLabel() {
+ return $this->_label;
+ }
+
+ /**
+ * Sends a single error to the reporter.
+ * @param SimpleReporter $reporter Current test reporter.
+ * @access public
+ */
+ function run($reporter) {
+ $reporter->paintGroupStart($this->getLabel(), $this->getSize());
+ $reporter->paintFail('Bad GroupTest [' . $this->getLabel() .
+ '] with error [' . $this->_error . ']');
+ $reporter->paintGroupEnd($this->getLabel());
+ return $reporter->getStatus();
+ }
+
+ /**
+ * Number of contained test cases. Always zero.
+ * @return integer Total count of cases in the group.
+ * @access public
+ */
+ function getSize() {
+ return 0;
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/socket.php b/tests/test_tools/simpletest/socket.php
new file mode 100644
index 00000000..4c3c592d
--- /dev/null
+++ b/tests/test_tools/simpletest/socket.php
@@ -0,0 +1,216 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage MockObjects
+ * @version $Id: socket.php,v 1.23 2004/09/30 16:46:31 lastcraft Exp $
+ */
+
+ /**#@+
+ * include SimpleTest files
+ */
+ require_once(dirname(__FILE__) . '/options.php');
+ /**#@-*/
+
+ /**
+ * Stashes an error for later. Useful for constructors
+ * until PHP gets exceptions.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleStickyError {
+ protected $_error = 'Constructor not chained';
+
+ /**
+ * Sets the error to empty.
+ * @access public
+ */
+ function SimpleStickyError() {
+ $this->_clearError();
+ }
+
+ /**
+ * Test for an outstanding error.
+ * @return boolean True if there is an error.
+ * @access public
+ */
+ function isError() {
+ return ($this->_error != '');
+ }
+
+ /**
+ * Accessor for an outstanding error.
+ * @return string Empty string if no error otherwise
+ * the error message.
+ * @access public
+ */
+ function getError() {
+ return $this->_error;
+ }
+
+ /**
+ * Sets the internal error.
+ * @param string Error message to stash.
+ * @access protected
+ */
+ function _setError($error) {
+ $this->_error = $error;
+ }
+
+ /**
+ * Resets the error state to no error.
+ * @access protected
+ */
+ function _clearError() {
+ $this->_setError('');
+ }
+ }
+
+ /**
+ * Wrapper for TCP/IP socket.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleSocket extends SimpleStickyError {
+ protected $_handle;
+ protected $_is_open;
+ protected $_sent;
+
+ /**
+ * Opens a socket for reading and writing.
+ * @param string $host Hostname to send request to.
+ * @param integer $port Port on remote machine to open.
+ * @param integer $timeout Connection timeout in seconds.
+ * @access public
+ */
+ function SimpleSocket($host, $port, $timeout) {
+ $this->SimpleStickyError();
+ $this->_is_open = false;
+ $this->_sent = '';
+ if (! ($this->_handle = $this->_openSocket($host, $port, $error_number, $error, $timeout))) {
+ $this->_setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds");
+ return;
+ }
+ $this->_is_open = true;
+ SimpleTestCompatibility::setTimeout($this->_handle, $timeout);
+ }
+
+ /**
+ * Writes some data to the socket and saves alocal copy.
+ * @param string $message String to send to socket.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function write($message) {
+ if ($this->isError() || ! $this->isOpen()) {
+ return false;
+ }
+ $count = fwrite($this->_handle, $message);
+ if (! $count) {
+ if ($count === false) {
+ $this->_setError('Cannot write to socket');
+ $this->close();
+ }
+ return false;
+ }
+ fflush($this->_handle);
+ $this->_sent .= $message;
+ return true;
+ }
+
+ /**
+ * Reads data from the socket. The error suppresion
+ * is a workaround for PHP4 always throwing a warning
+ * with a secure socket.
+ * @param integer $block_size Size of chunk to read.
+ * @return integer Incoming bytes. False
+ * on error.
+ * @access public
+ */
+ function read($block_size = 255) {
+ if ($this->isError() || ! $this->isOpen()) {
+ return false;
+ }
+ $raw = @fread($this->_handle, $block_size);
+ if ($raw === false) {
+ $this->_setError('Cannot read from socket');
+ $this->close();
+ }
+ return $raw;
+ }
+
+ /**
+ * Accessor for socket open state.
+ * @return boolean True if open.
+ * @access public
+ */
+ function isOpen() {
+ return $this->_is_open;
+ }
+
+ /**
+ * Closes the socket preventing further reads.
+ * Cannot be reopened once closed.
+ * @return boolean True if successful.
+ * @access public
+ */
+ function close() {
+ $this->_is_open = false;
+ return fclose($this->_handle);
+ }
+
+ /**
+ * Accessor for content so far.
+ * @return string Bytes sent only.
+ * @access public
+ */
+ function getSent() {
+ return $this->_sent;
+ }
+
+ /**
+ * Actually opens the low level socket.
+ * @param string $host Host to connect to.
+ * @param integer $port Port on host.
+ * @param integer $error_number Recipient of error code.
+ * @param string $error Recipoent of error message.
+ * @param integer $timeout Maximum time to wait for connection.
+ * @access protected
+ */
+ function _openSocket($host, $port, $error_number, $error, $timeout) {
+ return @fsockopen($host, $port, $error_number, $error, $timeout);
+ }
+ }
+
+ /**
+ * Wrapper for TCP/IP socket over TLS.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleSecureSocket extends SimpleSocket {
+
+ /**
+ * Opens a secure socket for reading and writing.
+ * @param string $host Hostname to send request to.
+ * @param integer $port Port on remote machine to open.
+ * @param integer $timeout Connection timeout in seconds.
+ * @access public
+ */
+ function SimpleSecureSocket($host, $port, $timeout) {
+ $this->SimpleSocket($host, $port, $timeout);
+ }
+
+ /**
+ * Actually opens the low level socket.
+ * @param string $host Host to connect to.
+ * @param integer $port Port on host.
+ * @param integer $error_number Recipient of error code.
+ * @param string $error Recipient of error message.
+ * @param integer $timeout Maximum time to wait for connection.
+ * @access protected
+ */
+ function _openSocket($host, $port, $error_number, $error, $timeout) {
+ return parent::_openSocket("tls://$host", $port, $error_number, $error, $timeout);
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/tag.php b/tests/test_tools/simpletest/tag.php
new file mode 100644
index 00000000..9386712a
--- /dev/null
+++ b/tests/test_tools/simpletest/tag.php
@@ -0,0 +1,1241 @@
+<?php
+ /**
+ * Base include file for SimpleTest.
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: tag.php,v 1.73 2005/02/02 22:49:36 lastcraft Exp $
+ */
+
+ /**#@+
+ * include SimpleTest files
+ */
+ require_once(dirname(__FILE__) . '/parser.php');
+ /**#@-*/
+
+ /**
+ * HTML or XML tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleTag {
+ protected $_name;
+ protected $_attributes;
+ protected $_content;
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param string $name Tag name.
+ * @param hash $attributes Attribute names and
+ * string values. Note that
+ * the keys must have been
+ * converted to lower case.
+ */
+ function SimpleTag($name, $attributes) {
+ $this->_name = $name;
+ $this->_attributes = $attributes;
+ $this->_content = '';
+ }
+
+ /**
+ * Check to see if the tag can have both start and
+ * end tags with content in between.
+ * @return boolean True if content allowed.
+ * @access public
+ */
+ function expectEndTag() {
+ return true;
+ }
+
+ /**
+ * Appends string content to the current content.
+ * @param string $content Additional text.
+ * @access public
+ */
+ function addContent($content) {
+ $this->_content .= (string)$content;
+ }
+
+ /**
+ * Adds an enclosed tag to the content.
+ * @param SimpleTag $tag New tag.
+ * @access public
+ */
+ function addTag($tag) {
+ }
+
+ /**
+ * Accessor for tag name.
+ * @return string Name of tag.
+ * @access public
+ */
+ function getTagName() {
+ return $this->_name;
+ }
+
+ /**
+ * List oflegal child elements.
+ * @return array List of element names.
+ * @access public
+ */
+ function getChildElements() {
+ return array();
+ }
+
+ /**
+ * Accessor for an attribute.
+ * @param string $label Attribute name.
+ * @return string Attribute value.
+ * @access public
+ */
+ function getAttribute($label) {
+ $label = strtolower($label);
+ if (! isset($this->_attributes[$label])) {
+ return false;
+ }
+ if ($this->_attributes[$label] === '') {
+ return true;
+ }
+ return (string)$this->_attributes[$label];
+ }
+
+ /**
+ * Sets an attribute.
+ * @param string $label Attribute name.
+ * @return string $value New attribute value.
+ * @access protected
+ */
+ function _setAttribute($label, $value) {
+ $this->_attributes[strtolower($label)] = $value;
+ }
+
+ /**
+ * Accessor for the whole content so far.
+ * @return string Content as big raw string.
+ * @access public
+ */
+ function getContent() {
+ return $this->_content;
+ }
+
+ /**
+ * Accessor for content reduced to visible text. Acts
+ * like a text mode browser, normalising space and
+ * reducing images to their alt text.
+ * @return string Content as plain text.
+ * @access public
+ */
+ function getText() {
+ return SimpleSaxParser::normalise($this->_content);
+ }
+
+ /**
+ * Test to see if id attribute matches.
+ * @param string $id ID to test against.
+ * @return boolean True on match.
+ * @access public
+ */
+ function isId($id) {
+ return ($this->getAttribute('id') == $id);
+ }
+ }
+
+ /**
+ * Page title.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleTitleTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleTitleTag($attributes) {
+ $this->SimpleTag('title', $attributes);
+ }
+ }
+
+ /**
+ * Link.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleAnchorTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleAnchorTag($attributes) {
+ $this->SimpleTag('a', $attributes);
+ }
+
+ /**
+ * Accessor for URL as string.
+ * @return string Coerced as string.
+ * @access public
+ */
+ function getHref() {
+ $url = $this->getAttribute('href');
+ if (is_bool($url)) {
+ $url = '';
+ }
+ return $url;
+ }
+ }
+
+ /**
+ * Form element.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleWidget extends SimpleTag {
+ protected $_value;
+ protected $_is_set;
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param string $name Tag name.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleWidget($name, $attributes) {
+ $this->SimpleTag($name, $attributes);
+ $this->_value = false;
+ $this->_is_set = false;
+ }
+
+ /**
+ * Accessor for name submitted as the key in
+ * GET/POST variables hash.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getName() {
+ return $this->getAttribute('name');
+ }
+
+ /**
+ * Accessor for default value parsed with the tag.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ $default = $this->getAttribute('value');
+ if ($default === true) {
+ $default = '';
+ }
+ if ($default === false) {
+ $default = '';
+ }
+ return $default;
+ }
+
+ /**
+ * Accessor for currently set value or default if
+ * none.
+ * @return string Value set by form or default
+ * if none.
+ * @access public
+ */
+ function getValue() {
+ if (! $this->_is_set) {
+ return $this->getDefault();
+ }
+ return $this->_value;
+ }
+
+ /**
+ * Sets the current form element value.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ $this->_value = $value;
+ $this->_is_set = true;
+ return true;
+ }
+
+ /**
+ * Resets the form element value back to the
+ * default.
+ * @access public
+ */
+ function resetValue() {
+ $this->_is_set = false;
+ }
+ }
+
+ /**
+ * Text, password and hidden field.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleTextTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleTextTag($attributes) {
+ $this->SimpleWidget('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->_setAttribute('value', '');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Sets the current form element value. Cannot
+ * change the value of a hidden field.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($this->getAttribute('type') == 'hidden') {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+ }
+
+ /**
+ * Submit button as input tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleSubmitTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleSubmitTag($attributes) {
+ $this->SimpleWidget('input', $attributes);
+ if ($this->getAttribute('name') === false) {
+ $this->_setAttribute('name', 'submit');
+ }
+ if ($this->getAttribute('value') === false) {
+ $this->_setAttribute('value', 'Submit');
+ }
+ }
+
+ /**
+ * Tag contains no end element.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Disables the setting of the button value.
+ * @param string $value Ignored.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Value of browser visible text.
+ * @return string Visible label.
+ * @access public
+ */
+ function getLabel() {
+ return $this->getValue();
+ }
+
+ /**
+ * Gets the values submitted as a form.
+ * @return array Hash of name and values.
+ * @access public
+ */
+ function getSubmitValues() {
+ return array($this->getName() => $this->getValue());
+ }
+ }
+
+ /**
+ * Image button as input tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleImageSubmitTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleImageSubmitTag($attributes) {
+ $this->SimpleWidget('input', $attributes);
+ }
+
+ /**
+ * Tag contains no end element.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * Disables the setting of the button value.
+ * @param string $value Ignored.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Value of browser visible text.
+ * @return string Visible label.
+ * @access public
+ */
+ function getLabel() {
+ if ($this->getAttribute('title')) {
+ return $this->getAttribute('title');
+ }
+ return $this->getAttribute('alt');
+ }
+
+ /**
+ * Gets the values submitted as a form.
+ * @return array Hash of name and values.
+ * @access public
+ */
+ function getSubmitValues($x, $y) {
+ return array(
+ $this->getName() . '.x' => $x,
+ $this->getName() . '.y' => $y);
+ }
+ }
+
+ /**
+ * Submit button as button tag.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleButtonTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * Defaults are very browser dependent.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleButtonTag($attributes) {
+ $this->SimpleWidget('button', $attributes);
+ }
+
+ /**
+ * Check to see if the tag can have both start and
+ * end tags with content in between.
+ * @return boolean True if content allowed.
+ * @access public
+ */
+ function expectEndTag() {
+ return true;
+ }
+
+ /**
+ * Disables the setting of the button value.
+ * @param string $value Ignored.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Value of browser visible text.
+ * @return string Visible label.
+ * @access public
+ */
+ function getLabel() {
+ return $this->getContent();
+ }
+
+ /**
+ * Gets the values submitted as a form. Gone
+ * for the Mozilla defaults values.
+ * @return array Hash of name and values.
+ * @access public
+ */
+ function getSubmitValues() {
+ if ($this->getAttribute('name') === false) {
+ return array();
+ }
+ if ($this->getAttribute('value') === false) {
+ return array($this->getName() => '');
+ }
+ return array($this->getName() => $this->getValue());
+ }
+ }
+
+ /**
+ * Content tag for text area.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleTextAreaTag extends SimpleWidget {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleTextAreaTag($attributes) {
+ $this->SimpleWidget('textarea', $attributes);
+ }
+
+ /**
+ * Accessor for starting value.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->_wrapIsEnabled()) {
+ return wordwrap(
+ $this->getContent(),
+ (integer)$this->getAttribute('cols'),
+ "\n");
+ }
+ return $this->getContent();
+ }
+
+ /**
+ * Applies word wrapping if needed.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($this->_wrapIsEnabled()) {
+ $value = wordwrap(
+ $value,
+ (integer)$this->getAttribute('cols'),
+ "\n");
+ }
+ return parent::setValue($value);
+ }
+
+ /**
+ * Test to see if text should be wrapped.
+ * @return boolean True if wrapping on.
+ * @access private
+ */
+ function _wrapIsEnabled() {
+ if ($this->getAttribute('cols')) {
+ $wrap = $this->getAttribute('wrap');
+ if (($wrap == 'physical') || ($wrap == 'hard')) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Checkbox widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleCheckboxTag extends SimpleWidget {
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleCheckboxTag($attributes) {
+ $this->SimpleWidget('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->_setAttribute('value', 'on');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * The only allowed value in the one in the
+ * "value" attribute. The default for this
+ * attribute is "on".
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($value === false) {
+ return parent::setValue($value);
+ }
+ if ($value != $this->getAttribute('value')) {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+
+ /**
+ * Accessor for starting value. The default
+ * value is "on".
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('checked')) {
+ return $this->getAttribute('value');
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Drop down widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleSelectionTag extends SimpleWidget {
+ protected $_options;
+ protected $_choice;
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleSelectionTag($attributes) {
+ $this->SimpleWidget('select', $attributes);
+ $this->_options = array();
+ $this->_choice = false;
+ }
+
+ /**
+ * Adds an option tag to a selection field.
+ * @param SimpleOptionTag $tag New option.
+ * @access public
+ */
+ function addTag($tag) {
+ if ($tag->getTagName() == 'option') {
+ $this->_options[] = $tag;
+ }
+ }
+
+ /**
+ * Text within the selection element is ignored.
+ * @param string $content Ignored.
+ * @access public
+ */
+ function addContent($content) {
+ }
+
+ /**
+ * Scans options for defaults. If none, then
+ * the first option is selected.
+ * @return string Selected field.
+ * @access public
+ */
+ function getDefault() {
+ for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
+ if ($this->_options[$i]->getAttribute('selected')) {
+ return $this->_options[$i]->getDefault();
+ }
+ }
+ if ($count > 0) {
+ return $this->_options[0]->getDefault();
+ }
+ return '';
+ }
+
+ /**
+ * Can only set allowed values.
+ * @param string $value New choice.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
+ if (trim($this->_options[$i]->getContent()) == trim($value)) {
+ $this->_choice = $i;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for current selection value.
+ * @return string Value attribute or
+ * content of opton.
+ * @access public
+ */
+ function getValue() {
+ if ($this->_choice === false) {
+ return $this->getDefault();
+ }
+ return $this->_options[$this->_choice]->getValue();
+ }
+ }
+
+ /**
+ * Drop down widget.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class MultipleSelectionTag extends SimpleWidget {
+ protected $_options;
+ protected $_values;
+
+ /**
+ * Starts with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function MultipleSelectionTag($attributes) {
+ $this->SimpleWidget('select', $attributes);
+ $this->_options = array();
+ $this->_values = false;
+ }
+
+ /**
+ * Adds an option tag to a selection field.
+ * @param SimpleOptionTag $tag New option.
+ * @access public
+ */
+ function addTag($tag) {
+ if ($tag->getTagName() == 'option') {
+ $this->_options[] = $tag;
+ }
+ }
+
+ /**
+ * Text within the selection element is ignored.
+ * @param string $content Ignored.
+ * @access public
+ */
+ function addContent($content) {
+ }
+
+ /**
+ * Scans options for defaults to populate the
+ * value array().
+ * @return array Selected fields.
+ * @access public
+ */
+ function getDefault() {
+ $default = array();
+ for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
+ if ($this->_options[$i]->getAttribute('selected')) {
+ $default[] = $this->_options[$i]->getDefault();
+ }
+ }
+ return $default;
+ }
+
+ /**
+ * Can only set allowed values.
+ * @param array $values New choices.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($values) {
+ foreach ($values as $value) {
+ $is_option = false;
+ for ($i = 0, $count = count($this->_options); $i < $count; $i++) {
+ if (trim($this->_options[$i]->getContent()) == trim($value)) {
+ $is_option = true;
+ break;
+ }
+ }
+ if (! $is_option) {
+ return false;
+ }
+ }
+ $this->_values = $values;
+ return true;
+ }
+
+ /**
+ * Accessor for current selection value.
+ * @return array List of currently set options.
+ * @access public
+ */
+ function getValue() {
+ if ($this->_values === false) {
+ return $this->getDefault();
+ }
+ return $this->_values;
+ }
+ }
+
+ /**
+ * Option for selection field.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleOptionTag extends SimpleWidget {
+
+ /**
+ * Stashes the attributes.
+ */
+ function SimpleOptionTag($attributes) {
+ $this->SimpleWidget('option', $attributes);
+ }
+
+ /**
+ * Does nothing.
+ * @param string $value Ignored.
+ * @return boolean Not allowed.
+ * @access public
+ */
+ function setValue($value) {
+ return false;
+ }
+
+ /**
+ * Accessor for starting value. Will be set to
+ * the option label if no value exists.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('value') === false) {
+ return $this->getContent();
+ }
+ return $this->getAttribute('value');
+ }
+ }
+
+ /**
+ * Radio button.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleRadioButtonTag extends SimpleWidget {
+
+ /**
+ * Stashes the attributes.
+ * @param array $attributes Hash of attributes.
+ */
+ function SimpleRadioButtonTag($attributes) {
+ $this->SimpleWidget('input', $attributes);
+ if ($this->getAttribute('value') === false) {
+ $this->_setAttribute('value', 'on');
+ }
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+
+ /**
+ * The only allowed value in the one in the
+ * "value" attribute.
+ * @param string $value New value.
+ * @return boolean True if allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if ($value === false) {
+ return parent::setValue($value);
+ }
+ if ($value != $this->getAttribute('value')) {
+ return false;
+ }
+ return parent::setValue($value);
+ }
+
+ /**
+ * Accessor for starting value.
+ * @return string Parsed value.
+ * @access public
+ */
+ function getDefault() {
+ if ($this->getAttribute('checked')) {
+ return $this->getAttribute('value');
+ }
+ return false;
+ }
+ }
+
+ /**
+ * A group of tags with the same name within a form.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleCheckboxGroup {
+ protected $_widgets;
+
+ /**
+ * Starts empty.
+ * @access public
+ */
+ function SimpleCheckboxGroup() {
+ $this->_widgets = array();
+ }
+
+ /**
+ * Accessor for an attribute.
+ * @param string $label Attribute name.
+ * @return boolean Always false.
+ * @access public
+ */
+ function getAttribute($label) {
+ return false;
+ }
+
+ /**
+ * Scans the checkboxes for one with the appropriate
+ * ID field.
+ * @param string $id ID value to try.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isId($id) {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->isId($id)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Adds a tag to the group.
+ * @param SimpleWidget $widget
+ * @access public
+ */
+ function addWidget($widget) {
+ $this->_widgets[] = $widget;
+ }
+
+ /**
+ * Fetches the name for the widget from the first
+ * member.
+ * @return string Name of widget.
+ * @access public
+ */
+ function getName() {
+ if (count($this->_widgets) > 0) {
+ return $this->_widgets[0]->getName();
+ }
+ }
+
+ /**
+ * Accessor for current selected widget or false
+ * if none.
+ * @return string/array Widget values or false if none.
+ * @access public
+ */
+ function getValue() {
+ $values = array();
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->getValue()) {
+ $values[] = $this->_widgets[$i]->getValue();
+ }
+ }
+ return $this->_coerceValues($values);
+ }
+
+ /**
+ * Accessor for starting value that is active.
+ * @return string/array Widget values or false if none.
+ * @access public
+ */
+ function getDefault() {
+ $values = array();
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->getDefault()) {
+ $values[] = $this->_widgets[$i]->getDefault();
+ }
+ }
+ return $this->_coerceValues($values);
+ }
+
+ /**
+ * Accessor for current set values.
+ * @param string/array/boolean $values Either a single string, a
+ * hash or false for nothing set.
+ * @return boolean True if all values can be set.
+ * @access public
+ */
+ function setValue($values) {
+ $values = $this->_makeArray($values);
+ if (! $this->_valuesArePossible($values)) {
+ return false;
+ }
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ $possible = $this->_widgets[$i]->getAttribute('value');
+ if (in_array($this->_widgets[$i]->getAttribute('value'), $values)) {
+ $this->_widgets[$i]->setValue($possible);
+ } else {
+ $this->_widgets[$i]->setValue(false);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests to see if a possible value set is legal.
+ * @param string/array/boolean $values Either a single string, a
+ * hash or false for nothing set.
+ * @return boolean False if trying to set a
+ * missing value.
+ * @access private
+ */
+ function _valuesArePossible($values) {
+ $matches = array();
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ $possible = $this->_widgets[$i]->getAttribute('value');
+ if (in_array($possible, $values)) {
+ $matches[] = $possible;
+ }
+ }
+ return ($values == $matches);
+ }
+
+ /**
+ * Converts the output to an appropriate format. This means
+ * that no values is false, a single value is just that
+ * value and only two or more are contained in an array.
+ * @param array $values List of values of widgets.
+ * @return string/array/boolean Expected format for a tag.
+ * @access private
+ */
+ function _coerceValues($values) {
+ if (count($values) == 0) {
+ return false;
+ } elseif (count($values) == 1) {
+ return $values[0];
+ } else {
+ return $values;
+ }
+ }
+
+ /**
+ * Converts false or string into array. The opposite of
+ * the coercian method.
+ * @param string/array/boolean $value A single item is converted
+ * to a one item list. False
+ * gives an empty list.
+ * @return array List of values, possibly empty.
+ * @access private
+ */
+ function _makeArray($value) {
+ if ($value === false) {
+ return array();
+ }
+ if (is_string($value)) {
+ return array($value);
+ }
+ return $value;
+ }
+ }
+
+ /**
+ * A group of tags with the same name within a form.
+ * Used for radio buttons.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleRadioGroup {
+ protected $_widgets;
+
+ /**
+ * Starts empty.
+ * @access public
+ */
+ function SimpleRadioGroup() {
+ $this->_widgets = array();
+ }
+
+ /**
+ * Accessor for an attribute.
+ * @param string $label Attribute name.
+ * @return boolean Always false.
+ * @access public
+ */
+ function getAttribute($label) {
+ return false;
+ }
+
+ /**
+ * Scans the checkboxes for one with the appropriate
+ * ID field.
+ * @param string $id ID value to try.
+ * @return boolean True if matched.
+ * @access public
+ */
+ function isId($id) {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->isId($id)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Adds a tag to the group.
+ * @param SimpleWidget $widget
+ * @access public
+ */
+ function addWidget($widget) {
+ $this->_widgets[] = $widget;
+ }
+
+ /**
+ * Fetches the name for the widget from the first
+ * member.
+ * @return string Name of widget.
+ * @access public
+ */
+ function getName() {
+ if (count($this->_widgets) > 0) {
+ return $this->_widgets[0]->getName();
+ }
+ }
+
+ /**
+ * Each tag is tried in turn until one is
+ * successfully set. The others will be
+ * unchecked if successful.
+ * @param string $value New value.
+ * @return boolean True if any allowed.
+ * @access public
+ */
+ function setValue($value) {
+ if (! $this->_valueIsPossible($value)) {
+ return false;
+ }
+ $index = false;
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if (! $this->_widgets[$i]->setValue($value)) {
+ $this->_widgets[$i]->setValue(false);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests to see if a value is allowed.
+ * @param string Attempted value.
+ * @return boolean True if a valid value.
+ * @access private
+ */
+ function _valueIsPossible($value) {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->getAttribute('value') == $value) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for current selected widget or false
+ * if none.
+ * @return string/boolean Value attribute or
+ * content of opton.
+ * @access public
+ */
+ function getValue() {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->getValue()) {
+ return $this->_widgets[$i]->getValue();
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Accessor for starting value that is active.
+ * @return string/boolean Value of first checked
+ * widget or false if none.
+ * @access public
+ */
+ function getDefault() {
+ for ($i = 0, $count = count($this->_widgets); $i < $count; $i++) {
+ if ($this->_widgets[$i]->getDefault()) {
+ return $this->_widgets[$i]->getDefault();
+ }
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Tag to aid parsing the form.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleFormTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleFormTag($attributes) {
+ $this->SimpleTag('form', $attributes);
+ }
+ }
+
+ /**
+ * Tag to aid parsing the frames in a page.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleFrameTag extends SimpleTag {
+
+ /**
+ * Starts with a named tag with attributes only.
+ * @param hash $attributes Attribute names and
+ * string values.
+ */
+ function SimpleFrameTag($attributes) {
+ $this->SimpleTag('frame', $attributes);
+ }
+
+ /**
+ * Tag contains no content.
+ * @return boolean False.
+ * @access public
+ */
+ function expectEndTag() {
+ return false;
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/unit_tester.php b/tests/test_tools/simpletest/unit_tester.php
new file mode 100644
index 00000000..fa5e28b4
--- /dev/null
+++ b/tests/test_tools/simpletest/unit_tester.php
@@ -0,0 +1,303 @@
+<?php
+ /**
+ * 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 $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/simple_test.php');
+ require_once(dirname(__FILE__) . '/errors.php');
+ require_once(dirname(__FILE__) . '/dumper.php');
+ /**#@-*/
+
+ /**
+ * Standard unit test class for day to day testing
+ * of PHP code XP style. Adds some useful standard
+ * assertions.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class UnitTestCase extends SimpleTestCase {
+
+ /**
+ * Creates an empty test case. Should be subclassed
+ * with test methods for a functional test case.
+ * @param string $label Name of test case. Will use
+ * the class name if none specified.
+ * @access public
+ */
+ function UnitTestCase($label = false) {
+ if (! $label) {
+ $label = get_class($this);
+ }
+ $this->SimpleTestCase($label);
+ }
+
+ /**
+ * Will be true if the value is null.
+ * @param null $value Supposedly null value.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNull($value, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($value) . "] should be null");
+ return $this->assertTrue(! isset($value), $message);
+ }
+
+ /**
+ * Will be true if the value is set.
+ * @param mixed $value Supposedly set value.
+ * @param string $message Message to display.
+ * @return boolean True on pass.
+ * @access public
+ */
+ function assertNotNull($value, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($value) . "] should not be null");
+ return $this->assertTrue(isset($value), $message);
+ }
+
+ /**
+ * Type and class test. Will pass if class
+ * matches the type name or is a subclass or
+ * if not an object, but the type is correct.
+ * @param mixed $object Object to test.
+ * @param string $type Type name as string.
+ * @param string $message Message to display.
+ * @return boolean True on pass.
+ * @access public
+ */
+ function assertIsA($object, $type, $message = "%s") {
+ return $this->assertExpectation(
+ new IsAExpectation($type),
+ $object,
+ $message);
+ }
+
+ /**
+ * Type and class mismatch test. Will pass if class
+ * name or underling type does not match the one
+ * specified.
+ * @param mixed $object Object to test.
+ * @param string $type Type name as string.
+ * @param string $message Message to display.
+ * @return boolean True on pass.
+ * @access public
+ */
+ function assertNotA($object, $type, $message = "%s") {
+ return $this->assertExpectation(
+ new NotAExpectation($type),
+ $object,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value only. Otherwise a fail.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertEqual($first, $second, $message = "%s") {
+ return $this->assertExpectation(
+ new EqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * a different value. Otherwise a fail.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotEqual($first, $second, $message = "%s") {
+ return $this->assertExpectation(
+ new NotEqualExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the same value and same type. Otherwise a fail.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertIdentical($first, $second, $message = "%s") {
+ return $this->assertExpectation(
+ new IdenticalExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the two parameters have
+ * the different value or different type.
+ * @param mixed $first Value to compare.
+ * @param mixed $second Value to compare.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNotIdentical($first, $second, $message = "%s") {
+ return $this->assertExpectation(
+ new NotIdenticalExpectation($first),
+ $second,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if both parameters refer
+ * to the same object. Fail otherwise.
+ * @param mixed $first Object reference to check.
+ * @param mixed $second Hopefully the same object.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertReference($first, $second, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should reference the same object");
+ return $this->assertTrue(
+ SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if both parameters refer
+ * to different objects. Fail otherwise.
+ * @param mixed $first Object reference to check.
+ * @param mixed $second Hopefully not the same object.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertCopy($first, $second, $message = "%s") {
+ $dumper = new SimpleDumper();
+ $message = sprintf(
+ $message,
+ "[" . $dumper->describeValue($first) .
+ "] and [" . $dumper->describeValue($second) .
+ "] should not be the same object");
+ return $this->assertFalse(
+ SimpleTestCompatibility::isReference($first, $second),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the Perl regex pattern
+ * is found in the subject. Fail otherwise.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $subject String to search in.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertWantedPattern($pattern, $subject, $message = "%s") {
+ return $this->assertExpectation(
+ new WantedPatternExpectation($pattern),
+ $subject,
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the perl regex pattern
+ * is not present in subject. Fail if found.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $subject String to search in.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNoUnwantedPattern($pattern, $subject, $message = "%s") {
+ return $this->assertExpectation(
+ new UnwantedPatternExpectation($pattern),
+ $subject,
+ $message);
+ }
+
+ /**
+ * Confirms that no errors have occoured so
+ * far in the test method.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertNoErrors($message = "%s") {
+ $queue =SimpleErrorQueue::instance();
+ return $this->assertTrue(
+ $queue->isEmpty(),
+ sprintf($message, "Should be no errors"));
+ }
+
+ /**
+ * Confirms that an error has occoured and
+ * optionally that the error text matches exactly.
+ * @param string $expected Expected error text or
+ * false for no check.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertError($expected = false, $message = "%s") {
+ $queue =SimpleErrorQueue::instance();
+ if ($queue->isEmpty()) {
+ $this->fail(sprintf($message, "Expected error not found"));
+ return;
+ }
+ list($severity, $content, $file, $line, $globals) = $queue->extract();
+ $severity = SimpleErrorQueue::getSeverityAsString($severity);
+ return $this->assertTrue(
+ ! $expected || ($expected == $content),
+ "Expected [$expected] in PHP error [$content] severity [$severity] in [$file] line [$line]");
+ }
+
+ /**
+ * Confirms that an error has occoured and
+ * that the error text matches a Perl regular
+ * expression.
+ * @param string $pattern Perl regular expresion to
+ * match against.
+ * @param string $message Message to display.
+ * @return boolean True on pass
+ * @access public
+ */
+ function assertErrorPattern($pattern, $message = "%s") {
+ $queue =SimpleErrorQueue::instance();
+ if ($queue->isEmpty()) {
+ $this->fail(sprintf($message, "Expected error not found"));
+ return;
+ }
+ list($severity, $content, $file, $line, $globals) = $queue->extract();
+ $severity = SimpleErrorQueue::getSeverityAsString($severity);
+ return $this->assertTrue(
+ (boolean)preg_match($pattern, $content),
+ "Expected pattern match [$pattern] in PHP error [$content] severity [$severity] in [$file] line [$line]");
+ }
+ }
+?>
diff --git a/tests/test_tools/simpletest/url.php b/tests/test_tools/simpletest/url.php
new file mode 100644
index 00000000..03902ed0
--- /dev/null
+++ b/tests/test_tools/simpletest/url.php
@@ -0,0 +1,508 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage WebTester
+ * @version $Id: url.php,v 1.22 2005/02/02 23:25:23 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/encoding.php');
+ /**#@-*/
+
+ /**
+ * URL parser to replace parse_url() PHP function which
+ * got broken in PHP 4.3.0. Adds some browser specific
+ * functionality such as expandomatics.
+ * Guesses a bit trying to separate the host from
+ * the path.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleUrl {
+ protected $_scheme;
+ protected $_username;
+ protected $_password;
+ protected $_host;
+ protected $_port;
+ protected $_path;
+ protected $_request;
+ protected $_fragment;
+ protected $_target;
+
+ /**
+ * Constructor. Parses URL into sections.
+ * @param string $url Incoming URL.
+ * @access public
+ */
+ function SimpleUrl($url) {
+ list($x, $y) = $this->_chompCoordinates($url);
+ $this->_scheme = $this->_chompScheme($url);
+ list($this->_username, $this->_password) = $this->_chompLogin($url);
+ $this->_host = $this->_chompHost($url);
+ $this->_port = false;
+ if (preg_match('/(.*?):(.*)/', $this->_host, $host_parts)) {
+ $this->_host = $host_parts[1];
+ $this->_port = (integer)$host_parts[2];
+ }
+ $this->_path = $this->_chompPath($url);
+ $this->_request = $this->_parseRequest($this->_chompRequest($url));
+ $this->_request->setCoordinates($x, $y);
+ $this->_fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false);
+ $this->_target = false;
+ }
+
+ /**
+ * Extracts the X, Y coordinate pair from an image map.
+ * @param string $url URL so far. The coordinates will be
+ * removed.
+ * @return array X, Y as a pair of integers.
+ * @access private
+ */
+ function _chompCoordinates($url) {
+ if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) {
+ $url = $matches[1];
+ return array((integer)$matches[2], (integer)$matches[3]);
+ }
+ return array(false, false);
+ }
+
+ /**
+ * Extracts the scheme part of an incoming URL.
+ * @param string $url URL so far. The scheme will be
+ * removed.
+ * @return string Scheme part or false.
+ * @access private
+ */
+ function _chompScheme($url) {
+ if (preg_match('/(.*?):(\/\/)(.*)/', $url, $matches)) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ }
+ return false;
+ }
+
+ /**
+ * Extracts the username and password from the
+ * incoming URL. The // prefix will be reattached
+ * to the URL after the doublet is extracted.
+ * @param string $url URL so far. The username and
+ * password are removed.
+ * @return array Two item list of username and
+ * password. Will urldecode() them.
+ * @access private
+ */
+ function _chompLogin($url) {
+ $prefix = '';
+ if (preg_match('/(\/\/)(.*)/', $url, $matches)) {
+ $prefix = $matches[1];
+ $url = $matches[2];
+ }
+ if (preg_match('/(.*?)@(.*)/', $url, $matches)) {
+ $url = $prefix . $matches[2];
+ $parts = split(":", $matches[1]);
+ return array(
+ urldecode($parts[0]),
+ isset($parts[1]) ? urldecode($parts[1]) : false);
+ }
+ $url = $prefix . $url;
+ return array(false, false);
+ }
+
+ /**
+ * Extracts the host part of an incoming URL.
+ * Includes the port number part. Will extract
+ * the host if it starts with // or it has
+ * a top level domain or it has at least two
+ * dots.
+ * @param string $url URL so far. The host will be
+ * removed.
+ * @return string Host part guess or false.
+ * @access private
+ */
+ function _chompHost($url) {
+ if (preg_match('/(\/\/)(.*?)(\/.*|\?.*|#.*|$)/', $url, $matches)) {
+ $url = $matches[3];
+ return $matches[2];
+ }
+ if (preg_match('/(.*?)(\.\.\/|\.\/|\/|\?|#|$)(.*)/', $url, $matches)) {
+ $tlds = SimpleUrl::getAllTopLevelDomains();
+ if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ } elseif (preg_match('/[a-z0-9\-]+\.[a-z0-9\-]+\.[a-z0-9\-]+/i', $matches[1])) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Extracts the path information from the incoming
+ * URL. Strips this path from the URL.
+ * @param string $url URL so far. The host will be
+ * removed.
+ * @return string Path part or '/'.
+ * @access private
+ */
+ function _chompPath($url) {
+ if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) {
+ $url = $matches[2] . $matches[3];
+ return ($matches[1] ? $matches[1] : '');
+ }
+ return '';
+ }
+
+ /**
+ * Strips off the request data.
+ * @param string $url URL so far. The request will be
+ * removed.
+ * @return string Raw request part.
+ * @access private
+ */
+ function _chompRequest($url) {
+ if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) {
+ $url = $matches[2] . $matches[3];
+ return $matches[1];
+ }
+ return '';
+ }
+
+ /**
+ * Breaks the request down into an object.
+ * @param string $raw Raw request.
+ * @return SimpleFormEncoding Parsed data.
+ * @access private
+ */
+ function _parseRequest($raw) {
+ $request = new SimpleFormEncoding();
+ foreach (split("&", $raw) as $pair) {
+ if (preg_match('/(.*?)=(.*)/', $pair, $matches)) {
+ $request->add($matches[1], urldecode($matches[2]));
+ } elseif ($pair) {
+ $request->add($pair, '');
+ }
+ }
+ return $request;
+ }
+
+ /**
+ * Accessor for protocol part.
+ * @param string $default Value to use if not present.
+ * @return string Scheme name, e.g "http".
+ * @access public
+ */
+ function getScheme($default = false) {
+ return $this->_scheme ? $this->_scheme : $default;
+ }
+
+ /**
+ * Accessor for user name.
+ * @return string Username preceding host.
+ * @access public
+ */
+ function getUsername() {
+ return $this->_username;
+ }
+
+ /**
+ * Accessor for password.
+ * @return string Password preceding host.
+ * @access public
+ */
+ function getPassword() {
+ return $this->_password;
+ }
+
+ /**
+ * Accessor for hostname and port.
+ * @param string $default Value to use if not present.
+ * @return string Hostname only.
+ * @access public
+ */
+ function getHost($default = false) {
+ return $this->_host ? $this->_host : $default;
+ }
+
+ /**
+ * Accessor for top level domain.
+ * @return string Last part of host.
+ * @access public
+ */
+ function getTld() {
+ $path_parts = pathinfo($this->getHost());
+ return (isset($path_parts['extension']) ? $path_parts['extension'] : false);
+ }
+
+ /**
+ * Accessor for port number.
+ * @return integer TCP/IP port number.
+ * @access public
+ */
+ function getPort() {
+ return $this->_port;
+ }
+
+ /**
+ * Accessor for path.
+ * @return string Full path including leading slash if implied.
+ * @access public
+ */
+ function getPath() {
+ if (! $this->_path && $this->_host) {
+ return '/';
+ }
+ return $this->_path;
+ }
+
+ /**
+ * Accessor for page if any. This may be a
+ * directory name if ambiguious.
+ * @return Page name.
+ * @access public
+ */
+ function getPage() {
+ if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) {
+ return false;
+ }
+ return $matches[1];
+ }
+
+ /**
+ * Gets the path to the page.
+ * @return string Path less the page.
+ * @access public
+ */
+ function getBasePath() {
+ if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) {
+ return false;
+ }
+ return $matches[1];
+ }
+
+ /**
+ * Accessor for fragment at end of URL after the "#".
+ * @return string Part after "#".
+ * @access public
+ */
+ function getFragment() {
+ return $this->_fragment;
+ }
+
+ /**
+ * Accessor for horizontal image coordinate.
+ * @return integer X value.
+ * @access public
+ */
+ function getX() {
+ return $this->_request->getX();
+ }
+
+ /**
+ * Accessor for vertical image coordinate.
+ * @return integer Y value.
+ * @access public
+ */
+ function getY() {
+ return $this->_request->getY();
+ }
+
+ /**
+ * Accessor for current request parameters
+ * in URL string form
+ * @return string Form is string "?a=1&b=2", etc.
+ * @access public
+ */
+ function getEncodedRequest() {
+ $encoded = $this->_request->asString();
+ if ($encoded) {
+ return '?' . preg_replace('/^\?/', '', $encoded);
+ }
+ return '';
+ }
+
+ /**
+ * Adds an additional parameter to the request.
+ * @param string $key Name of parameter.
+ * @param string $value Value as string.
+ * @access public
+ */
+ function addRequestParameter($key, $value) {
+ $this->_request->add($key, $value);
+ }
+
+ /**
+ * Adds additional parameters to the request.
+ * @param hash/SimpleFormEncoding $parameters Additional
+ * parameters.
+ * @access public
+ */
+ function addRequestParameters($parameters) {
+ $this->_request->merge($parameters);
+ }
+
+ /**
+ * Clears down all parameters.
+ * @access public
+ */
+ function clearRequest() {
+ $this->_request = new SimpleFormEncoding();
+ }
+
+ /**
+ * Sets image coordinates. Set to flase to clear
+ * them.
+ * @param integer $x Horizontal position.
+ * @param integer $y Vertical position.
+ * @access public
+ */
+ function setCoordinates($x = false, $y = false) {
+ $this->_request->setCoordinates($x, $y);
+ }
+
+ /**
+ * Gets the frame target if present. Although
+ * not strictly part of the URL specification it
+ * acts as similarily to the browser.
+ * @return boolean/string Frame name or false if none.
+ * @access public
+ */
+ function getTarget() {
+ return $this->_target;
+ }
+
+ /**
+ * Attaches a frame target.
+ * @param string $frame Name of frame.
+ * @access public
+ */
+ function setTarget($frame) {
+ $this->_target = $frame;
+ }
+
+ /**
+ * Renders the URL back into a string.
+ * @return string URL in canonical form.
+ * @access public
+ */
+ function asString() {
+ $scheme = $identity = $host = $path = $encoded = $fragment = '';
+ if ($this->_username && $this->_password) {
+ $identity = $this->_username . ':' . $this->_password . '@';
+ }
+ if ($this->getHost()) {
+ $scheme = $this->getScheme() ? $this->getScheme() : 'http';
+ $host = $this->getHost();
+ }
+ if (substr($this->_path, 0, 1) == '/') {
+ $path = $this->normalisePath($this->_path);
+ }
+ $encoded = $this->getEncodedRequest();
+ $fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
+ return "$scheme://$identity$host$path$encoded$fragment";
+ }
+
+ /**
+ * Replaces unknown sections to turn a relative
+ * URL into an absolute one. The base URL can
+ * be either a string or a SimpleUrl object.
+ * @param string/SimpleUrl $base Base URL.
+ * @access public
+ */
+ function makeAbsolute($base) {
+ if (! is_object($base)) {
+ $base = new SimpleUrl($base);
+ }
+ $scheme = $this->getScheme() ? $this->getScheme() : $base->getScheme();
+ $host = $this->getHost() ? $this->getHost() : $base->getHost();
+ $port = $this->_extractAbsolutePort($base);
+ $path = $this->normalisePath($this->_extractAbsolutePath($base));
+ $identity = $this->_getIdentity() ? $this->_getIdentity() . '@' : '';
+ $encoded = $this->getEncodedRequest();
+ $fragment = $this->getFragment() ? '#'. $this->getFragment() : '';
+ return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment");
+ }
+
+ /**
+ * Extracts the port from the base URL if it's needed, but
+ * not present, in the current URL.
+ * @param string/SimpleUrl $base Base URL.
+ * @param string Absolute port number.
+ * @access private
+ */
+ function _extractAbsolutePort($base) {
+ if ($this->getHost()) {
+ return ($this->getPort() ? ':' . $this->getPort() : '');
+ }
+ return ($base->getPort() ? ':' . $base->getPort() : '');
+ }
+
+ /**
+ * Replaces unknown sections of the path with base parts
+ * to return a complete absolute one.
+ * @param string/SimpleUrl $base Base URL.
+ * @param string Absolute path.
+ * @access private
+ */
+ function _extractAbsolutePath($base) {
+ if ($this->getHost()) {
+ return $this->_path;
+ }
+ if (! $this->_isRelativePath($this->_path)) {
+ return $this->_path;
+ }
+ if ($this->_path) {
+ return $base->getBasePath() . $this->_path;
+ }
+ return $base->getPath();
+ }
+
+ /**
+ * Simple test to see if a path part is relative.
+ * @param string $path Path to test.
+ * @return boolean True if starts with a "/".
+ * @access private
+ */
+ function _isRelativePath($path) {
+ return (substr($path, 0, 1) != '/');
+ }
+
+ /**
+ * Extracts the username and password for use in rendering
+ * a URL.
+ * @return string/boolean Form of username:password@ or false.
+ * @access private
+ */
+ function _getIdentity() {
+ if ($this->_username && $this->_password) {
+ return $this->_username . ':' . $this->_password;
+ }
+ return false;
+ }
+
+ /**
+ * Replaces . and .. sections of the path.
+ * @param string $path Unoptimised path.
+ * @return string Path with dots removed if possible.
+ * @access public
+ */
+ function normalisePath($path) {
+ $path = preg_replace('|/[^/]+/\.\./|', '/', $path);
+ return preg_replace('|/\./|', '/', $path);
+ }
+
+ /**
+ * A pipe seperated list of all TLDs that result in two part
+ * domain names.
+ * @return string Pipe separated list.
+ * @access public
+ * @static
+ */
+ function getAllTopLevelDomains() {
+ return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum';
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/user_agent.php b/tests/test_tools/simpletest/user_agent.php
new file mode 100644
index 00000000..c65d5110
--- /dev/null
+++ b/tests/test_tools/simpletest/user_agent.php
@@ -0,0 +1,490 @@
+<?php
+ /**
+ * 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 $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ 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);
+
+ /**
+ * 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);
+ }
+ }
+ }
+
+ /**
+ * Fetches web pages whilst keeping track of
+ * cookies and authentication.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class SimpleUserAgent {
+ protected $_cookie_jar;
+ protected $_authenticator;
+ protected $_max_redirects;
+ protected $_proxy;
+ protected $_proxy_username;
+ protected $_proxy_password;
+ protected $_connection_timeout;
+ protected $_additional_headers;
+
+ /**
+ * Starts with no cookies, realms or proxies.
+ * @access public
+ */
+ function SimpleUserAgent() {
+ $this->_cookie_jar = new SimpleCookieJar();
+ $this->_authenticator = new SimpleAuthenticator();
+ $this->setMaximumRedirects(DEFAULT_MAX_REDIRECTS);
+ $this->_proxy = false;
+ $this->_proxy_username = false;
+ $this->_proxy_password = false;
+ $this->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
+ $this->_additional_headers = array();
+ }
+
+ /**
+ * Removes expired and temporary cookies as if
+ * the browser was closed and re-opened. Authorisation
+ * has to be obtained again as well.
+ * @param string/integer $date Time when session restarted.
+ * If omitted then all persistent
+ * cookies are kept.
+ * @access public
+ */
+ function restart($date = false) {
+ $this->_cookie_jar->restartSession($date);
+ $this->_authenticator->restartSession();
+ }
+
+ /**
+ * Adds a header to every fetch.
+ * @param string $header Header line to add to every
+ * request until cleared.
+ * @access public
+ */
+ function addHeader($header) {
+ $this->_additional_headers[] = $header;
+ }
+
+ /**
+ * Ages the cookies by the specified time.
+ * @param integer $interval Amount in seconds.
+ * @access public
+ */
+ function ageCookies($interval) {
+ $this->_cookie_jar->agePrematurely($interval);
+ }
+
+ /**
+ * Sets an additional cookie. If a cookie has
+ * the same name and path it is replaced.
+ * @param string $name Cookie key.
+ * @param string $value Value of cookie.
+ * @param string $host Host upon which the cookie is valid.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date.
+ * @access public
+ */
+ function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
+ $cookie = new SimpleCookie($name, $value, $path, $expiry);
+ if ($host) {
+ $cookie->setHost($host);
+ }
+ $this->_cookie_jar->setCookie($cookie);
+ }
+
+ /**
+ * Reads the most specific cookie value from the
+ * browser cookies.
+ * @param string $host Host to search.
+ * @param string $path Applicable path.
+ * @param string $name Name of cookie to read.
+ * @return string False if not present, else the
+ * value as a string.
+ * @access public
+ */
+ function getCookieValue($host, $path, $name) {
+ $longest_path = '';
+ foreach ($this->_cookie_jar->getValidCookies($host, $path) as $cookie) {
+ if ($name == $cookie->getName()) {
+ if (strlen($cookie->getPath()) > strlen($longest_path)) {
+ $value = $cookie->getValue();
+ $longest_path = $cookie->getPath();
+ }
+ }
+ }
+ return (isset($value) ? $value : false);
+ }
+
+ /**
+ * Reads the current cookies within the base URL.
+ * @param string $name Key of cookie to find.
+ * @param SimpleUrl $base Base URL to search from.
+ * @return string Null if there is no base URL, false
+ * if the cookie is not set.
+ * @access public
+ */
+ function getBaseCookieValue($name, $base) {
+ if (! $base) {
+ return null;
+ }
+ return $this->getCookieValue($base->getHost(), $base->getPath(), $name);
+ }
+
+ /**
+ * Sets the socket timeout for opening a connection.
+ * @param integer $timeout Maximum time in seconds.
+ * @access public
+ */
+ function setConnectionTimeout($timeout) {
+ $this->_connection_timeout = $timeout;
+ }
+
+ /**
+ * Sets the maximum number of redirects before
+ * a page will be loaded anyway.
+ * @param integer $max Most hops allowed.
+ * @access public
+ */
+ function setMaximumRedirects($max) {
+ $this->_max_redirects = $max;
+ }
+
+ /**
+ * Sets proxy to use on all requests for when
+ * testing from behind a firewall. Set URL
+ * to false to disable.
+ * @param string $proxy Proxy URL.
+ * @param string $username Proxy username for authentication.
+ * @param string $password Proxy password for authentication.
+ * @access public
+ */
+ function useProxy($proxy, $username, $password) {
+ if (! $proxy) {
+ $this->_proxy = false;
+ return;
+ }
+ if (strncmp($proxy, 'http://', 7) != 0) {
+ $proxy = 'http://'. $proxy;
+ }
+ $this->_proxy = new SimpleUrl($proxy);
+ $this->_proxy_username = $username;
+ $this->_proxy_password = $password;
+ }
+
+ /**
+ * Test to see if the redirect limit is passed.
+ * @param integer $redirects Count so far.
+ * @return boolean True if over.
+ * @access private
+ */
+ function _isTooManyRedirects($redirects) {
+ return ($redirects > $this->_max_redirects);
+ }
+
+ /**
+ * Sets the identity for the current realm.
+ * @param string $host Host to which realm applies.
+ * @param string $realm Full name of realm.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @access public
+ */
+ function setIdentity($host, $realm, $username, $password) {
+ $this->_authenticator->setIdentityForRealm($host, $realm, $username, $password);
+ }
+
+ /**
+ * Fetches a URL as a response object. Will keep trying if redirected.
+ * It will also collect authentication realm information.
+ * @param string $method GET, POST, etc.
+ * @param string/SimpleUrl $url Target to fetch.
+ * @param SimpleFormEncoding $parameters Additional parameters for request.
+ * @return SimpleHttpResponse Hopefully the target page.
+ * @access public
+ */
+ function fetchResponse($method, $url, $parameters = false) {
+ if ($method != 'POST') {
+ $url->addRequestParameters($parameters);
+ $parameters = false;
+ }
+ $response = $this->_fetchWhileRedirected($method, $url, $parameters);
+ if ($headers = $response->getHeaders()) {
+ if ($headers->isChallenge()) {
+ $this->_authenticator->addRealm(
+ $url,
+ $headers->getAuthentication(),
+ $headers->getRealm());
+ }
+ }
+ return $response;
+ }
+
+ /**
+ * Fetches the page until no longer redirected or
+ * until the redirect limit runs out.
+ * @param string $method GET, POST, etc.
+ * @param SimpleUrl $url Target to fetch.
+ * @param SimpelFormEncoding $parameters Additional parameters for request.
+ * @return SimpleHttpResponse Hopefully the target page.
+ * @access private
+ */
+ function _fetchWhileRedirected($method, $url, $parameters) {
+ $redirects = 0;
+ do {
+ $response = $this->_fetch($method, $url, $parameters);
+ if ($response->isError()) {
+ return $response;
+ }
+ $headers = $response->getHeaders();
+ $location = new SimpleUrl($headers->getLocation());
+ $url = $location->makeAbsolute($url);
+ $this->_addCookiesToJar($url, $headers->getNewCookies());
+ if (! $headers->isRedirect()) {
+ break;
+ }
+ $method = 'GET';
+ $parameters = false;
+ } while (! $this->_isTooManyRedirects(++$redirects));
+ return $response;
+ }
+
+ /**
+ * Actually make the web request.
+ * @param string $method GET, POST, etc.
+ * @param SimpleUrl $url Target to fetch.
+ * @param SimpleFormEncoding $parameters Additional parameters for request.
+ * @return SimpleHttpResponse Headers and hopefully content.
+ * @access protected
+ */
+ function _fetch($method, $url, $parameters) {
+ if (! $parameters) {
+ $parameters = new SimpleFormEncoding();
+ }
+ $request = $this->_createRequest($method, $url, $parameters);
+ return $request->fetch($this->_connection_timeout);
+ }
+
+ /**
+ * Creates a full page request.
+ * @param string $method Fetching method.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @param SimpleFormEncoding $parameters POST/GET parameters.
+ * @return SimpleHttpRequest New request.
+ * @access private
+ */
+ function _createRequest($method, $url, $parameters) {
+ $request = $this->_createHttpRequest($method, $url, $parameters);
+ $this->_addAdditionalHeaders($request);
+ $this->_cookie_jar->addHeaders($request, $url);
+ $this->_authenticator->addHeaders($request, $url);
+ return $request;
+ }
+
+ /**
+ * Builds the appropriate HTTP request object.
+ * @param string $method Fetching method.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @param SimpleFormEncoding $parameters POST/GET parameters.
+ * @return SimpleHttpRequest New request object.
+ * @access protected
+ */
+ function _createHttpRequest($method, $url, $parameters) {
+ if ($method == 'POST') {
+ $request = new SimpleHttpRequest(
+ $this->_createRoute($url),
+ 'POST',
+ $parameters);
+ return $request;
+ }
+ if ($parameters) {
+ $url->addRequestParameters($parameters);
+ }
+ return new SimpleHttpRequest($this->_createRoute($url), $method);
+ }
+
+ /**
+ * Sets up either a direct route or via a proxy.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @return SimpleRoute Route to take to fetch URL.
+ * @access protected
+ */
+ function _createRoute($url) {
+ if ($this->_proxy) {
+ return new SimpleProxyRoute(
+ $url,
+ $this->_proxy,
+ $this->_proxy_username,
+ $this->_proxy_password);
+ }
+ return new SimpleRoute($url);
+ }
+
+ /**
+ * Adds additional manual headers.
+ * @param SimpleHttpRequest $request Outgoing request.
+ * @access private
+ */
+ function _addAdditionalHeaders($request) {
+ foreach ($this->_additional_headers as $header) {
+ $request->addHeaderLine($header);
+ }
+ }
+
+ /**
+ * Extracts new cookies into the cookie jar.
+ * @param SimpleUrl $url Target to fetch as url object.
+ * @param array $cookies New cookies.
+ * @access private
+ */
+ function _addCookiesToJar($url, $cookies) {
+ foreach ($cookies as $cookie) {
+ if ($url->getHost()) {
+ $cookie->setHost($url->getHost());
+ }
+ $this->_cookie_jar->setCookie($cookie);
+ }
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/web_tester.php b/tests/test_tools/simpletest/web_tester.php
new file mode 100644
index 00000000..4981d25a
--- /dev/null
+++ b/tests/test_tools/simpletest/web_tester.php
@@ -0,0 +1,1330 @@
+<?php
+ /**
+ * 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 $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/simple_test.php');
+ require_once(dirname(__FILE__) . '/browser.php');
+ require_once(dirname(__FILE__) . '/page.php');
+ require_once(dirname(__FILE__) . '/expectation.php');
+ /**#@-*/
+
+ /**
+ * Test for an HTML widget value match.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class FieldExpectation extends SimpleExpectation {
+ protected $_value;
+
+ /**
+ * Sets the field value to compare against.
+ * @param mixed $value Test value to match.
+ * @access public
+ */
+ function FieldExpectation($value) {
+ $this->SimpleExpectation();
+ if (is_array($value)) {
+ sort($value);
+ }
+ $this->_value = $value;
+ }
+
+ /**
+ * Tests the expectation. True if it matches
+ * a string value or an array value in any order.
+ * @param mixed $compare Comparison value. False for
+ * an unset field.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ if ($this->_value === false) {
+ return ($compare === false);
+ }
+ if ($this->_isSingle($this->_value)) {
+ return $this->_testSingle($compare);
+ }
+ if (is_array($this->_value)) {
+ return $this->_testMultiple($compare);
+ }
+ return false;
+ }
+
+ /**
+ * Tests for valid field comparisons with a single option.
+ * @param mixed $value Value to type check.
+ * @return boolean True if integer, string or float.
+ * @access private
+ */
+ function _isSingle($value) {
+ return is_string($value) || is_integer($value) || is_float($value);
+ }
+
+ /**
+ * String comparison for simple field with a single option.
+ * @param mixed $compare String to test against.
+ * @returns boolean True if matching.
+ * @access private
+ */
+ function _testSingle($compare) {
+ if (is_array($compare) && count($compare) == 1) {
+ $compare = $compare[0];
+ }
+ if (! $this->_isSingle($compare)) {
+ return false;
+ }
+ return ($this->_value == $compare);
+ }
+
+ /**
+ * List comparison for multivalue field.
+ * @param mixed $compare List in any order to test against.
+ * @returns boolean True if matching.
+ * @access private
+ */
+ function _testMultiple($compare) {
+ if (is_string($compare)) {
+ $compare = array($compare);
+ }
+ if (! is_array($compare)) {
+ return false;
+ }
+ sort($compare);
+ return ($this->_value === $compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $dumper = $this->_getDumper();
+ if (is_array($compare)) {
+ sort($compare);
+ }
+ if ($this->test($compare)) {
+ return "Field expectation [" . $dumper->describeValue($this->_value) . "]";
+ } else {
+ return "Field expectation [" . $dumper->describeValue($this->_value) .
+ "] fails with [" .
+ $this->_dumper->describeValue($compare) . "] " .
+ $this->_dumper->describeDifference($this->_value, $compare);
+ }
+ }
+ }
+
+ /**
+ * Test for a specific HTTP header within a header block.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class HttpHeaderExpectation extends SimpleExpectation {
+ protected $_expected_header;
+ protected $_expected_value;
+
+ /**
+ * Sets the field and value to compare against.
+ * @param string $header Case insenstive trimmed header name.
+ * @param string $value Optional value to compare. If not
+ * given then any value will match.
+ */
+ function HttpHeaderExpectation($header, $value = false) {
+ $this->_expected_header = $this->_normaliseHeader($header);
+ $this->_expected_value = $value;
+ }
+
+ /**
+ * Accessor for subclases.
+ * @return mixed Expectation set in constructor.
+ * @access protected
+ */
+ function _getExpectation() {
+ return $this->_expected_value;
+ }
+
+ /**
+ * Removes whitespace at ends and case variations.
+ * @param string $header Name of header.
+ * @param string Trimmed and lowecased header
+ * name.
+ * @access private
+ */
+ function _normaliseHeader($header) {
+ return strtolower(trim($header));
+ }
+
+ /**
+ * Tests the expectation. True if it matches
+ * a string value or an array value in any order.
+ * @param mixed $compare Raw header block to search.
+ * @return boolean True if header present.
+ * @access public
+ */
+ function test($compare) {
+ return is_string($this->_findHeader($compare));
+ }
+
+ /**
+ * Searches the incoming result. Will extract the matching
+ * line as text.
+ * @param mixed $compare Raw header block to search.
+ * @return string Matching header line.
+ * @access protected
+ */
+ function _findHeader($compare) {
+ $lines = split("\r\n", $compare);
+ foreach ($lines as $line) {
+ if ($this->_testHeaderLine($line)) {
+ return $line;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Compares a single header line against the expectation.
+ * @param string $line A single line to compare.
+ * @return boolean True if matched.
+ * @access private
+ */
+ function _testHeaderLine($line) {
+ if (count($parsed = split(':', $line)) < 2) {
+ return false;
+ }
+ list($header, $value) = $parsed;
+ if ($this->_normaliseHeader($header) != $this->_expected_header) {
+ return false;
+ }
+ return $this->_testHeaderValue($value, $this->_expected_value);
+ }
+
+ /**
+ * Tests the value part of the header.
+ * @param string $value Value to test.
+ * @param mixed $expected Value to test against.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ function _testHeaderValue($value, $expected) {
+ if ($expected === false) {
+ return true;
+ }
+ return (trim($value) == trim($expected));
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Raw header block to search.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $expectation = $this->_expected_header;
+ if ($this->_expected_value) {
+ $expectation .= ': ' . $this->_expected_header;
+ }
+ if (is_string($line = $this->_findHeader($compare))) {
+ return "Searching for header [$expectation] found [$line]";
+ } else {
+ return "Failed to find header [$expectation]";
+ }
+ }
+ }
+
+ /**
+ * Test for a specific HTTP header within a header block that
+ * should not be found.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class HttpUnwantedHeaderExpectation extends HttpHeaderExpectation {
+ protected $_expected_header;
+ protected $_expected_value;
+
+ /**
+ * Sets the field and value to compare against.
+ * @param string $unwanted Case insenstive trimmed header name.
+ */
+ function HttpUnwantedHeaderExpectation($unwanted) {
+ $this->HttpHeaderExpectation($unwanted);
+ }
+
+ /**
+ * Tests that the unwanted header is not found.
+ * @param mixed $compare Raw header block to search.
+ * @return boolean True if header present.
+ * @access public
+ */
+ function test($compare) {
+ return ($this->_findHeader($compare) === false);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Raw header block to search.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ $expectation = $this->_getExpectation();
+ if (is_string($line = $this->_findHeader($compare))) {
+ return "Found unwanted header [$expectation] with [$line]";
+ } else {
+ return "Did not find unwanted header [$expectation]";
+ }
+ }
+ }
+
+ /**
+ * Test for a specific HTTP header within a header block.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class HttpHeaderPatternExpectation extends HttpHeaderExpectation {
+
+ /**
+ * Sets the field and value to compare against.
+ * @param string $header Case insenstive header name.
+ * @param string $pattern Pattern to compare value against.
+ * @access public
+ */
+ function HttpHeaderPatternExpectation($header, $pattern) {
+ $this->HttpHeaderExpectation($header, $pattern);
+ }
+
+ /**
+ * Tests the value part of the header.
+ * @param string $value Value to test.
+ * @param mixed $pattern Pattern to test against.
+ * @return boolean True if matched.
+ * @access protected
+ */
+ function _testHeaderValue($value, $expected) {
+ return (boolean)preg_match($expected, trim($value));
+ }
+ }
+
+ /**
+ * Test for a text substring.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class WantedTextExpectation extends SimpleExpectation {
+ protected $_substring;
+
+ /**
+ * Sets the value to compare against.
+ * @param string $substring Text to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function WantedTextExpectation($substring, $message = '%s') {
+ $this->SimpleExpectation($message);
+ $this->_substring = $substring;
+ }
+
+ /**
+ * Accessor for the substring.
+ * @return string Text to match.
+ * @access protected
+ */
+ function _getSubstring() {
+ return $this->_substring;
+ }
+
+ /**
+ * Tests the expectation. True if the text contains the
+ * substring.
+ * @param string $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return (strpos($compare, $this->_substring) !== false);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param mixed $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ return $this->_describeTextMatch($this->_getSubstring(), $compare);
+ } else {
+ $dumper = $this->_getDumper();
+ return "Text [" . $this->_getSubstring() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ }
+ }
+
+ /**
+ * Describes a pattern match including the string
+ * found and it's position.
+ * @param string $substring Text to search for.
+ * @param string $subject Subject to search.
+ * @access protected
+ */
+ function _describeTextMatch($substring, $subject) {
+ $position = strpos($subject, $substring);
+ $dumper = $this->_getDumper();
+ return "Text [$substring] detected at character [$position] in [" .
+ $dumper->describeValue($subject) . "] in region [" .
+ $dumper->clipString($subject, 100, $position) . "]";
+ }
+ }
+
+ /**
+ * Fail if a substring is detected within the
+ * comparison text.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class UnwantedTextExpectation extends WantedTextExpectation {
+
+ /**
+ * Sets the reject pattern
+ * @param string $substring Text to search for.
+ * @param string $message Customised message on failure.
+ * @access public
+ */
+ function UnwantedTextExpectation($substring, $message = '%s') {
+ $this->WantedTextExpectation($substring, $message);
+ }
+
+ /**
+ * Tests the expectation. False if the substring appears
+ * in the text.
+ * @param string $compare Comparison value.
+ * @return boolean True if correct.
+ * @access public
+ */
+ function test($compare) {
+ return ! parent::test($compare);
+ }
+
+ /**
+ * Returns a human readable test message.
+ * @param string $compare Comparison value.
+ * @return string Description of success
+ * or failure.
+ * @access public
+ */
+ function testMessage($compare) {
+ if ($this->test($compare)) {
+ $dumper = $this->_getDumper();
+ return "Text [" . $this->_getSubstring() .
+ "] not detected in [" .
+ $dumper->describeValue($compare) . "]";
+ } else {
+ return $this->_describeTextMatch($this->_getSubstring(), $compare);
+ }
+ }
+ }
+
+ /**
+ * Extension that builds a web browser at the start of each
+ * test.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class WebTestCaseInvoker extends SimpleInvokerDecorator {
+
+ /**
+ * Takes in the test case and reporter to mediate between.
+ * @param SimpleTestCase $test_case Test case to run.
+ * @param SimpleScorer $scorer Reporter to receive events.
+ */
+ function WebTestCaseInvoker($invoker) {
+ $this->SimpleInvokerDecorator($invoker);
+ }
+
+ /**
+ * Builds the browser and runs the test.
+ * @param string $method Test method to call.
+ * @access public
+ */
+ function invoke($method) {
+ $test = $this->getTestCase();
+ $test->setBrowser($test->createBrowser());
+ parent::invoke($method);
+ $test->unsetBrowser();
+ }
+ }
+
+ /**
+ * Test case for testing of web pages. Allows
+ * fetching of pages, parsing of HTML and
+ * submitting forms.
+ * @package SimpleTest
+ * @subpackage WebTester
+ */
+ class WebTestCase extends SimpleTestCase {
+ protected $_browser;
+
+ /**
+ * Creates an empty test case. Should be subclassed
+ * with test methods for a functional test case.
+ * @param string $label Name of test case. Will use
+ * the class name if none specified.
+ * @access public
+ */
+ function WebTestCase($label = false) {
+ $this->SimpleTestCase($label);
+ }
+
+ /**
+ * Sets the invoker to one that restarts the browser on
+ * each request.
+ * @return SimpleInvoker Invoker for each method.
+ * @access public
+ */
+ function createInvoker() {
+ return new WebTestCaseInvoker(parent::createInvoker());
+ }
+
+ /**
+ * Gets a current browser reference for setting
+ * special expectations or for detailed
+ * examination of page fetches.
+ * @return SimpleBrowser Current test browser object.
+ * @access public
+ */
+ function getBrowser() {
+ return $this->_browser;
+ }
+
+ /**
+ * Gets a current browser reference for setting
+ * special expectations or for detailed
+ * examination of page fetches.
+ * @param SimpleBrowser $browser New test browser object.
+ * @access public
+ */
+ function setBrowser($browser) {
+ return $this->_browser = $browser;
+ }
+
+ /**
+ * Clears the current browser reference to help the
+ * PHP garbage collector.
+ * @access public
+ */
+ function unsetBrowser() {
+ unset($this->_browser);
+ }
+
+ /**
+ * Creates a new default web browser object.
+ * Will be cleared at the end of the test method.
+ * @return TestBrowser New browser.
+ * @access public
+ */
+ function createBrowser() {
+ return new SimpleBrowser();
+ }
+
+ /**
+ * Gets the last response error.
+ * @return string Last low level HTTP error.
+ * @access public
+ */
+ function getTransportError() {
+ return $this->_browser->getTransportError();
+ }
+
+ /**
+ * Accessor for the currently selected URL.
+ * @return string Current location or false if
+ * no page yet fetched.
+ * @access public
+ */
+ function getUrl() {
+ return $this->_browser->getUrl();
+ }
+
+ /**
+ * Dumps the current request for debugging.
+ * @access public
+ */
+ function showRequest() {
+ $this->dump($this->_browser->getRequest());
+ }
+
+ /**
+ * Dumps the current HTTP headers for debugging.
+ * @access public
+ */
+ function showHeaders() {
+ $this->dump($this->_browser->getHeaders());
+ }
+
+ /**
+ * Dumps the current HTML source for debugging.
+ * @access public
+ */
+ function showSource() {
+ $this->dump($this->_browser->getContent());
+ }
+
+ /**
+ * Simulates the closing and reopening of the browser.
+ * Temporary cookies will be discarded and timed
+ * cookies will be expired if later than the
+ * specified time.
+ * @param string/integer $date Time when session restarted.
+ * If ommitted then all persistent
+ * cookies are kept. Time is either
+ * Cookie format string or timestamp.
+ * @access public
+ */
+ function restart($date = false) {
+ if ($date === false) {
+ $date = time();
+ }
+ $this->_browser->restart($date);
+ }
+
+ /**
+ * Moves cookie expiry times back into the past.
+ * Useful for testing timeouts and expiries.
+ * @param integer $interval Amount to age in seconds.
+ * @access public
+ */
+ function ageCookies($interval) {
+ $this->_browser->ageCookies($interval);
+ }
+
+ /**
+ * Disables frames support. Frames will not be fetched
+ * and the frameset page will be used instead.
+ * @access public
+ */
+ function ignoreFrames() {
+ $this->_browser->ignoreFrames();
+ }
+
+ /**
+ * Adds a header to every fetch.
+ * @param string $header Header line to add to every
+ * request until cleared.
+ * @access public
+ */
+ function addHeader($header) {
+ $this->_browser->addHeader($header);
+ }
+
+ /**
+ * Sets the maximum number of redirects before
+ * the web page is loaded regardless.
+ * @param integer $max Maximum hops.
+ * @access public
+ */
+ function setMaximumRedirects($max) {
+ if (! $this->_browser) {
+ trigger_error(
+ 'Can only set maximum redirects in a test method, setUp() or tearDown()');
+ }
+ $this->_browser->setMaximumRedirects($max);
+ }
+
+ /**
+ * Sets the socket timeout for opening a connection and
+ * receiving at least one byte of information.
+ * @param integer $timeout Maximum time in seconds.
+ * @access public
+ */
+ function setConnectionTimeout($timeout) {
+ $this->_browser->setConnectionTimeout($timeout);
+ }
+
+ /**
+ * Sets proxy to use on all requests for when
+ * testing from behind a firewall. Set URL
+ * to false to disable.
+ * @param string $proxy Proxy URL.
+ * @param string $username Proxy username for authentication.
+ * @param string $password Proxy password for authentication.
+ * @access public
+ */
+ function useProxy($proxy, $username = false, $password = false) {
+ $this->_browser->useProxy($proxy, $username, $password);
+ }
+
+ /**
+ * Fetches a page into the page buffer. If
+ * there is no base for the URL then the
+ * current base URL is used. After the fetch
+ * the base URL reflects the new location.
+ * @param string $url URL to fetch.
+ * @param hash $parameters Optional additional GET data.
+ * @return boolean True on success.
+ * @access public
+ */
+ function get($url, $parameters = false) {
+ $content = $this->_browser->get($url, $parameters);
+ if ($content === false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Fetches a page by POST into the page buffer.
+ * If there is no base for the URL then the
+ * current base URL is used. After the fetch
+ * the base URL reflects the new location.
+ * @param string $url URL to fetch.
+ * @param hash $parameters Optional additional GET data.
+ * @return boolean True on success.
+ * @access public
+ */
+ function post($url, $parameters = false) {
+ $content = $this->_browser->post($url, $parameters);
+ if ($content === false) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Does a HTTP HEAD fetch, fetching only the page
+ * headers. The current base URL is unchanged by this.
+ * @param string $url URL to fetch.
+ * @param hash $parameters Optional additional GET data.
+ * @return boolean True on success.
+ * @access public
+ */
+ function head($url, $parameters = false) {
+ return $this->_browser->head($url, $parameters);
+ }
+
+ /**
+ * Equivalent to hitting the retry button on the
+ * browser. Will attempt to repeat the page fetch.
+ * @return boolean True if fetch succeeded.
+ * @access public
+ */
+ function retry() {
+ return $this->_browser->retry();
+ }
+
+ /**
+ * Equivalent to hitting the back button on the
+ * browser.
+ * @return boolean True if history entry and
+ * fetch succeeded.
+ * @access public
+ */
+ function back() {
+ return $this->_browser->back();
+ }
+
+ /**
+ * Equivalent to hitting the forward button on the
+ * browser.
+ * @return boolean True if history entry and
+ * fetch succeeded.
+ * @access public
+ */
+ function forward() {
+ return $this->_browser->forward();
+ }
+
+ /**
+ * Retries a request after setting the authentication
+ * for the current realm.
+ * @param string $username Username for realm.
+ * @param string $password Password for realm.
+ * @return boolean True if successful fetch. Note
+ * that authentication may still have
+ * failed.
+ * @access public
+ */
+ function authenticate($username, $password) {
+ return $this->_browser->authenticate($username, $password);
+ }
+
+ /**
+ * Gets the cookie value for the current browser context.
+ * @param string $name Name of cookie.
+ * @return string Value of cookie or false if unset.
+ * @access public
+ */
+ function getCookie($name) {
+ return $this->_browser->getCurrentCookieValue($name);
+ }
+
+ /**
+ * Sets a cookie in the current browser.
+ * @param string $name Name of cookie.
+ * @param string $value Cookie value.
+ * @param string $host Host upon which the cookie is valid.
+ * @param string $path Cookie path if not host wide.
+ * @param string $expiry Expiry date.
+ * @access public
+ */
+ function setCookie($name, $value, $host = false, $path = "/", $expiry = false) {
+ $this->_browser->setCookie($name, $value, $host, $path, $expiry);
+ }
+
+ /**
+ * Accessor for current frame focus. Will be
+ * false if no frame has focus.
+ * @return integer/string/boolean Label if any, otherwise
+ * the position in the frameset
+ * or false if none.
+ * @access public
+ */
+ function getFrameFocus() {
+ return $this->_browser->getFrameFocus();
+ }
+
+ /**
+ * Sets the focus by index. The integer index starts from 1.
+ * @param integer $choice Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocusByIndex($choice) {
+ return $this->_browser->setFrameFocusByIndex($choice);
+ }
+
+ /**
+ * Sets the focus by name.
+ * @param string $name Chosen frame.
+ * @return boolean True if frame exists.
+ * @access public
+ */
+ function setFrameFocus($name) {
+ return $this->_browser->setFrameFocus($name);
+ }
+
+ /**
+ * Clears the frame focus. All frames will be searched
+ * for content.
+ * @access public
+ */
+ function clearFrameFocus() {
+ return $this->_browser->clearFrameFocus();
+ }
+
+ /**
+ * Clicks the submit button by label. The owning
+ * form will be submitted by this.
+ * @param string $label Button label. An unlabeled
+ * button can be triggered by 'Submit'.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickSubmit($label = 'Submit', $additional = false) {
+ return $this->_browser->clickSubmit($label, $additional);
+ }
+
+ /**
+ * Clicks the submit button by name attribute. The owning
+ * form will be submitted by this.
+ * @param string $name Name attribute of button.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickSubmitByName($name, $additional = false) {
+ return $this->_browser->clickSubmitByName($name, $additional);
+ }
+
+ /**
+ * Clicks the submit button by ID attribute. The owning
+ * form will be submitted by this.
+ * @param string $id ID attribute of button.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickSubmitById($id, $additional = false) {
+ return $this->_browser->clickSubmitById($id, $additional);
+ }
+
+ /**
+ * Clicks the submit image by some kind of label. Usually
+ * the alt tag or the nearest equivalent. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param string $label Alt attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickImage($label, $x = 1, $y = 1, $additional = false) {
+ return $this->_browser->clickImage($label, $x, $y, $additional);
+ }
+
+ /**
+ * Clicks the submit image by the name. Usually
+ * the alt tag or the nearest equivalent. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param string $name Name attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickImageByName($name, $x = 1, $y = 1, $additional = false) {
+ return $this->_browser->clickImageByName($name, $x, $y, $additional);
+ }
+
+ /**
+ * Clicks the submit image by ID attribute. The owning
+ * form will be submitted by this. Clicking outside of
+ * the boundary of the coordinates will result in
+ * a failure.
+ * @param integer/string $id ID attribute of button.
+ * @param integer $x X-coordinate of imaginary click.
+ * @param integer $y Y-coordinate of imaginary click.
+ * @param hash $additional Additional form values.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickImageById($id, $x = 1, $y = 1, $additional = false) {
+ return $this->_browser->clickImageById($id, $x, $y, $additional);
+ }
+
+ /**
+ * Submits a form by the ID.
+ * @param string $id Form ID. No button information
+ * is submitted this way.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function submitFormById($id) {
+ return $this->_browser->submitFormById($id);
+ }
+
+ /**
+ * Follows a link by name. Will click the first link
+ * found with this link text by default, or a later
+ * one if an index is given. Match is case insensitive
+ * with normalised space.
+ * @param string $label Text between the anchor tags.
+ * @param integer $index Link position counting from zero.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickLink($label, $index = 0) {
+ return $this->_browser->clickLink($label, $index);
+ }
+
+ /**
+ * Follows a link by id attribute.
+ * @param string $id ID attribute value.
+ * @return boolean/string Page on success.
+ * @access public
+ */
+ function clickLinkById($id) {
+ return $this->_browser->clickLinkById($id);
+ }
+
+ /**
+ * Tests for the presence of a link label. Match is
+ * case insensitive with normalised space.
+ * @param string $label Text between the anchor tags.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function assertLink($label, $message = "%s") {
+ return $this->assertTrue(
+ $this->_browser->isLink($label),
+ sprintf($message, "Link [$label] should exist"));
+ }
+
+ /**
+ * Tests for the non-presence of a link label. Match is
+ * case insensitive with normalised space.
+ * @param string/integer $label Text between the anchor tags
+ * or ID attribute.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link missing.
+ * @access public
+ */
+ function assertNoLink($label, $message = "%s") {
+ return $this->assertFalse(
+ $this->_browser->isLink($label),
+ sprintf($message, "Link [$label] should not exist"));
+ }
+
+ /**
+ * Tests for the presence of a link id attribute.
+ * @param string $id Id attribute value.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link present.
+ * @access public
+ */
+ function assertLinkById($id, $message = "%s") {
+ return $this->assertTrue(
+ $this->_browser->isLinkById($id),
+ sprintf($message, "Link ID [$id] should exist"));
+ }
+
+ /**
+ * Tests for the non-presence of a link label. Match is
+ * case insensitive with normalised space.
+ * @param string $id Id attribute value.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if link missing.
+ * @access public
+ */
+ function assertNoLinkById($id, $message = "%s") {
+ return $this->assertFalse(
+ $this->_browser->isLinkById($id),
+ sprintf($message, "Link ID [$id] should not exist"));
+ }
+
+ /**
+ * Sets all form fields with that name.
+ * @param string $name Name of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setField($name, $value) {
+ return $this->_browser->setField($name, $value);
+ }
+
+ /**
+ * Sets all form fields with that name.
+ * @param string/integer $id Id of field in forms.
+ * @param string $value New value of field.
+ * @return boolean True if field exists, otherwise false.
+ * @access public
+ */
+ function setFieldById($id, $value) {
+ return $this->_browser->setFieldById($id, $value);
+ }
+
+ /**
+ * Confirms that the form element is currently set
+ * to the expected value. A missing form will always
+ * fail. If no value is given then only the existence
+ * of the field is checked.
+ * @param string $name Name of field in forms.
+ * @param mixed $expected Expected string/array value or
+ * false for unset fields.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertField($name, $expected = true, $message = "%s") {
+ $value = $this->_browser->getField($name);
+ if ($expected === true) {
+ return $this->assertTrue(
+ isset($value),
+ sprintf($message, "Field [$name] should exist"));
+ } else {
+ return $this->assertExpectation(
+ new FieldExpectation($expected),
+ $value,
+ sprintf($message, "Field [$name] should match with [%s]"));
+ }
+ }
+
+ /**
+ * Confirms that the form element is currently set
+ * to the expected value. A missing form will always
+ * fail. If no ID is given then only the existence
+ * of the field is checked.
+ * @param string/integer $id Name of field in forms.
+ * @param mixed $expected Expected string/array value or
+ * false for unset fields.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertFieldById($id, $expected = true, $message = "%s") {
+ $value = $this->_browser->getFieldById($id);
+ if ($expected === true) {
+ return $this->assertTrue(
+ isset($value),
+ sprintf($message, "Field of ID [$id] should exist"));
+ } else {
+ return $this->assertExpectation(
+ new FieldExpectation($expected),
+ $value,
+ sprintf($message, "Field of ID [$id] should match with [%s]"));
+ }
+ }
+
+ /**
+ * Checks the response code against a list
+ * of possible values.
+ * @param array $responses Possible responses for a pass.
+ * @param string $message Message to display. Default
+ * can be embedded with %s.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertResponse($responses, $message = '%s') {
+ $responses = (is_array($responses) ? $responses : array($responses));
+ $code = $this->_browser->getResponseCode();
+ $message = sprintf($message, "Expecting response in [" .
+ implode(", ", $responses) . "] got [$code]");
+ return $this->assertTrue(in_array($code, $responses), $message);
+ }
+
+ /**
+ * Checks the mime type against a list
+ * of possible values.
+ * @param array $types Possible mime types for a pass.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertMime($types, $message = '%s') {
+ $types = (is_array($types) ? $types : array($types));
+ $type = $this->_browser->getMimeType();
+ $message = sprintf($message, "Expecting mime type in [" .
+ implode(", ", $types) . "] got [$type]");
+ return $this->assertTrue(in_array($type, $types), $message);
+ }
+
+ /**
+ * Attempt to match the authentication type within
+ * the security realm we are currently matching.
+ * @param string $authentication Usually basic.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertAuthentication($authentication = false, $message = '%s') {
+ if (! $authentication) {
+ $message = sprintf($message, "Expected any authentication type, got [" .
+ $this->_browser->getAuthentication() . "]");
+ return $this->assertTrue(
+ $this->_browser->getAuthentication(),
+ $message);
+ } else {
+ $message = sprintf($message, "Expected authentication [$authentication] got [" .
+ $this->_browser->getAuthentication() . "]");
+ return $this->assertTrue(
+ strtolower($this->_browser->getAuthentication()) == strtolower($authentication),
+ $message);
+ }
+ }
+
+ /**
+ * Checks that no authentication is necessary to view
+ * the desired page.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoAuthentication($message = '%s') {
+ $message = sprintf($message, "Expected no authentication type, got [" .
+ $this->_browser->getAuthentication() . "]");
+ return $this->assertFalse($this->_browser->getAuthentication(), $message);
+ }
+
+ /**
+ * Attempts to match the current security realm.
+ * @param string $realm Name of security realm.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertRealm($realm, $message = '%s') {
+ $message = sprintf($message, "Expected realm [$realm] got [" .
+ $this->_browser->getRealm() . "]");
+ return $this->assertTrue(
+ strtolower($this->_browser->getRealm()) == strtolower($realm),
+ $message);
+ }
+
+ /**
+ * Checks each header line for the required value. If no
+ * value is given then only an existence check is made.
+ * @param string $header Case insensitive header name.
+ * @param string $value Case sensitive trimmed string to
+ * match against.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertHeader($header, $value = false, $message = '%s') {
+ return $this->assertExpectation(
+ new HttpHeaderExpectation($header, $value),
+ $this->_browser->getHeaders(),
+ $message);
+ }
+
+ /**
+ * Checks each header line for the required pattern.
+ * @param string $header Case insensitive header name.
+ * @param string $pattern Pattern to match value against.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertHeaderPattern($header, $pattern, $message = '%s') {
+ return $this->assertExpectation(
+ new HttpHeaderPatternExpectation($header, $pattern),
+ $this->_browser->getHeaders(),
+ $message);
+ }
+
+ /**
+ * Confirms that the header type has not been received.
+ * Only the landing page is checked. If you want to check
+ * redirect pages, then you should limit redirects so
+ * as to capture the page you want.
+ * @param string $header Case insensitive header name.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoUnwantedHeader($header, $message = '%s') {
+ return $this->assertExpectation(
+ new HttpUnwantedHeaderExpectation($header),
+ $this->_browser->getHeaders(),
+ $message);
+ }
+
+ /**
+ * Tests the text between the title tags.
+ * @param string $title Expected title or empty
+ * if expecting no title.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertTitle($title = false, $message = '%s') {
+ return $this->assertTrue(
+ $title === $this->_browser->getTitle(),
+ sprintf($message, "Expecting title [$title] got [" .
+ $this->_browser->getTitle() . "]"));
+ }
+
+ /**
+ * Will trigger a pass if the text is found in the plain
+ * text form of the page.
+ * @param string $text Text to look for.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertWantedText($text, $message = '%s') {
+ return $this->assertExpectation(
+ new WantedTextExpectation($text),
+ $this->_browser->getContentAsText(),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the text is not found in the plain
+ * text form of the page.
+ * @param string $text Text to look for.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoUnwantedText($text, $message = '%s') {
+ return $this->assertExpectation(
+ new UnwantedTextExpectation($text),
+ $this->_browser->getContentAsText(),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the Perl regex pattern
+ * is found in the raw content.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertWantedPattern($pattern, $message = '%s') {
+ return $this->assertExpectation(
+ new WantedPatternExpectation($pattern),
+ $this->_browser->getContent(),
+ $message);
+ }
+
+ /**
+ * Will trigger a pass if the perl regex pattern
+ * is not present in raw content.
+ * @param string $pattern Perl regex to look for including
+ * the regex delimiters.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoUnwantedPattern($pattern, $message = '%s') {
+ return $this->assertExpectation(
+ new UnwantedPatternExpectation($pattern),
+ $this->_browser->getContent(),
+ $message);
+ }
+
+ /**
+ * Checks that a cookie is set for the current page
+ * and optionally checks the value.
+ * @param string $name Name of cookie to test.
+ * @param string $expected Expected value as a string or
+ * false if any value will do.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertCookie($name, $expected = false, $message = '%s') {
+ $value = $this->getCookie($name);
+ if ($expected) {
+ return $this->assertTrue($value === $expected, sprintf(
+ $message,
+ "Expecting cookie [$name] value [$expected], got [$value]"));
+ } else {
+ return $this->assertTrue(
+ $value,
+ sprintf($message, "Expecting cookie [$name]"));
+ }
+ }
+
+ /**
+ * Checks that no cookie is present or that it has
+ * been successfully cleared.
+ * @param string $name Name of cookie to test.
+ * @param string $message Message to display.
+ * @return boolean True if pass.
+ * @access public
+ */
+ function assertNoCookie($name, $message = '%s') {
+ return $this->assertTrue(
+ $this->getCookie($name) === false,
+ sprintf($message, "Not expecting cookie [$name]"));
+ }
+ }
+?> \ No newline at end of file
diff --git a/tests/test_tools/simpletest/xml.php b/tests/test_tools/simpletest/xml.php
new file mode 100644
index 00000000..dd007d41
--- /dev/null
+++ b/tests/test_tools/simpletest/xml.php
@@ -0,0 +1,615 @@
+<?php
+ /**
+ * base include file for SimpleTest
+ * @package SimpleTest
+ * @subpackage UnitTester
+ * @version $Id: xml.php,v 1.20 2004/08/04 22:09:39 lastcraft Exp $
+ */
+
+ /**#@+
+ * include other SimpleTest class files
+ */
+ require_once(dirname(__FILE__) . '/scorer.php');
+ /**#@-*/
+
+ /**
+ * Creates the XML needed for remote communication
+ * by SimpleTest.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class XmlReporter extends SimpleReporter {
+ protected $_indent;
+ protected $_namespace;
+
+ /**
+ * Does nothing yet.
+ * @access public
+ */
+ function XmlReporter($namespace = false, $indent = ' ') {
+ $this->SimpleReporter();
+ $this->_namespace = ($namespace ? $namespace . ':' : '');
+ $this->_indent = $indent;
+ }
+
+ /**
+ * Calculates the pretty printing indent level
+ * from the current level of nesting.
+ * @param integer $offset Extra indenting level.
+ * @return string Leading space.
+ * @access protected
+ */
+ function _getIndent($offset = 0) {
+ return str_repeat(
+ $this->_indent,
+ count($this->getTestList()) + $offset);
+ }
+
+ /**
+ * Converts character string to parsed XML
+ * entities string.
+ * @param string text Unparsed character data.
+ * @return string Parsed character data.
+ * @access public
+ */
+ function toParsedXml($text) {
+ return str_replace(
+ array('&', '<', '>', '"', '\''),
+ array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;'),
+ $text);
+ }
+
+ /**
+ * Paints the start of a group test.
+ * @param string $test_name Name of test that is starting.
+ * @param integer $size Number of test cases starting.
+ * @access public
+ */
+ function paintGroupStart($test_name, $size) {
+ parent::paintGroupStart($test_name, $size);
+ print $this->_getIndent();
+ print "<" . $this->_namespace . "group size=\"$size\">\n";
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "name>" .
+ $this->toParsedXml($test_name) .
+ "</" . $this->_namespace . "name>\n";
+ }
+
+ /**
+ * Paints the end of a group test.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintGroupEnd($test_name) {
+ print $this->_getIndent();
+ print "</" . $this->_namespace . "group>\n";
+ parent::paintGroupEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test case.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintCaseStart($test_name) {
+ parent::paintCaseStart($test_name);
+ print $this->_getIndent();
+ print "<" . $this->_namespace . "case>\n";
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "name>" .
+ $this->toParsedXml($test_name) .
+ "</" . $this->_namespace . "name>\n";
+ }
+
+ /**
+ * Paints the end of a test case.
+ * @param string $test_name Name of test that is ending.
+ * @access public
+ */
+ function paintCaseEnd($test_name) {
+ print $this->_getIndent();
+ print "</" . $this->_namespace . "case>\n";
+ parent::paintCaseEnd($test_name);
+ }
+
+ /**
+ * Paints the start of a test method.
+ * @param string $test_name Name of test that is starting.
+ * @access public
+ */
+ function paintMethodStart($test_name) {
+ parent::paintMethodStart($test_name);
+ print $this->_getIndent();
+ print "<" . $this->_namespace . "test>\n";
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "name>" .
+ $this->toParsedXml($test_name) .
+ "</" . $this->_namespace . "name>\n";
+ }
+
+ /**
+ * Paints the end of a test method.
+ * @param string $test_name Name of test that is ending.
+ * @param integer $progress Number of test cases ending.
+ * @access public
+ */
+ function paintMethodEnd($test_name) {
+ print $this->_getIndent();
+ print "</" . $this->_namespace . "test>\n";
+ parent::paintMethodEnd($test_name);
+ }
+
+ /**
+ * Increments the pass count.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintPass($message) {
+ parent::paintPass($message);
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "pass>";
+ print $this->toParsedXml($message);
+ print "</" . $this->_namespace . "pass>\n";
+ }
+
+ /**
+ * Increments the fail count.
+ * @param string $message Message is ignored.
+ * @access public
+ */
+ function paintFail($message) {
+ parent::paintFail($message);
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "fail>";
+ print $this->toParsedXml($message);
+ print "</" . $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);
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "exception>";
+ print $this->toParsedXml($message);
+ print "</" . $this->_namespace . "exception>\n";
+ }
+
+ /**
+ * Paints a simple supplementary message.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintMessage($message) {
+ parent::paintMessage($message);
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "message>";
+ print $this->toParsedXml($message);
+ print "</" . $this->_namespace . "message>\n";
+ }
+
+ /**
+ * Paints a formatted ASCII message such as a
+ * variable dump.
+ * @param string $message Text to display.
+ * @access public
+ */
+ function paintFormattedMessage($message) {
+ parent::paintFormattedMessage($message);
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "formatted>";
+ print "<![CDATA[$message]]>";
+ print "</" . $this->_namespace . "formatted>\n";
+ }
+
+ /**
+ * Serialises the event object.
+ * @param string $type Event type as text.
+ * @param mixed $payload Message or object.
+ * @access public
+ */
+ function paintSignal($type, $payload) {
+ parent::paintSignal($type, $payload);
+ print $this->_getIndent(1);
+ print "<" . $this->_namespace . "signal type=\"$type\">";
+ print "<![CDATA[" . serialize($payload) . "]]>";
+ print "</" . $this->_namespace . "signal>\n";
+ }
+
+ /**
+ * Paints the test document header.
+ * @param string $test_name First test top level
+ * to start.
+ * @access public
+ * @abstract
+ */
+ function paintHeader($test_name) {
+ if (! SimpleReporter::inCli()) {
+ header('Content-type: text/xml');
+ }
+ print "<?xml version=\"1.0\"";
+ if ($this->_namespace) {
+ print " xmlns:" . $this->_namespace .
+ "=\"www.lastcraft.com/SimpleTest/Beta3/Report\"";
+ }
+ print "?>\n";
+ print "<" . $this->_namespace . "run>\n";
+ }
+
+ /**
+ * Paints the test document footer.
+ * @param string $test_name The top level test.
+ * @access public
+ * @abstract
+ */
+ function paintFooter($test_name) {
+ print "</" . $this->_namespace . "run>\n";
+ }
+ }
+
+ /**
+ * Accumulator for incoming tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NestingXmlTag {
+ protected $_name;
+ protected $_attributes;
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingXmlTag($attributes) {
+ $this->_name = false;
+ $this->_attributes = $attributes;
+ }
+
+ /**
+ * Sets the test case/method name.
+ * @param string $name Name of test.
+ * @access public
+ */
+ function setName($name) {
+ $this->_name = $name;
+ }
+
+ /**
+ * Accessor for name.
+ * @return string Name of test.
+ * @access public
+ */
+ function getName() {
+ return $this->_name;
+ }
+
+ /**
+ * Accessor for attributes.
+ * @return hash All attributes.
+ * @access protected
+ */
+ function _getAttributes() {
+ return $this->_attributes;
+ }
+ }
+
+ /**
+ * Accumulator for incoming method tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NestingMethodTag extends NestingXmlTag {
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingMethodTag($attributes) {
+ $this->NestingXmlTag($attributes);
+ }
+
+ /**
+ * Signals the appropriate start event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintStart($listener) {
+ $listener->paintMethodStart($this->getName());
+ }
+
+ /**
+ * Signals the appropriate end event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintEnd($listener) {
+ $listener->paintMethodEnd($this->getName());
+ }
+ }
+
+ /**
+ * Accumulator for incoming case tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NestingCaseTag extends NestingXmlTag {
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingCaseTag($attributes) {
+ $this->NestingXmlTag($attributes);
+ }
+
+ /**
+ * Signals the appropriate start event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintStart($listener) {
+ $listener->paintCaseStart($this->getName());
+ }
+
+ /**
+ * Signals the appropriate end event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintEnd($listener) {
+ $listener->paintCaseEnd($this->getName());
+ }
+ }
+
+ /**
+ * Accumulator for incoming group tag. Holds the
+ * incoming test structure information for
+ * later dispatch to the reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class NestingGroupTag extends NestingXmlTag {
+
+ /**
+ * Sets the basic test information except
+ * the name.
+ * @param hash $attributes Name value pairs.
+ * @access public
+ */
+ function NestingGroupTag($attributes) {
+ $this->NestingXmlTag($attributes);
+ }
+
+ /**
+ * Signals the appropriate start event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintStart($listener) {
+ $listener->paintGroupStart($this->getName(), $this->getSize());
+ }
+
+ /**
+ * Signals the appropriate end event on the
+ * listener.
+ * @param SimpleReporter $listener Target for events.
+ * @access public
+ */
+ function paintEnd($listener) {
+ $listener->paintGroupEnd($this->getName());
+ }
+
+ /**
+ * The size in the attributes.
+ * @return integer Value of size attribute or zero.
+ * @access public
+ */
+ function getSize() {
+ $attributes = $this->_getAttributes();
+ if (isset($attributes['SIZE'])) {
+ return (integer)$attributes['SIZE'];
+ }
+ return 0;
+ }
+ }
+
+ /**
+ * Parser for importing the output of the XmlReporter.
+ * Dispatches that output to another reporter.
+ * @package SimpleTest
+ * @subpackage UnitTester
+ */
+ class SimpleTestXmlParser {
+ protected $_listener;
+ protected $_expat;
+ protected $_tag_stack;
+ protected $_in_content_tag;
+ protected $_content;
+ protected $_attributes;
+
+ /**
+ * Loads a listener with the SimpleReporter
+ * interface.
+ * @param SimpleReporter $listener Listener of tag events.
+ * @access public
+ */
+ function SimpleTestXmlParser($listener) {
+ $this->_listener = $listener;
+ $this->_expat = $this->_createParser();
+ $this->_tag_stack = array();
+ $this->_in_content_tag = false;
+ $this->_content = '';
+ $this->_attributes = array();
+ }
+
+ /**
+ * Parses a block of XML sending the results to
+ * the listener.
+ * @param string $chunk Block of text to read.
+ * @return boolean True if valid XML.
+ * @access public
+ */
+ function parse($chunk) {
+ if (! xml_parse($this->_expat, $chunk)) {
+ trigger_error('XML parse error with ' .
+ xml_error_string(xml_get_error_code($this->_expat)));
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Sets up expat as the XML parser.
+ * @return resource Expat handle.
+ * @access protected
+ */
+ function _createParser() {
+ $expat = xml_parser_create();
+ xml_set_object($expat, $this);
+ xml_set_element_handler($expat, '_startElement', '_endElement');
+ xml_set_character_data_handler($expat, '_addContent');
+ xml_set_default_handler($expat, '_default');
+ return $expat;
+ }
+
+ /**
+ * Opens a new test nesting level.
+ * @return NestedXmlTag The group, case or method tag
+ * to start.
+ * @access private
+ */
+ function _pushNestingTag($nested) {
+ array_unshift($this->_tag_stack, $nested);
+ }
+
+ /**
+ * Accessor for current test structure tag.
+ * @return NestedXmlTag The group, case or method tag
+ * being parsed.
+ * @access private
+ */
+ function _getCurrentNestingTag() {
+ return $this->_tag_stack[0];
+ }
+
+ /**
+ * Ends a nesting tag.
+ * @return NestedXmlTag The group, case or method tag
+ * just finished.
+ * @access private
+ */
+ function _popNestingTag() {
+ return array_shift($this->_tag_stack);
+ }
+
+ /**
+ * Test if tag is a leaf node with only text content.
+ * @param string $tag XML tag name.
+ * @return @boolean True if leaf, false if nesting.
+ * @private
+ */
+ function _isLeaf($tag) {
+ return in_array(
+ $tag,
+ array('NAME', 'PASS', 'FAIL', 'EXCEPTION', 'MESSAGE', 'FORMATTED', 'SIGNAL'));
+ }
+
+ /**
+ * Handler for start of event element.
+ * @param resource $expat Parser handle.
+ * @param string $tag Element name.
+ * @param hash $attributes Name value pairs.
+ * Attributes without content
+ * are marked as true.
+ * @access protected
+ */
+ function _startElement($expat, $tag, $attributes) {
+ $this->_attributes = $attributes;
+ if ($tag == 'GROUP') {
+ $this->_pushNestingTag(new NestingGroupTag($attributes));
+ } elseif ($tag == 'CASE') {
+ $this->_pushNestingTag(new NestingCaseTag($attributes));
+ } elseif ($tag == 'TEST') {
+ $this->_pushNestingTag(new NestingMethodTag($attributes));
+ } elseif ($this->_isLeaf($tag)) {
+ $this->_in_content_tag = true;
+ $this->_content = '';
+ }
+ }
+
+ /**
+ * End of element event.
+ * @param resource $expat Parser handle.
+ * @param string $tag Element name.
+ * @access protected
+ */
+ function _endElement($expat, $tag) {
+ $this->_in_content_tag = false;
+ if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) {
+ $nesting_tag = $this->_popNestingTag();
+ $nesting_tag->paintEnd($this->_listener);
+ } elseif ($tag == 'NAME') {
+ $nesting_tag = $this->_getCurrentNestingTag();
+ $nesting_tag->setName($this->_content);
+ $nesting_tag->paintStart($this->_listener);
+ } elseif ($tag == 'PASS') {
+ $this->_listener->paintPass($this->_content);
+ } elseif ($tag == 'FAIL') {
+ $this->_listener->paintFail($this->_content);
+ } elseif ($tag == 'EXCEPTION') {
+ $this->_listener->paintException($this->_content);
+ } elseif ($tag == 'SIGNAL') {
+ $this->_listener->paintSignal(
+ $this->_attributes['TYPE'],
+ unserialize($this->_content));
+ } elseif ($tag == 'MESSAGE') {
+ $this->_listener->paintMessage($this->_content);
+ } elseif ($tag == 'FORMATTED') {
+ $this->_listener->paintFormattedMessage($this->_content);
+ }
+ }
+
+ /**
+ * Content between start and end elements.
+ * @param resource $expat Parser handle.
+ * @param string $text Usually output messages.
+ * @access protected
+ */
+ function _addContent($expat, $text) {
+ if ($this->_in_content_tag) {
+ $this->_content .= $text;
+ }
+ return true;
+ }
+
+ /**
+ * XML and Doctype handler. Discards all such content.
+ * @param resource $expat Parser handle.
+ * @param string $default Text of default content.
+ * @access protected
+ */
+ function _default($expat, $default) {
+ }
+ }
+?>
diff --git a/tests/test_tools/unit_tests.php b/tests/test_tools/unit_tests.php
new file mode 100644
index 00000000..732c6826
--- /dev/null
+++ b/tests/test_tools/unit_tests.php
@@ -0,0 +1,134 @@
+<?php
+
+if(!defined('PRADO_FRAMEWORK'))
+ define('PRADO_FRAMEWORK',realpath(dirname(__FILE__).'/../../framework'));
+
+$TEST_TOOLS = dirname(__FILE__);
+
+require_once($TEST_TOOLS.'/simpletest/unit_tester.php');
+require_once($TEST_TOOLS.'/simpletest/web_tester.php');
+require_once($TEST_TOOLS.'/simpletest/mock_objects.php');
+require_once($TEST_TOOLS.'/simpletest/reporter.php');
+
+require_once(PRADO_FRAMEWORK.'/prado.php');
+
+class TMockApplication extends TApplication
+{
+ public function run()
+ {
+ $this->initApplication();
+ }
+}
+
+class TestFolder
+{
+ public $name='';
+ public $url='';
+ public $subFolders=array();
+ public $testFiles=array();
+
+ public function __construct($path,$rootPath,$rootUri)
+ {
+ $script = basename($_SERVER['SCRIPT_NAME']);
+ $this->url="$rootUri/$script?target=".strtr(substr($path,strlen($rootPath)+1),"\\",'/');
+ $this->name=basename($path);
+ $dir=opendir($path);
+ while(($entry=readdir($dir))!==false)
+ {
+ $fullpath="$path/$entry";
+ if($entry!=='.' && $entry!=='..' && $entry!=='.svn' && is_dir($fullpath))
+ {
+ $folder=new TestFolder($fullpath,$rootPath,$rootUri);
+ if(!empty($folder->subFolders) || !empty($folder->testFiles))
+ $this->subFolders[]=$folder;
+ }
+ else if(is_file($fullpath) && (strncmp($entry,'ut',2)===0
+ || preg_match('/test.*\.php/', strtolower($entry))))
+ {
+ $this->testFiles[$entry]="$rootUri/$script?target=".strtr(substr($fullpath,strlen($rootPath)+1),"\\",'/');
+ }
+ }
+ closedir($dir);
+ }
+
+ public function getHtml($level=0)
+ {
+ $str=str_repeat('&nbsp;',$level*4)."[ <a href=\"{$this->url}\">{$this->name}</a> ]<br/>\n";
+ foreach($this->subFolders as $folder)
+ $str.=$folder->getHtml($level+1);
+ foreach($this->testFiles as $name=>$url)
+ $str.=str_repeat('&nbsp;',($level+1)*4)."<a href=\"$url\">$name</a><br/>\n";
+ return $str;
+ }
+}
+
+class PradoUnitTester
+{
+ private $_root;
+
+ function __construct($root, $app_dir)
+ {
+ $this->_root = $root;
+ $app = new TMockApplication($app_dir);
+ $app->run();
+ }
+
+ function addTests($test,$path,$recursive)
+ {
+ $dir=opendir($path);
+ while(($entry=readdir($dir))!==false)
+ {
+ if(is_file($path.'/'.$entry) && (strncmp($entry,'ut',2)===0||preg_match('/test.*\.php/', strtolower($entry))))
+ $test->addTestFile($path.'/'.$entry);
+ else if($entry!=='.' && $entry!=='..' && $entry!=='.svn' && is_dir($path.'/'.$entry) && $recursive)
+ $this->addTests($test,$path.'/'.$entry,$recursive);
+ }
+ closedir($dir);
+ }
+
+ function run($reporter)
+ {
+ $rootPath=realpath($this->_root);
+ $rootUri=dirname($_SERVER['PHP_SELF']);
+ if(isset($_GET['target']))
+ {
+ $target=$_GET['target'];
+ $recursive=true;
+ $fullpath=realpath("$rootPath/$target");
+ if($fullpath===false || strpos($fullpath,$rootPath)!==0)
+ die('invalid test target');
+
+ if(is_dir($fullpath))
+ {
+
+ $test=new GroupTest(basename($rootPath)."/$target");
+ $this->addTests($test,$fullpath,$recursive);
+ $test->run($reporter);
+ //$test->run(new HtmlReporterWithCoverage('index.php',$rootPath));
+ }
+ else
+ {
+ $testClass=basename($fullpath,'.php');
+ include_once($fullpath);
+ $test=new $testClass(basename($rootPath)."/$target");
+ $test->run($reporter);
+ }
+ }
+ else
+ {
+ echo "<html>
+ <head>
+ <title>Prado Unit Tests</title>
+ <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">
+ </head>
+ <body>
+ <h1>Prado Unit Tests</h1>
+ ";
+ $root=new TestFolder($rootPath,$rootPath,$rootUri);
+ echo $root->getHtml();
+ echo "</body>\n</html>";
+ }
+ }
+}
+
+?> \ No newline at end of file