diff --git a/application/libraries/simpletest/docs/en/authentication_documentation.html b/application/libraries/simpletest/docs/en/authentication_documentation.html deleted file mode 100644 index e058e19a111..00000000000 --- a/application/libraries/simpletest/docs/en/authentication_documentation.html +++ /dev/null @@ -1,378 +0,0 @@ - - - -SimpleTest documentation for testing log-in and authentication - - - - -

Authentication documentation

- This page... - -
- -

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

- -

-Basic HTTP authentication

-

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

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

File test

-
-HTTP/1.1 401 Authorization Required
-Date: Sat, 18 Sep 2004 19:25:18 GMT
-Server: Apache/1.3.29 (Unix) PHP/4.3.4
-WWW-Authenticate: Basic realm="SimpleTest basic authentication"
-Connection: close
-Content-Type: text/html; charset=iso-8859-1
-
-
1/1 test cases complete. - 0 passes, 0 fails and 0 exceptions.
-
- We are trying to get away from visual inspection though, and so SimpleTest - allows to make automated assertions against the challenge. - Here is a thorough test of our header... -
-class AuthenticationTest extends WebTestCase {
-    function test401Header() {
-        $this->get('http://www.lastcraft.com/protected/');
-        $this->assertAuthentication('Basic');
-        $this->assertResponse(401);
-        $this->assertRealm('SimpleTest basic authentication');
-    }
-}
-
- Any one of these tests would normally do on it's own depending - on the amount of detail you want to see. -

-

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

-class AuthenticationTest extends WebTestCase {
-    function test401Header() {
-        $this->get('http://www.lastcraft.com/protected/');
-        $this->assertRealm(new PatternExpectation('/simpletest/i'));
-    }
-}
-
- This type of test, testing HTTP responses, is not typical. -

-

- Most of the time we are not interested in testing the - authentication itself, but want to get past it to test - the pages underneath. - As soon as the challenge has been issued we can reply with - an authentication response... -

-class AuthenticationTest extends WebTestCase {
-    function testCanAuthenticate() {
-        $this->get('http://www.lastcraft.com/protected/');
-        $this->authenticate('Me', 'Secret');
-        $this->assertTitle(...);
-    }
-}
-
- The username and password will now be sent with every - subsequent request to that directory and subdirectories. - You will have to authenticate again if you step outside - the authenticated directory, but SimpleTest is smart enough - to merge subdirectories into a common realm. -

-

- If you want, you can shortcut this step further by encoding - the log in details straight into the URL... -

-class AuthenticationTest extends WebTestCase {
-    function testCanReadAuthenticatedPages() {
-        $this->get('http://Me:Secret@www.lastcraft.com/protected/');
-        $this->assertTitle(...);
-    }
-}
-
- If your username or password has special characters, then you - will have to URL encode them or the request will not be parsed - correctly. - I'm afraid we leave this up to you. -

-

- A problem with encoding the login details directly in the URL is - the authentication header will not be sent on subsequent requests. - If you navigate with relative URLs though, the authentication - information will be preserved along with the domain name. -

-

- Normally though, you use the authenticate() call. - SimpleTest will then remember your login information on each request. -

-

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

- -

-Cookies

-

- Basic authentication doesn't give enough control over the - user interface for web developers. - More likely this functionality will be coded directly into - the web architecture using cookies with complicated timeouts. - We need to be able to test this too. -

-

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

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

-

-

- Username: -
- Password: -
- -
-

-

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

-class LogInTest extends WebTestCase {
-    function testSessionCookieSetBeforeForm() {
-        $this->get('http://www.my-site.com/login.php');
-        $this->assertCookie('SID');
-    }
-}
-
- All we are doing is confirming that the cookie is set. - As the value is likely to be rather cryptic it's not - really worth testing this with... -
-class LogInTest extends WebTestCase {
-    function testSessionCookieIsCorrectPattern() {
-        $this->get('http://www.my-site.com/login.php');
-        $this->assertCookie('SID', new PatternExpectation('/[a-f0-9]{32}/i'));
-    }
-}
-
- If you are using PHP to handle sessions for you then - this test is even more useless, as we are just testing PHP itself. -

-

- The simplest test of logging in is to visually inspect the - next page to see if you are really logged in. - Just test the next page with WebTestCase::assertText(). -

-

- The test is similar to any other form test, - but we might want to confirm that we still have the same - cookie after log-in as before we entered. - We wouldn't want to lose track of this after all. - Here is a possible test for this... -

-class LogInTest extends WebTestCase {
-    ...
-    function testSessionCookieSameAfterLogIn() {
-        $this->get('http://www.my-site.com/login.php');
-        $session = $this->getCookie('SID');
-        $this->setField('u', 'Me');
-        $this->setField('p', 'Secret');
-        $this->click('Log in');
-        $this->assertText('Welcome Me');
-        $this->assertCookie('SID', $session);
-    }
-}
-
- This confirms that the session identifier is maintained - afer log-in and we haven't accidently reset it. -

-

- We could even attempt to hack our own system by setting - arbitrary cookies to gain access... -

-class LogInTest extends WebTestCase {
-    ...
-    function testSessionCookieSameAfterLogIn() {
-        $this->get('http://www.my-site.com/login.php');
-        $this->setCookie('SID', 'Some other session');
-        $this->get('http://www.my-site.com/restricted.php');
-        $this->assertText('Access denied');
-    }
-}
-
- Is your site protected from this attack? -

- -

-Browser sessions

-

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

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

-

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

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/browser_documentation.html b/application/libraries/simpletest/docs/en/browser_documentation.html deleted file mode 100644 index 809c1431137..00000000000 --- a/application/libraries/simpletest/docs/en/browser_documentation.html +++ /dev/null @@ -1,501 +0,0 @@ - - - -SimpleTest documentation for the scriptable web browser component - - - - -

PHP Scriptable Web Browser

- This page... - -
- -

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

- -

-The Scriptable Browser

-

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

-<?php
-require_once('simpletest/browser.php');
-    
-$browser = &new SimpleBrowser();
-$browser->get('http://php.net/');
-$browser->click('reporting bugs');
-$browser->click('statistics');
-$page = $browser->click('PHP 5 bugs only');
-preg_match('/status=Open.*?by=Any.*?(\d+)<\/a>/', $page, $matches);
-print $matches[1];
-?>
-
- There are simpler methods to do this particular example in PHP - of course. - For example you can just use the PHP file() - command against what here is a pretty fixed page. - However, using the web browser for scripts allows authentication, - correct handling of cookies, automatic loading of frames, redirects, - form submission and the ability to examine the page headers. -

-

- Methods such as periodic scraping are fragile against a site that is constantly - evolving and you would want a more direct way of accessing - data in a permanent set up, but for simple tasks this can provide - a very rapid solution. -

-

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

-

- Navigating forms is similar to the - WebTestCase form navigation... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
setField($label, $value)Sets all form fields with that label or name
setFieldByName($name, $value)Sets all form fields with that name
setFieldById($id, $value)Sets all form fields with that id
getField($label)Accessor for a form element value by label tag and then name
getFieldByName($name)Accessor for a form element value using name attribute
getFieldById($id)Accessor for a form element value
clickSubmit($label)Submits form by button label
clickSubmitByName($name)Submits form by button attribute
clickSubmitById($id)Submits form by button attribute
clickImage($label, $x, $y)Clicks an input tag of type image by title or alt text
clickImageByName($name, $x, $y)Clicks an input tag of type image by name
clickImageById($id, $x, $y)Clicks an input tag of type image by ID attribute
submitFormById($id)Submits by the form tag attribute
- At the moment there aren't many methods to list available links and fields. - - - - - - - - - - - - - - - - - - - - - - - - - -
isClickable($label)Test to see if a click target exists by label or name
isSubmit($label)Test for the existence of a button with that label or name
isImage($label)Test for the existence of an image button with that label or name
getLink($label)Finds a URL from its label
getLinkById($label)Finds a URL from its ID attribute
getUrls()Lists available links in the current page
- This will be expanded in later versions of SimpleTest. -

-

- Frames are a rather esoteric feature these days, but SimpleTest has - retained support for them. -

-

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

- -

-What went wrong?

-

- All of this functionality is great when we actually manage to fetch pages, - but that doesn't always happen. - To help figure out what went wrong, the browser has some methods to - aid in debugging... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
setConnectionTimeout($timeout)Close the socket on overrun
getUrl()Url of most recent page fetched
getRequest()Raw request header of page or frame
getHeaders()Raw response header of page or frame
getTransportError()Any socket level errors in the last fetch
getResponseCode()HTTP response of page or frame
getMimeType()Mime type of page or frame
getAuthentication()Authentication type in 401 challenge header
getRealm()Authentication realm in 401 challenge header
getBaseUrl()Base url only of most recent page fetched
setMaximumRedirects($max)Number of redirects before page is loaded anyway
setMaximumNestedFrames($max)Protection against recursive framesets
ignoreFrames()Disables frames support
useFrames()Enables frames support
ignoreCookies()Disables sending and receiving of cookies
useCookies()Enables cookie support
- The methods SimpleBrowser::setConnectionTimeout() - SimpleBrowser::setMaximumRedirects(), - SimpleBrowser::setMaximumNestedFrames(), - SimpleBrowser::ignoreFrames(), - SimpleBrowser::useFrames(), - SimpleBrowser::ignoreCookies() and - SimpleBrowser::useCokies() continue to apply - to every subsequent request. - The other methods are frames aware. - This means that if you have an individual frame that is not - loading, navigate to it using SimpleBrowser::setFrameFocus() - and you can then use SimpleBrowser::getRequest(), etc to - see what happened. -

- -

-Complex unit tests with multiple browsers

-

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

-class TestOfRegistration extends UnitTestCase {
-    function testNewUserAddedToAuthenticator() {
-        $browser = new SimpleBrowser();
-        $browser->get('http://my-site.com/register.php');
-        $browser->setField('email', 'me@here');
-        $browser->setField('password', 'Secret');
-        $browser->click('Register');
-        
-        $authenticator = new Authenticator();
-        $member = $authenticator->findByEmail('me@here');
-        $this->assertEqual($member->getPassword(), 'Secret');
-    }
-}
-
- While this may be a useful temporary expediency, I am not a fan - of this type of testing. - The testing has cut across application layers, make it twice as - likely it will need refactoring when the code changes. -

-

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

-

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

-class TestOfSecurity extends UnitTestCase {
-    function testNoMultipleLoginsFromSameUser() {
-        $first_attempt = new SimpleBrowser();
-        $first_attempt->get('http://my-site.com/login.php');
-        $first_attempt->setField('name', 'Me');
-        $first_attempt->setField('password', 'Secret');
-        $first_attempt->click('Enter');
-        $this->assertEqual($first_attempt->getTitle(), 'Welcome');
-        
-        $second_attempt = new SimpleBrowser();
-        $second_attempt->get('http://my-site.com/login.php');
-        $second_attempt->setField('name', 'Me');
-        $second_attempt->setField('password', 'Secret');
-        $second_attempt->click('Enter');
-        $this->assertEqual($second_attempt->getTitle(), 'Access Denied');
-    }
-}
-
- You can also use the SimpleBrowser class - directly when you want to write test cases using a different - test tool than SimpleTest, such as PHPUnit. -

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

Expectation documentation

- This page... - -
-

-More control over mock objects

-

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

-

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

-

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

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

-

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

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

-

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

-

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

-

- Some examples... -

-

-

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

- -

-Using expectations to control stubs

-

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

-

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

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

-

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

- -

-Creating your own expectations

-

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

-

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

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

-

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

-

- Here is a more typical example, matching part of a hash... -

-class JustField extends EqualExpectation {
-    private $key;
-    
-    function __construct($key, $expected) {
-        parent::__construct($expected);
-        $this->key = $key;
-    }
-    
-    function test($compare) {
-        if (! isset($compare[$this->key])) {
-            return false;
-        }
-        return parent::test($compare[$this->key]);
-    }
-    
-    function testMessage($compare) {
-        if (! isset($compare[$this->key])) {
-            return 'Key [' . $this->key . '] does not exist';
-        }
-        return 'Key [' . $this->key . '] -> ' .
-                parent::testMessage($compare[$this->key]);
-    }
-}
-
- We tend to seperate message clauses with - "&nbsp;->&nbsp;". - This allows derivative tools to reformat the output. -

-

- Suppose some authenticator is expecting to be given - a database row corresponding to the user, and we - only need to confirm the username is correct. - We can assert just their username with... -

-$mock->expectOnce('authenticate',
-                  array(new JustKey('username', 'marcus')));
-
-

- -

-Under the bonnet of the unit tester

-

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

-

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

-class TestOfNetworking extends UnitTestCase {
-    ...
-    function testGetValidIp() {
-        $server = &new Server();
-        $this->assert(
-                new ValidIp(),
-                $server->getIp(),
-                'Server IP address->%s');
-    }
-}
-
- assert() will test any expectation class directly. -

-

- This is a little untidy compared with our usual - assert...() syntax. -

-

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

-class TestOfNetworking extends UnitTestCase {
-    ...
-    function assertValidIp($ip, $message = '%s') {
-        $this->assert(new ValidIp(), $ip, $message);
-    }
-    
-    function testGetValidIp() {
-        $server = &new Server();
-        $this->assertValidIp(
-                $server->getIp(),
-                'Server IP address->%s');
-    }
-}
-
- It is rare to need the expectations for more than pattern - matching, but these facilities do allow testers to build - some sort of domain language for testing their application. - Also, complex expectation classes could make the tests - harder to read and debug. - In effect extending the test framework to create their own tool set. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/form_testing_documentation.html b/application/libraries/simpletest/docs/en/form_testing_documentation.html deleted file mode 100644 index 328735c9dca..00000000000 --- a/application/libraries/simpletest/docs/en/form_testing_documentation.html +++ /dev/null @@ -1,351 +0,0 @@ - - - -SimpleTest documentation for testing HTML forms - - - - -

Form testing documentation

- This page... - -
-

-Submitting a simple form

-

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

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

-

-

- - -
-

-

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

-class SimpleFormTests extends WebTestCase {
-    function testDefaultValue() {
-        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
-        $this->assertField('a', 'A default');
-    }
-}
-
- Immediately after loading the page all of the HTML controls are set at - their default values just as they would appear in the web browser. - The assertion tests that a HTML widget exists in the page with the - name "a" and that it is currently set to the value - "A default". - As usual, we could use a pattern expectation instead of a fixed - string. -
-class SimpleFormTests extends WebTestCase {
-    function testDefaultValue() {
-        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
-        $this->assertField('a', new PatternExpectation('/default/'));
-    }
-}
-
- We could submit the form straight away, but first we'll change - the value of the text field and only then submit it... -
-class SimpleFormTests extends WebTestCase {
-    function testDefaultValue() {
-        $this->get('http://www.my-site.com/');
-        $this->assertField('a', 'A default');
-        $this->setField('a', 'New value');
-        $this->click('Go');
-    }
-}
-
- Because we didn't specify a method attribute on the form tag, and - didn't specify an action either, the test case will follow - the usual browser behaviour of submitting the form data as a GET - request back to the same location. - In general SimpleTest tries to emulate typical browser behaviour as much as possible, - rather than attempting to catch any form of HTML omission. - This is because the target of the testing framework is the PHP application - logic, not syntax or other errors in the HTML code. - For HTML errors, other tools such as - HTMLTidy should be used, - or any of the HTML and CSS validators already out there. -

-

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

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

-

-

- Select type of user to add: - -
-

-

- The following test will confirm it... -

-class SimpleFormTests extends WebTestCase {
-    ...
-    function testNoSuperuserChoiceAvailable() {
-        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
-        $this->assertFalse($this->setField('type', 'Superuser'));
-    }
-}
-
- The current selection will not be changed if the new value is not an option. -

-

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

-

-

- The browser emulation offered by SimpleTest mimics - the actions which can be perform by a user on a - standard HTML page. Javascript is not supported, and - it's unlikely that support will be added any time - soon. -

-

- Of particular note is that the Javascript idiom of - passing form results by setting a hidden field cannot - be performed using the normal SimpleTest - commands. See below for a way to test such forms. -

- -

-Fields with multiple values

-

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

-<form class="demo">
-    <strong>Create privileges allowed:</strong>
-    <input type="checkbox" name="crud" value="c" checked><br>
-    <strong>Retrieve privileges allowed:</strong>
-    <input type="checkbox" name="crud" value="r" checked><br>
-    <strong>Update privileges allowed:</strong>
-    <input type="checkbox" name="crud" value="u" checked><br>
-    <strong>Destroy privileges allowed:</strong>
-    <input type="checkbox" name="crud" value="d" checked><br>
-    <input type="submit" value="Enable Privileges">
-</form>
-
- Which renders as... -

-

-

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

-

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

-class SimpleFormTests extends WebTestCase {
-    ...
-    function testDisableNastyPrivileges() {
-        $this->get('http://www.lastcraft.com/form_testing_documentation.php');
-        $this->assertField('crud', array('c', 'r', 'u', 'd'));
-        $this->setField('crud', array('r'));
-        $this->click('Enable Privileges');
-    }
-}
-
- Instead of setting the field to a single value, we give it a list - of values. - We do the same when testing expected values. - We can then write other test code to confirm the effect of this, perhaps - by logging in as that user and attempting an update. -

- -

-Forms which use javascript to set a hidden field

-

- If you want to test a form which relies on javascript to set a hidden - field, you can't just call setField(). - The following code will not work: -

-class SimpleFormTests extends WebTestCase {
-    function testEmulateMyJavascriptForm() {
-        // This does *not* work
-        $this->setField('a_hidden_field', '123');
-        $this->clickSubmit('OK');
-    }
-}
-
- Instead, you need to pass the additional form parameters to the - clickSubmit() method: -
-class SimpleFormTests extends WebTestCase {
-    function testMyJavascriptForm() {
-        $this->clickSubmit('OK', array('a_hidden_field'=>'123'));
-    }
-
-}
-
- Bear in mind that in doing this you're effectively stubbing out a - part of your software (the javascript code in the form), and - perhaps you might be better off using something like - Selenium to ensure a complete - test. -

- -

-Raw posting

-

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

-class SimpleFormTests extends WebTestCase {
-    ...    
-    function testAttemptedHack() {
-        $this->post(
-                'http://www.my-site.com/add_user.php',
-                array('type' => 'superuser'));
-        $this->assertNoText('user created');
-    }
-}
-
- By adding data to the WebTestCase::post() - method, we are emulating a form submission. - You would normally only do this as a temporary expedient, or where - you are expecting a 3rd party to submit to a form. - The exception is when you want tests to protect you from - attempts to spoof your pages. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/group_test_documentation.html b/application/libraries/simpletest/docs/en/group_test_documentation.html deleted file mode 100644 index 10f22a2b1b9..00000000000 --- a/application/libraries/simpletest/docs/en/group_test_documentation.html +++ /dev/null @@ -1,252 +0,0 @@ - - - -SimpleTest for PHP test suites - - - - -

Test suite documentation

- This page... - -
-

-Grouping tests into suites

-

- There are many ways to group tests together into test suites. - One way is to simply place multiple test cases into a single file... -

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

-

- Occasionally special subclasses are created that methods useful - for testing part of the application. - These new base classes are then used in place of UnitTestCase - or WebTestCase. - You don't normally want to run these as test cases. - Simply mark any base test cases that should not be run as abstract... -

-abstract class MyFileTestCase extends UnitTestCase {
-    ...
-}
-
-class FileTester extends MyFileTestCase { ... }
-
-class SocketTester extends UnitTestCase { ... }
-
- Here the FileTester class does - not contain any actual tests, but is the base class for other - test cases. -

-

- We will call this sample file_test.php. - Currently the test cases are grouped simply by being in the same file. - We can build larger constructs just by including other test files in. -

-<?php
-require_once('simpletest/autorun.php');
-require_once('file_test.php');
-?>
-
- This will work, but create a purely flat hierarchy. - INstead we create a test suite file. - Our top level test suite can look like this... -
-<?php
-require_once('simpletest/autorun.php');
-
-class AllFileTests extends TestSuite {
-    function __construct() {
-        parent::__construct();
-        $this->addFile('file_test.php');
-    }
-}
-?>
-
- What happens here is that the TestSuite - class will do the require_once() - for us. - It then checks to see if any new test case classes - have been created by the new file and automatically composes - them to the test suite. - This method gives us the most control as we just manually add - more test files as our test suite grows. -

-

- If this is too much typing, and you are willing to group - test suites together in their own directories or otherwise - tag the file names, then there is a more automatic way... -

-<?php
-require_once('simpletest/autorun.php');
-
-class AllFileTests extends TestSuite {
-    function __construct() {
-        parent::__construct();
-        $this->collect(dirname(__FILE__) . '/unit',
-                       new SimplePatternCollector('/_test.php/'));
-    }
-}
-?>
-
- This will scan a directory called "unit" for any files - ending with "_test.php" and load them. - You don't have to use SimplePatternCollector to - filter by a pattern in the filename, but this is the most common - usage. -

-

- That snippet above is very common in practice. - Now all you have to do is drop a file of test cases into the - directory and it will run just by running the test suite script. -

-

- The catch is that you cannot control the order in which the test - cases are run. - If you want to see lower level components fail first in the test suite, - and this will make diagnosis a lot easier, then you should manually - call addFile() for these. - Tests cases are only loaded once, so it's fine to have these included - again by a directory scan. -

-

- Test cases loaded with the addFile method have some - useful properties. - You can guarantee that the constructor is run - just before the first test method and the destructor - is run just after the last test method. - This allows you to place test case wide set up and tear down - code in the constructor and destructor, just like a normal - class. -

- -

-Composite suites

-

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

-

- Everything we have described so far with test scripts applies to - TestSuites as well... -

-<?php
-require_once('simpletest/autorun.php');
-
-class BigTestSuite extends TestSuite {
-    function __construct() {
-        parent::__construct();
-        $this->addFile('file_tests.php');
-    }
-}
-?>
-
- This effectively adds our test cases and a single suite below - the first. - When a test fails, we see the breadcrumb trail of the nesting. - We can even mix groups and test cases freely as long as - we are careful about loops in our includes. -
-<?php
-require_once('simpletest/autorun.php');
-
-class BigTestSuite extends TestSuite {
-    function __construct() {
-        parent::__construct();
-        $this->addFile('file_tests.php');
-        $this->addFile('some_other_test.php');
-    }
-}
-?>
-
- Note that in the event of a double include, ony the first instance - of the test case will be run. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/index.html b/application/libraries/simpletest/docs/en/index.html deleted file mode 100644 index 9f022d6b10b..00000000000 --- a/application/libraries/simpletest/docs/en/index.html +++ /dev/null @@ -1,542 +0,0 @@ - - - - - Download the SimpleTest testing framework - - Unit tests and mock objects for PHP - - - - - -

SimpleTest for PHP

- This page... - -
- - -

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

- -

-Using the tester quickly

-

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

-

- What makes this tool immediately useful to the PHP developer is the internal - web browser. - This allows tests that navigate web sites, fill in forms and test pages. - Being able to write these test in PHP means that it is easy to write - integrated tests. - An example might be confirming that a user was written to a database - after a signing up through the web site. -

-

- The quickest way to demonstrate SimpleTest is with an example. -

-

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

-<?php
-require_once('simpletest/autorun.php');
-require_once('../classes/log.php');
-
-class TestOfLogging extends UnitTestCase {
-}
-?>
-
- Here the simpletest folder is either local or in the path. - You would have to edit these locations depending on where you - unpacked the toolset. - The "autorun.php" file does more than just include the - SimpleTest files, it also runs our test for us. -

-

- The TestOfLogging is our first test case and it's - currently empty. - Each test case is a class that extends one of the SimpleTet base classes - and we can have as many of these in the file as we want. -

-

- With three lines of scaffolding, and our Log class - include, we have a test suite. - No tests though. -

-

- For our first test, we'll assume that the Log class - takes the file name to write to in the constructor, and we have - a temporary folder in which to place this file... -

-<?php
-require_once('simpletest/autorun.php');
-require_once('../classes/log.php');
-
-class TestOfLogging extends UnitTestCase {
-    function testLogCreatesNewFileOnFirstMessage() {
-        @unlink('/temp/test.log');
-        $log = new Log('/temp/test.log');
-        $this->assertFalse(file_exists('/temp/test.log'));
-        $log->message('Should write this to a file');
-        $this->assertTrue(file_exists('/temp/test.log'));
-    }
-}
-?>
-
- When a test case runs, it will search for any method that - starts with the string "test" - and execute that method. - If the method starts "test", it's a test. - Note the very long name testLogCreatesNewFileOnFirstMessage(). - This is considered good style and makes the test output more readable. -

-

- We would normally have more than one test method in a test case, - but that's for later. -

-

- Assertions within the test methods trigger messages to the - test framework which displays the result immediately. - This immediate response is important, not just in the event - of the code causing a crash, but also so that - print statements can display - their debugging content right next to the assertion concerned. -

-

- To see these results we have to actually run the tests. - No other code is necessary - we can just open the page - with our browser. -

-

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

-

TestOfLogging

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

TestOfLogging

-
1/1 test cases complete. - 2 passes and 0 fails.
-
- And if you get this... -
- Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7 -
- it means you're missing the classes/Log.php file that could look like... -
-<?php
-class Log {
-    function Log($file_path) {
-    }
-
-    function message() {
-    }
-}
-?>
-
- It's fun to write the code after the test. - More than fun even - - this system is called "Test Driven Development". -

-

- For more information about UnitTestCase, see - the unit test documentation. -

- -

-Building test suites

-

- 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 for the application. -

-

- Our first step is to create a new file called tests/all_tests.php - and insert the following code... -

-<?php
-require_once('simpletest/autorun.php');
-
-class AllTests extends TestSuite {
-    function AllTests() {
-        $this->TestSuite('All tests');
-        $this->addFile('log_test.php');
-    }
-}
-?>
-
- The "autorun" include allows our upcoming test suite - to be run just by invoking this script. -

-

- The TestSuite subclass must chain it's constructor. - This limitation will be removed in future versions. -

-

- The method TestSuite::addFile() - will include the test case file and read any new classes - that are descended from SimpleTestCase. - UnitTestCase is just one example of a class derived from - SimpleTestCase, and you can create your own. - TestSuite::addFile() can include other test suites. -

-

- The class will not be instantiated yet. - When the test suite runs it will construct each instance once - it reaches that test, then destroy it straight after. - This means that the constructor is run just before each run - of that test case, and the destructor is run before the next test case starts. -

-

- It is common to group test case code into superclasses which are not - supposed to run, but become the base classes of other tests. - For "autorun" to work properly the test case file should not blindly run - 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 mark your - base class as abstract. - SimpleTest won't run abstract classes. - If you are still using PHP4, then - a SimpleTestOptions::ignore() directive - somewhere in the test case file will have the same effect. -

-

- Also, the test case file should not have been included - elsewhere or no cases will be added to this group test. - This would be a more serious error as if the test case classes are - already loaded by PHP the TestSuite::addFile() - method will not detect them. -

-

- To display the results it is necessary only to invoke - tests/all_tests.php from the web server or the command line. -

-

- For more information about building test suites, - see the test suite documentation. -

- -

-Using mock objects

-

- Let's move further into the future and do something really complicated. -

-

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


-class SessionPool {
-    ...
-    function logIn($username) {
-        ...
-        $this->_log->message("User $username logged in.");
-        ...
-    }
-    ...
-}
-
-
- In the spirit of reuse, we are using our - Log class. - A conventional test case might look like this... -
-<?php
-require_once('simpletest/autorun.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 testLoggingInIsLogged() {
-        $log = new Log('/temp/test.log');
-        $session_pool = &new SessionPool($log);
-        $session_pool->logIn('fred');
-        $messages = file('/temp/test.log');
-        $this->assertEqual($messages[0], "User fred logged in.\n");
-    }
-}
-?>
-
- We'll explain the setUp() and tearDown() - methods later. -

-

- 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. - We have created close ties with the Log class and - this test. - What if we don't use files any more, but use ths - syslog library instead? - It means that our TestOfSessionLogging test will - fail, even thouh it's not testing Logging. -

-

- It's fragile in smaller ways too. - Did you notice the extra carriage return in the message? - Was that added by the logger? - What if it also added a time stamp or other data? -

-

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

-

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

-

- Too good to be true? - We can create such an object easily... -
-<?php
-require_once('simpletest/autorun.php');
-require_once('../classes/log.php');
-require_once('../classes/session_pool.php');
-
-Mock::generate('Log');
-
-class TestOfSessionLogging extends UnitTestCase {
-    
-    function testLoggingInIsLogged() {
-        $log = &new MockLog();
-        $log->expectOnce('message', array('User fred logged in.'));
-        $session_pool = &new SessionPool($log);
-        $session_pool->logIn('fred');
-    }
-}
-?>
-
- The Mock::generate() call code generated a new class - called MockLog. - This looks like an identical clone, except that we can wire test code - to it. - That's what expectOnce() does. - It says that if message() is ever called on me, it had - better be with the parameter "User fred logged in.". -

-

- The test will be triggered when the call to - message() is invoked on the - MockLog object by SessionPool::logIn() code. - 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 you don't have to test every parameter of - a call when you only want to test one. -

-

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

-

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

-

- For more information about mocking and stubbing, see the - mock objects documentation. -

- -

-Web page testing

-

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

-

- The web testing in SimpleTest is fairly primitive, as there is - no JavaScript. - Most other browser operations are simulated. -

-

- To give an idea here is a trivial example where a home - page is fetched, from which we navigate to an "about" - page and then test some client determined content. -

-<?php
-require_once('simpletest/autorun.php');
-require_once('simpletest/web_tester.php');
-
-class TestOfAbout extends WebTestCase {
-    function testOurAboutPageGivesFreeReignToOurEgo() {
-        $this->get('http://test-server/index.php');
-        $this->click('About');
-        $this->assertTitle('About why we are so great');
-        $this->assertText('We are really great');
-    }
-}
-?>
-
- 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. -

-

- You can navigate forms too... -

-<?php
-require_once('simpletest/autorun.php');
-require_once('simpletest/web_tester.php');
-
-class TestOfRankings extends WebTestCase {
-    function testWeAreTopOfGoogle() {
-        $this->get('http://google.com/');
-        $this->setField('q', 'simpletest');
-        $this->click("I'm Feeling Lucky");
-        $this->assertTitle('SimpleTest - Unit Testing for PHP');
-    }
-}
-?>
-
- ...although this could violate Google's(tm) terms and conditions. -

-

- For more information about web testing, see the - scriptable - browser documentation and the - WebTestCase. -

-

- SourceForge.net Logo -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/mock_objects_documentation.html b/application/libraries/simpletest/docs/en/mock_objects_documentation.html deleted file mode 100644 index b4697f9ee3b..00000000000 --- a/application/libraries/simpletest/docs/en/mock_objects_documentation.html +++ /dev/null @@ -1,870 +0,0 @@ - - - -SimpleTest for PHP mock objects documentation - - - - -

Mock objects documentation

- This page... - -
-

-What are mock objects?

-

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

-

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

-

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

-

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

-

- However, the mock objects not only play a part (by supplying chosen - return values on demand) they are also sensitive to the - messages sent to them (via expectations). - By setting expected parameters for a method call they act - as a guard that the calls upon them are made correctly. - If expectations are not met they save us the effort of - writing a failed test assertion by performing that duty on our - behalf. -

-

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

- -

-Creating mock objects

-

- All we need is an existing class or interface, say a database connection - that looks like this... -

-class DatabaseConnection {
-    function DatabaseConnection() { }
-    function query($sql) { }
-    function selectQuery($sql) { }
-}
-
- To create a mock version of the class we need to run a - code generator... -
-require_once('simpletest/autorun.php');
-require_once('database_connection.php');
-
-Mock::generate('DatabaseConnection');
-
- This code generates a clone class called - MockDatabaseConnection. - This new class appears to be the same, but actually has no behaviour at all. -

-

- The new class is usually a subclass of DatabaseConnection. - Unfortunately, there is no way to create a mock version of a - class with a final method without having a living version of - that method. - We consider that unsafe. - If the target is an interface, or if final methods are - present in a target class, then a whole new class - is created, but one implemeting the same interfaces. - If you try to pass this separate class through a type hint that specifies - the old concrete class name, it will fail. - Code like that insists on type hinting to a class with final - methods probably cannot be safely tested with mocks. -

-

- If you want to see the generated code, then simply print - the output of Mock::generate(). - Here is the generated code for the DatabaseConnection - class rather than the interface version... -

-class MockDatabaseConnection extends DatabaseConnection {
-    public $mock;
-    protected $mocked_methods = array('databaseconnection', 'query', 'selectquery');
-
-    function MockDatabaseConnection() {
-        $this->mock = new SimpleMock();
-        $this->mock->disableExpectationNameChecks();
-    }
-    ...
-    function DatabaseConnection() {
-        $args = func_get_args();
-        $result = &$this->mock->invoke("DatabaseConnection", $args);
-        return $result;
-    }
-    function query($sql) {
-        $args = func_get_args();
-        $result = &$this->mock->invoke("query", $args);
-        return $result;
-    }
-    function selectQuery($sql) {
-        $args = func_get_args();
-        $result = &$this->mock->invoke("selectQuery", $args);
-        return $result;
-    }
-}
-
- Your output may vary depending on the exact version - of SimpleTest you are using. -

-

- Besides the original methods of the class, you will see some extra - methods that help testing. - More on these later. -

-

- We can now create instances of the new class within - our test case... -

-require_once('simpletest/autorun.php');
-require_once('database_connection.php');
-
-Mock::generate('DatabaseConnection');
-
-class MyTestCase extends UnitTestCase {
-
-    function testSomething() {
-        $connection = new MockDatabaseConnection();
-    }
-}
-
- The mock version now has all the methods of the original. - Also, any type hints will be faithfully preserved. - Say our query methods expect a Query object... -
-class DatabaseConnection {
-    function DatabaseConnection() { }
-    function query(Query $query) { }
-    function selectQuery(Query $query) { }
-}
-
- If we now pass the wrong type of object, or worse a non-object... -
-class MyTestCase extends UnitTestCase {
-
-    function testSomething() {
-        $connection = new MockDatabaseConnection();
-        $connection->query('insert into accounts () values ()');
-    }
-}
-
- ...the code will throw a type violation at you just as the - original class would. -

-

- The mock version now has all the methods of the original. - Unfortunately, they all return null. - As methods that always return null are not that useful, - we need to be able to set them to something else... -

-

-

Mocks as actors

-

-

- Changing the return value of a method from null - to something else is pretty easy... -

-$connection->returns('query', 37)
-
- Now every time we call - $connection->query() we get - the result of 37. - There is nothing special about 37. - The return value can be arbitrarily complicated. -

-

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

-

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

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

-

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

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

-

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


-$config->returns('get', false, array('*'));
-
- This is not the same as setting the return value without - any argument requirements like this... -

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

-

- There are times when you want a specific reference to be - dished out by the mock rather than a copy or object handle. - This a rarity to say the least, but you might be simulating - a container that can hold primitives such as strings. - For example... -

-class Pad {
-    function Pad() { }
-    function &note($index) { }
-}
-
- In this case you can set a reference into the mock's - return list... -
-function testTaskReads() {
-    $note = 'Buy books';
-    $pad = new MockPad();
-    $vector->returnsByReference('note', $note, array(3));
-    $task = new Task($pad);
-    ...
-}
-
- With this arrangement you know that every time - $pad->note(3) is - called it will return the same $note each time, - even if it get's modified. -

-

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

-$buy_books = 'Buy books';
-$write_code = 'Write code';
-$pad = new MockPad();
-$vector->returnsByReferenceAt(0, 'note', $buy_books, array('*', 3));
-$vector->returnsByReferenceAt(1, 'note', $write_code, array('*', 3));
-
- This will return a reference to $buy_books and - then to $write_code, but only if two parameters - were set the second of which must be the integer 3. - That should cover most situations. -

-

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

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

-

- We could refine this test further by insisting that the correct - query is sent... -

-$connection->returns('selectQuery', $result, array('select name, id from people'));
-
- This is actually a bad idea. -

-

- We have a UserFinder in object land, talking to - database tables using a large interface - the whole of SQL. - Imagine that we have written a lot of tests that now depend - on the exact SQL string passed. - These queries could change en masse for all sorts of reasons - not related to the specific test. - For example the quoting rules could change, a table name could - change, a link table added or whatever. - This would require the rewriting of every single test any time - one of these refactoring is made, yet the intended behaviour has - stayed the same. - Tests are supposed to help refactoring, not hinder it. - I'd certainly like to have a test suite that passes while I change - table names. -

-

- As a rule it is best not to mock a fat interface. -

-

- By contrast, here is the round trip test... -

-class DatabaseTest extends UnitTestCase {
-    function setUp() { ... }
-    function tearDown() { ... }
-
-    function testUserFinderReadsResultsFromDatabase() {
-        $finder = new UserFinder(new DatabaseConnection());
-        $finder->add('tom');
-        $finder->add('dick');
-        $finder->add('harry');
-        $this->assertIdentical(
-                $finder->findNames(),
-                array('tom', 'dick', 'harry'));
-    }
-}
-
- This test is immune to schema changes. - It will only fail if you actually break the functionality, which - is what you want a test to do. -

-

- The catch is those setUp() and tearDown() - methods that we've rather glossed over. - They have to clear out the database tables and ensure that the - schema is defined correctly. - That can be a chunk of extra work, but you usually have this code - lying around anyway for deployment purposes. -

-

- One place where you definitely need a mock is simulating failures. - Say the database goes down while UserFinder is doing - it's work. - Does UserFinder behave well...? -

-class DatabaseTest extends UnitTestCase {
-
-    function testUserFinder() {
-        $connection = new MockDatabaseConnection();
-        $connection->throwOn('selectQuery', new TimedOut('Ouch!'));
-        $alert = new MockAlerts();
-        $alert->expectOnce('notify', 'Database is busy - please retry');
-        $finder = new UserFinder($connection, $alert);
-        $this->assertIdentical($finder->findNames(), array());
-    }
-}
-
- We've passed the UserFinder an $alert - object. - This is going to do some kind of pretty notifications in the - user interface in the event of an error. - We'd rather not sprinkle our code with hard wired print - statements if we can avoid it. - Wrapping the means of output means we can use this code anywhere. - It also makes testing easier. -

-

- To pass this test, the finder has to write a nice user friendly - message to $alert, rather than propogating the exception. - So far, so good. -

-

- How do we get the mock DatabaseConnection to throw an exception? - We generate the exception using the throwOn method - on the mock. -

-

- Finally, what if the method you want to simulate does not exist yet? - If you set a return value on a method that is not there, SimpleTest - will throw an error. - What if you are using __call() to simulate dynamic methods? -

-

- Objects with dynamic interfaces, using __call, can - be problematic with the current mock objects implementation. - You can mock the __call() method, but this is ugly. - Why should a test know anything about such low level implementation details? - It just wants to simulate the call. -

-

- The way round this is to add extra methods to the mock when - generating it. -

-Mock::generate('DatabaseConnection', 'MockDatabaseConnection', array('setOptions'));
-
- In a large test suite this could cause trouble, as you probably - already have a mock version of the class called - MockDatabaseConnection without the extra methods. - The code generator will not generate a mock version of the class if - one of the same name already exists. - You will confusingly fail to see your method if another definition - was run first. -

-

- To cope with this, SimpleTest allows you to choose any name for the - new class at the same time as you add the extra methods. -

-Mock::generate('DatabaseConnection', 'MockDatabaseConnectionWithOptions', array('setOptions'));
-
- Here the mock will behave as if the setOptions() - existed in the original class. -

-

- Mock objects can only be used within test cases, as upon expectations - they send messages straight to the currently running test case. - Creating them outside a test case will cause a run time error - when an expectation is triggered and there is no running test case - for the message to end up. - We cover expectations next. -

- -

-Mocks as critics

-

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

-

- By way of example, let's take a simple PageController - class to handle a credit card payment form... -

-class PaymentForm extends PageController {
-    function __construct($alert, $payment_gateway) { ... }
-    function makePayment($request) { ... }
-}
-
- This class takes a PaymentGateway to actually talk - to the bank. - It also takes an Alert object to handle errors. - This class talks to the page or template. - It's responsible for painting the error message and highlighting any - form fields that are incorrect. -

-

- It might look something like... -

-class Alert {
-    function warn($warning, $id) {
-        print '<div class="warning">' . $warning . '</div>';
-        print '<style type="text/css">#' . $id . ' { background-color: red }</style>';
-    }
-}
-
-

-

- Our interest is in the makePayment() method. - If we fail to enter a "CVV2" number (the three digit number - on the back of the credit card), we want to show an error rather than - try to process the payment. - In test form... -

-<?php
-require_once('simpletest/autorun.php');
-require_once('payment_form.php');
-Mock::generate('Alert');
-Mock::generate('PaymentGateway');
-
-class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
-
-    function testMissingCvv2CausesAlert() {
-        $alert = new MockAlert();
-        $alert->expectOnce(
-                    'warn',
-                    array('Missing three digit security code', 'cvv2'));
-        $controller = new PaymentForm($alert, new MockPaymentGateway());
-        $controller->makePayment($this->requestWithMissingCvv2());
-    }
-
-    function requestWithMissingCvv2() { ... }
-}
-?>
-
- The first question you may be asking is, where are the assertions? -

-

- The call to expectOnce('warn', array(...)) instructs the mock - to expect a call to warn() before the test ends. - When it gets a call to warn(), it checks the arguments. - If the arguments don't match, then a failure is generated. - It also fails if the method is never called at all. -

-

- The test above not only asserts that warn was called, - but that it received the string "Missing three digit security code" - and also the tag "cvv2". - The equivalent of assertIdentical() is applied to both - fields when the parameters are compared. -

-

- If you are not interested in the actual message, and we are not - for user interface code that changes often, we can skip that - parameter with the "*" operator... -

-class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
-
-    function testMissingCvv2CausesAlert() {
-        $alert = new MockAlert();
-        $alert->expectOnce('warn', array('*', 'cvv2'));
-        $controller = new PaymentForm($alert, new MockPaymentGateway());
-        $controller->makePayment($this->requestWithMissingCvv2());
-    }
-
-    function requestWithMissingCvv2() { ... }
-}
-
- We can weaken the test further by missing - out the parameters array... -
-function testMissingCvv2CausesAlert() {
-    $alert = new MockAlert();
-    $alert->expectOnce('warn');
-    $controller = new PaymentForm($alert, new MockPaymentGateway());
-    $controller->makePayment($this->requestWithMissingCvv2());
-}
-
- This will only test that the method is called, - which is a bit drastic in this case. - Later on, we'll see how we can weaken the expectations more precisely. -

-

- Tests without assertions can be both compact and very expressive. - Because we intercept the call on the way into an object, here of - the Alert class, we avoid having to assert its state - afterwards. - This not only avoids the assertions in the tests, but also having - to add extra test only accessors to the original code. - If you catch yourself adding such accessors, called "state based testing", - it's probably time to consider using mocks in the tests. - This is called "behaviour based testing", and is normally superior. -

-

- Let's add another test. - Let's make sure that we don't even attempt a payment without a CVV2... -

-class PaymentFormFailuresShouldBeGraceful extends UnitTestCase {
-
-    function testMissingCvv2CausesAlert() { ... }
-
-    function testNoPaymentAttemptedWithMissingCvv2() {
-        $payment_gateway = new MockPaymentGateway();
-        $payment_gateway->expectNever('pay');
-        $controller = new PaymentForm(new MockAlert(), $payment_gateway);
-        $controller->makePayment($this->requestWithMissingCvv2());
-    }
-
-    ...
-}
-
- Asserting a negative can be very hard in tests, but - expectNever() makes it easy. -

-

- expectOnce() and expectNever() are - sufficient for most tests, but - occasionally you want to test multiple events. - Normally for usability purposes we want all missing fields - in the form to light up, not just the first one. - This means that we should get multiple calls to - Alert::warn(), not just one... -

-function testAllRequiredFieldsHighlightedOnEmptyRequest() {
-    $alert = new MockAlert();
-    $alert->expectAt(0, 'warn', array('*', 'cc_number'));
-    $alert->expectAt(1, 'warn', array('*', 'expiry'));
-    $alert->expectAt(2, 'warn', array('*', 'cvv2'));
-    $alert->expectAt(3, 'warn', array('*', 'card_holder'));
-    $alert->expectAt(4, 'warn', array('*', 'address'));
-    $alert->expectAt(5, 'warn', array('*', 'postcode'));
-    $alert->expectAt(6, 'warn', array('*', 'country'));
-    $alert->expectCallCount('warn', 7);
-    $controller = new PaymentForm($alert, new MockPaymentGateway());
-    $controller->makePayment($this->requestWithMissingCvv2());
-}
-
- The counter in expectAt() is the number of times - the method has been called already. - Here we are asserting that every field will be highlighted. -

-

- Note that we are forced to assert the order too. - SimpleTest does not yet have a way to avoid this, but - this will be fixed in future versions. -

-

- Here is the full list of expectations you can set on a mock object - in SimpleTest. - As with the assertions, these methods take an optional failure message. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ExpectationDescription
expect($method, $args)Arguments must match if called
expectAt($timing, $method, $args)Arguments must match when called on the $timing'th time
expectCallCount($method, $count)The method must be called exactly this many times
expectMaximumCallCount($method, $count)Call this method no more than $count times
expectMinimumCallCount($method, $count)Must be called at least $count times
expectNever($method)Must never be called
expectOnce($method, $args)Must be called once and with the expected arguments if supplied
expectAtLeastOnce($method, $args)Must be called at least once, and always with any expected arguments
- Where the parameters are... -

-
$method
-
The method name, as a string, to apply the condition to.
-
$args
-
- The arguments as a list. Wildcards can be included in the same - manner as for setReturn(). - This argument is optional for expectOnce() - and expectAtLeastOnce(). -
-
$timing
-
- The only point in time to test the condition. - The first call starts at zero and the count is for - each method independently. -
-
$count
-
The number of calls expected.
-
-

-

- If you have just one call in your test, make sure you're using - expectOnce.
- Using $mocked->expectAt(0, 'method', 'args); - on its own will allow the method to never be called. - Checking the arguments and the overall call count - are currently independant. - Add an expectCallCount() expectation when you - are using expectAt() unless zero calls is allowed. -

-

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/overview.html b/application/libraries/simpletest/docs/en/overview.html deleted file mode 100644 index 85ea9407749..00000000000 --- a/application/libraries/simpletest/docs/en/overview.html +++ /dev/null @@ -1,487 +0,0 @@ - - - - - Overview and feature list for the SimpleTest PHP unit tester and web tester - - - - - -

Overview of SimpleTest

- This page... - -
-

-What is SimpleTest?

-

- The heart of SimpleTest is a testing framework built around - test case classes. - These are written as extensions of base test case classes, - each extended with methods that actually contain test code. - Each test method of a test case class is written to invoke - various assertions that the developer expects to be true such as - assertEqual(). - If the expectation is correct, then a successful result is - dispatched to the observing test reporter, but any failure - or unexpected exception triggers an alert and a description - of the mismatch. - These test case declarations are transformed into executable - test scripts by including a SimpleTest aurorun.php file. -

-

- These documents apply to SimpleTest version 1.1, although we - try hard to maintain compatibility between versions. - If you get a test failure after an upgrade, check out the - file "HELP_MY_TESTS_DONT_WORK_ANYMORE" in the - simpletest directory to see if a feature you are using - has since been deprecated and later removed. -

-

- A test case looks like this... -

-<?php
-require_once('simpletest/autorun.php');
-
-class CanAddUp extends UnitTestCase {
-    function testOneAndOneMakesTwo() {
-        $this->assertEqual(1 + 1, 2);
-    }
-}
-?>
-
- Tests are grouped into test cases, which are just - PHP classes that extend UnitTestCase - or WebTestCase. - The tests themselves are just normal methods that start - their name with the letters "test". - You can have as many test cases as you want in a test - script and each test case can have as many test methods - as it wants too. -

-

- This test script is immediately runnable. - You just invoke it on the command line like so... -

-php adding_test.php
-
-

-

- When run on the command line you should see something like... -

-adding_test.php
-OK
-Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0
-
-

-

- If you place it on a web server and point your - web browser at it... -

-

adding_test.php

-
1/1 test cases complete. - 6 passes, 0 fails and 0 exceptions.
-
-

-

- Of course this is a silly example. - A more realistic example might be... -

-<?php
-require_once('simpletest/autorun.php');
-require_once('log.php');
-
-class TestOfLogging extends UnitTestCase {
-    function testWillCreateLogFileOnFirstMessage() {
-        $log = new Log('my.log');
-        $this->assertFalse(file_exists('my.log'));
-        $log->message('Hello');
-        $this->assertTrue(file_exists('my.log'));
-    }</strong>
-}
-?>
-
-

-

- This tool is designed for the developer. - The target audience of this tool is anyone developing a small - to medium PHP application, including developers new to - unit and web regression testing. - The core principles are ease of use first, with extendibility and - essential features. -

-

- Tests are written in the PHP language itself more or less - as the application itself is built. - The advantage of using PHP 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 when they are in the same programming language. -

-

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

-

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

-

- A WebTestCase looks like this... -

-<?php
-require_once('simpletest/autorun.php');
-require_once('simpletest/web_tester.php');
-
-class MySiteTest extends WebTestCase {
-    
-    function testHomePageHasContactDetailsLink() {
-        $this->get('http://www.my-site.com/index.php');
-        $this->assertTitle('My Home Page');
-        $this->clickLink('Contact');
-        $this->assertTitle('Contact me');
-        $this->assertText('/Email me at/');
-    }
-}
-?>
-
-

- -

-Feature list

-

- The following is a very rough outline of past and future features - and their expected point of release. - I am afraid it is liable to change without warning, as meeting the - milestones rather depends on time available. -

-

- Green stuff has been coded, but not necessarily released yet. - If you have a pressing need for a green but unreleased feature - then you should check-out the code from Sourceforge SVN directly. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureDescriptionRelease
Unit test caseCore test case class and assertions1.0
Html displaySimplest possible display1.0
Autoloading of test cases - Reading a file with test cases and loading them into a - group test automatically - 1.0
Mock objects - Objects capable of simulating other objects removing - test dependencies - 1.0
Web test caseAllows link following and title tag matching1.0
Partial mocks - Mocking parts of a class for testing less than a class - or for complex simulations - 1.0
Web cookie handlingCorrect handling of cookies when fetching pages1.0
Following redirectsPage fetching automatically follows 300 redirects1.0
Form parsingAbility to submit simple forms and read default form values1.0
Command line interfaceTest display without the need of a web browser1.0
Exposure of expectation classesCan create precise tests with mocks as well as test cases1.0
XML output and parsing - Allows multi host testing and the integration of acceptance - testing extensions - 1.0
Browser component - Exposure of lower level web browser interface for more - detailed test cases - 1.0
HTTP authentication - Fetching protected web pages with basic authentication - only - 1.0
SSL supportCan connect to https: pages1.0
Proxy supportCan connect via. common proxies1.0
Frames supportHandling of frames in web test cases1.0
File upload testingCan simulate the input type file tag1.0.1
Mocking interfaces - Can generate mock objects to interfaces as well as classes - and class interfaces are carried for type hints - 1.0.1
Testing exceptionsSimilar to testing PHP errors1.0.1
HTML label supportCan access all controls using the visual label1.0.1
Base tag supportRespects page base tag when clicking1.0.1
PHP 5 E_STRICT compliantPHP 5 only version that works with the E_STRICT error level1.1
Alternate HTML parsersCan detect compiled parsers for performance improvements1.1
REST supportSupport for REST verbs as put(), delete(), etc.1.1
BDD style fixturesCan import fixtures using a mixin like given() method1.5
Plug-in architectureAutomatic import of extensions including command line options1.5
Reporting machinery enhancementsImproved message passing for better cooperation with IDEs1.5
Fluent mock interfaceMore flexible and concise mock objects1.6
LocalisationMessages abstracted and code generated as well as UTF support1.6
CSS selectorsHTML content can be examined using CSS selectors1.7
HTML table assertionsCan match HTML or other table elements to expectations1.7
Unified acceptance testing modelContent searchable through selectors combined with expectations1.7
DatabaseTestCaseSQL selectors and DB drivers1.7
IFrame supportReads IFrame content that can be refreshed1.8
Integrated Selenium supportEasy to use built in Selenium driver and tutorial or similar browser automation1.9
Code coverageReports using the bundled tool when using XDebug1.9
Deprecation of old methodsSimpler interface for SimpleTest22.0
Javascript suportUse of PECL module to add Javascript to the native browser3.0
- PHP 5 migration is complete, which means that only PHP 5.0.3+ - will be supported in SimpleTest version 1.1+. - Earlier versions of SimpleTest are compatible with PHP 4.2 up to - PHP 5 (non E_STRICT). -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/partial_mocks_documentation.html b/application/libraries/simpletest/docs/en/partial_mocks_documentation.html deleted file mode 100644 index cb70b1f86df..00000000000 --- a/application/libraries/simpletest/docs/en/partial_mocks_documentation.html +++ /dev/null @@ -1,457 +0,0 @@ - - - -SimpleTest for PHP partial mocks documentation - - - - -

Partial mock objects documentation

- This page... - -
- -

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

- -

-The mock injection problem

-

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

-

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

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

-

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

-

- Here this would be... -

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

-

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

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

-

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

-<?php
-require_once('socket.php');
-
-class Telnet {
-   function Telnet($network) {
-        $this->_network = $network;
-    }
-    ...
-    function connect($ip, $port, $username, $password) {
-        $socket = $this->_network->createSocket($ip, $port);
-        $socket->read( ... );
-        ...
-        return $socket;
-    }
-}
-?>
-
- This is probably the most highly factored answer as creation - is now moved into a small specialist class. - The networking factory can now be tested separately, but mocked - easily when we are testing the telnet class... -
-class TelnetTest extends UnitTestCase {
-    ...
-    function testConnection() {
-        $socket = new MockSocket();
-        ...
-        $network = new MockNetwork();
-        $network->returnsByReference('createSocket', $socket);
-        $telnet = new Telnet($network);
-        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
-    }
-}
-
- The downside is that we are adding a lot more classes to the - library. - Also we are passing a lot of factories around which will - make the code a little less intuitive. - The most flexible solution, but the most complex. -

-

- Well techniques like "Dependency Injection" tackle the problem of - instantiating a lot of constructor parameters. - Unfortunately knowledge of this pattern is not widespread, and if you - are trying to get older code to work, rearchitecting the whole - application is not really an option. -

-

- Is there a middle ground? -

- -

-Protected factory method

-

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

-<?php
-require_once('socket.php');
-
-class Telnet {
-    ...
-    function connect($ip, $port, $username, $password) {
-        $socket = $this->createSocket($ip, $port);
-        $socket->read( ... );
-        ...
-    }
-
-    protected function createSocket($ip, $port) {
-        return new Socket($ip, $port);
-    }
-}
-?>
-
- This is a pretty safe step even for very tangled legacy code. - This is the only change we make to the application. -

-

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

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

-

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

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

- -

-A partial mock

-

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

-

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

-Mock::generatePartial(
-        'Telnet',
-        'TelnetTestVersion',
-        array('createSocket'));
-
-class TelnetTest extends UnitTestCase {
-    ...
-    function testConnection() {
-        $socket = new MockSocket();
-        ...
-        $telnet = new TelnetTestVersion();
-        $telnet->setReturnReference('createSocket', $socket);
-        $telnet->Telnet();
-        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
-    }
-}
-
- The partial mock is a subclass of the original with - selected methods "knocked out" with test - versions. - The generatePartial() call - takes three parameters: the class to be subclassed, - the new test class name and a list of methods to mock. -

-

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

-

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

-

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

-class TelnetTest extends UnitTestCase {
-    ...
-    function testConnection() {
-        $socket = new MockSocket();
-        ...
-        $telnet = new TelnetTestVersion();
-        $telnet->setReturnReference('createSocket', $socket);
-        $telnet->expectOnce('createSocket', array('127.0.0.1', 21));
-        $telnet->Telnet();
-        $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
-    }
-}
-
- Partial mocks are not used often. - I consider them transitory. - Useful while refactoring, but once the application has - all of it's dependencies nicely separated then the - partial mocks can wither away. -

- -

-Testing less than a class

-

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

-

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

-

- It's all going to come down to the coding standards of your - project to decide if you allow test mechanisms like this. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/reporter_documentation.html b/application/libraries/simpletest/docs/en/reporter_documentation.html deleted file mode 100644 index 28b6cc9bebc..00000000000 --- a/application/libraries/simpletest/docs/en/reporter_documentation.html +++ /dev/null @@ -1,616 +0,0 @@ - - - -SimpleTest for PHP test runner and display documentation - - - - -

Test reporter documentation

- This page... - -
- -

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

- -

-Reporting results in HTML

-

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

-

File test

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

File test

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

-

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

-class HtmlReporter extends SimpleReporter {
-    public __construct($encoding) { ... }
-    public makeDry(boolean $is_dry) { ... }
-    public void paintHeader(string $test_name) { ... }
-    public void sendNoCacheHeaders() { ... }
-    public void paintFooter(string $test_name) { ... }
-    public void paintGroupStart(string $test_name, integer $size) { ... }
-    public void paintGroupEnd(string $test_name) { ... }
-    public void paintCaseStart(string $test_name) { ... }
-    public void paintCaseEnd(string $test_name) { ... }
-    public void paintMethodStart(string $test_name) { ... }
-    public void paintMethodEnd(string $test_name) { ... }
-    public void paintFail(string $message) { ... }
-    public void paintPass(string $message) { ... }
-    public void paintError(string $message) { ... }
-    public void paintException(string $message) { ... }
-    public void paintMessage(string $message) { ... }
-    public void paintFormattedMessage(string $message) { ... }
-    protected string getCss() { ... }
-    public array getTestList() { ... }
-    public integer getPassCount() { ... }
-    public integer getFailCount() { ... }
-    public integer getExceptionCount() { ... }
-    public integer getTestCaseCount() { ... }
-    public integer getTestCaseProgress() { ... }
-}
-
- Here is what some of these methods mean. First the display methods - that you will probably want to override... - - There are also some accessors to get information on the current - state of the test suite. - Use these to enrich the display... - - One simple modification is to get the HtmlReporter to display - the passes as well as the failures and errors... -
-class ReporterShowingPasses extends HtmlReporter {
-    
-    function paintPass($message) {
-        parent::paintPass($message);
-        print "<span class=\"pass\">Pass</span>: ";
-        $breadcrumb = $this->getTestList();
-        array_shift($breadcrumb);
-        print implode("-&gt;", $breadcrumb);
-        print "-&gt;$message<br />\n";
-    }
-    
-    protected function getCss() {
-        return parent::getCss() . ' .pass { color: green; }';
-    }
-}
-
-

-

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

-

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

- -

-Extending the reporter

-

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

-

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

-require_once('simpletest/simpletest.php');
-
-class MyDisplay extends SimpleReporter {
-    
-    function paintHeader($test_name) { }
-    
-    function paintFooter($test_name) { }
-    
-    function paintStart($test_name, $size) {
-        parent::paintStart($test_name, $size);
-    }
-    
-    function paintEnd($test_name, $size) {
-        parent::paintEnd($test_name, $size);
-    }
-    
-    function paintPass($message) {
-        parent::paintPass($message);
-    }
-    
-    function paintFail($message) {
-        parent::paintFail($message);
-    }
-    
-    function paintError($message) {
-        parent::paintError($message);
-    }
-    
-    function paintException($exception) {
-        parent::paintException($exception);
-    }
-}
-
- No output would come from this class until you add it. -

-

- The catch with using this low level class is that you must - explicitely invoke it in the test script. - The "autorun" facility will not be able to use - it's runime context (whether it's running in a web browser - or the command line) to select the reporter. -

-

- You explicitely invoke the test runner like so... -

-<?php
-require_once('simpletest/autorun.php');
-
-$test = new TestSuite('File test');
-$test->addFile('tests/file_test.php');
-$test->run(new MyReporter());
-?>
-
- ...perhaps like this... -
-<?php
-require_once('simpletest/simpletest.php');
-require_once('my_reporter.php');
-
-class MyTest extends TestSuite {
-    function __construct() {
-        parent::__construct();
-        $this->addFile('tests/file_test.php');
-    }
-}
-
-$test = new MyTest();
-$test->run(new MyReporter());
-?>
-
- We'll show how to fit in with "autorun" later. -

- -

-The command line reporter

-

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

-<?php
-require_once('simpletest/autorun.php');
-
-$test = new TestSuite('File test');
-$test->addFile('tests/file_test.php');
-$test->run(new TextReporter());
-?>
-
- Then invoke the test suite from the command line... -
-php file_test.php
-
- You will need the command line version of PHP installed - of course. - A passing test suite looks like this... -
-File test
-OK
-Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0
-
- A failure triggers a display like this... -
-File test
-1) True assertion failed.
-    in createNewFile
-FAILURES!!!
-Test cases run: 1/1, Passes: 0, Failures: 1, Exceptions: 0
-
-

-

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

-<?php
-require_once('simpletest/autorun.php');
-
-$test = new TestSuite('File test');
-$test->addFile('tests/file_test.php');
-exit ($test->run(new TextReporter()) ? 0 : 1);
-?>
-
- Of course we wouldn't really want to create two test scripts, - a command line one and a web browser one, for each test suite. - The command line reporter includes a method to sniff out the - run time environment... -
-<?php
-require_once('simpletest/autorun.php');
-
-$test = new TestSuite('File test');
-$test->addFile('tests/file_test.php');
-if (TextReporter::inCli()) {
-    exit ($test->run(new TextReporter()) ? 0 : 1);
-}
-$test->run(new HtmlReporter());
-?>
-
- This is the form used within SimpleTest itself. - When you use the "autorun.php", and no - test has been run by the end, this is pretty much - the code that SimpleTest will run for you implicitely. -

-

- In other words, this is gives the same result... -

-<?php
-require_once('simpletest/autorun.php');
-
-class MyTest extends TestSuite {
-    function __construct() {
-        parent::__construct();
-        $this->addFile('tests/file_test.php');
-    }
-}
-?>
-
-

- -

-Remote testing

-

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

-<?xml version="1.0"?>
-<run>
-  <group size="4">
-    <name>Remote tests</name>
-    <group size="4">
-      <name>Visual test with 48 passes, 48 fails and 4 exceptions</name>
-      <case>
-        <name>testofunittestcaseoutput</name>
-        <test>
-          <name>testofresults</name>
-          <pass>This assertion passed</pass>
-          <fail>This assertion failed</fail>
-        </test>
-        <test>
-          ...
-        </test>
-      </case>
-    </group>
-  </group>
-</run>
-
- To get your normal test cases to produce this format, on the - command line add the --xml flag. -
-php my_test.php --xml
-
- You can do teh same thing in the web browser by adding the - URL parameter xml=1. - Any true value will do. -

-

- You can consume this format with the parser - supplied as part of SimpleTest itself. - This is called SimpleTestXmlParser and - resides in xml.php within the SimpleTest package... -

-<?php
-require_once('simpletest/xml.php');
-    
-...
-$parser = new SimpleTestXmlParser(new HtmlReporter());
-$parser->parse($test_output);
-?>
-
- The $test_output should be the XML format - from the XML reporter, and could come from say a command - line run of a test case. - The parser sends events to the reporter just like any - other test run. - There are some odd occasions where this is actually useful. -

-

- Most likely it's when you want to isolate a problematic crash - prone test. - You can collect the XML output using the backtick operator - from another test. - In that way it runs in it's own process... -

-<?php
-require_once('simpletest/xml.php');
-
-if (TextReporter::inCli()) {
-    $parser = new SimpleTestXmlParser(new TextReporter());
-} else {
-    $parser = new SimpleTestXmlParser(new HtmlReporter());
-}
-$parser->parse(`php flakey_test.php --xml`);
-?>
-
-

-

- Another use is breaking up large test suites. -

-

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

-

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

-<?php
-require_once('../remote.php');
-require_once('simpletest/autorun.php');
-    
-$test_url = ...;
-$dry_url = ...;
-
-class MyTestOnAnotherServer extends RemoteTestCase {
-    function __construct() {
-        $test_url = ...
-        parent::__construct($test_url, $test_url . ' --dry');
-    }
-}
-?>
-
- The RemoteTestCase takes the actual location - of the test runner, basically a web page in XML format. - It also takes the URL of a reporter set to do a dry run. - This is so that progress can be reported upward correctly. - The RemoteTestCase can be added to test suites - just like any other test suite. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/unit_test_documentation.html b/application/libraries/simpletest/docs/en/unit_test_documentation.html deleted file mode 100644 index a399bf34cb1..00000000000 --- a/application/libraries/simpletest/docs/en/unit_test_documentation.html +++ /dev/null @@ -1,442 +0,0 @@ - - - -SimpleTest for PHP regression test documentation - - - - -

PHP Unit Test documentation

- This page... - -
-

-Unit test cases

-

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

-class FileTestCase extends UnitTestCase {
-}
-
- Actual tests are added as methods in the test case whose names - by default start with the string "test" and - when the test case is invoked all such methods are run in - the order that PHP introspection finds them. - As many test methods can be added as needed. -

-

- For example... -

-require_once('simpletest/autorun.php');
-require_once('../classes/writer.php');
-
-class FileTestCase extends UnitTestCase {
-    function FileTestCase() {
-        $this->UnitTestCase('File test');
-    }
-
-    function setUp() {
-        @unlink('../temp/test.txt');
-    }
-
-    function tearDown() {
-        @unlink('../temp/test.txt');
-    }
-
-    function testCreation() {
-        $writer = &new FileWriter('../temp/test.txt');
-        $writer->write('Hello');
-        $this->assertTrue(file_exists('../temp/test.txt'), 'File created');
-    }
-}
-
- The constructor is optional and usually omitted. - Without a name, the class name is taken as the name of the test case. -

-

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

-

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

-

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

-

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

-

- Some examples... -

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

-

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

-

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

- -

-Extending test cases

-

- Of course additional test methods can be added to create - specific types of test case, so as to extend framework... -

-require_once('simpletest/autorun.php');
-
-class FileTester extends UnitTestCase {
-    function FileTester($name = false) {
-        $this->UnitTestCase($name);
-    }
-
-    function assertFileExists($filename, $message = '%s') {
-        $this->assertTrue(
-                file_exists($filename),
-                sprintf($message, 'File [$filename] existence check'));
-    }
-}
-
- Here the SimpleTest library is held in a folder called - simpletest that is local. - Substitute your own path for this. -

-

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

-

- Alternatively you could add a - SimpleTestOptions::ignore('FileTester'); - directive in your code. -

-

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

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

-

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

- -

-Running a single test case

-

- You won't often run single test cases except when bashing - away at a module that is having difficulty, and you don't - want to upset the main test suite. - With autorun no particular scaffolding is needed, - just launch your particular test file and you're ready to go. -

-

- You can even decide which reporter (for example, - TextReporter or HtmlReporter) - you prefer for a specific file when launched on its own... -

-<?php
-require_once('simpletest/autorun.php');
-SimpleTest :: prefer(new TextReporter());
-require_once('../classes/writer.php');
-
-class FileTestCase extends UnitTestCase {
-    ...
-}
-?>
-
- This script will run as is, but of course will output zero passes - and zero failures until test methods are added. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/en/web_tester_documentation.html b/application/libraries/simpletest/docs/en/web_tester_documentation.html deleted file mode 100644 index aa9df50a679..00000000000 --- a/application/libraries/simpletest/docs/en/web_tester_documentation.html +++ /dev/null @@ -1,588 +0,0 @@ - - - -SimpleTest for PHP web script testing documentation - - - - -

Web tester documentation

- This page... - -
-

-Fetching a page

-

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

-

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

-

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

-class TestOfLastcraft extends WebTestCase {
-}
-
- Here we are about to test the - Last Craft site itself. - If this test case is in a file called lastcraft_test.php - then it can be loaded in a runner script just like unit tests... -
-<?php
-require_once('simpletest/autorun.php');
-require_once('simpletest/web_tester.php');
-SimpleTest::prefer(new TextReporter());
-
-class WebTests extends TestSuite {
-    function WebTests() {
-        $this->TestSuite('Web site tests');
-        $this->addFile('lastcraft_test.php');
-    }
-}
-?>
-
- I am using the text reporter here to more clearly - distinguish the web content from the test output. -

-

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

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

-

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

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

- -

-Testing page content

-

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

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

-

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

-

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

-$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');
-
- ...or, if that is too long and fragile... -
-$this->assertTitle(new PatternExpectation('/The Last Craft/'));
-
- As well as the simple HTML content checks we can check - that the MIME type is in a list of allowed types with... -
-$this->assertMime(array('text/plain', 'text/html'));
-
- More interesting is checking the HTTP response code. - Like the MIME type, we can assert that the response code - is in a list of allowed values... -
-class TestOfLastcraft extends WebTestCase {
-    
-    function testRedirects() {
-        $this->get('http://www.lastcraft.com/test/redirect.php');
-        $this->assertResponse(200);</strong>
-    }
-}
-
- Here we are checking that the fetch is successful by - allowing only a 200 HTTP response. - This test will pass, but it is not actually correct to do so. - There is no page, instead the server issues a redirect. - The WebTestCase will - automatically follow up to three such redirects. - The tests are more robust this way and we are usually - interested in the interaction with the pages rather - than their delivery. - If the redirects are of interest then this ability must - be disabled... -
-class TestOfLastcraft extends WebTestCase {
-    
-    function testHomepage() {
-        $this->setMaximumRedirects(0);
-        $this->get('http://www.lastcraft.com/test/redirect.php');
-        $this->assertResponse(200);
-    }
-}
-
- The assertion now fails as expected... -
-Web site tests
-1) Expecting response in [200] got [302]
-    in testhomepage
-    in testoflastcraft
-    in lastcraft_test.php
-FAILURES!!!
-Test cases run: 1/1, Failures: 1, Exceptions: 0
-
- We can modify the test to correctly assert redirects with... -
-class TestOfLastcraft extends WebTestCase {
-    
-    function testHomepage() {
-        $this->setMaximumRedirects(0);
-        $this->get('http://www.lastcraft.com/test/redirect.php');
-        $this->assertResponse(array(301, 302, 303, 307));
-    }
-}
-
- This now passes. -

- -

-Navigating a web site

-

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

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

-

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

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

-

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

-

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

-

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

-

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

-

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

- -

-Modifying the request

-

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/authentication_documentation.html b/application/libraries/simpletest/docs/fr/authentication_documentation.html deleted file mode 100644 index fb9ca42d6a2..00000000000 --- a/application/libraries/simpletest/docs/fr/authentication_documentation.html +++ /dev/null @@ -1,371 +0,0 @@ - - - -Documentation Simple Test : tester l'authentification - - - - -

Documentation sur l'authentification

- This page... - -
- -

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

- -

-Authentification HTTP basique

-

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

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

File test

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

-

- Un des axes qui traverse SimpleTest est la possibilité d'utiliser - des objets SimpleExpectation à chaque fois qu'une - vérification simple suffit. - Si vous souhaitez vérifiez simplement le contenu du realm - l'identification - du domaine - dans notre exemple, il suffit de faire... -

-class AuthenticationTest extends WebTestCase {
-    function test401Header() {
-        $this->get('http://www.lastcraft.com/protected/');
-        $this->assertRealm(new PatternExpectation('/simpletest/i'));
-    }
-}
-
- Ce type de test, vérifier les réponses HTTP, n'est cependant pas commun. -

-

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

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

-

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

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

-

- Normalement, vous utilisez l'appel authenticate(). SimpleTest - utilisera alors vos informations de connexion à chaque requête. -

-

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

- -

-Cookies

-

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

-

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

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

-

-

- Username: -
- Password: -
- -
-

-

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

-class LogInTest extends WebTestCase {
-    function testSessionCookieSetBeforeForm() {
-        $this->get('http://www.my-site.com/login.php');
-        $this->assertCookie('SID');
-    }
-}
-
- Nous nous contentons ici de vérifier que le cookie a bien été défini. - Etant donné que sa valeur est plutôt énigmatique, - elle ne vaudrait pas la peine d'être testée avec... -
-class LogInTest extends WebTestCase {
-    function testSessionCookieIsCorrectPattern() {
-        $this->get('http://www.my-site.com/login.php');
-        $this->assertCookie('SID', new PatternExpectation('/[a-f0-9]{32}/i'));
-    }
-}
-
- Si vous utilisez PHP pour gérer vos sessions alors - ce test est encore plus inutile, étant donné qu'il ne fait - que tester PHP lui-même. -

-

- Le test le plus simple pour vérifier que la connexion a bien eu lieu - reste d'inspecter visuellement la page suivante : - un simple appel à WebTestCase::assertText() et le tour est joué. -

-

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

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

-

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

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

- -

-Sessions de navigateur

-

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

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

-

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

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/browser_documentation.html b/application/libraries/simpletest/docs/fr/browser_documentation.html deleted file mode 100644 index 6be1267773b..00000000000 --- a/application/libraries/simpletest/docs/fr/browser_documentation.html +++ /dev/null @@ -1,500 +0,0 @@ - - - -Documentation SimpleTest : le composant de navigation web scriptable - - - - -

Documentation sur le navigateur scriptable

- This page... - -
- -

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

- -

-Le navigateur scriptable

-

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

-<?php
-    require_once('simpletest/browser.php');
-    
-    $browser = &new SimpleBrowser();
-    $browser->get('http://php.net/');
-    $browser->clickLink('reporting bugs');
-    $browser->clickLink('statistics');
-    $browser->clickLink('PHP 5 bugs only');
-    $page = $browser->getContent();
-    preg_match('/status=Open.*?by=Any.*?(\d+)<\/a>/', $page, $matches);
-    print $matches[1];
-?>
-
- Bien sûr Il y a des méthodes plus simple pour réaliser - cet exemple en PHP. Par exemple, vous pourriez juste - utiliser la commande PHP file() sur ce qui est - ici une page fixe. Cependant, en utilisant des scripts - avec le navigateur web vous vous autorisez l'authentification, - la gestion des cookies, le chargement automatique des fenêtres, - les redirections, la transmission de formulaires et la capacité - d'examiner les entêtes. -

-

- Ces méthodes qui se basent sur le contenu textuel des pages - sont fragiles dans un site en constante évolution - et vous voudrez employer une méthode plus directe - pour accéder aux données de façon permanente, - mais pour des tâches simples cette technique peut s'avérer - une solution très rapide. -

-

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

-

- Naviguer dans les formulaires est similaire à la navigation des formulaires via WebTestCase... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
setField($label, $value)Modifie tous les champs avec cette étiquette ou ce nom
setFieldByName($name, $value)Modifie tous les champs avec ce nom
setFieldById($id, $value)Modifie tous les champs avec cet identifiant
getField($label)Accesseur de la valeur d'un élément de formulaire avec cette étiquette ou ce nom
getFieldByName($name)Accesseur de la valeur d'un élément de formulaire avec ce nom
getFieldById($id)Accesseur de la valeur de l'élément de formulaire avec cet identifiant
clickSubmit($label)Transmet le formulaire avec l'étiquette de son bouton
clickSubmitByName($name)Transmet le formulaire avec l'attribut de son bouton
clickSubmitById($id)Transmet le formulaire avec l'identifiant de son bouton
clickImage($label, $x, $y)Clique sur une balise input de type image par son titre (title="*") our son texte alternatif (alt="*")
clickImageByName($name, $x, $y)Clique sur une balise input de type image par son attribut (name="*")
clickImageById($id, $x, $y)Clique sur une balise input de type image par son identifiant (id="*")
submitFormById($id)Transmet le formulaire par son identifiant propre
- Au jourd d'aujourd'hui il n'existe pas beaucoup de méthodes pour lister - les formulaires et les champs disponibles. - - - - - - - - - - - - - - - - - - - - - - - - - -
isClickable($label)Vérifie si un lien existe avec cette étiquette ou ce nom
isSubmit($label)Vérifie si un bouton existe avec cette étiquette ou ce nom
isImage($label)Vérifie si un bouton image existe avec cette étiquette ou ce nom
getLink($label)Trouve une URL à partir de son label
getLinkById($label)Trouve une URL à partir de son identifiant
getUrls()Liste l'ensemble des liens de la page courante
- Ce sera probablement - ajouté dans des versions successives de SimpleTest. -

-

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

- -

-Où sont les erreurs ?

-

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

- -

-Tests unitaires complexes avec des navigateurs multiples

-

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


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

-

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

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/docs.css b/application/libraries/simpletest/docs/fr/docs.css deleted file mode 100644 index 49170486ab3..00000000000 --- a/application/libraries/simpletest/docs/fr/docs.css +++ /dev/null @@ -1,84 +0,0 @@ -body { - padding-left: 3%; - padding-right: 3%; -} -pre { - font-family: "courier new", 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/application/libraries/simpletest/docs/fr/expectation_documentation.html b/application/libraries/simpletest/docs/fr/expectation_documentation.html deleted file mode 100644 index ee579110a6d..00000000000 --- a/application/libraries/simpletest/docs/fr/expectation_documentation.html +++ /dev/null @@ -1,451 +0,0 @@ - - - -Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires - - - - -

Documentation sur les attentes

- This page... - -
-

-Plus de contrôle sur les objets fantaisie

-

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

-

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

-

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

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

-

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

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

-

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

-

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

- -

-Utiliser les attentes pour contrôler les bouchons serveur

-

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

-

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

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

-

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

- -

-Créer vos propres attentes

-

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

-

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

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

-

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

-

- Voici un exemple plus typique, vérifier un hash... -

-class JustField extends EqualExpectation {
-    private $key;
-    
-    function __construct($key, $expected) {
-        parent::__construct($expected);
-        $this->key = $key;
-    }
-    
-    function test($compare) {
-        if (! isset($compare[$this->key])) {
-            return false;
-        }
-        return parent::test($compare[$this->key]);
-    }
-    
-    function testMessage($compare) {
-        if (! isset($compare[$this->key])) {
-            return 'Key [' . $this->key . '] does not exist';
-        }
-        return 'Key [' . $this->key . '] -> ' .
-                parent::testMessage($compare[$this->key]);
-    }
-}
-
- L'habitude a été prise pour séparer les clauses du message avec - "&nbsp;->&nbsp;". - Cela permet aux outils dérivés de reformater la sortie. -

-

- Supposons qu'un authentificateur s'attend à recevoir - une ligne de base de données correspondant à l'utilisateur, - et que nous avons juste besoin de valider le nom d'utilisateur. - Nous pouvons le faire très simplement avec... -

-$mock->expectOnce('authenticate',
-                  array(new JustKey('username', 'marcus')));
-
-

- -

-Sous le capot du testeur unitaire

-

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

-

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

-class TestOfNetworking extends UnitTestCase {
-    ...
-    function testGetValidIp() {
-        $server = &new Server();
-        $this->assert(
-                new ValidIp(),
-                $server->getIp(),
-                'Server IP address->%s');
-    }
-}
-
- assert() testera toute attente directement. -

-

- C'est plutôt sale par rapport à notre syntaxe habituelle - du type assert...(). -

-

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

-class TestOfNetworking extends UnitTestCase {
-    ...
-    function assertValidIp($ip, $message = '%s') {
-        $this->assertExpectation(new ValidIp(), $ip, $message);
-    }
-    
-    function testGetValidIp() {
-        $server = &new Server();
-        $this->assertValidIp(
-                $server->getIp(),
-                'Server IP address->%s');
-    }
-}
-
- It is rare to need the expectations for more than pattern - matching, but these facilities do allow testers to build - some sort of domain language for testing their application. - Also, complex expectation classes could make the tests - harder to read and debug. - In effect extending the test framework to create their own tool set. - - - Il est assez rare que le besoin d'une attente dépasse - le stade de la reconnaissance d'un motif, mais ils permettent - aux testeurs de construire leur propre langage dédié ou DSL - (Domain Specific Language) pour tester leurs applications. - Attention, les classes d'attente complexes peuvent rendre - les tests difficiles à lire et à déboguer. - Ces mécanismes sont véritablement là pour les auteurs - de système qui étendront le framework de test - pour leurs propres outils de test. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/form_testing_documentation.html b/application/libraries/simpletest/docs/fr/form_testing_documentation.html deleted file mode 100644 index 5ab914eda72..00000000000 --- a/application/libraries/simpletest/docs/fr/form_testing_documentation.html +++ /dev/null @@ -1,353 +0,0 @@ - - - -Documentation SimpleTest : tester des formulaires HTML - - - - -

Documentation sur les tests de formulaire

- This page... - -
-

-Valider un formulaire simple

-

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

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

-

-

- - -
-

-

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

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

-

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

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

-

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

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

-

-

- Select type of user to add: - -
-

-

- Le test suivant le confirmera... -

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

-

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

-

-

- Le navigateur proposé par SimpleTest émule les actions - qui peuvent être réalisées par un utilisateur sur - une page HTML standard. Javascript n'est pas supporté et - il y a peu de chance pour qu'il le soit prochainement. -

-

- Une attention particulière doit être porté aux techniques Javascript - qui changent la valeur d'un champ caché : elles ne peuvent pas être - réalisées avec les commandes classiques de SimpleTest. - Une méthode alternative est proposée plus loin. -

- -

-Champs à valeurs multiples

-

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

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

-

-

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

-

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

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

- -

-Formulaires utilisant Javascript pour changer un champ caché

-

- Si vous souhaitez tester un formulaire dépendant de Javascript - pour la modification d'un champ caché, vous ne pouvez pas - simplement utiliser setField(). - Le code suivant ne fonctionnera pas : -

-class SimpleFormTests extends WebTestCase {
-    function testMyJavascriptForm() {
-        // Ne fonctionne *pas*
-        $this->setField('un_champ_caché', '123');
-        $this->clickSubmit('OK');
-    }
-}
-
- A la place, vous aurez besoin d'ajouter le paramètre supplémentaire - du formulaire à la méthode clickSubmit() : -
-class SimpleFormTests extends WebTestCase {
-    function testMyJavascriptForm() {
-        // Ajoute le champ caché comme variable POST supplémentaire
-        $this->clickSubmit('OK', array('un_champ_caché'=>'123'));
-    }
-
-}
-
-

-

- N'oubliez pas que de la sorte, vous êtes effectivement en train - de court-circuitez une partie de votre application (le code Javascript - dans le formulaire) et que peut-être serait-il plus prudent - d'utiliser un outil comme - Selenium pour mettre sur pied - un test de recette complet. -

- -

-Envoi brut

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/group_test_documentation.html b/application/libraries/simpletest/docs/fr/group_test_documentation.html deleted file mode 100644 index a384f9510d5..00000000000 --- a/application/libraries/simpletest/docs/fr/group_test_documentation.html +++ /dev/null @@ -1,401 +0,0 @@ - - - -Documentation SimpleTest : Grouper des tests - - - - -

Documentation sur le groupement des tests

- This page... - -
-

-Grouper des tests

-

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

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

-

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

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

-

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

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

-

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

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

- -

-Groupements de plus haut niveau

-

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

-

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

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

- -

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

-

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

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/index.html b/application/libraries/simpletest/docs/fr/index.html deleted file mode 100644 index 964be9e5ad1..00000000000 --- a/application/libraries/simpletest/docs/fr/index.html +++ /dev/null @@ -1,576 +0,0 @@ - - - - - Prise en main rapide de SimpleTest pour PHP - - Tests unitaire et objets fantaisie pour PHP - - - - - -

Prise en main rapide de SimpleTest

- This page... - -
- -

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

- -

-Utiliser le testeur rapidement

-

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

-

- Ce qui rend cet outil immédiatement utile pour un développeur PHP, - c'est son navigateur web interne. - Il permet des tests qui parcourent des sites web, remplissent - des formulaires et testent le contenu des pages. - Etre capable d'écrire ces tests en PHP veut dire qu'il devient - facile d'écrire des tests de recette (ou d'intégration). - Un exemple serait de confirmer qu'un utilisateur a bien été ajouté - dans une base de données après s'être enregistré sur une site web. -

-

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

-

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

-<?php
-require_once('simpletest/autorun.php');
-require_once('../classes/log.php');
-
-class TestOfLogging extends UnitTestCase {
-}
-?>
-
- Ici le répertoire simpletest est soit dans le - dossier courant, soit dans les dossiers pour fichiers - inclus. Vous auriez à éditer ces arborescences suivant - l'endroit où vous avez installé SimpleTest. - Le fichier "autorun.php" fait plus que juste inclure - les éléments de SimpleTest : il lance aussi les tests pour nous. -

-

- TestOfLogging est notre premier scénario de test - et il est pour l'instant vide. - Chaque scénario de test est une classe qui étend une des classes - de base de SimpleTest. Nous pouvons avoir autant de classes de ce type - que nous voulons. -

-

- Avec ces trois lignes d'échafaudage - l'inclusion de notre classe Log, nous avons une suite - de tests. Mais pas encore de test ! -

-

- Pour notre premier test, supposons que la classe Log - prenne le nom du fichier à écrire au sein du constructeur, - et que nous avons un répertoire temporaire dans lequel placer - ce fichier. -

-<?php
-require_once('simpletest/autorun.php');
-require_once('../classes/log.php');
-
-class TestOfLogging extends UnitTestCase {
-    function testLogCreatesNewFileOnFirstMessage() {
-        @unlink('/temp/test.log');
-        $log = new Log('/temp/test.log');
-        $this->assertFalse(file_exists('/temp/test.log'));
-        $log->message('Should write this to a file');
-        $this->assertTrue(file_exists('/temp/test.log'));
-    }
-}
-?>
-
- Au lancement du scénario de test, toutes les méthodes qui - commencent avec la chaîne test sont - identifiées puis exécutées. - Si la méthode commence par test, c'est un test. - Remarquez bien le nom très long de notre exemple : - testLogCreatesNewFileOnFirstMessage(). - C'est bel et bien délibéré : ce style est considéré désirable - et il rend la sortie du test plus lisible. -

-

- D'ordinaire nous avons bien plusieurs méthodes de tests. - Mais ce sera pour plus tard. -

-

- Les assertions dans les - méthodes de test envoient des messages vers le framework de - test qui affiche immédiatement le résultat. Cette réponse - immédiate est importante, non seulement lors d'un crash - causé par le code, mais aussi de manière à rapprocher - l'affichage de l'erreur au plus près du scénario de test - concerné via un appel à printcode>. -

-

- Pour voir ces résultats lançons effectivement les tests. - Aucun autre code n'est nécessaire, il suffit d'ouvrir - la page dans un navigateur. -

-

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

-

TestOfLogging

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

TestOfLogging

-
1/1 test cases complete. - 2 passes and 0 fails.
-
- Et si vous obtenez ça... -
- Fatal error: Failed opening required '../classes/log.php' (include_path='') in /home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php on line 7 -
- c'est qu'il vous manque le fichier classes/Log.php - qui pourrait ressembler à : -
-<?php
-class Log {
-    function Log($file_path) {
-    }
-
-    function message() {
-    }
-}
-?>
-
- C'est largement plus sympathique d'écrire le code après le test. - Plus que sympatique même - cette technique s'appelle - "Développement Piloté par les Tests" ou - "Test Driven Development" en anglais. -

-

- Pour plus de renseignements sur le testeur, voyez la - documentation pour les tests de régression. -

- -

-Construire des groupes de tests

-

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

-

- Notre première étape est de créer un nouveau fichier appelé - tests/all_tests.php et d'y inclure le code suivant... -

-<?php
-require_once('simpletest/autorun.php');
-
-class AllTests extends TestSuite {
-    function AllTests() {
-        $this->TestSuite('All tests');
-        $this->addFile('log_test.php');
-    }
-}
-?>
-
- L'inclusion de "autorun" permettra à notre future suite - de tests d'être lancée juste en invoquant ce script. -

-

- La sous-classe TestSuite doit chaîner - son constructeur. Cette limitation sera supprimée dans - les versions à venir. -

-

- The method TestSuite::addFile() - will include the test case file and read any new classes - that are descended from SimpleTestCase. - - Cette méthode TestSuite::addTestFile() va - inclure le fichier de scénarios de test et lire parmi - toutes les nouvelles classes créées celles qui sont issues - de SimpleTestCase. - UnitTestCase est juste un exemple de classe dérivée - depuis SimpleTestCase et vous pouvez créer les vôtres. - TestSuite::addFile() peut aussi inclure d'autres suites. -

-

- La classe ne sera pas encore instanciée. - Quand la suite de tests est lancée, elle construira chaque instance - une fois le test atteint, et le détuira juste ensuite. - Cela veut dire que le constructeur n'est lancé qu'une fois avant - chaque initialisation de ce scénario de test et que le destructeur - est lui aussi lancé avant que le test suivant ne commence. -

-

- Il est commun de grouper des scénarios de test dans des super-classes - qui ne sont pas sensées être lancées, mais qui deviennent une classe de base - pour d'autres tests. - Pour que "autorun" fonctionne proprement les fichiers - des scénarios de test ne devraient pas lancer aveuglement - d'autres extensions de scénarios de test qui ne lanceraient pas - effectivement des tests. - Cela pourrait aboutir à un mauvais comptages des scénarios de test - pendant la procédure. - Pas vraiement un problème majeure, mais pour éviter cet inconvénient - il suffit de marquer vos classes de base comme abstract. - SimpleTest ne lance pas les classes abstraites. Et si vous utilisez encore - PHP4 alors une directive SimpleTestOptions::ignore() - dans votre fichier de scénario de test aura le même effet. -

-

- Par ailleurs, le fichier avec le scénario de test ne devrait pas - avoir été inclus ailleurs. Sinon aucun scénario de test - ne sera inclus à ce groupe. - Ceci pourrait se transformer en un problème plus grave : - si des fichiers ont déjà été inclus par PHP alors la méthode - TestSuite::addFile() ne les détectera pas. -

-

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

-

- Pour plus de renseignements des groupes de tests, voyez le - documentation sur le groupement des tests. -

- -

-Utiliser les objets fantaisie

-

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

-

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


-class SessionPool {
-    ...
-    function logIn($username) {
-        ...
-        $this->_log->message('User $username logged in.');
-        ...
-    }
-    ...
-}
-
-
- Avec le concept de "réutilisation de code" comme fil - conducteur, nous utilisons notre class Log. Un - scénario de test classique ressemblera peut-être à... -
-<?php
-require_once('simpletest/autorun.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 testLoggingInIsLogged() {
-        $log = new Log('/temp/test.log');
-        $session_pool = &new SessionPool($log);
-        $session_pool->logIn('fred');
-        $messages = file('/temp/test.log');
-        $this->assertEqual($messages[0], "User fred logged in.\n");
-    }
-}
-?>
-
- Nous expliquerons les méthodes setUp() - et tearDown() plus tard. -

-

- Le design de ce scénario de test n'est pas complètement - mauvais, mais on peut l'améliorer. Nous passons du temps à - tripoter les fichiers de log qui ne font pas partie de - notre test. - Pire, nous avons créé des liens de proximité - entre la classe Log et ce test. Que se - passerait-il si nous n'utilisions plus de fichiers, mais la - bibliothèque syslog à la place ? - - Cela veut dire que notre test TestOfSessionLogging - enverra un échec alors même qu'il ne teste pas Logging. -

-

- Il est aussi fragile sur des petites retouches. Avez-vous - remarqué le retour chariot supplémentaire à la fin du - message ? A-t-il été ajouté par le loggueur ? Et si il - ajoutait aussi un timestamp ou d'autres données ? -

-

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

-

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

-

- Trop beau pour être vrai ? Pas vraiement on peut créer un tel - objet très facilement... -
-<?php
-require_once('simpletest/autorun.php');
-require_once('../classes/log.php');
-require_once('../classes/session_pool.php');
-
-Mock::generate('Log');
-
-class TestOfSessionLogging extends UnitTestCase {
-    
-    function testLoggingInIsLogged() {
-        $log = &new MockLog();
-        $log->expectOnce('message', array('User fred logged in.'));
-        $session_pool = &new SessionPool($log);
-        $session_pool->logIn('fred');
-    }
-}
-?>
-
- L'appel Mock::generate() a généré - une nouvelle classe appelé MockLog. - Cela ressemble à un clone identique, sauf que nous pouvons - y adjoindre du code de test. - C'est ce que fait expectOnce(). - Cela dit que si message() m'est appelé, - il a intérêt à l'être avec le paramètre - "User fred logged in.". -

-

- L'appel tally() est nécessaire pour annoncer à - l'objet fantaisie qu'il n'y aura plus d'appels ultérieurs. - Sans ça l'objet fantaisie pourrait attendre pendant une - éternité l'appel de la méthode sans jamais prévenir le - scénario de test. Les autres tests sont déclenchés - automatiquement quand l'appel à message() est - invoqué sur l'objet MockLog par le code - SessionPool::logIn(). - L'appel mock va déclencher une comparaison des - paramètres et ensuite envoyer le message "pass" ou "fail" - au test pour l'affichage. Des jokers peuvent être inclus - pour ne pas avoir à tester tous les paramètres d'un appel - alors que vous ne souhaitez qu'en tester un. -

-

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

-

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

-

- Pour plus de renseignements sur les objets fantaisie, voyez le - documentation sur les objets fantaisie. -

- -

-Tester une page web

-

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

-

- Effectuer un test web via SimpleTest reste assez primitif : - il n'y a pas de javascript par exemple. - La plupart des autres opérations d'un navigateur sont simulées. -

-

- Pour vous donner une idée, voici un exemple assez trivial : - aller chercher une page web, - à partir de là naviguer vers la page "about" - et finalement tester un contenu déterminé par le client. -

-<?php
-require_once('simpletest/autorun.php');
-require_once('simpletest/web_tester.php');
-
-class TestOfAbout extends WebTestCase {
-    function testOurAboutPageGivesFreeReignToOurEgo() {
-        $this->get('http://test-server/index.php');
-        $this->click('About');
-        $this->assertTitle('About why we are so great');
-        $this->assertText('We are really great');
-    }
-}
-?>
-
- Avec ce code comme test de recette, vous pouvez vous - assurer que le contenu corresponde toujours aux - spécifications à la fois des développeurs et des autres - parties prenantes au projet. -

-

- Vous pouvez aussi naviguer à travers des formulaires... -

-<?php
-require_once('simpletest/autorun.php');
-require_once('simpletest/web_tester.php');
-
-class TestOfRankings extends WebTestCase {
-    function testWeAreTopOfGoogle() {
-        $this->get('http://google.com/');
-        $this->setField('q', 'simpletest');
-        $this->click("I'm Feeling Lucky");
-        $this->assertTitle('SimpleTest - Unit Testing for PHP');
-    }
-}
-?>
-
- ...même si cela pourrait constituer une violation - des documents juridiques de Google(tm). -

-

- Pour plus de renseignements sur comment tester une page web, voyez la - documentation sur tester des scripts web. -

-

- SourceForge.net Logo -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/mock_objects_documentation.html b/application/libraries/simpletest/docs/fr/mock_objects_documentation.html deleted file mode 100644 index 9d2ad41b2c8..00000000000 --- a/application/libraries/simpletest/docs/fr/mock_objects_documentation.html +++ /dev/null @@ -1,784 +0,0 @@ - - - -Documentation SimpleTest : les objets fantaise - - - - -

Documentation sur les objets fantaisie

- This page... - -
-

-Que sont les objets fantaisie ?

-

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

-

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

-

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

-

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

- -

-Créer des objets fantaisie

-

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

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

- -

-Objets fantaisie en action

-

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

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

-

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

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

-

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

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

-

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

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

- -

-Objets fantaisie en critique

-

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

-

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

-class SessionPool {
-    function SessionPool() {
-        ...
-    }
-    
-    function &findSession($cookie) {
-        ...
-    }
-    ...
-}
-
-class Session {
-    ...
-}
-
-
- Alors que pour notre code de log, nous avons... -

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

-

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

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

-

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

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

-

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

-

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

-

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

-

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

-

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

-

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

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

-

- Par ailleurs si vous avez just un appel dans votre test, - vérifiez bien que vous utiliser - expectOnce.
- Utiliser $mocked->expectAt(0, 'method', 'args); - tout seul ne sera pas pris en compte : - la vérification des arguments et le comptage total - sont pour l'instant encore indépendant. -

-

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

- -

-D'autres approches

-

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

-

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

-

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

-

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

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

-

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

- -

-Je pense que SimpleTest pue !

-

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

-

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

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

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/overview.html b/application/libraries/simpletest/docs/fr/overview.html deleted file mode 100644 index 968bbc48e50..00000000000 --- a/application/libraries/simpletest/docs/fr/overview.html +++ /dev/null @@ -1,321 +0,0 @@ - - - - - Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP - - - - - -

Apercu de SimpleTest

- This page... - -
-

-Qu'est-ce que SimpleTest ?

-

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

-

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

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

-

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

-

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

-

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

-

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

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

- -

-Liste des fonctionnalites

-

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

- -

-Ressources sur le web pour les tests

-

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

-

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

-

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

-

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

-

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/partial_mocks_documentation.html b/application/libraries/simpletest/docs/fr/partial_mocks_documentation.html deleted file mode 100644 index 3a0ee35cfcd..00000000000 --- a/application/libraries/simpletest/docs/fr/partial_mocks_documentation.html +++ /dev/null @@ -1,464 +0,0 @@ - - - -Documentation SimpleTest : les objets fantaisie partiels - - - - -

Documentation sur les objets fantaisie partiels

- This page... - -
- -

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

- -

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

-

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

-

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

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

-

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

-

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

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

-

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

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

-

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

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

-

- Peut-on trouver un juste milieu ? -

- -

-Méthode fabrique protégée

-

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

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

-

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

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

-

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

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

- -

-Un objet fantaisie partiel

-

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

-

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

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

-

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

-

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

-

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

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

- -

-Tester moins qu'une classe

-

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

-

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

-

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/reporter_documentation.html b/application/libraries/simpletest/docs/fr/reporter_documentation.html deleted file mode 100644 index c9665d55e2d..00000000000 --- a/application/libraries/simpletest/docs/fr/reporter_documentation.html +++ /dev/null @@ -1,538 +0,0 @@ - - - -Documentation SimpleTest : le rapporteur de test - - - - -

Documentation sur le rapporteur de test

- This page... - -
- -

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

- -

-Les résultats rapportés au format HTML

-

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

-

File test

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

File test

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

-

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

-class HtmlReporter extends SimpleReporter {
-    public HtmlReporter($encoding) { ... }
-    public makeDry(boolean $is_dry) { ... }
-    public void paintHeader(string $test_name) { ... }
-    public void sendNoCacheHeaders() { ... }
-    public void paintFooter(string $test_name) { ... }
-    public void paintGroupStart(string $test_name, integer $size) { ... }
-    public void paintGroupEnd(string $test_name) { ... }
-    public void paintCaseStart(string $test_name) { ... }
-    public void paintCaseEnd(string $test_name) { ... }
-    public void paintMethodStart(string $test_name) { ... }
-    public void paintMethodEnd(string $test_name) { ... }
-    public void paintFail(string $message) { ... }
-    public void paintPass(string $message) { ... }
-    public void paintError(string $message) { ... }
-    public void paintException(string $message) { ... }
-    public void paintMessage(string $message) { ... }
-    public void paintFormattedMessage(string $message) { ... }
-    protected string getCss() { ... }
-    public array getTestList() { ... }
-    public integer getPassCount() { ... }
-    public integer getFailCount() { ... }
-    public integer getExceptionCount() { ... }
-    public integer getTestCaseCount() { ... }
-    public integer getTestCaseProgress() { ... }
-}
-
- Voici ce que certaines de ces méthodes veulent dire. - Premièrement les méthodes d'affichage que vous voudrez probablement surcharger... - - Il y a aussi des accesseurs pour aller chercher l'information - sur l'état courant de la suite de test. Vous les utiliserez - pour enrichir l'affichage... - - Une modification simple : demander à l'HtmlReporter d'afficher - aussi bien les succès que les échecs et les erreurs... -

-class ShowPasses extends HtmlReporter {
-    
-    function paintPass($message) {
-        parent::paintPass($message);
-        print "&<span class=\"pass\">Pass</span>: ";
-        $breadcrumb = $this->getTestList();
-        array_shift($breadcrumb);
-        print implode("-&gt;", $breadcrumb);
-        print "-&gt;$message<br />\n";
-    }
-    
-    protected function getCss() {
-        return parent::getCss() . ' .pass { color: green; }';
-    }
-}
-
-

-

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

-

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

- -

-Etendre le rapporteur

-

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

-

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


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

- -

-Le rapporteur en ligne de commande

-

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

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

-

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

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

- -

-Test distant

-

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

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

-

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

-

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

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/unit_test_documentation.html b/application/libraries/simpletest/docs/fr/unit_test_documentation.html deleted file mode 100644 index 300f1656a3f..00000000000 --- a/application/libraries/simpletest/docs/fr/unit_test_documentation.html +++ /dev/null @@ -1,450 +0,0 @@ - - - -Documentation SimpleTest pour les tests de régression en PHP - - - - -

Documentation sur les tests unitaires en PHP

- This page... - -
-

-Scénarios de tests unitaires

-

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

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

-

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

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

-

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

-

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

-

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

-

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

-

- D'autres exemples... -

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

-

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

-

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

- -

-Etendre les scénarios de test

-

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

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

-

- Alternativement vous pourriez utiliser dans votre code - un directive SimpleTestOptions::ignore('FileTester');. -

-

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

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

-

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

- -

-Lancer un unique scénario de test

-

- Ce n'est pas souvent qu'il faille lancer des scénarios - avec un unique test. Sauf lorsqu'il s'agit de s'arracher - les cheveux sur un module à problème sans pour - autant désorganiser la suite de test principale. - Avec autorun aucun échafaudage particulier - n'est nécessaire, il suffit de lancer votre test et - vous y êtes. -

-

- Vous pouvez même décider quel rapporteur - (par exemple, TextReporter ou HtmlReporter) - vous préférez pour un fichier spécifique quand il est lancé - tout seul... -

-<?php
-require_once('simpletest/autorun.php');
-SimpleTest :: prefer(new TextReporter());
-require_once('../classes/writer.php');
-
-class FileTestCase extends UnitTestCase {
-    ...
-}
-?>
-
- Ce script sera lancé tel que mais il n'y aura - aucun succès ou échec avant que des méthodes de test soient ajoutées. -

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/docs/fr/web_tester_documentation.html b/application/libraries/simpletest/docs/fr/web_tester_documentation.html deleted file mode 100644 index 308fbc9ccbb..00000000000 --- a/application/libraries/simpletest/docs/fr/web_tester_documentation.html +++ /dev/null @@ -1,570 +0,0 @@ - - - -Documentation SimpleTest : tester des scripts web - - - - -

Documentation sur le testeur web

- This page... - -
-

-Télécharger une page

-

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

-

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

-

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

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

-

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

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

-

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

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

- -

-Tester le contenu d'une page

-

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

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

-

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

-

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

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

- -

-Navigeur dans un site web

-

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

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

-

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

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

-

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

-

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

-

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

-

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

-

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

- -

-Modifier la requête

-

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

- -
- References and related information... - - - - - diff --git a/application/libraries/simpletest/extensions/pear_test_case.php b/application/libraries/simpletest/extensions/pear_test_case.php deleted file mode 100644 index 71657ae4cea..00000000000 --- a/application/libraries/simpletest/extensions/pear_test_case.php +++ /dev/null @@ -1,196 +0,0 @@ -_loosely_typed = false; - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEquals($first, $second, $message = "%s", $delta = 0) { - if ($this->_loosely_typed) { - $expectation = new EqualExpectation($first); - } else { - $expectation = new IdenticalExpectation($first); - } - $this->assert($expectation, $second, $message); - } - - /** - * Passes if the value tested is not null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNotNull($value, $message = "%s") { - parent::assert(new TrueExpectation(), isset($value), $message); - } - - /** - * Passes if the value tested is null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNull($value, $message = "%s") { - parent::assert(new TrueExpectation(), !isset($value), $message); - } - - /** - * Identity test tests for the same object. - * @param $first First object handle. - * @param $second Hopefully the same handle. - * @param $message Message to display. - * @public - */ - function assertSame($first, $second, $message = "%s") { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should reference the same object"); - return $this->assert( - new TrueExpectation(), - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Inverted identity test. - * @param $first First object handle. - * @param $second Hopefully a different handle. - * @param $message Message to display. - * @public - */ - function assertNotSame($first, $second, $message = "%s") { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should not be the same object"); - return $this->assert( - new falseExpectation(), - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Sends pass if the test condition resolves true, - * a fail otherwise. - * @param $condition Condition to test true. - * @param $message Message to display. - * @public - */ - function assertTrue($condition, $message = "%s") { - parent::assert(new TrueExpectation(), $condition, $message); - } - - /** - * Sends pass if the test condition resolves false, - * a fail otherwise. - * @param $condition Condition to test false. - * @param $message Message to display. - * @public - */ - function assertFalse($condition, $message = "%s") { - parent::assert(new FalseExpectation(), $condition, $message); - } - - /** - * Tests a regex match. Needs refactoring. - * @param $pattern Regex to match. - * @param $subject String to search in. - * @param $message Message to display. - * @public - */ - function assertRegExp($pattern, $subject, $message = "%s") { - $this->assert(new PatternExpectation($pattern), $subject, $message); - } - - /** - * Tests the type of a value. - * @param $value Value to take type of. - * @param $type Hoped for type. - * @param $message Message to display. - * @public - */ - function assertType($value, $type, $message = "%s") { - parent::assert(new TrueExpectation(), gettype($value) == strtolower($type), $message); - } - - /** - * Sets equality operation to act as a simple equal - * comparison only, allowing a broader range of - * matches. - * @param $loosely_typed True for broader comparison. - * @public - */ - function setLooselyTyped($loosely_typed) { - $this->_loosely_typed = $loosely_typed; - } - - /** - * For progress indication during - * a test amongst other things. - * @return Usually one. - * @public - */ - function countTestCases() { - return $this->getSize(); - } - - /** - * Accessor for name, normally just the class - * name. - * @public - */ - function getName() { - return $this->getLabel(); - } - - /** - * Does nothing. For compatibility only. - * @param $name Dummy - * @public - */ - function setName($name) { - } - } -?> \ No newline at end of file diff --git a/application/libraries/simpletest/extensions/testdox.php b/application/libraries/simpletest/extensions/testdox.php deleted file mode 100644 index 5cf32f35162..00000000000 --- a/application/libraries/simpletest/extensions/testdox.php +++ /dev/null @@ -1,53 +0,0 @@ -_test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern; - } - - function paintCaseStart($test_name) { - preg_match($this->_test_case_pattern, $test_name, $matches); - if (!empty($matches[1])) { - echo $matches[1] . "\n"; - } else { - echo $test_name . "\n"; - } - } - - function paintCaseEnd($test_name) { - echo "\n"; - } - - function paintMethodStart($test_name) { - if (!preg_match('/^test(.*)$/i', $test_name, $matches)) { - return; - } - $test_name = $matches[1]; - $test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name); - echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name)); - } - - function paintMethodEnd($test_name) { - echo "\n"; - } - - function paintFail($message) { - echo " [FAILED]"; - } -} -?> diff --git a/application/libraries/simpletest/extensions/testdox/test.php b/application/libraries/simpletest/extensions/testdox/test.php deleted file mode 100644 index b03abe510ab..00000000000 --- a/application/libraries/simpletest/extensions/testdox/test.php +++ /dev/null @@ -1,107 +0,0 @@ -assertIsA($dox, 'SimpleScorer'); - $this->assertIsA($dox, 'SimpleReporter'); - } - - function testOutputsNameOfTestCase() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintCaseStart('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertPattern('/^TestDoxReporter/', $buffer); - } - - function testOutputOfTestCaseNameFilteredByConstructParameter() { - $dox = new TestDoxReporter('/^(.*)Test$/'); - ob_start(); - $dox->paintCaseStart('SomeGreatWidgetTest'); - $buffer = ob_get_clean(); - $this->assertPattern('/^SomeGreatWidget/', $buffer); - } - - function testIfTest_case_patternIsEmptyAssumeEverythingMatches() { - $dox = new TestDoxReporter(''); - ob_start(); - $dox->paintCaseStart('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertPattern('/^TestOfTestDoxReporter/', $buffer); - } - - function testEmptyLineInsertedWhenCaseEnds() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintCaseEnd('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertEqual("\n", $buffer); - } - - function testPaintsTestMethodInTestDoxFormat() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('testSomeGreatTestCase'); - $buffer = ob_get_clean(); - $this->assertEqual("- some great test case", $buffer); - unset($buffer); - - $random = rand(100, 200); - ob_start(); - $dox->paintMethodStart("testRandomNumberIs{$random}"); - $buffer = ob_get_clean(); - $this->assertEqual("- random number is {$random}", $buffer); - } - - function testDoesNotOutputAnythingOnNoneTestMethods() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('nonMatchingMethod'); - $buffer = ob_get_clean(); - $this->assertEqual('', $buffer); - } - - function testPaintMethodAddLineBreak() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodEnd('someMethod'); - $buffer = ob_get_clean(); - $this->assertEqual("\n", $buffer); - } - - function testProperlySpacesSingleLettersInMethodName() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('testAVerySimpleAgainAVerySimpleMethod'); - $buffer = ob_get_clean(); - $this->assertEqual('- a very simple again a very simple method', $buffer); - } - - function testOnFailureThisPrintsFailureNotice() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintFail(''); - $buffer = ob_get_clean(); - $this->assertEqual(' [FAILED]', $buffer); - } - - function testWhenMatchingMethodNamesTestPrefixIsCaseInsensitive() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('TESTSupportsAllUppercaseTestPrefixEvenThoughIDoNotKnowWhyYouWouldDoThat'); - $buffer = ob_get_clean(); - $this->assertEqual( - '- supports all uppercase test prefix even though i do not know why you would do that', - $buffer - ); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/acceptance_test.php b/application/libraries/simpletest/test/acceptance_test.php deleted file mode 100644 index e96fe737e5f..00000000000 --- a/application/libraries/simpletest/test/acceptance_test.php +++ /dev/null @@ -1,1729 +0,0 @@ -addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?
GET<\/dd>/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Simple test target file'); - $this->assertEqual($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - } - - function testPost() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->post($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); - } - - function testAbsoluteLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Absolute')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeEncodedLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - // Warning: the below data is ISO 8859-1 encoded - $this->assertTrue($browser->clickLink("m\xE4rc\xEAl kiek'eboe")); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testUnifiedClickLinkClicking() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->click('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testIdLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLinkById(1)); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testCookieReading() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'set_cookies.php'); - $this->assertEqual($browser->getCurrentCookieValue('session_cookie'), 'A'); - $this->assertEqual($browser->getCurrentCookieValue('short_cookie'), 'B'); - $this->assertEqual($browser->getCurrentCookieValue('day_cookie'), 'C'); - } - - function testSimpleSubmit() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } - - function testUnifiedClickCanSubmit() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->click('Go!')); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } -} - -class TestOfLocalFileBrowser extends UnitTestCase { - function samples() { - return 'file://'.dirname(__FILE__).'/site/'; - } - - function testGet() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'file.html')); - $this->assertPattern('/Link to SimpleTest/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Link to SimpleTest'); - $this->assertFalse($browser->getResponseCode()); - $this->assertEqual($browser->getMimeType(), ''); - } -} - -class TestOfRequestMethods extends UnitTestCase { - function samples() { - return SimpleTestAcceptanceTest::samples(); - } - - function testHeadRequest() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->head($this->samples() . 'request_methods.php')); - $this->assertEqual($browser->getResponseCode(), 202); - } - - function testGetRequest() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->get($this->samples() . 'request_methods.php')); - $this->assertEqual($browser->getResponseCode(), 405); - } - - function testPostWithPlainEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->post($this->samples() . 'request_methods.php', 'A content message')); - $this->assertEqual($browser->getResponseCode(), 406); - $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent()); - } - - function testPostWithXmlEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->post($this->samples() . 'request_methods.php', 'c', 'text/xml')); - $this->assertEqual($browser->getResponseCode(), 201); - $this->assertPattern('/c/', $browser->getContent()); - } - - function testPutWithPlainEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->put($this->samples() . 'request_methods.php', 'A content message')); - $this->assertEqual($browser->getResponseCode(), 406); - $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent()); - } - - function testPutWithXmlEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->put($this->samples() . 'request_methods.php', 'c', 'application/xml')); - $this->assertEqual($browser->getResponseCode(), 201); - $this->assertPattern('/c/', $browser->getContent()); - } - - function testDeleteRequest() { - $browser = new SimpleBrowser(); - $browser->delete($this->samples() . 'request_methods.php'); - $this->assertEqual($browser->getResponseCode(), 202); - $this->assertPattern('/Your delete request was accepted/', $browser->getContent()); - } - -} - -class TestRadioFields extends SimpleTestAcceptanceTest { - function testSetFieldAsInteger() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', 2)); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } - - function testSetFieldAsString() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', '2')); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } -} - -class TestOfLiveFetching extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testFormWithArrayBasedInputs() { - $this->get($this->samples() . 'form_with_array_based_inputs.php'); - $this->setField('value[]', '3', '1'); - $this->setField('value[]', '4', '2'); - $this->clickSubmit('Go'); - $this->assertPattern('/QUERY_STRING : value%5B%5D=3&value%5B%5D=4&submit=Go/'); - } - - function testFormWithQuotedValues() { - $this->get($this->samples() . 'form_with_quoted_values.php'); - $this->assertField('a', 'default'); - $this->assertFieldById('text_field', 'default'); - $this->clickSubmit('Go'); - $this->assertPattern('/a=default&submit=Go/'); - } - - function testGet() { - $this->assertTrue($this->get($this->samples() . 'network_confirm.php')); - $this->assertEqual($this->getUrl(), $this->samples() . 'network_confirm.php'); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertTitle('Simple test target file'); - $this->assertTitle(new PatternExpectation('/target file/')); - $this->assertResponse(200); - $this->assertMime('text/html'); - $this->assertHeader('connection', 'close'); - $this->assertHeader('connection', new PatternExpectation('/los/')); - } - - function testSlowGet() { - $this->assertTrue($this->get($this->samples() . 'slow_page.php')); - } - - function testTimedOutGet() { - $this->setConnectionTimeout(1); - $this->ignoreErrors(); - $this->assertFalse($this->get($this->samples() . 'slow_page.php')); - } - - function testPost() { - $this->assertTrue($this->post($this->samples() . 'network_confirm.php')); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - } - - function testGetWithData() { - $this->get($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithRecursiveData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa]" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa][aaa]" => "aaaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => "aaa"))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => array("aaa" => "aaaa")))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - } - - function testRelativeGet() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->get('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativePost() { - $this->post($this->samples() . 'link_confirm.php', array('a' => '123')); - $this->assertTrue($this->post('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } -} - -class TestOfLinkFollowing extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testLinkAssertions() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLink('Absolute', $this->samples() . 'network_confirm.php'); - $this->assertLink('Absolute', new PatternExpectation('/confirm/')); - $this->assertClickable('Absolute'); - } - - function testAbsoluteLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Absolute')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativeLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Relative')); - $this->assertText('target for the SimpleTest'); - } - - function testLinkIdFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLinkById(1); - $this->assertTrue($this->clickLinkById(1)); - $this->assertText('target for the SimpleTest'); - } - - function testAbsoluteUrlBehavesAbsolutely() { - $this->get($this->samples() . 'link_confirm.php'); - $this->get('http://www.lastcraft.com'); - $this->assertText('No guarantee of quality is given or even intended'); - } - - function testRelativeUrlRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/base_link.html'); - $this->click('Back to test pages'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLivePageLinkingWithMinimalLinks extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testClickToExplicitelyNamedSelfReturns() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->assertEqual($this->getUrl(), $this->samples() . 'front_controller_style/a_page.php'); - $this->assertTitle('Simple test page with links'); - $this->assertLink('Self'); - $this->clickLink('Self'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToMissingPageReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('No page'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=no_page]'); - } - - function testClickToBareActionReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Bare action'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=]'); - } - - function testClickToSingleQuestionMarkReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty query'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToEmptyStringReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty link'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToSingleDotGoesToCurrentDirectory() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Current directory'); - $this->assertTitle( - 'Simple test front controller', - '%s -> index.php needs to be set as a default web server home page'); - } - - function testClickBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|i'); - } -} - -class TestOfLiveFrontControllerEmulation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testJumpToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - } - - function testJumpToUnnamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - } - - function testJumpToUnnamedPageWithBareParameter() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - } - - function testJumpToUnnamedPageWithEmptyQuery() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpToUnnamedPageWithEmptyLink() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - } - - function testSubmitToSameDirectory() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - } - - function testSubmitToEmptyAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - } - - function testSubmitToNoAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - } - - function testSubmitBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickSubmit('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPageWithMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/?a=A'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index post'); - $this->assertText('action=[Index post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToSameDirectoryMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Same directory post'); - $this->assertText('action=[Same directory post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToEmptyActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Empty action post'); - $this->assertText('action=[Empty action post]'); - $this->assertText('[a=A]'); - } - - function testSubmitToNoActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('No action post'); - $this->assertText('action=[No action post]'); - $this->assertText('[a=A]'); - } -} - -class TestOfLiveHeaders extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testConfirmingHeaderExistence() { - $this->get('http://www.lastcraft.com/'); - $this->assertHeader('content-type'); - $this->assertHeader('content-type', 'text/html'); - $this->assertHeader('content-type', new PatternExpectation('/HTML/i')); - $this->assertNoHeader('WWW-Authenticate'); - } -} - -class TestOfLiveRedirects extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoRedirects() { - $this->setMaximumRedirects(0); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Redirection test'); - } - - function testRedirects() { - $this->setMaximumRedirects(1); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectLosesGetData() { - $this->get($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectKeepsExtraRequestDataOfItsOwn() { - $this->get($this->samples() . 'redirect.php'); - $this->assertText('r=[rrr]'); - } - - function testRedirectLosesPostData() { - $this->post($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertTitle('Simple test target file'); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectWithBaseUrlChange() { - $this->get($this->samples() . 'base_change_redirect.php'); - $this->assertTitle('Simple test target file in folder'); - $this->get($this->samples() . 'path/base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectWithDoubleBaseUrlChange() { - $this->get($this->samples() . 'double_base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLiveCookies extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function here() { - return new SimpleUrl($this->samples()); - } - - function thisHost() { - $here = $this->here(); - return $here->getHost(); - } - - function thisPath() { - $here = $this->here(); - return $here->getPath(); - } - - function testCookieSettingAndAssertions() { - $this->setCookie('a', 'Test cookie a'); - $this->setCookie('b', 'Test cookie b', $this->thisHost()); - $this->setCookie('c', 'Test cookie c', $this->thisHost(), $this->thisPath()); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertText('Test cookie a'); - $this->assertText('Test cookie b'); - $this->assertText('Test cookie c'); - $this->assertCookie('a'); - $this->assertCookie('b', 'Test cookie b'); - $this->assertTrue($this->getCookie('c') == 'Test cookie c'); - } - - function testNoCookieSetWhenCookiesDisabled() { - $this->setCookie('a', 'Test cookie a'); - $this->ignoreCookies(); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertNoText('Test cookie a'); - } - - function testCookieReading() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', 'A'); - $this->assertCookie('short_cookie', 'B'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoCookie() { - $this->assertNoCookie('aRandomCookie'); - } - - function testNoCookieReadingWhenCookiesDisabled() { - $this->ignoreCookies(); - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('short_cookie'); - $this->assertNoCookie('day_cookie'); - } - - function testCookiePatternAssertions() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', new PatternExpectation('/a/i')); - } - - function testTemporaryCookieExpiry() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(); - $this->assertNoCookie('session_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testTimedCookieExpiryWith100SecondMargin() { - $this->get($this->samples() . 'set_cookies.php'); - $this->ageCookies(3600); - $this->restart(time() + 100); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('hour_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoClockOverDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 200); - $this->assertNoCookie( - 'short_cookie', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testNoClockUnderDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 0); - $this->assertCookie( - 'short_cookie', - 'B', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testCookiePath() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('path_cookie', 'D'); - $this->get('./path/show_cookies.php'); - $this->assertPattern('/path_cookie/'); - $this->assertCookie('path_cookie', 'D'); - } -} - -class LiveTestOfForms extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSimpleSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('go=[Go!]'); - } - - function testDefaultFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldByName('a', ''); - $this->assertFieldByName('b', 'Default text'); - $this->assertFieldByName('c', ''); - $this->assertFieldByName('d', 'd1'); - $this->assertFieldByName('e', false); - $this->assertFieldByName('f', 'on'); - $this->assertFieldByName('g', 'g3'); - $this->assertFieldByName('h', 2); - $this->assertFieldByName('go', 'Go!'); - $this->assertClickable('Go!'); - $this->assertSubmit('Go!'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - $this->assertText('b=[Default text]'); - $this->assertText('c=[]'); - $this->assertText('d=[d1]'); - $this->assertNoText('e=['); - $this->assertText('f=[on]'); - $this->assertText('g=[g3]'); - } - - function testFormSubmissionByButtonLabel() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'aaa'); - $this->setFieldByName('b', 'bbb'); - $this->setFieldByName('c', 'ccc'); - $this->setFieldByName('d', 'D2'); - $this->setFieldByName('e', 'on'); - $this->setFieldByName('f', false); - $this->setFieldByName('g', 'g2'); - $this->setFieldByName('h', 1); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - } - - function testAdditionalFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'A'); - $this->assertTrue($this->clickSubmitByName('go')); - $this->assertText('a=[A]'); - } - - function testFormSubmissionByNameAndAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionBySubmitButtonLabeledSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('test')); - $this->assertText('test=[Submit]'); - } - - function testFormSubmissionWithIds() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldById(1, ''); - $this->assertFieldById(2, 'Default text'); - $this->assertFieldById(3, ''); - $this->assertFieldById(4, 'd1'); - $this->assertFieldById(5, false); - $this->assertFieldById(6, 'on'); - $this->assertFieldById(8, 'g3'); - $this->assertFieldById(11, 2); - $this->setFieldById(1, 'aaa'); - $this->setFieldById(2, 'bbb'); - $this->setFieldById(3, 'ccc'); - $this->setFieldById(4, 'D2'); - $this->setFieldById(5, 'on'); - $this->setFieldById(6, false); - $this->setFieldById(8, 'g2'); - $this->setFieldById(11, 'H1'); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testFormSubmissionWithIdsAndAdditionnalData() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitById(99, array('additionnal' => "data"))); - $this->assertText('additionnal=[data]'); - } - - function testFormSubmissionWithLabels() { - $this->get($this->samples() . 'form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->clickSubmit('Go!'); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingCheckboxWithBooleanTrueSetsUnderlyingValue() { - $this->get($this->samples() . 'form.html'); - $this->setField('Checkbox E', true); - $this->assertField('Checkbox E', 'on'); - $this->clickSubmit('Go!'); - $this->assertText('e=[on]'); - } - - function testFormSubmissionWithMixedPostAndGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text A', 'Hello'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithMixedPostAndEncodedGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text B', 'Hello'); - $this->assertTrue($this->clickSubmit('Go encoded!')); - $this->assertText('b=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithoutAction() { - $this->get($this->samples() . 'form_without_action.php?test=test'); - $this->assertText('_GET : [test]'); - $this->assertTrue($this->clickSubmit('Submit Post With Empty Action')); - $this->assertText('_GET : [test]'); - $this->assertText('_POST : [test]'); - } - - function testImageSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertImage('Image go!'); - $this->assertTrue($this->clickImage('Image go!', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionByLabelWithAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImage('Image go!', 10, 12, array('add' => 'A'))); - $this->assertText('add=[A]'); - } - - function testImageSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageByName('go', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionById() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageById(97, 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testButtonSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Button go!', 10, 12)); - $this->assertPattern('/go=\[ButtonGo\]/s'); - } - - function testNamelessSubmitSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Go!'); - $this->assertNoText('Go!'); - $this->assertNoText('submit'); - } - - function testNamelessImageSendsXAndYValues() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->clickImage('Image go!', 4, 5); - $this->assertNoText('ImageGo'); - $this->assertText('x=[4]'); - $this->assertText('y=[5]'); - } - - function testNamelessButtonSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Button Go!'); - $this->assertNoText('ButtonGo'); - } - - function testSelfSubmit() { - $this->get($this->samples() . 'self_form.php'); - $this->assertNoText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTitle('Test of form self submission'); - } - - function testSelfSubmitWithParameters() { - $this->get($this->samples() . 'self_form.php'); - $this->setFieldByName('visible', 'Resent'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Resent]'); - } - - function testSettingOfBlankOption() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->setFieldByName('d', '')); - $this->clickSubmit('Go!'); - $this->assertText('d=[]'); - } - - function testAssertingFieldValueWithPattern() { - $this->get($this->samples() . 'form.html'); - $this->setField('c', 'A very long string'); - $this->assertField('c', new PatternExpectation('/very long/')); - } - - function testSendingMultipartFormDataEncodedForm() { - $this->get($this->samples() . 'form_data_encoded_form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingVariousBlanksInFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text A', ''); - $this->setField('Text A', '0'); - $this->assertField('Text A', '0'); - $this->assertField('Text area B', ''); - $this->setField('Text area B', '0'); - $this->assertField('Text area B', '0'); - $this->assertField('Selection D', ''); - $this->setField('Selection D', 'D2'); - $this->assertField('Selection D', 'D2'); - $this->setField('Selection D', 'D3'); - $this->assertField('Selection D', '0'); - $this->setField('Selection D', 'D4'); - $this->assertField('Selection D', '?'); - $this->assertField('Checkbox E', ''); - $this->assertField('Checkbox F', 'on'); - $this->assertField('Checkbox G', '0'); - $this->assertField('Checkbox H', '?'); - $this->assertFieldByName('i', 'on'); - $this->setFieldByName('i', ''); - $this->assertFieldByName('i', ''); - $this->setFieldByName('i', '0'); - $this->assertFieldByName('i', '0'); - $this->setFieldByName('i', '?'); - $this->assertFieldByName('i', '?'); - } - - function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreserved() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text area C', ' '); - } - - function chars($t) { - for ($i = 0; $i < strlen($t); $i++) { - print "[$t[$i]]"; - } - } - - function testSubmissionOfBlankFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', ''); - $this->setField('Text area B', ''); - $this->setFieldByName('i', ''); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[]'); - $this->assertText('e=[]'); - $this->assertText('i=[]'); - } - - function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreservedOnSubmission() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->click('Go!'); - $this->assertPattern('/c=\[ \]/'); - } - - function testSubmissionOfEmptyValues() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Selection D', 'D2'); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[D2]'); - $this->assertText('f=[on]'); - $this->assertText('i=[on]'); - } - - function testSubmissionOfZeroes() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '0'); - $this->setField('Text area B', '0'); - $this->setField('Selection D', 'D3'); - $this->setFieldByName('i', '0'); - $this->click('Go!'); - $this->assertText('a=[0]'); - $this->assertText('b=[0]'); - $this->assertText('d=[0]'); - $this->assertText('g=[0]'); - $this->assertText('i=[0]'); - } - - function testSubmissionOfQuestionMarks() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '?'); - $this->setField('Text area B', '?'); - $this->setField('Selection D', 'D4'); - $this->setFieldByName('i', '?'); - $this->click('Go!'); - $this->assertText('a=[?]'); - $this->assertText('b=[?]'); - $this->assertText('d=[?]'); - $this->assertText('h=[?]'); - $this->assertText('i=[?]'); - } - - function testSubmissionOfHtmlEncodedValues() { - $this->get($this->samples() . 'form_with_tricky_defaults.html'); - $this->assertField('Text A', '&\'"<>'); - $this->assertField('Text B', '"'); - $this->assertField('Text area C', '&\'"<>'); - $this->assertField('Selection D', "'"); - $this->assertField('Checkbox E', '&\'"<>'); - $this->assertField('Checkbox F', false); - $this->assertFieldByname('i', "'"); - $this->click('Go!'); - $this->assertText('a=[&\'"<>, "]'); - $this->assertText('c=[&\'"<>]'); - $this->assertText("d=[']"); - $this->assertText('e=[&\'"<>]'); - $this->assertText("i=[']"); - } - - function testFormActionRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - } -} - -class TestOfLiveMultiValueWidgets extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testDefaultFormValueSubmission() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->assertFieldByName('a', array('a2', 'a3')); - $this->assertFieldByName('b', array('b2', 'b3')); - $this->assertFieldByName('c[]', array('c2', 'c3')); - $this->assertFieldByName('d', array('2', '3')); - $this->assertFieldByName('e', array('2', '3')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a2, a3]'); - $this->assertText('b=[b2, b3]'); - $this->assertText('c=[c2, c3]'); - $this->assertText('d=[2, 3]'); - $this->assertText('e=[2, 3]'); - } - - function testSubmittingMultipleValues() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a4', 'a1')); - $this->setFieldByName('b', array('b1', 'b4')); - $this->assertFieldByName('b', array('b1', 'b4')); - $this->setFieldByName('c[]', array('c1', 'c4')); - $this->assertField('c[]', array('c1', 'c4')); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->setFieldByName('e', array('e1', 'e4')); - $this->assertField('e', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('b=[b1, b4]'); - $this->assertText('c=[c1, c4]'); - $this->assertText('d=[1, 4]'); - $this->assertText('e=[1, 4]'); - } - - function testSettingByOptionValue() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('d=[1, 4]'); - } - - function testSubmittingMultipleValuesByLabel() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a4', 'a1')); - $this->setField('multiple selection C', array('c1', 'c4')); - $this->assertField('multiple selection C', array('c1', 'c4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('c=[c1, c4]'); - } - - function testSavantStyleHiddenFieldDefaults() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldByName('a', array('a0')); - $this->assertFieldByName('b', array('b0')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a0]'); - $this->assertText('b=[b0]'); - } - - function testSavantStyleHiddenDefaultsAreOverridden() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertTrue($this->setFieldByName('a', array('a1'))); - $this->assertTrue($this->setFieldByName('b', 'b1')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } - - function testSavantStyleFormSettingById() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldById(1, array('a0')); - $this->assertFieldById(4, array('b0')); - $this->assertTrue($this->setFieldById(2, 'a1')); - $this->assertTrue($this->setFieldById(5, 'b1')); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } -} - -class TestOfFileUploads extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSingleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - } - - function testMultipleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertTrue($this->setField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt')); - $this->assertField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - $this->assertText('Some more text content'); - } - - function testBinaryFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/latin1_sample')); - $this->click('Go!'); - $this->assertText( - implode('', file(dirname(__FILE__) . '/support/latin1_sample'))); - } -} - -class TestOfLiveHistoryNavigation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testRetry() { - $this->get($this->samples() . 'cookie_based_counter.php'); - $this->assertPattern('/count: 1/i'); - $this->retry(); - $this->assertPattern('/count: 2/i'); - $this->retry(); - $this->assertPattern('/count: 3/i'); - } - - function testOfBackButton() { - $this->get($this->samples() . '1.html'); - $this->clickLink('2'); - $this->assertTitle('2'); - $this->assertTrue($this->back()); - $this->assertTitle('1'); - $this->assertTrue($this->forward()); - $this->assertTitle('2'); - $this->assertFalse($this->forward()); - } - - function testGetRetryResubmitsData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=aaa')); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsExtraData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostRetryResubmitsData() { - $this->assertTrue($this->post( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsRepeatedData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=1&a=2')); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - } -} - -class TestOfLiveAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testChallengeFromProtectedPage() { - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertRealm(new PatternExpectation('/simpletest/i')); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->retry(); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedWithinRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected'); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedSettingRealm() { - $this->get($this->samples() . 'protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPage() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() { - $this->get('http://test:secret@www.lastcraft.com/test/protected'); - $this->assertResponse(200); - } - - function testRealmExtendsToWholeDirectory() { - $this->get($this->samples() . 'protected/1.html'); - $this->authenticate('test', 'secret'); - $this->clickLink('2'); - $this->assertResponse(200); - $this->clickLink('3'); - $this->assertResponse(200); - } - - function testRedirectKeepsAuthentication() { - $this->get($this->samples() . 'protected/local_redirect.php'); - $this->authenticate('test', 'secret'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectKeepsEncodedAuthentication() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php'); - $this->assertResponse(200); - $this->assertTitle('Simple test target file'); - } - - function testSessionRestartLosesAuthentication() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->restart(); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - } -} - -class TestOfLoadingFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoFramesContentWhenFramesDisabled() { - $this->ignoreFrames(); - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This content is for no frames only'); - } - - function testPatternMatchCanReadTheOnlyFrame() { - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertText('A target for the SimpleTest test suite'); - $this->assertNoText('This content is for no frames only'); - } - - function testMessyFramesetResponsesByName() { - $this->assertTrue($this->get( - $this->samples() . 'messy_frameset.html')); - $this->assertTitle('Frameset for testing of SimpleTest'); - - $this->assertTrue($this->setFrameFocus('Front controller')); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocus('One')); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocus('Frame links')); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocus('Counter')); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocus('Redirected')); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocus('Protected')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocus('Protected redirect')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(1)); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocusByIndex(2)); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocusByIndex(3)); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocusByIndex(4)); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocusByIndex(5)); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocusByIndex(6)); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(7)); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertText('Count: 1'); - $this->retry(); - $this->assertText('Count: 2'); - $this->retry(); - $this->assertText('Count: 3'); - } - - function testReloadingSingleFrameWithCookieCounter() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->setFrameFocus('a'); - $this->retry(); - $this->assertText('Count: 3'); - $this->retry(); - $this->assertText('Count: 4'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - } - - function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->clearFrameFocus('a'); - $this->retry(); - - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->setFrameFocus('a'); - $this->assertText('Count: 3'); - $this->setFrameFocus('b'); - $this->assertText('Count: 4'); - } - - function testClickingNormalLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('2'); - $this->assertLink('3'); - $this->assertText('Simple test front controller'); - } - - function testJumpToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testSubmitToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - $this->assertText('Count: 1'); - } - - function testSubmitToSameDirectoryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - $this->assertText('Count: 1'); - } - - function testSubmitToEmptyActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitToNoActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testTopLinkExitsFrameset() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Exit the frameset'); - $this->assertTitle('Simple test target file'); - } - - function testLinkInOnePageCanLoadAnother() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertNoLink('3'); - $this->clickLink('Set one to 2'); - $this->assertLink('3'); - $this->assertNoLink('2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - } - - function testFrameWithRelativeLinksRespectsBaseTagForThatPage() { - $this->get($this->samples() . 'base_tag/frameset.html'); - $this->click('Back to test pages'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testRelativeLinkInFrameIsNotAffectedByFramesetBaseTag() { - $this->get($this->samples() . 'base_tag/frameset_with_base_tag.html'); - $this->assertText('This is page 1'); - $this->click('To page 2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This is page 2'); - } -} - -class TestOfFrameAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testUnauthenticatedFrameSendsChallenge() { - $this->get($this->samples() . 'protected/'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - } - - function testCanReadFrameFromAlreadyAuthenticatedRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testCanAuthenticateFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } - - function testCanAuthenticateRedirectedFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected redirect'); - $this->assertResponse(401); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } -} - -class TestOfNestedFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testCanNavigateToSpecificContent() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertTitle('Nested frameset for testing of SimpleTest'); - - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertPattern('/Simple test front controller/'); - $this->assertLink('2'); - $this->assertLink('Set one to 2'); - $this->assertPattern('/Count: 1/'); - $this->assertPattern('/r=rrr/'); - - $this->setFrameFocus('pair'); - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertNoPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - - $this->setFrameFocus('aaa'); - $this->assertPattern('/This is frame A/'); - $this->assertNoPattern('/This is frame B/'); - - $this->clearFrameFocus(); - $this->assertResponse(200); - $this->setFrameFocus('messy'); - $this->assertResponse(200); - $this->setFrameFocus('Front controller'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - } - - function testRetryingNestedPageOnlyRetriesThatSet() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->setFrameFocus('messy'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->setFrameFocus('Counter'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - - $this->clearFrameFocus(); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Front controller'); - $this->retry(); - - $this->clearFrameFocus(); - $this->assertPattern('/Count: 3/'); - } - - function testAuthenticatingNestedPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertPattern('/A target for the SimpleTest test suite/'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/adapter_test.php b/application/libraries/simpletest/test/adapter_test.php deleted file mode 100644 index c1a06a2f653..00000000000 --- a/application/libraries/simpletest/test/adapter_test.php +++ /dev/null @@ -1,50 +0,0 @@ -assertTrue(true, "PEAR true"); - $this->assertFalse(false, "PEAR false"); - } - - function testName() { - $this->assertTrue($this->getName() == get_class($this)); - } - - function testPass() { - $this->pass("PEAR pass"); - } - - function testNulls() { - $value = null; - $this->assertNull($value, "PEAR null"); - $value = 0; - $this->assertNotNull($value, "PEAR not null"); - } - - function testType() { - $this->assertType("Hello", "string", "PEAR type"); - } - - function testEquals() { - $this->assertEquals(12, 12, "PEAR identity"); - $this->setLooselyTyped(true); - $this->assertEquals("12", 12, "PEAR equality"); - } - - function testSame() { - $same = new SameTestClass(); - $this->assertSame($same, $same, "PEAR same"); - } - - function testRegExp() { - $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex"); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/all_tests.php b/application/libraries/simpletest/test/all_tests.php deleted file mode 100644 index 99ce9451e32..00000000000 --- a/application/libraries/simpletest/test/all_tests.php +++ /dev/null @@ -1,13 +0,0 @@ -TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion()); - $this->addFile(dirname(__FILE__) . '/unit_tests.php'); - $this->addFile(dirname(__FILE__) . '/shell_test.php'); - $this->addFile(dirname(__FILE__) . '/live_test.php'); - $this->addFile(dirname(__FILE__) . '/acceptance_test.php'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/authentication_test.php b/application/libraries/simpletest/test/authentication_test.php deleted file mode 100644 index 081cccddfae..00000000000 --- a/application/libraries/simpletest/test/authentication_test.php +++ /dev/null @@ -1,145 +0,0 @@ -assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testInsideWithLongerUrl() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testBelowRootIsOutside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/more/hello.html'))); - } - - function testOldNetscapeDefinitionIsOutside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathmore/hello.html'))); - } - - function testInsideWithMissingTrailingSlash() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path'))); - } - - function testDifferentPageNameStillInside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/goodbye.html'))); - } - - function testNewUrlInSameDirectoryDoesNotChangeRealm() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - } - - function testNewUrlMakesRealmTheCommonPath() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/here/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/here/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/there/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/paths/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathindex.html'))); - } -} - -class TestOfAuthenticator extends UnitTestCase { - - function testNoRealms() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = new SimpleAuthenticator(); - $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); - } - - function &createSingleRealm() { - $authenticator = new SimpleAuthenticator(); - $authenticator->addRealm( - new SimpleUrl('http://www.here.com/path/hello.html'), - 'Basic', - 'Sanctuary'); - $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret'); - return $authenticator; - } - - function testOutsideRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testWithinRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectOnce('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/path/more/hello.html')); - } - - function testRestartingClearsRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->restartSession(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testDifferentHostIsOutsideRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://here.com/path/hello.html')); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/autorun_test.php b/application/libraries/simpletest/test/autorun_test.php deleted file mode 100644 index 67a884c77e6..00000000000 --- a/application/libraries/simpletest/test/autorun_test.php +++ /dev/null @@ -1,23 +0,0 @@ -addFile(dirname(__FILE__) . '/support/test1.php'); - $this->assertEqual($tests->getSize(), 1); - } - - function testExitStatusOneIfTestsFail() { - exec('php ' . dirname(__FILE__) . '/support/failing_test.php', $output, $exit_status); - $this->assertEqual($exit_status, 1); - } - - function testExitStatusZeroIfTestsPass() { - exec('php ' . dirname(__FILE__) . '/support/passing_test.php', $output, $exit_status); - $this->assertEqual($exit_status, 0); - } -} - -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/bad_test_suite.php b/application/libraries/simpletest/test/bad_test_suite.php deleted file mode 100644 index b426013be40..00000000000 --- a/application/libraries/simpletest/test/bad_test_suite.php +++ /dev/null @@ -1,10 +0,0 @@ -TestSuite('Two bad test cases'); - $this->addFile(dirname(__FILE__) . '/support/empty_test_file.php'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/browser_test.php b/application/libraries/simpletest/test/browser_test.php deleted file mode 100644 index 3a52aaa8ff4..00000000000 --- a/application/libraries/simpletest/test/browser_test.php +++ /dev/null @@ -1,802 +0,0 @@ -assertIdentical($history->getUrl(), false); - $this->assertIdentical($history->getParameters(), false); - } - - function testCannotMoveInEmptyHistory() { - $history = new SimpleBrowserHistory(); - $this->assertFalse($history->back()); - $this->assertFalse($history->forward()); - } - - function testCurrentTargetAccessors() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.here.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testSecondEntryAccessors() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testGoingBackwards() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsOffBeginning() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingForwardsOffEnd() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsAndForwards() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertTrue($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testNewEntryReplacesNextOne() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testNewEntryDropsFutureEntries() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $history->back(); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.fourth.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/')); - $this->assertFalse($history->forward()); - $history->back(); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertFalse($history->back()); - } -} - -class TestOfParsedPageAccess extends UnitTestCase { - - function loadPage(&$page) { - $response = new MockSimpleHttpResponse($this); - $agent = new MockSimpleUserAgent($this); - $agent->returns('fetchResponse', $response); - - $browser = new MockParseSimpleBrowser($this); - $browser->returns('createUserAgent', $agent); - $browser->returns('parse', $page); - $browser->__construct(); - - $browser->get('http://this.com/page.html'); - return $browser; - } - - function testAccessorsWhenNoPage() { - $agent = new MockSimpleUserAgent($this); - $browser = new MockParseSimpleBrowser($this); - $browser->returns('createUserAgent', $agent); - $browser->__construct(); - $this->assertEqual($browser->getContent(), ''); - } - - function testParse() { - $page = new MockSimplePage(); - $page->setReturnValue('getRequest', "GET here.html\r\n\r\n"); - $page->setReturnValue('getRaw', 'Raw HTML'); - $page->setReturnValue('getTitle', 'Here'); - $page->setReturnValue('getFrameFocus', 'Frame'); - $page->setReturnValue('getMimeType', 'text/html'); - $page->setReturnValue('getResponseCode', 200); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Somewhere'); - $page->setReturnValue('getTransportError', 'Ouch!'); - - $browser = $this->loadPage($page); - $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n"); - $this->assertEqual($browser->getContent(), 'Raw HTML'); - $this->assertEqual($browser->getTitle(), 'Here'); - $this->assertEqual($browser->getFrameFocus(), 'Frame'); - $this->assertIdentical($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - $this->assertEqual($browser->getAuthentication(), 'Basic'); - $this->assertEqual($browser->getRealm(), 'Somewhere'); - $this->assertEqual($browser->getTransportError(), 'Ouch!'); - } - - function testLinkAffirmationWhenPresent() { - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); - $page->expectOnce('getUrlsByLabel', array('a link label')); - $browser = $this->loadPage($page); - $this->assertIdentical($browser->getLink('a link label'), 'http://www.nowhere.com'); - } - - function testLinkAffirmationByIdWhenPresent() { - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', 'a_page.com', array(99)); - $page->setReturnValue('getUrlById', false, array('*')); - $browser = $this->loadPage($page); - $this->assertIdentical($browser->getLinkById(99), 'a_page.com'); - $this->assertFalse($browser->getLinkById(98)); - } - - function testSettingFieldIsPassedToPage() { - $page = new MockSimplePage(); - $page->expectOnce('setField', array(new SimpleByLabelOrName('key'), 'Value', false)); - $page->setReturnValue('getField', 'Value'); - $browser = $this->loadPage($page); - $this->assertEqual($browser->getField('key'), 'Value'); - $browser->setField('key', 'Value'); - } -} - -class TestOfBrowserNavigation extends UnitTestCase { - function createBrowser($agent, $page) { - $browser = new MockParseSimpleBrowser(); - $browser->returns('createUserAgent', $agent); - $browser->returns('parse', $page); - $browser->__construct(); - return $browser; - } - - function testBrowserRequestMethods() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/get.req'), new SimpleGetEncoding())); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/post.req'), new SimplePostEncoding())); - $agent->expectAt( - 2, - 'fetchResponse', - array(new SimpleUrl('http://this.com/put.req'), new SimplePutEncoding())); - $agent->expectAt( - 3, - 'fetchResponse', - array(new SimpleUrl('http://this.com/delete.req'), new SimpleDeleteEncoding())); - $agent->expectAt( - 4, - 'fetchResponse', - array(new SimpleUrl('http://this.com/head.req'), new SimpleHeadEncoding())); - $agent->expectCallCount('fetchResponse', 5); - - $page = new MockSimplePage(); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/get.req'); - $browser->post('http://this.com/post.req'); - $browser->put('http://this.com/put.req'); - $browser->delete('http://this.com/delete.req'); - $browser->head('http://this.com/head.req'); - } - - function testClickLinkRequestsPage() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html'))); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickLinkWithUnknownFrameStillRequestsWholePage() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $target = new SimpleUrl('http://this.com/new.html'); - $target->setTarget('missing'); - $agent->expectAt( - 1, - 'fetchResponse', - array($target, new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $parsed_url = new SimpleUrl('http://this.com/new.html'); - $parsed_url->setTarget('missing'); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array($parsed_url)); - $page->setReturnValue('hasFrames', false); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickingMissingLinkFails() { - $agent = new MockSimpleUserAgent($this); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array()); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $this->assertTrue($browser->get('http://this.com/page.html')); - $this->assertFalse($browser->clickLink('New')); - } - - function testClickIndexedLink() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('1.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('0.html'), new SimpleUrl('1.html'))); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New', 1)); - } - - function testClinkLinkById() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/link.html'), - new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html')); - $page->expectOnce('getUrlById', array(2)); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLinkById(2)); - } - - function testClickingMissingLinkIdFails() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', false); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertFalse($browser->clickLink(0)); - } - - function testSubmitFormByLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false)); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Go'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit('Go')); - } - - function testDefaultSubmitFormByLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); - $form->setReturnValue('getMethod', 'get'); - $form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Submit'))); - $page->setReturnValue('getRaw', 'stuff'); - $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html')); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit()); - } - - function testSubmitFormByName() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByName('me'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitByName('me')); - } - - function testSubmitFormById() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleById(99), false)); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitById(99)); - } - - function testSubmitFormByImageLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByLabel('Go!'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImage('Go!', 10, 11)); - } - - function testSubmitFormByImageName() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByName('a'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageByName('a', 10, 11)); - } - - function testSubmitFormByImageId() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageById(99, 10, 11)); - } - - function testSubmitFormByFormId() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormById', $form); - $page->expectOnce('getFormById', array(33)); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->submitFormById(33)); - } -} - -class TestOfBrowserFrames extends UnitTestCase { - - function createBrowser($agent) { - $browser = new MockUserAgentSimpleBrowser(); - $browser->returns('createUserAgent', $agent); - $browser->__construct(); - return $browser; - } - - function createUserAgent($pages) { - $agent = new MockSimpleUserAgent(); - foreach ($pages as $url => $raw) { - $url = new SimpleUrl($url); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', $url); - $response->setReturnValue('getContent', $raw); - $agent->returns('fetchResponse', $response, array($url, '*')); - } - return $agent; - } - - function testSimplePageHasNoFrames() { - $browser = $this->createBrowser($this->createUserAgent( - array('http://site.with.no.frames/' => 'A non-framed page'))); - $this->assertEqual( - $browser->get('http://site.with.no.frames/'), - 'A non-framed page'); - $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/'); - } - - function testFramesetWithSingleFrame() { - $frameset = ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'A frame'))); - $this->assertEqual($browser->get('http://site.with.one.frame/'), 'A frame'); - $this->assertIdentical( - $browser->getFrames(), - array('a' => 'http://site.with.one.frame/frame.html')); - } - - function testTitleTakenFromFramesetPage() { - $frameset = 'Frameset title' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'Page title'))); - $browser->get('http://site.with.one.frame/'); - $this->assertEqual($browser->getTitle(), 'Frameset title'); - } - - function testFramesetWithSingleUnnamedFrame() { - $frameset = ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'One frame'))); - $this->assertEqual( - $browser->get('http://site.with.one.frame/'), - 'One frame'); - $this->assertIdentical( - $browser->getFrames(), - array(1 => 'http://site.with.one.frame/frame.html')); - } - - function testFramesetWithMultipleFrames() { - $frameset = '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 'b' => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html')); - } - - function testFrameFocusByName() { - $frameset = '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus('b'); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - } - - function testFramesetWithSomeNamedFrames() { - $frameset = '' . - '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frameD frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 2 => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html', - 4 => 'http://site.with.frames/frame_d.html')); - } - - function testFrameFocusWithMixedNamesAndIndexes() { - $frameset = '' . - '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus(2); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - $browser->setFrameFocus(4); - $this->assertEqual($browser->getContent(), 'D frame'); - $browser->clearFrameFocus(); - $this->assertEqual($browser->getContent(), 'A frameB frameC frameD frame'); - } - - function testNestedFrameset() { - $inner = '' . - '' . - ''; - $outer = '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frame/' => $outer, - 'http://site.with.nested.frame/inner.html' => $inner, - 'http://site.with.nested.frame/page.html' => 'The page'))); - $this->assertEqual( - $browser->get('http://site.with.nested.frame/'), - 'The page'); - $this->assertIdentical($browser->getFrames(), array( - 'inner' => array( - 'page' => 'http://site.with.nested.frame/page.html'))); - } - - function testCanNavigateToNestedFrame() { - $inner = '' . - '' . - '' . - ''; - $outer = '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getFrameFocus(), array('inner')); - $this->assertTrue($browser->setFrameFocus('one')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'one')); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocus('two')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'two')); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocus('three')); - $this->assertEqual($browser->getFrameFocus(), array('three')); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } - - function testCanNavigateToNestedFrameByIndex() { - $inner = '' . - '' . - '' . - ''; - $outer = '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1)); - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1, 1)); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(1, 2)); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(2)); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/collector_test.php b/application/libraries/simpletest/test/collector_test.php deleted file mode 100644 index efdbf377ece..00000000000 --- a/application/libraries/simpletest/test/collector_test.php +++ /dev/null @@ -1,50 +0,0 @@ -expectMinimumCallCount('addFile', 2); - $suite->expect( - 'addFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = new SimpleCollector(); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} - -class TestOfPatternCollector extends UnitTestCase { - - function testAddingEverythingToGroup() { - $suite = new MockTestSuite(); - $suite->expectCallCount('addFile', 2); - $suite->expect( - 'addFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = new SimplePatternCollector('/.*/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } - - function testOnlyMatchedFilesAreAddedToGroup() { - $suite = new MockTestSuite(); - $suite->expectOnce('addFile', array(new PathEqualExpectation( - dirname(__FILE__) . '/support/collector/collectable.1'))); - $collector = new SimplePatternCollector('/1$/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/command_line_test.php b/application/libraries/simpletest/test/command_line_test.php deleted file mode 100644 index 5baabff33c6..00000000000 --- a/application/libraries/simpletest/test/command_line_test.php +++ /dev/null @@ -1,40 +0,0 @@ -assertIdentical($parser->getTest(), ''); - $this->assertIdentical($parser->getTestCase(), ''); - } - - function testNotXmlByDefault() { - $parser = new SimpleCommandLineParser(array()); - $this->assertFalse($parser->isXml()); - } - - function testCanDetectRequestForXml() { - $parser = new SimpleCommandLineParser(array('--xml')); - $this->assertTrue($parser->isXml()); - } - - function testCanReadAssignmentSyntax() { - $parser = new SimpleCommandLineParser(array('--test=myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadFollowOnSyntax() { - $parser = new SimpleCommandLineParser(array('--test', 'myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadShortForms() { - $parser = new SimpleCommandLineParser(array('-t', 'myTest', '-c', 'MyClass', '-x')); - $this->assertEqual($parser->getTest(), 'myTest'); - $this->assertEqual($parser->getTestCase(), 'MyClass'); - $this->assertTrue($parser->isXml()); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/compatibility_test.php b/application/libraries/simpletest/test/compatibility_test.php deleted file mode 100644 index b8635e5bb83..00000000000 --- a/application/libraries/simpletest/test/compatibility_test.php +++ /dev/null @@ -1,87 +0,0 @@ -assertTrue(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonClass')); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonSubclass')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonSubclass(), - 'ComparisonClass')); - } - - function testIdentityOfNumericStrings() { - $numericString1 = "123"; - $numericString2 = "00123"; - $this->assertNotIdentical($numericString1, $numericString2); - } - - function testIdentityOfObjects() { - $object1 = new ComparisonClass(); - $object2 = new ComparisonClass(); - $this->assertIdentical($object1, $object2); - } - - function testReferences () { - $thing = "Hello"; - $thing_reference = &$thing; - $thing_copy = $thing; - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $thing, - $thing_copy)); - } - - function testObjectReferences () { - $object = new ComparisonClass(); - $object_reference = $object; - $object_copy = new ComparisonClass(); - $object_assignment = $object; - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_copy)); - if (version_compare(phpversion(), '5', '>=')) { - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } else { - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } - } - - function testInteraceComparison() { - $object = new ComparisonClassWithInterface(); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonInterface')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonClassWithInterface(), - 'ComparisonInterface')); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/cookies_test.php b/application/libraries/simpletest/test/cookies_test.php deleted file mode 100644 index 0b49e43bf9f..00000000000 --- a/application/libraries/simpletest/test/cookies_test.php +++ /dev/null @@ -1,227 +0,0 @@ -assertFalse($cookie->getValue()); - $this->assertEqual($cookie->getPath(), "/"); - $this->assertIdentical($cookie->getHost(), false); - $this->assertFalse($cookie->getExpiry()); - $this->assertFalse($cookie->isSecure()); - } - - function testCookieAccessors() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT", - true); - $this->assertEqual($cookie->getName(), "name"); - $this->assertEqual($cookie->getValue(), "value"); - $this->assertEqual($cookie->getPath(), "/path/"); - $this->assertEqual($cookie->getExpiry(), "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isSecure()); - } - - function testFullHostname() { - $cookie = new SimpleCookie("name"); - $this->assertTrue($cookie->setHost("host.name.here")); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $this->assertTrue($cookie->setHost("host.com")); - $this->assertEqual($cookie->getHost(), "host.com"); - } - - function testHostTruncation() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $cookie->setHost("this.host.com"); - $this->assertEqual($cookie->getHost(), "host.com"); - $this->assertTrue($cookie->setHost("dashes.in-host.com")); - $this->assertEqual($cookie->getHost(), "in-host.com"); - } - - function testBadHosts() { - $cookie = new SimpleCookie("name"); - $this->assertFalse($cookie->setHost("gibberish")); - $this->assertFalse($cookie->setHost("host.here")); - $this->assertFalse($cookie->setHost("host..com")); - $this->assertFalse($cookie->setHost("...")); - $this->assertFalse($cookie->setHost("host.com.")); - } - - function testHostValidity() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertTrue($cookie->isValidHost("host.name.here")); - $this->assertTrue($cookie->isValidHost("that.host.name.here")); - $this->assertFalse($cookie->isValidHost("bad.host")); - $this->assertFalse($cookie->isValidHost("nearly.name.here")); - } - - function testPathValidity() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertFalse($cookie->isValidPath("/")); - $this->assertTrue($cookie->isValidPath("/path/")); - $this->assertTrue($cookie->isValidPath("/path/more")); - } - - function testSessionExpiring() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertTrue($cookie->isExpired(0)); - } - - function testTimestampExpiry() { - $cookie = new SimpleCookie("name", "value", "/path", 456); - $this->assertFalse($cookie->isExpired(0)); - $this->assertTrue($cookie->isExpired(457)); - $this->assertFalse($cookie->isExpired(455)); - } - - function testDateExpiry() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isExpired("Mon, 18 Nov 2002 15:50:30 GMT")); - $this->assertFalse($cookie->isExpired("Mon, 18 Nov 2002 15:50:28 GMT")); - } - - function testAging() { - $cookie = new SimpleCookie("name", "value", "/path", 200); - $cookie->agePrematurely(199); - $this->assertFalse($cookie->isExpired(0)); - $cookie->agePrematurely(2); - $this->assertTrue($cookie->isExpired(0)); - } -} - -class TestOfCookieJar extends UnitTestCase { - - function testAddCookie() { - $jar = new SimpleCookieJar(); - $jar->setCookie("a", "A"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - } - - function testHostFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', 'my-host.com'); - $jar->setCookie('b', 'B', 'another-host.com'); - $jar->setCookie('c', 'C'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com')), - array('a=A', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('www.another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('new-host.org')), - array('c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=A', 'b=B', 'c=C')); - } - - function testPathFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/elsewhere')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/here')), array('a=A')); - } - - function testPathFilterDeeply() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/more_path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/and_more')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/not_here/')), array()); - } - - function testMultipleCookieWithDifferentPathsButSameName() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '123', false, '/path/here/'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here')), - array('a=abc', 'a=123')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here/there')), - array('a=abc', 'a=123')); - } - - function testOverwrite() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', 'cde', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=cde')); - } - - function testClearSessionCookies() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/'); - $jar->restartSession(); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByAgeing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->agePrematurely(2); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testCookieClearing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=')); - } - - function testCookieClearByLoweringDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/', 'Wed, 25-Dec-02 04:24:21 GMT'); - $jar->setCookie('a', 'def', false, '/', 'Wed, 25-Dec-02 04:24:19 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=def')); - $jar->restartSession('Wed, 25-Dec-02 04:24:20 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/detached_test.php b/application/libraries/simpletest/test/detached_test.php deleted file mode 100644 index f651d97eb61..00000000000 --- a/application/libraries/simpletest/test/detached_test.php +++ /dev/null @@ -1,15 +0,0 @@ -add(new DetachedTestCase($command)); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/dumper_test.php b/application/libraries/simpletest/test/dumper_test.php deleted file mode 100644 index 789047de924..00000000000 --- a/application/libraries/simpletest/test/dumper_test.php +++ /dev/null @@ -1,88 +0,0 @@ -assertEqual( - $dumper->clipString("Hello", 6), - "Hello", - "Hello, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello", 5), - "Hello", - "Hello, 5->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3), - "Hel...", - "Hello world, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 6, 3), - "Hello ...", - "Hello world, 6, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3, 6), - "...o w...", - "Hello world, 3, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 11), - "...orld", - "Hello world, 4, 11->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 12), - "...orld", - "Hello world, 4, 12->%s"); - } - - function testDescribeNull() { - $dumper = new SimpleDumper(); - $this->assertPattern('/null/i', $dumper->describeValue(null)); - } - - function testDescribeBoolean() { - $dumper = new SimpleDumper(); - $this->assertPattern('/boolean/i', $dumper->describeValue(true)); - $this->assertPattern('/true/i', $dumper->describeValue(true)); - $this->assertPattern('/false/i', $dumper->describeValue(false)); - } - - function testDescribeString() { - $dumper = new SimpleDumper(); - $this->assertPattern('/string/i', $dumper->describeValue('Hello')); - $this->assertPattern('/Hello/', $dumper->describeValue('Hello')); - } - - function testDescribeInteger() { - $dumper = new SimpleDumper(); - $this->assertPattern('/integer/i', $dumper->describeValue(35)); - $this->assertPattern('/35/', $dumper->describeValue(35)); - } - - function testDescribeFloat() { - $dumper = new SimpleDumper(); - $this->assertPattern('/float/i', $dumper->describeValue(0.99)); - $this->assertPattern('/0\.99/', $dumper->describeValue(0.99)); - } - - function testDescribeArray() { - $dumper = new SimpleDumper(); - $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4))); - $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4))); - } - - function testDescribeObject() { - $dumper = new SimpleDumper(); - $this->assertPattern( - '/object/i', - $dumper->describeValue(new DumperDummy())); - $this->assertPattern( - '/DumperDummy/i', - $dumper->describeValue(new DumperDummy())); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/eclipse_test.php b/application/libraries/simpletest/test/eclipse_test.php deleted file mode 100644 index c90cbc918fd..00000000000 --- a/application/libraries/simpletest/test/eclipse_test.php +++ /dev/null @@ -1,32 +0,0 @@ -expectOnce('write',array($expected)); - $listener->setReturnValue('write',-1); - - $pathparts = pathinfo($fullpath); - $filename = $pathparts['basename']; - $test= &new TestSuite($filename); - $test->addTestFile($fullpath); - $test->run(new EclipseReporter($listener)); - $this->assertEqual($expected,$listener->output); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/encoding_test.php b/application/libraries/simpletest/test/encoding_test.php deleted file mode 100644 index a09236e057c..00000000000 --- a/application/libraries/simpletest/test/encoding_test.php +++ /dev/null @@ -1,240 +0,0 @@ -assertEqual($pair->asRequest(), 'a=A'); - } - - function testMimeEncodedAsHeadersAndContent() { - $pair = new SimpleEncodedPair('a', 'A'); - $this->assertEqual( - $pair->asMime(), - "Content-Disposition: form-data; name=\"a\"\r\n\r\nA"); - } - - function testAttachmentEncodedAsHeadersWithDispositionAndContent() { - $part = new SimpleAttachment('a', 'A', 'aaa.txt'); - $this->assertEqual( - $part->asMime(), - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n\r\nA"); - } -} - -class TestOfEncoding extends UnitTestCase { - private $content_so_far; - - function write($content) { - $this->content_so_far .= $content; - } - - function clear() { - $this->content_so_far = ''; - } - - function assertWritten($encoding, $content, $message = '%s') { - $this->clear(); - $encoding->writeTo($this); - $this->assertIdentical($this->content_so_far, $content, $message); - } - - function testGetEmpty() { - $encoding = new SimpleGetEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertIdentical($encoding->asUrlRequest(), ''); - } - - function testPostEmpty() { - $encoding = new SimplePostEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testPrefilled() { - $encoding = new SimplePostEncoding(array('a' => 'aaa')); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testPrefilledWithTwoLevels() { - $query = array('a' => array('aa' => 'aaa')); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa]' => 'aaa')); - $this->assertIdentical($encoding->getValue('a[aa]'), 'aaa'); - $this->assertWritten($encoding, 'a%5Baa%5D=aaa'); - } - - function testPrefilledWithThreeLevels() { - $query = array('a' => array('aa' => array('aaa' => 'aaaa'))); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa][aaa]' => 'aaaa')); - $this->assertIdentical($encoding->getValue('a[aa][aaa]'), 'aaaa'); - $this->assertWritten($encoding, 'a%5Baa%5D%5Baaa%5D=aaaa'); - } - - function testPrefilledWithObject() { - $encoding = new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa'))); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testMultiplePrefilled() { - $query = array('a' => array('a1', 'a2')); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[0]' => 'a1', 'a[1]' => 'a2')); - $this->assertIdentical($encoding->getValue('a[0]'), 'a1'); - $this->assertIdentical($encoding->getValue('a[1]'), 'a2'); - $this->assertWritten($encoding, 'a%5B0%5D=a1&a%5B1%5D=a2'); - } - - function testSingleParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $this->assertEqual($encoding->getValue('a'), 'Hello'); - $this->assertWritten($encoding, 'a=Hello'); - } - - function testFalseParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', false); - $this->assertEqual($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testUrlEncoding() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello there!'); - $this->assertWritten($encoding, 'a=Hello+there%21'); - } - - function testUrlEncodingOfKey() { - $encoding = new SimplePostEncoding(); - $encoding->add('a!', 'Hello'); - $this->assertWritten($encoding, 'a%21=Hello'); - } - - function testMultipleParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('b', 'Goodbye'); - $this->assertWritten($encoding, 'a=Hello&b=Goodbye'); - } - - function testEmptyParameters() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', ''); - $encoding->add('b', ''); - $this->assertWritten($encoding, 'a=&b='); - } - - function testRepeatedParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('a', 'Goodbye'); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testAddingLists() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', array('Hello', 'Goodbye')); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testMergeInHash() { - $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(array('a' => 'A2')); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testMergeInObject() { - $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(new SimpleEncoding(array('a' => 'A2'))); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testPrefilledMultipart() { - $encoding = new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary'); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testAttachment() { - $encoding = new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->attach('a', 'aaa', 'aaa.txt'); - $this->assertIdentical($encoding->getValue('a'), 'aaa.txt'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testEntityEncodingDefaultContentType() { - $encoding = new SimpleEntityEncoding(); - $this->assertIdentical($encoding->getContentType(), 'application/x-www-form-urlencoded'); - $this->assertWritten($encoding, ''); - } - - function testEntityEncodingTextBody() { - $encoding = new SimpleEntityEncoding('plain text'); - $this->assertIdentical($encoding->getContentType(), 'text/plain'); - $this->assertWritten($encoding, 'plain text'); - } - - function testEntityEncodingXmlBody() { - $encoding = new SimpleEntityEncoding('

xmltext

', 'text/xml'); - $this->assertIdentical($encoding->getContentType(), 'text/xml'); - $this->assertWritten($encoding, '

xmltext

'); - } -} - -class TestOfEncodingHeaders extends UnitTestCase { - - function testEmptyEncodingWritesZeroContentLength() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $encoding = new SimpleEntityEncoding(); - $encoding->writeHeadersTo($socket); - } - - function testTextEncodingWritesDefaultContentType() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 18\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); - $encoding = new SimpleEntityEncoding('one two three four'); - $encoding->writeHeadersTo($socket); - } - - function testEmptyMultipartEncodingWritesEndBoundaryContentLength() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 14\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: multipart/form-data; boundary=boundary\r\n")); - $encoding = new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->writeHeadersTo($socket); - } - -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/errors_test.php b/application/libraries/simpletest/test/errors_test.php deleted file mode 100644 index ebb9e05891f..00000000000 --- a/application/libraries/simpletest/test/errors_test.php +++ /dev/null @@ -1,229 +0,0 @@ -get('SimpleErrorQueue'); - $queue->clear(); - } - - function tearDown() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $queue->clear(); - } - - function testExpectationMatchCancelsIncomingError() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new AnythingExpectation()), - 'B', - 'a message')); - $test->setReturnValue('assert', true); - $test->expectNever('error'); - $queue = new SimpleErrorQueue(); - $queue->setTestCase($test); - $queue->expectError(new AnythingExpectation(), 'a message'); - $queue->add(1024, 'B', 'b.php', 100); - } -} - -class TestOfErrorTrap extends UnitTestCase { - private $old; - - function setUp() { - $this->old = error_reporting(E_ALL); - set_error_handler('SimpleTestErrorHandler'); - } - - function tearDown() { - restore_error_handler(); - error_reporting($this->old); - } - - function testQueueStartsEmpty() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $this->assertFalse($queue->extract()); - } - - function testErrorsAreSwallowedByMatchingExpectation() { - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testErrorsAreSwallowedInOrder() { - $this->expectError('a'); - $this->expectError('b'); - trigger_error('a'); - trigger_error('b'); - } - - function testAnyErrorCanBeSwallowed() { - $this->expectError(); - trigger_error('Ouch!'); - } - - function testErrorCanBeSwallowedByPatternMatching() { - $this->expectError(new PatternExpectation('/ouch/i')); - trigger_error('Ouch!'); - } - - function testErrorWithPercentsPassesWithNoSprintfError() { - $this->expectError("%"); - trigger_error('%'); - } -} - -class TestOfErrors extends UnitTestCase { - private $old; - - function setUp() { - $this->old = error_reporting(E_ALL); - } - - function tearDown() { - error_reporting($this->old); - } - - function testDefaultWhenAllReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testNoticeWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testNoNoticeWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testNoWarningWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testNoticeSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWithPercentsReportedWithNoSprintfError() { - $this->expectError('%'); - trigger_error('%'); - } -} - -class TestOfPHP52RecoverableErrors extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '<'), - 'E_RECOVERABLE_ERROR not tested for PHP below 5.2'); - } - - function testError() { - eval(' - class RecoverableErrorTestingStub { - function ouch(RecoverableErrorTestingStub $obj) { - } - } - '); - - $stub = new RecoverableErrorTestingStub(); - $this->expectError(new PatternExpectation('/must be an instance of RecoverableErrorTestingStub/i')); - $stub->ouch(new stdClass()); - } -} - -class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '>='), - 'E_USER_ERROR not tested for PHP 5.2 and above'); - } - - function testNoErrorWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testErrorSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_ERROR); - } -} - -SimpleTest::ignore('TestOfNotEnoughErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfNotEnoughErrors extends UnitTestCase { - function testExpectTwoErrorsThrowOne() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - $this->expectError('Error 2'); - } -} - -SimpleTest::ignore('TestOfLeftOverErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfLeftOverErrors extends UnitTestCase { - function testExpectOneErrorGetTwo() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - trigger_error('Error 2'); - } -} - -class TestRunnerForLeftOverAndNotEnoughErrors extends UnitTestCase { - function testRunLeftOverErrorsTestCase() { - $test = new TestOfLeftOverErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } - - function testRunNotEnoughErrors() { - $test = new TestOfNotEnoughErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } -} - -// TODO: Add stacked error handler test -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/exceptions_test.php b/application/libraries/simpletest/test/exceptions_test.php deleted file mode 100644 index 1011543d4fa..00000000000 --- a/application/libraries/simpletest/test/exceptions_test.php +++ /dev/null @@ -1,183 +0,0 @@ -assertTrue($expectation->test(new MyTestException())); - $this->assertTrue($expectation->test(new HigherTestException())); - $this->assertFalse($expectation->test(new OtherTestException())); - } - - function testMatchesClassAndMessageWhenExceptionExpected() { - $expectation = new ExceptionExpectation(new MyTestException('Hello')); - $this->assertTrue($expectation->test(new MyTestException('Hello'))); - $this->assertFalse($expectation->test(new HigherTestException('Hello'))); - $this->assertFalse($expectation->test(new OtherTestException('Hello'))); - $this->assertFalse($expectation->test(new MyTestException('Goodbye'))); - $this->assertFalse($expectation->test(new MyTestException())); - } - - function testMessagelessExceptionMatchesOnlyOnClass() { - $expectation = new ExceptionExpectation(new MyTestException()); - $this->assertTrue($expectation->test(new MyTestException())); - $this->assertFalse($expectation->test(new HigherTestException())); - } -} - -class TestOfExceptionTrap extends UnitTestCase { - - function testNoExceptionsInQueueMeansNoTestMessages() { - $test = new MockSimpleTestCase(); - $test->expectNever('assert'); - $queue = new SimpleExceptionTrap(); - $this->assertFalse($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionGivesTrue() { - $expectation = new MockSimpleExpectation(); - $expectation->setReturnValue('test', true); - $test = new MockSimpleTestCase(); - $test->setReturnValue('assert', true); - $queue = new SimpleExceptionTrap(); - $queue->expectException($expectation, 'message'); - $this->assertTrue($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionTriggersAssertion() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - '*', - new ExceptionExpectation(new Exception()), - 'message')); - $queue = new SimpleExceptionTrap(); - $queue->expectException(new ExceptionExpectation(new Exception()), 'message'); - $queue->isExpected($test, new Exception()); - } -} - -class TestOfCatchingExceptions extends UnitTestCase { - - function testCanCatchAnyExpectedException() { - $this->expectException(); - throw new Exception(); - } - - function testCanMatchExceptionByClass() { - $this->expectException('MyTestException'); - throw new HigherTestException(); - } - - function testCanMatchExceptionExactly() { - $this->expectException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testLastListedExceptionIsTheOneThatCounts() { - $this->expectException('OtherTestException'); - $this->expectException('MyTestException'); - throw new HigherTestException(); - } -} - -class TestOfIgnoringExceptions extends UnitTestCase { - - function testCanIgnoreAnyException() { - $this->ignoreException(); - throw new Exception(); - } - - function testCanIgnoreSpecificException() { - $this->ignoreException('MyTestException'); - throw new MyTestException(); - } - - function testCanIgnoreExceptionExactly() { - $this->ignoreException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testIgnoredExceptionsDoNotMaskExpectedExceptions() { - $this->ignoreException('Exception'); - $this->expectException('MyTestException'); - throw new MyTestException(); - } - - function testCanIgnoreMultipleExceptions() { - $this->ignoreException('MyTestException'); - $this->ignoreException('OtherTestException'); - throw new OtherTestException(); - } -} - -class TestOfCallingTearDownAfterExceptions extends UnitTestCase { - private $debri = 0; - - function tearDown() { - $this->debri--; - } - - function testLeaveSomeDebri() { - $this->debri++; - $this->expectException(); - throw new Exception(__FUNCTION__); - } - - function testDebriWasRemovedOnce() { - $this->assertEqual($this->debri, 0); - } -} - -class TestOfExceptionThrownInSetUpDoesNotRunTestBody extends UnitTestCase { - - function setUp() { - $this->expectException(); - throw new Exception(); - } - - function testShouldNotBeRun() { - $this->fail('This test body should not be run'); - } - - function testShouldNotBeRunEither() { - $this->fail('This test body should not be run either'); - } -} - -class TestOfExpectExceptionWithSetUp extends UnitTestCase { - - function setUp() { - $this->expectException(); - } - - function testThisExceptionShouldBeCaught() { - throw new Exception(); - } - - function testJustThrowingMyTestException() { - throw new MyTestException(); - } -} - -class TestOfThrowingExceptionsInTearDown extends UnitTestCase { - - function tearDown() { - throw new Exception(); - } - - function testDoesntFatal() { - $this->expectException(); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/expectation_test.php b/application/libraries/simpletest/test/expectation_test.php deleted file mode 100644 index 31fbe65e683..00000000000 --- a/application/libraries/simpletest/test/expectation_test.php +++ /dev/null @@ -1,317 +0,0 @@ -assertTrue($is_true->test(true)); - $this->assertFalse($is_true->test(false)); - } - - function testStringMatch() { - $hello = new EqualExpectation("Hello"); - $this->assertTrue($hello->test("Hello")); - $this->assertFalse($hello->test("Goodbye")); - } - - function testInteger() { - $fifteen = new EqualExpectation(15); - $this->assertTrue($fifteen->test(15)); - $this->assertFalse($fifteen->test(14)); - } - - function testFloat() { - $pi = new EqualExpectation(3.14); - $this->assertTrue($pi->test(3.14)); - $this->assertFalse($pi->test(3.15)); - } - - function testArray() { - $colours = new EqualExpectation(array("r", "g", "b")); - $this->assertTrue($colours->test(array("r", "g", "b"))); - $this->assertFalse($colours->test(array("g", "b", "r"))); - } - - function testHash() { - $is_blue = new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255)); - $this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255))); - $this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0))); - } - - function testHashWithOutOfOrderKeysShouldStillMatch() { - $any_order = new EqualExpectation(array('a' => 1, 'b' => 2)); - $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1))); - } -} - -class TestOfWithin extends UnitTestCase { - - function testWithinFloatingPointMargin() { - $within = new WithinMarginExpectation(1.0, 0.2); - $this->assertFalse($within->test(0.7)); - $this->assertTrue($within->test(0.8)); - $this->assertTrue($within->test(0.9)); - $this->assertTrue($within->test(1.1)); - $this->assertTrue($within->test(1.2)); - $this->assertFalse($within->test(1.3)); - } - - function testOutsideFloatingPointMargin() { - $within = new OutsideMarginExpectation(1.0, 0.2); - $this->assertTrue($within->test(0.7)); - $this->assertFalse($within->test(0.8)); - $this->assertFalse($within->test(1.2)); - $this->assertTrue($within->test(1.3)); - } -} - -class TestOfInequality extends UnitTestCase { - - function testStringMismatch() { - $not_hello = new NotEqualExpectation("Hello"); - $this->assertTrue($not_hello->test("Goodbye")); - $this->assertFalse($not_hello->test("Hello")); - } -} - -class RecursiveNasty { - private $me; - - function RecursiveNasty() { - $this->me = $this; - } -} - -class OpaqueContainer { - private $stuff; - private $value; - - public function __construct($value) { - $this->value = $value; - } -} - -class DerivedOpaqueContainer extends OpaqueContainer { - // Deliberately have a variable whose name with the same suffix as a later - // variable - private $new_value = 1; - - // Deliberately obscures the variable of the same name in the base - // class. - private $value; - - public function __construct($value, $base_value) { - parent::__construct($base_value); - $this->value = $value; - } -} - -class TestOfIdentity extends UnitTestCase { - - function testType() { - $string = new IdenticalExpectation("37"); - $this->assertTrue($string->test("37")); - $this->assertFalse($string->test(37)); - $this->assertFalse($string->test("38")); - } - - function _testNastyPhp5Bug() { - $this->assertFalse(new RecursiveNasty() != new RecursiveNasty()); - } - - function _testReallyHorribleRecursiveStructure() { - $hopeful = new IdenticalExpectation(new RecursiveNasty()); - $this->assertTrue($hopeful->test(new RecursiveNasty())); - } - - function testCanComparePrivateMembers() { - $expectFive = new IdenticalExpectation(new OpaqueContainer(5)); - $this->assertTrue($expectFive->test(new OpaqueContainer(5))); - $this->assertFalse($expectFive->test(new OpaqueContainer(6))); - } - - function testCanComparePrivateMembersOfObjectsInArrays() { - $expectFive = new IdenticalExpectation(array(new OpaqueContainer(5))); - $this->assertTrue($expectFive->test(array(new OpaqueContainer(5)))); - $this->assertFalse($expectFive->test(array(new OpaqueContainer(6)))); - } - - function testCanComparePrivateMembersOfObjectsWherePrivateMemberOfBaseClassIsObscured() { - $expectFive = new IdenticalExpectation(array(new DerivedOpaqueContainer(1,2))); - $this->assertTrue($expectFive->test(array(new DerivedOpaqueContainer(1,2)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,2)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,9)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(1,0)))); - } -} - -class TransparentContainer { - public $value; - - public function __construct($value) { - $this->value = $value; - } -} - -class TestOfMemberComparison extends UnitTestCase { - - function testMemberExpectationCanMatchPublicMember() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new TransparentContainer(5))); - $this->assertFalse($expect_five->test(new TransparentContainer(8))); - } - - function testMemberExpectationCanMatchPrivateMember() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new OpaqueContainer(5))); - $this->assertFalse($expect_five->test(new OpaqueContainer(8))); - } - - function testMemberExpectationCanMatchPrivateMemberObscuredByDerivedClass() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,8))); - $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,5))); - $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,8))); - $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,5))); - } - -} - -class DummyReferencedObject{} - -class TestOfReference extends UnitTestCase { - - function testReference() { - $foo = "foo"; - $ref = &$foo; - $not_ref = $foo; - $bar = "bar"; - - $expect = new ReferenceExpectation($foo); - $this->assertTrue($expect->test($ref)); - $this->assertFalse($expect->test($not_ref)); - $this->assertFalse($expect->test($bar)); - } -} - -class TestOfNonIdentity extends UnitTestCase { - - function testType() { - $string = new NotIdenticalExpectation("37"); - $this->assertTrue($string->test("38")); - $this->assertTrue($string->test(37)); - $this->assertFalse($string->test("37")); - } -} - -class TestOfPatterns extends UnitTestCase { - - function testWanted() { - $pattern = new PatternExpectation('/hello/i'); - $this->assertTrue($pattern->test("Hello world")); - $this->assertFalse($pattern->test("Goodbye world")); - } - - function testUnwanted() { - $pattern = new NoPatternExpectation('/hello/i'); - $this->assertFalse($pattern->test("Hello world")); - $this->assertTrue($pattern->test("Goodbye world")); - } -} - -class ExpectedMethodTarget { - function hasThisMethod() {} -} - -class TestOfMethodExistence extends UnitTestCase { - - function testHasMethod() { - $instance = new ExpectedMethodTarget(); - $expectation = new MethodExistsExpectation('hasThisMethod'); - $this->assertTrue($expectation->test($instance)); - $expectation = new MethodExistsExpectation('doesNotHaveThisMethod'); - $this->assertFalse($expectation->test($instance)); - } -} - -class TestOfIsA extends UnitTestCase { - - function testString() { - $expectation = new IsAExpectation('string'); - $this->assertTrue($expectation->test('Hello')); - $this->assertFalse($expectation->test(5)); - } - - function testBoolean() { - $expectation = new IsAExpectation('boolean'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testBool() { - $expectation = new IsAExpectation('bool'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testDouble() { - $expectation = new IsAExpectation('double'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testFloat() { - $expectation = new IsAExpectation('float'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testReal() { - $expectation = new IsAExpectation('real'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testInteger() { - $expectation = new IsAExpectation('integer'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testInt() { - $expectation = new IsAExpectation('int'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testScalar() { - $expectation = new IsAExpectation('scalar'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(array(5))); - } - - function testNumeric() { - $expectation = new IsAExpectation('numeric'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test('string')); - } - - function testNull() { - $expectation = new IsAExpectation('null'); - $this->assertTrue($expectation->test(null)); - $this->assertFalse($expectation->test('string')); - } -} - -class TestOfNotA extends UnitTestCase { - - function testString() { - $expectation = new NotAExpectation('string'); - $this->assertFalse($expectation->test('Hello')); - $this->assertTrue($expectation->test(5)); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/form_test.php b/application/libraries/simpletest/test/form_test.php deleted file mode 100644 index 70a18f2b3a0..00000000000 --- a/application/libraries/simpletest/test/form_test.php +++ /dev/null @@ -1,344 +0,0 @@ -returns('getUrl', new SimpleUrl($url)); - $page->returns('expandUrl', new SimpleUrl($url)); - return $page; - } - - function testFormAttributes() { - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual($form->getMethod(), 'get'); - $this->assertIdentical($form->getId(), '33'); - $this->assertNull($form->getValue(new SimpleByName('a'))); - } - - function testAction() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = new SimpleForm($tag, $page); - $this->assertEqual($form->getAction(), new SimpleUrl('http://host/here.php')); - } - - function testEmptyAction() { - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testMissingAction() { - $tag = new SimpleFormTag(array('method' => 'GET')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testRootAction() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('/'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '/')); - $form = new SimpleForm($tag, $page); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/')); - } - - function testDefaultFrameTargetOnForm() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = new SimpleForm($tag, $page); - $form->setDefaultTarget('frame'); - $expected = new SimpleUrl('http://host/here.php'); - $expected->setTarget('frame'); - $this->assertEqual($form->getAction(), $expected); - } - - function testTextWidget() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me')); - $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me'); - $this->assertNull($form->getValue(new SimpleByName('not_present'))); - } - - function testTextWidgetById() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50))); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself'); - $this->assertTrue($form->setField(new SimpleById(50), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me'); - } - - function testTextWidgetByLabel() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $widget = new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a')); - $form->addWidget($widget); - $widget->setLabel('thing'); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a'); - $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b'); - } - - function testSubmitEmpty() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $this->assertIdentical($form->submit(), new SimpleGetEncoding()); - } - - function testSubmitButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9'))); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!'); - $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!'); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go!'))); - } - - function testSubmitWithAdditionalParameters() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')), - new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A'))); - } - - function testSubmitButtonWithLabelOfSubmit() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('test')), - new SimpleGetEncoding(array('test' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => 'Submit'))); - } - - function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => ' Submit '))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => ' Submit '))); - } - - function testImageSubmitButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!', - 'id' => '9'))); - $this->assertTrue($form->hasImage(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleByName('go'))); - $this->assertEqual( - $form->submitImage(new SimpleByName('go'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleById(9))); - $this->assertEqual( - $form->submitImage(new SimpleById(9), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - } - - function testImageSubmitButtonWithAdditionalData() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); - } - - function testButtonTag() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $widget = new SimpleButtonTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9')); - $widget->addContent('Go!'); - $form->addWidget($widget); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go'))); - } - - function testMultipleFieldsWithSameNameSubmitted() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '1')); - $form->addWidget($input); - $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '2')); - $form->addWidget($input); - $form->setField(new SimpleByLabelOrName('elements[]'), '3', 1); - $form->setField(new SimpleByLabelOrName('elements[]'), '4', 2); - $submit = $form->submit(); - $requests = $submit->getAll(); - $this->assertEqual(count($requests), 2); - $this->assertIdentical($requests[0], new SimpleEncodedPair('elements[]', '3')); - $this->assertIdentical($requests[1], new SimpleEncodedPair('elements[]', '4')); - } - - function testSingleSelectFieldSubmitted() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $select = new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimpleGetEncoding(array('a' => 'aaa'))); - } - - function testSingleSelectFieldSubmittedWithPost() { - $form = new SimpleForm(new SimpleFormTag(array('method' => 'post')), $this->page('htp://host')); - $select = new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimplePostEncoding(array('a' => 'aaa'))); - } - - function testUnchecked() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'type' => 'checkbox'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'on')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - } - - function testChecked() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), false)); - $this->assertEqual($form->getValue(new SimpleByName('me')), false); - } - - function testSingleUncheckedRadioButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - } - - function testSingleCheckedRadioButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - } - - function testUncheckedRadioButtons() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'c')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - } - - function testCheckedRadioButtons() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - } - - function testMultipleFieldsWithSameKey() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'me'))); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'you'))); - $this->assertIdentical($form->getValue(new SimpleByName('a')), false); - $this->assertTrue($form->setField(new SimpleByName('a'), 'me')); - $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me'); - } - - function testRemoveGetParamsFromAction() { - Mock::generatePartial('SimplePage', 'MockPartialSimplePage', array('getUrl')); - $page = new MockPartialSimplePage(); - $page->returns('getUrl', new SimpleUrl('htp://host/')); - - # Keep GET params in "action", if the form has no widgets - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page); - $form->addWidget(new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a'))); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1', 'method'=>'post')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/?test=1'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/frames_test.php b/application/libraries/simpletest/test/frames_test.php deleted file mode 100644 index 29309700e31..00000000000 --- a/application/libraries/simpletest/test/frames_test.php +++ /dev/null @@ -1,549 +0,0 @@ -setReturnValue('getTitle', 'This page'); - $frameset = new SimpleFrameset($page); - $this->assertEqual($frameset->getTitle(), 'This page'); - } - - function TestHeadersReadFromFramesetByDefault() { - $page = new MockSimplePage(); - $page->setReturnValue('getHeaders', 'Header: content'); - $page->setReturnValue('getMimeType', 'text/xml'); - $page->setReturnValue('getResponseCode', 401); - $page->setReturnValue('getTransportError', 'Could not parse headers'); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Safe place'); - - $frameset = new SimpleFrameset($page); - - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testEmptyFramesetHasNoContent() { - $page = new MockSimplePage(); - $page->setReturnValue('getRaw', 'This content'); - $frameset = new SimpleFrameset($page); - $this->assertEqual($frameset->getRaw(), ''); - } - - function testRawContentIsFromOnlyFrame() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - } - - function testRawContentIsFromAllFrames() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testTextContentIsFromOnlyFrame() { - $page = new MockSimplePage(); - $page->expectNever('getText'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getText', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getText(), 'Stuff'); - } - - function testTextContentIsFromAllFrames() { - $page = new MockSimplePage(); - $page->expectNever('getText'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getText', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getText', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2'); - } - - function testFieldFoundIsFirstInFramelist() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getField', null); - $frame1->expectOnce('getField', array(new SimpleByName('a'))); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getField', 'A'); - $frame2->expectOnce('getField', array(new SimpleByName('a'))); - - $frame3 = new MockSimplePage(); - $frame3->expectNever('getField'); - - $page = new MockSimplePage(); - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $frameset->addFrame($frame3); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'A'); - } - - function testFrameReplacementByIndex() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->setFrame(array(1), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } - - function testFrameReplacementByName() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1, 'a'); - $frameset->setFrame(array('a'), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } -} - -class TestOfFrameNavigation extends UnitTestCase { - - function testStartsWithoutFrameFocus() { - $page = new MockSimplePage(); - $frameset = new SimpleFrameset($page); - $frameset->addFrame(new MockSimplePage()); - $this->assertFalse($frameset->getFrameFocus()); - } - - function testCanFocusOnSingleFrame() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getFrameFocus', array()); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - - $this->assertFalse($frameset->setFrameFocusByIndex(0)); - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - $this->assertFalse($frameset->setFrameFocusByIndex(2)); - $this->assertIdentical($frameset->getFrameFocus(), array(1)); - } - - function testContentComesFromFrameInFocus() { - $page = new MockSimplePage(); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getFrameFocus(), array(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocusByIndex(3)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testCanFocusByName() { - $page = new MockSimplePage(); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - - $this->assertTrue($frameset->setFrameFocus('A')); - $this->assertEqual($frameset->getFrameFocus(), array('A')); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array('B')); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocus('z')); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } -} - -class TestOfFramesetPageInterface extends UnitTestCase { - private $page_interface; - private $frameset_interface; - - function __construct() { - parent::__construct(); - $this->page_interface = $this->getPageMethods(); - $this->frameset_interface = $this->getFramesetMethods(); - } - - function assertListInAnyOrder($list, $expected) { - sort($list); - sort($expected); - $this->assertEqual($list, $expected); - } - - private function getPageMethods() { - $methods = array(); - foreach (get_class_methods('SimplePage') as $method) { - if (strtolower($method) == strtolower('SimplePage')) { - continue; - } - if (strtolower($method) == strtolower('getFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (in_array($method, array('setTitle', 'setBase', 'setForms', 'normalise', 'setFrames', 'addLink'))) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - private function getFramesetMethods() { - $methods = array(); - foreach (get_class_methods('SimpleFrameset') as $method) { - if (strtolower($method) == strtolower('SimpleFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (strncmp($method, 'add', 3) == 0) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - function testFramsetHasPageInterface() { - $difference = array(); - foreach ($this->page_interface as $method) { - if (! in_array($method, $this->frameset_interface)) { - $this->fail("No [$method] in Frameset class"); - return; - } - } - $this->pass('Frameset covers Page interface'); - } - - function testHeadersReadFromFrameIfInFocus() { - $frame = new MockSimplePage(); - $frame->setReturnValue('getUrl', new SimpleUrl('http://localhost/stuff')); - - $frame->setReturnValue('getRequest', 'POST stuff'); - $frame->setReturnValue('getMethod', 'POST'); - $frame->setReturnValue('getRequestData', array('a' => 'A')); - $frame->setReturnValue('getHeaders', 'Header: content'); - $frame->setReturnValue('getMimeType', 'text/xml'); - $frame->setReturnValue('getResponseCode', 401); - $frame->setReturnValue('getTransportError', 'Could not parse headers'); - $frame->setReturnValue('getAuthentication', 'Basic'); - $frame->setReturnValue('getRealm', 'Safe place'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame); - $frameset->setFrameFocusByIndex(1); - - $url = new SimpleUrl('http://localhost/stuff'); - $url->setTarget(1); - $this->assertIdentical($frameset->getUrl(), $url); - - $this->assertIdentical($frameset->getRequest(), 'POST stuff'); - $this->assertIdentical($frameset->getMethod(), 'POST'); - $this->assertIdentical($frameset->getRequestData(), array('a' => 'A')); - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testUrlsComeFromBothFrames() { - $page = new MockSimplePage(); - $page->expectNever('getUrls'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://myserver/')); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://test/')); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertListInAnyOrder( - $frameset->getUrls(), - array('http://www.lastcraft.com/', 'http://myserver/', 'http://test/')); - } - - function testLabelledUrlsComeFromBothFrames() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('goodbye.php')), - array('a')); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('hello.php')), - array('a')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2, 'Two'); - - $expected1 = new SimpleUrl('goodbye.php'); - $expected1->setTarget(1); - $expected2 = new SimpleUrl('hello.php'); - $expected2->setTarget('Two'); - $this->assertEqual( - $frameset->getUrlsByLabel('a'), - array($expected1, $expected2)); - } - - function testUrlByIdComesFromFirstFrameToRespond() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4)); - $frame1->setReturnValue('getUrlById', false, array(5)); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getUrlById', false, array(4)); - $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5)); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $four = new SimpleUrl('four.php'); - $four->setTarget(1); - $this->assertEqual($frameset->getUrlById(4), $four); - $five = new SimpleUrl('five.php'); - $five->setTarget(2); - $this->assertEqual($frameset->getUrlById(5), $five); - } - - function testReadUrlsFromFrameInFocus() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getUrls', array('a')); - $frame1->setReturnValue('getUrlsByLabel', array(new SimpleUrl('l'))); - $frame1->setReturnValue('getUrlById', new SimpleUrl('i')); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('getUrls'); - $frame2->expectNever('getUrlsByLabel'); - $frame2->expectNever('getUrlById'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrls(), array('a')); - $expected = new SimpleUrl('l'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($expected)); - $expected = new SimpleUrl('i'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlById(99), $expected); - } - - function testReadFrameTaggedUrlsFromFrameInFocus() { - $frame = new MockSimplePage(); - - $by_label = new SimpleUrl('l'); - $by_label->setTarget('L'); - $frame->setReturnValue('getUrlsByLabel', array($by_label)); - - $by_id = new SimpleUrl('i'); - $by_id->setTarget('I'); - $frame->setReturnValue('getUrlById', $by_id); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame, 'A'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label)); - $this->assertIdentical($frameset->getUrlById(99), $by_id); - } - - function testFindingFormsById() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns('getFormById', $form, array('a')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormById('a'), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormById('a')); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormById('a'), $form); - } - - function testFindingFormsBySubmit() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns( - 'getFormBySubmit', - $form, - array(new SimpleByLabel('a'))); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormBySubmit(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - } - - function testFindingFormsByImage() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns( - 'getFormByImage', - $form, - array(new SimpleByLabel('a'))); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormByImage(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form); - } - - function testSettingAllFrameFieldsWhenNoFrameFocus() { - $frame1 = new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frame2 = new MockSimplePage(); - $frame2->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setField(new SimpleById(22), 'A'); - } - - function testOnlySettingFieldFromFocusedFrame() { - $frame1 = new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleByLabelOrName('a'), 'A')); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('setField'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $frameset->setField(new SimpleByLabelOrName('a'), 'A'); - } - - function testOnlyGettingFieldFromFocusedFrame() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getField', 'f', array(new SimpleByName('a'))); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('getField'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'f'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/http_test.php b/application/libraries/simpletest/test/http_test.php deleted file mode 100644 index bd3fdd0d028..00000000000 --- a/application/libraries/simpletest/test/http_test.php +++ /dev/null @@ -1,492 +0,0 @@ -expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('GET', 15), $socket); - } - - function testDefaultPostRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("POST /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - - $route->createConnection('POST', 15); - } - - function testDefaultDeleteRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("DELETE /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('DELETE', 15), $socket); - } - - function testDefaultHeadRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("HEAD /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('HEAD', 15), $socket); - } - - function testGetWithPort() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host:81\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host:81/here.html')); - - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2')); - - $route->createConnection('GET', 15); - } -} - -class TestOfProxyRoute extends UnitTestCase { - - function testDefaultGet() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testDefaultPost() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("POST http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('POST', 15); - } - - function testGetWithPort() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host:81/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8081\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host:81/here.html'), - new SimpleUrl('http://my-proxy:8081')); - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testGetWithAuthentication() { - $encoded = base64_encode('Me:Secret'); - - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Proxy-Authorization: Basic $encoded\r\n")); - $socket->expectAt(3, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 4); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy'), - 'Me', - 'Secret'); - $route->createConnection('GET', 15); - } -} - -class TestOfHttpRequest extends UnitTestCase { - - function testReadingBadConnection() { - $socket = new MockSimpleSocket(); - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $reponse = $request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = new MockSimpleSocket(); - $socket->expectOnce('write', array("\r\n")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('GET', 15)); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testWritingAdditionalHeaders() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("My: stuff\r\n")); - $socket->expectAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->addHeaderLine('My: stuff'); - $request->fetch(15); - } - - function testCookieWriting() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Cookie: a=A\r\n")); - $socket->expectAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testMultipleCookieWriting() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Cookie: a=A;b=B\r\n")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - $jar->setCookie('b', 'B'); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $request->fetch(15); - } - - function testReadingDeleteConnection() { - $socket = new MockSimpleSocket(); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('DELETE', 15)); - - $request = new SimpleHttpRequest($route, new SimpleDeleteEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpPostRequest extends UnitTestCase { - - function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() { - $socket = new MockSimpleSocket(); - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $request = new SimpleHttpRequest($route, new SimplePostEncoding()); - $reponse = $request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest($route, new SimplePostEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithUrlEncodedParams() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 3\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("a=A")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding(array('a' => 'A'))); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithRawEntityBody() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 8\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("raw body")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding('raw body')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithXmlEntityBody() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 27\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/xml\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("onetwo")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding('onetwo', 'text/xml')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpHeaders extends UnitTestCase { - - function testParseBasicHeaders() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - } - - function testNonStandardResponseHeader() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 302 (HTTP-Version SP Status-Code CRLF)\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 302); - } - - function testCanParseMultipleCookies() { - $jar = new MockSimpleCookieJar(); - $jar->expectAt(0, 'setCookie', array('a', 'aaa', 'host', '/here/', 'Wed, 25 Dec 2002 04:24:20 GMT')); - $jar->expectAt(1, 'setCookie', array('b', 'bbb', 'host', '/', false)); - - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n" . - "Set-Cookie: b=bbb\r\n" . - "Connection: close"); - $headers->writeCookiesToJar($jar, new SimpleUrl('http://host')); - } - - function testCanRecogniseRedirect() { - $headers = new SimpleHttpHeaders("HTTP/1.1 301 OK\r\n" . - "Content-Type: text/plain\r\n" . - "Content-Length: 0\r\n" . - "Location: http://www.somewhere-else.com/\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 301); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - $this->assertTrue($headers->isRedirect()); - } - - function testCanParseChallenge() { - $headers = new SimpleHttpHeaders("HTTP/1.1 401 Authorization required\r\n" . - "Content-Type: text/plain\r\n" . - "Connection: close\r\n" . - "WWW-Authenticate: Basic realm=\"Somewhere\""); - $this->assertEqual($headers->getAuthentication(), 'Basic'); - $this->assertEqual($headers->getRealm(), 'Somewhere'); - $this->assertTrue($headers->isChallenge()); - } -} - -class TestOfHttpResponse extends UnitTestCase { - - function testBadRequest() { - $socket = new MockSimpleSocket(); - $socket->setReturnValue('getSent', ''); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertPattern('/Nothing fetched/', $response->getError()); - $this->assertIdentical($response->getContent(), false); - $this->assertIdentical($response->getSent(), ''); - } - - function testBadSocketDuringResponse() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValue("read", ""); - $socket->setReturnValue('getSent', 'HTTP/1.1 ...'); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ''); - $this->assertEqual($response->getSent(), 'HTTP/1.1 ...'); - } - - function testIncompleteHeader() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ""); - } - - function testParseOfResponseHeadersWhenChunked() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\nDate: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\nConne"); - $socket->setReturnValueAt(3, "read", "ction: close\r\n\r\nthis is a test file\n"); - $socket->setReturnValueAt(4, "read", "with two lines in it\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertFalse($response->isError()); - $this->assertEqual( - $response->getContent(), - "this is a test file\nwith two lines in it\n"); - $headers = $response->getHeaders(); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - $this->assertFalse($headers->isRedirect()); - $this->assertFalse($headers->getLocation()); - } - - function testRedirect() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - } - - function testRedirectWithPort() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com:80/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/"); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/interfaces_test.php b/application/libraries/simpletest/test/interfaces_test.php deleted file mode 100644 index ab30fe47ff8..00000000000 --- a/application/libraries/simpletest/test/interfaces_test.php +++ /dev/null @@ -1,137 +0,0 @@ -=')) { - include(dirname(__FILE__) . '/interfaces_test_php5_1.php'); -} - -interface DummyInterface { - function aMethod(); - function anotherMethod($a); - function &referenceMethod(&$a); -} - -Mock::generate('DummyInterface'); -Mock::generatePartial('DummyInterface', 'PartialDummyInterface', array()); - -class TestOfMockInterfaces extends UnitTestCase { - - function testCanMockAnInterface() { - $mock = new MockDummyInterface(); - $this->assertIsA($mock, 'SimpleMock'); - $this->assertIsA($mock, 'MockDummyInterface'); - $this->assertTrue(method_exists($mock, 'aMethod')); - $this->assertTrue(method_exists($mock, 'anotherMethod')); - $this->assertNull($mock->aMethod()); - } - - function testMockedInterfaceExpectsParameters() { - $mock = new MockDummyInterface(); - $this->expectError(); - $mock->anotherMethod(); - } - - function testCannotPartiallyMockAnInterface() { - $this->assertFalse(class_exists('PartialDummyInterface')); - } -} - -class TestOfSpl extends UnitTestCase { - - function skip() { - $this->skipUnless(function_exists('spl_classes'), 'No SPL module loaded'); - } - - function testCanMockAllSplClasses() { - if (! function_exists('spl_classes')) { - return; - } - foreach(spl_classes() as $class) { - if ($class == 'SplHeap' or $class = 'SplFileObject') { - continue; - } - if (version_compare(PHP_VERSION, '5.1', '<') && - $class == 'CachingIterator' || - $class == 'CachingRecursiveIterator' || - $class == 'FilterIterator' || - $class == 'LimitIterator' || - $class == 'ParentIterator') { - // These iterators require an iterator be passed to them during - // construction in PHP 5.0; there is no way for SimpleTest - // to supply such an iterator, however, so support for it is - // disabled. - continue; - } - $mock_class = "Mock$class"; - Mock::generate($class); - $this->assertIsA(new $mock_class(), $mock_class); - } - } - - function testExtensionOfCommonSplClasses() { - Mock::generate('IteratorImplementation'); - $this->assertIsA( - new IteratorImplementation(), - 'IteratorImplementation'); - Mock::generate('IteratorAggregateImplementation'); - $this->assertIsA( - new IteratorAggregateImplementation(), - 'IteratorAggregateImplementation'); - } -} - -class WithHint { - function hinted(DummyInterface $object) { } -} - -class ImplementsDummy implements DummyInterface { - function aMethod() { } - function anotherMethod($a) { } - function &referenceMethod(&$a) { } - function extraMethod($a = false) { } -} -Mock::generate('ImplementsDummy'); - -class TestOfImplementations extends UnitTestCase { - - function testMockedInterfaceCanPassThroughTypeHint() { - $mock = new MockDummyInterface(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testImplementedInterfacesAreCarried() { - $mock = new MockImplementsDummy(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testNoSpuriousWarningsWhenSkippingDefaultedParameter() { - $mock = new MockImplementsDummy(); - $mock->extraMethod(); - } -} - -interface SampleInterfaceWithConstruct { - function __construct($something); -} - -class TestOfInterfaceMocksWithConstruct extends UnitTestCase { - function TODO_testBasicConstructOfAnInterface() { // Fails in PHP 5.3dev - Mock::generate('SampleInterfaceWithConstruct'); - } -} - -interface SampleInterfaceWithClone { - function __clone(); -} - -class TestOfSampleInterfaceWithClone extends UnitTestCase { - function testCanMockWithoutErrors() { - Mock::generate('SampleInterfaceWithClone'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/interfaces_test_php5_1.php b/application/libraries/simpletest/test/interfaces_test_php5_1.php deleted file mode 100644 index 3d154f99539..00000000000 --- a/application/libraries/simpletest/test/interfaces_test_php5_1.php +++ /dev/null @@ -1,14 +0,0 @@ -assertIsA($mock, 'SampleInterfaceWithHintInSignature'); - } -} - diff --git a/application/libraries/simpletest/test/live_test.php b/application/libraries/simpletest/test/live_test.php deleted file mode 100644 index 3fbb54499d3..00000000000 --- a/application/libraries/simpletest/test/live_test.php +++ /dev/null @@ -1,47 +0,0 @@ -assertTrue($socket->isError()); - $this->assertPattern( - '/Cannot open \\[bad_url:111\\] with \\[/', - $socket->getError()); - $this->assertFalse($socket->isOpen()); - $this->assertFalse($socket->write('A message')); - } - - function testSocketClosure() { - $socket = new SimpleSocket('www.lastcraft.com', 80, 15, 8); - $this->assertTrue($socket->isOpen()); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $this->assertEqual($socket->read(), "HTTP/1.1"); - $socket->close(); - $this->assertIdentical($socket->read(), false); - } - - function testRecordOfSentCharacters() { - $socket = new SimpleSocket('www.lastcraft.com', 80, 15); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $socket->close(); - $this->assertEqual($socket->getSent(), - "GET /test/network_confirm.php HTTP/1.0\r\n" . - "Host: www.lastcraft.com\r\n" . - "Connection: close\r\n\r\n"); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/mock_objects_test.php b/application/libraries/simpletest/test/mock_objects_test.php deleted file mode 100644 index 7f3178995a7..00000000000 --- a/application/libraries/simpletest/test/mock_objects_test.php +++ /dev/null @@ -1,985 +0,0 @@ -assertTrue($expectation->test(33)); - $this->assertTrue($expectation->test(false)); - $this->assertTrue($expectation->test(null)); - } -} - -class TestOfParametersExpectation extends UnitTestCase { - - function testEmptyMatch() { - $expectation = new ParametersExpectation(array()); - $this->assertTrue($expectation->test(array())); - $this->assertFalse($expectation->test(array(33))); - } - - function testSingleMatch() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array(1))); - $this->assertTrue($expectation->test(array(0))); - } - - function testAnyMatch() { - $expectation = new ParametersExpectation(false); - $this->assertTrue($expectation->test(array())); - $this->assertTrue($expectation->test(array(1, 2))); - } - - function testMissingParameter() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array())); - } - - function testNullParameter() { - $expectation = new ParametersExpectation(array(null)); - $this->assertTrue($expectation->test(array(null))); - $this->assertFalse($expectation->test(array())); - } - - function testAnythingExpectations() { - $expectation = new ParametersExpectation(array(new AnythingExpectation())); - $this->assertFalse($expectation->test(array())); - $this->assertIdentical($expectation->test(array(null)), true); - $this->assertIdentical($expectation->test(array(13)), true); - } - - function testOtherExpectations() { - $expectation = new ParametersExpectation( - array(new PatternExpectation('/hello/i'))); - $this->assertFalse($expectation->test(array('Goodbye'))); - $this->assertTrue($expectation->test(array('hello'))); - $this->assertTrue($expectation->test(array('Hello'))); - } - - function testIdentityOnly() { - $expectation = new ParametersExpectation(array("0")); - $this->assertFalse($expectation->test(array(0))); - $this->assertTrue($expectation->test(array("0"))); - } - - function testLongList() { - $expectation = new ParametersExpectation( - array("0", 0, new AnythingExpectation(), false)); - $this->assertTrue($expectation->test(array("0", 0, 37, false))); - $this->assertFalse($expectation->test(array("0", 0, 37, true))); - $this->assertFalse($expectation->test(array("0", 0, 37))); - } -} - -class TestOfSimpleSignatureMap extends UnitTestCase { - - function testEmpty() { - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch("any", array())); - $this->assertNull($map->findFirstAction("any", array())); - } - - function testDifferentCallSignaturesCanHaveDifferentReferences() { - $map = new SimpleSignatureMap(); - $fred = 'Fred'; - $jim = 'jim'; - $map->add(array(0), $fred); - $map->add(array('0'), $jim); - $this->assertSame($fred, $map->findFirstAction(array(0))); - $this->assertSame($jim, $map->findFirstAction(array('0'))); - } - - function testWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $map->add(array(new AnythingExpectation(), 1, 3), $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testAllWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch(array(2, 1, 3))); - $map->add('', $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testOrdering() { - $map = new SimpleSignatureMap(); - $map->add(array(1, 2), new SimpleByValue("1, 2")); - $map->add(array(1, 3), new SimpleByValue("1, 3")); - $map->add(array(1), new SimpleByValue("1")); - $map->add(array(1, 4), new SimpleByValue("1, 4")); - $map->add(array(new AnythingExpectation()), new SimpleByValue("Any")); - $map->add(array(2), new SimpleByValue("2")); - $map->add("", new SimpleByValue("Default")); - $map->add(array(), new SimpleByValue("None")); - $this->assertEqual($map->findFirstAction(array(1, 2)), new SimpleByValue("1, 2")); - $this->assertEqual($map->findFirstAction(array(1, 3)), new SimpleByValue("1, 3")); - $this->assertEqual($map->findFirstAction(array(1, 4)), new SimpleByValue("1, 4")); - $this->assertEqual($map->findFirstAction(array(1)), new SimpleByValue("1")); - $this->assertEqual($map->findFirstAction(array(2)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array(3)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array()), new SimpleByValue("Default")); - } -} - -class TestOfCallSchedule extends UnitTestCase { - function testCanBeSetToAlwaysReturnTheSameReference() { - $a = 5; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByReference($a)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $a); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $a); - } - - function testSpecificSignaturesOverrideTheAlwaysCase() { - $any = 'any'; - $one = 'two'; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', array(1), new SimpleByReference($one)); - $schedule->register('aMethod', false, new SimpleByReference($any)); - $this->assertReference($schedule->respond(0, 'aMethod', array(2)), $any); - $this->assertReference($schedule->respond(0, 'aMethod', array(1)), $one); - } - - function testReturnsCanBeSetOverTime() { - $one = 'one'; - $two = 'two'; - $schedule = new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - } - - function testReturnsOverTimecanBeAlteredByTheArguments() { - $one = '1'; - $two = '2'; - $two_a = '2a'; - $schedule = new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', array('a'), new SimpleByReference($two_a)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - $this->assertReference($schedule->respond(1, 'aMethod', array('a')), $two_a); - } - - function testCanReturnByValue() { - $a = 5; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByValue($a)); - $this->assertCopy($schedule->respond(0, 'aMethod', array()), $a); - } - - function testCanThrowException() { - if (version_compare(phpversion(), '5', '>=')) { - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleThrower(new Exception('Ouch'))); - $this->expectException(new Exception('Ouch')); - $schedule->respond(0, 'aMethod', array()); - } - } - - function testCanEmitError() { - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleErrorThrower('Ouch', E_USER_WARNING)); - $this->expectError('Ouch'); - $schedule->respond(0, 'aMethod', array()); - } -} - -class Dummy { - function Dummy() { - } - - function aMethod() { - return true; - } - - function &aReferenceMethod() { - return true; - } - - function anotherMethod() { - return true; - } -} -Mock::generate('Dummy'); -Mock::generate('Dummy', 'AnotherMockDummy'); -Mock::generate('Dummy', 'MockDummyWithExtraMethods', array('extraMethod')); - -class TestOfMockGeneration extends UnitTestCase { - - function testCloning() { - $mock = new MockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - $this->assertNull($mock->aMethod()); - } - - function testCloningWithExtraMethod() { - $mock = new MockDummyWithExtraMethods(); - $this->assertTrue(method_exists($mock, "extraMethod")); - } - - function testCloningWithChosenClassName() { - $mock = new AnotherMockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - } -} - -class TestOfMockReturns extends UnitTestCase { - - function testDefaultReturn() { - $mock = new MockDummy(); - $mock->returnsByValue("aMethod", "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - } - - function testParameteredReturn() { - $mock = new MockDummy(); - $mock->returnsByValue('aMethod', 'aaa', array(1, 2, 3)); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(1, 2, 3), 'aaa'); - } - - function testSetReturnGivesObjectReference() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returns('aMethod', $object, array(1, 2, 3)); - $this->assertSame($mock->aMethod(1, 2, 3), $object); - } - - function testSetReturnReferenceGivesOriginalReference() { - $mock = new MockDummy(); - $object = 1; - $mock->returnsByReference('aReferenceMethod', $object, array(1, 2, 3)); - $this->assertReference($mock->aReferenceMethod(1, 2, 3), $object); - } - - function testReturnValueCanBeChosenJustByPatternMatchingArguments() { - $mock = new MockDummy(); - $mock->returnsByValue( - "aMethod", - "aaa", - array(new PatternExpectation('/hello/i'))); - $this->assertIdentical($mock->aMethod('Hello'), 'aaa'); - $this->assertNull($mock->aMethod('Goodbye')); - } - - function testMultipleMethods() { - $mock = new MockDummy(); - $mock->returnsByValue("aMethod", 100, array(1)); - $mock->returnsByValue("aMethod", 200, array(2)); - $mock->returnsByValue("anotherMethod", 10, array(1)); - $mock->returnsByValue("anotherMethod", 20, array(2)); - $this->assertIdentical($mock->aMethod(1), 100); - $this->assertIdentical($mock->anotherMethod(1), 10); - $this->assertIdentical($mock->aMethod(2), 200); - $this->assertIdentical($mock->anotherMethod(2), 20); - } - - function testReturnSequence() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa"); - $mock->returnsByValueAt(1, "aMethod", "bbb"); - $mock->returnsByValueAt(3, "aMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(), "ddd"); - } - - function testSetReturnReferenceAtGivesOriginal() { - $mock = new MockDummy(); - $object = 100; - $mock->returnsByReferenceAt(1, "aReferenceMethod", $object); - $this->assertNull($mock->aReferenceMethod()); - $this->assertReference($mock->aReferenceMethod(), $object); - $this->assertNull($mock->aReferenceMethod()); - } - - function testReturnsAtGivesOriginalObjectHandle() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returnsAt(1, "aMethod", $object); - $this->assertNull($mock->aMethod()); - $this->assertSame($mock->aMethod(), $object); - $this->assertNull($mock->aMethod()); - } - - function testComplicatedReturnSequence() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returnsAt(1, "aMethod", "aaa", array("a")); - $mock->returnsAt(1, "aMethod", "bbb"); - $mock->returnsAt(2, "aMethod", $object, array('*', 2)); - $mock->returnsAt(2, "aMethod", "value", array('*', 3)); - $mock->returns("aMethod", 3, array(3)); - $this->assertNull($mock->aMethod()); - $this->assertEqual($mock->aMethod("a"), "aaa"); - $this->assertSame($mock->aMethod(1, 2), $object); - $this->assertEqual($mock->aMethod(3), 3); - $this->assertNull($mock->aMethod()); - } - - function testMultipleMethodSequences() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa"); - $mock->returnsByValueAt(1, "aMethod", "bbb"); - $mock->returnsByValueAt(0, "anotherMethod", "ccc"); - $mock->returnsByValueAt(1, "anotherMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->anotherMethod(), "ccc"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertIdentical($mock->anotherMethod(), "ddd"); - } - - function testSequenceFallback() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa", array('a')); - $mock->returnsByValueAt(1, "aMethod", "bbb", array('a')); - $mock->returnsByValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod('a'), "aaa"); - $this->assertIdentical($mock->aMethod('b'), "AAA"); - } - - function testMethodInterference() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "anotherMethod", "aaa"); - $mock->returnsByValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod(), "AAA"); - $this->assertIdentical($mock->anotherMethod(), "aaa"); - } -} - -class TestOfMockExpectationsThatPass extends UnitTestCase { - - function testAnyArgument() { - $mock = new MockDummy(); - $mock->expect('aMethod', array('*')); - $mock->aMethod(1); - $mock->aMethod('hello'); - } - - function testAnyTwoArguments() { - $mock = new MockDummy(); - $mock->expect('aMethod', array('*', '*')); - $mock->aMethod(1, 2); - } - - function testSpecificArgument() { - $mock = new MockDummy(); - $mock->expect('aMethod', array(1)); - $mock->aMethod(1); - } - - function testExpectation() { - $mock = new MockDummy(); - $mock->expect('aMethod', array(new IsAExpectation('Dummy'))); - $mock->aMethod(new Dummy()); - } - - function testArgumentsInSequence() { - $mock = new MockDummy(); - $mock->expectAt(0, 'aMethod', array(1, 2)); - $mock->expectAt(1, 'aMethod', array(3, 4)); - $mock->aMethod(1, 2); - $mock->aMethod(3, 4); - } - - function testAtLeastOnceSatisfiedByOneCall() { - $mock = new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - } - - function testAtLeastOnceSatisfiedByTwoCalls() { - $mock = new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - } - - function testOnceSatisfiedByOneCall() { - $mock = new MockDummy(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByEnoughCalls() { - $mock = new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByTooManyCalls() { - $mock = new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 3); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByEnoughCalls() { - $mock = new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByNoCalls() { - $mock = new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - } -} - -class MockWithInjectedTestCase extends SimpleMock { - protected function getCurrentTestCase() { - return SimpleTest::getContext()->getTest()->getMockedTest(); - } -} -SimpleTest::setMockBaseClass('MockWithInjectedTestCase'); -Mock::generate('Dummy', 'MockDummyWithInjectedTestCase'); -SimpleTest::setMockBaseClass('SimpleMock'); -Mock::generate('SimpleTestCase'); - -class LikeExpectation extends IdenticalExpectation { - function __construct($expectation) { - $expectation->message = ''; - parent::__construct($expectation); - } - - function test($compare) { - $compare->message = ''; - return parent::test($compare); - } - - function testMessage($compare) { - $compare->message = ''; - return parent::testMessage($compare); - } -} - -class TestOfMockExpectations extends UnitTestCase { - private $test; - - function setUp() { - $this->test = new MockSimpleTestCase(); - } - - function getMockedTest() { - return $this->test; - } - - function testSettingExpectationOnNonMethodThrowsError() { - $mock = new MockDummyWithInjectedTestCase(); - $this->expectError(); - $mock->expectMaximumCallCount('aMissingMethod', 2); - } - - function testMaxCallsDetectsOverrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 3)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnMaxCallsSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount("aMethod", 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testExpectNeverDetectsOverrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnExpectNeverStillSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testMinCalls() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMinimumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testFailedNever() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testUnderOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testOverOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testUnderAtLeastOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectAtLeastOnce("aMethod"); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testZeroArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array()), array(), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array()); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testExpectedArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array(1, 2, 3)); - $mock->aMethod(1, 2, 3); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testFailedArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array('this')), array('that'), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array('this')); - $mock->aMethod('that'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testWildcardsAreTranslatedToAnythingExpectations() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', - array(new AnythingExpectation(), - 123, - new AnythingExpectation())), - array(100, 123, 101), '*')); - $mock = new MockDummyWithInjectedTestCase($this); - $mock->expect("aMethod", array('*', 123, '*')); - $mock->aMethod(100, 123, 101); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testSpecificPassingSequence() { - $this->test->expectAt(0, 'assert', - array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*')); - $this->test->expectAt(1, 'assert', - array(new MemberExpectation('expected', array('Hello')), array('Hello'), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectAt(1, 'aMethod', array(1, 2, 3)); - $mock->expectAt(2, 'aMethod', array('Hello')); - $mock->aMethod(); - $mock->aMethod(1, 2, 3); - $mock->aMethod('Hello'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testNonArrayForExpectedParametersGivesError() { - $mock = new MockDummyWithInjectedTestCase(); - $this->expectError(new PatternExpectation('/\$args.*not an array/i')); - $mock->expect("aMethod", "foo"); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } -} - -class TestOfMockComparisons extends UnitTestCase { - - function testEqualComparisonOfMocksDoesNotCrash() { - $expectation = new EqualExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy(), true)); - } - - function testIdenticalComparisonOfMocksDoesNotCrash() { - $expectation = new IdenticalExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy())); - } -} - -class ClassWithSpecialMethods { - function __get($name) { } - function __set($name, $value) { } - function __isset($name) { } - function __unset($name) { } - function __call($method, $arguments) { } - function __toString() { } -} -Mock::generate('ClassWithSpecialMethods'); - -class TestOfSpecialMethodsAfterPHP51 extends UnitTestCase { - - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1', '<'), '__isset and __unset overloading not tested unless PHP 5.1+'); - } - - function testCanEmulateIsset() { - $mock = new MockClassWithSpecialMethods(); - $mock->returnsByValue('__isset', true); - $this->assertIdentical(isset($mock->a), true); - } - - function testCanExpectUnset() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__unset', array('a')); - unset($mock->a); - } - -} - -class TestOfSpecialMethods extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5', '<'), 'Overloading not tested unless PHP 5+'); - } - - function testCanMockTheThingAtAll() { - $mock = new MockClassWithSpecialMethods(); - } - - function testReturnFromSpecialAccessor() { - $mock = new MockClassWithSpecialMethods(); - $mock->returnsByValue('__get', '1st Return', array('first')); - $mock->returnsByValue('__get', '2nd Return', array('second')); - $this->assertEqual($mock->first, '1st Return'); - $this->assertEqual($mock->second, '2nd Return'); - } - - function testcanExpectTheSettingOfValue() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__set', array('a', 'A')); - $mock->a = 'A'; - } - - function testCanSimulateAnOverloadmethod() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__call', array('amOverloaded', array('A'))); - $mock->returnsByValue('__call', 'aaa'); - $this->assertIdentical($mock->amOverloaded('A'), 'aaa'); - } - - function testToStringMagic() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__toString'); - $mock->returnsByValue('__toString', 'AAA'); - ob_start(); - print $mock; - $output = ob_get_contents(); - ob_end_clean(); - $this->assertEqual($output, 'AAA'); - } -} - -class WithStaticMethod { - static function aStaticMethod() { } -} -Mock::generate('WithStaticMethod'); - -class TestOfMockingClassesWithStaticMethods extends UnitTestCase { - - function testStaticMethodIsMockedAsStatic() { - $mock = new WithStaticMethod(); - $reflection = new ReflectionClass($mock); - $method = $reflection->getMethod('aStaticMethod'); - $this->assertTrue($method->isStatic()); - } -} - -class MockTestException extends Exception { } - -class TestOfThrowingExceptionsFromMocks extends UnitTestCase { - - function testCanThrowOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod'); - $this->expectException(); - $mock->aMethod(); - } - - function testCanThrowSpecificExceptionOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException()); - $this->expectException(); - $mock->aMethod(); - } - - function testThrowsOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException(), array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectException(); - $mock->aMethod(3); - } - - function testCanThrowOnParticularInvocation() { - $mock = new MockDummy(); - $mock->throwAt(2, 'aMethod', new MockTestException()); - $mock->aMethod(); - $mock->aMethod(); - $this->expectException(); - $mock->aMethod(); - } -} - -class TestOfThrowingErrorsFromMocks extends UnitTestCase { - - function testCanGenerateErrorFromMethodCall() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!'); - $this->expectError('Ouch!'); - $mock->aMethod(); - } - - function testGeneratesErrorOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!', array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectError(); - $mock->aMethod(3); - } - - function testCanGenerateErrorOnParticularInvocation() { - $mock = new MockDummy(); - $mock->errorAt(2, 'aMethod', 'Ouch!'); - $mock->aMethod(); - $mock->aMethod(); - $this->expectError(); - $mock->aMethod(); - } -} - -Mock::generatePartial('Dummy', 'TestDummy', array('anotherMethod', 'aReferenceMethod')); - -class TestOfPartialMocks extends UnitTestCase { - - function testMethodReplacementWithNoBehaviourReturnsNull() { - $mock = new TestDummy(); - $this->assertEqual($mock->aMethod(99), 99); - $this->assertNull($mock->anotherMethod()); - } - - function testSettingReturns() { - $mock = new TestDummy(); - $mock->returnsByValue('anotherMethod', 33, array(3)); - $mock->returnsByValue('anotherMethod', 22); - $mock->returnsByValueAt(2, 'anotherMethod', 44, array(3)); - $this->assertEqual($mock->anotherMethod(), 22); - $this->assertEqual($mock->anotherMethod(3), 33); - $this->assertEqual($mock->anotherMethod(3), 44); - } - - function testSetReturnReferenceGivesOriginal() { - $mock = new TestDummy(); - $object = 99; - $mock->returnsByReferenceAt(0, 'aReferenceMethod', $object, array(3)); - $this->assertReference($mock->aReferenceMethod(3), $object); - } - - function testReturnsAtGivesOriginalObjectHandle() { - $mock = new TestDummy(); - $object = new Dummy(); - $mock->returnsAt(0, 'anotherMethod', $object, array(3)); - $this->assertSame($mock->anotherMethod(3), $object); - } - - function testExpectations() { - $mock = new TestDummy(); - $mock->expectCallCount('anotherMethod', 2); - $mock->expect('anotherMethod', array(77)); - $mock->expectAt(1, 'anotherMethod', array(66)); - $mock->anotherMethod(77); - $mock->anotherMethod(66); - } - - function testSettingExpectationOnMissingMethodThrowsError() { - $mock = new TestDummy(); - $this->expectError(); - $mock->expectCallCount('aMissingMethod', 2); - } -} - -class ConstructorSuperClass { - function ConstructorSuperClass() { } -} - -class ConstructorSubClass extends ConstructorSuperClass { } - -class TestOfPHP4StyleSuperClassConstruct extends UnitTestCase { - function testBasicConstruct() { - Mock::generate('ConstructorSubClass'); - $mock = new MockConstructorSubClass(); - $this->assertIsA($mock, 'ConstructorSubClass'); - $this->assertTrue(method_exists($mock, 'ConstructorSuperClass')); - } -} - -class TestOfPHP5StaticMethodMocking extends UnitTestCase { - function testCanCreateAMockObjectWithStaticMethodsWithoutError() { - eval(' - class SimpleObjectContainingStaticMethod { - static function someStatic() { } - } - '); - Mock::generate('SimpleObjectContainingStaticMethod'); - } -} - -class TestOfPHP5AbstractMethodMocking extends UnitTestCase { - function testCanCreateAMockObjectFromAnAbstractWithProperFunctionDeclarations() { - eval(' - abstract class SimpleAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - '); - Mock::generate('SimpleAbstractClassContainingAbstractMethods'); - $this->assertTrue( - method_exists( - // Testing with class name alone does not work in PHP 5.0 - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstractWithMultipleParameters' - ) - ); - } - - function testMethodsDefinedAsAbstractInParentShouldHaveFullSignature() { - eval(' - abstract class SimpleParentAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - - class SimpleChildAbstractClassContainingAbstractMethods extends SimpleParentAbstractClassContainingAbstractMethods { - function anAbstract(){} - function anAbstractWithParameter($foo){} - function anAbstractWithMultipleParameters($foo, $bar){} - } - - class EvenDeeperEmptyChildClass extends SimpleChildAbstractClassContainingAbstractMethods {} - '); - Mock::generate('SimpleChildAbstractClassContainingAbstractMethods'); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstractWithMultipleParameters' - ) - ); - Mock::generate('EvenDeeperEmptyChildClass'); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstractWithMultipleParameters' - ) - ); - } -} - -class DummyWithProtected -{ - public function aMethodCallsProtected() { return $this->aProtectedMethod(); } - protected function aProtectedMethod() { return true; } -} - -Mock::generatePartial('DummyWithProtected', 'TestDummyWithProtected', array('aProtectedMethod')); -class TestOfProtectedMethodPartialMocks extends UnitTestCase -{ - function testProtectedMethodExists() { - $this->assertTrue( - method_exists( - new TestDummyWithProtected, - 'aProtectedMethod' - ) - ); - } - - function testProtectedMethodIsCalled() { - $object = new DummyWithProtected(); - $this->assertTrue($object->aMethodCallsProtected(), 'ensure original was called'); - } - - function testMockedMethodIsCalled() { - $object = new TestDummyWithProtected(); - $object->returnsByValue('aProtectedMethod', false); - $this->assertFalse($object->aMethodCallsProtected()); - } -} - -?> diff --git a/application/libraries/simpletest/test/page_test.php b/application/libraries/simpletest/test/page_test.php deleted file mode 100644 index fdc15c5d008..00000000000 --- a/application/libraries/simpletest/test/page_test.php +++ /dev/null @@ -1,166 +0,0 @@ -assertEqual($page->getTransportError(), 'No page fetched yet'); - $this->assertIdentical($page->getRaw(), false); - $this->assertIdentical($page->getHeaders(), false); - $this->assertIdentical($page->getMimeType(), false); - $this->assertIdentical($page->getResponseCode(), false); - $this->assertIdentical($page->getAuthentication(), false); - $this->assertIdentical($page->getRealm(), false); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getUrls(), array()); - $this->assertIdentical($page->getTitle(), false); - } -} - -class TestOfPageHeaders extends UnitTestCase { - - function testUrlAccessor() { - $headers = new MockSimpleHttpHeaders(); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - $response->setReturnValue('getMethod', 'POST'); - $response->setReturnValue('getUrl', new SimpleUrl('here')); - $response->setReturnValue('getRequestData', array('a' => 'A')); - - $page = new SimplePage($response); - $this->assertEqual($page->getMethod(), 'POST'); - $this->assertEqual($page->getUrl(), new SimpleUrl('here')); - $this->assertEqual($page->getRequestData(), array('a' => 'A')); - } - - function testTransportError() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getError', 'Ouch'); - - $page = new SimplePage($response); - $this->assertEqual($page->getTransportError(), 'Ouch'); - } - - function testHeadersAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getRaw', 'My: Headers'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getHeaders(), 'My: Headers'); - } - - function testMimeAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getMimeType', 'text/html'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getMimeType(), 'text/html'); - } - - function testResponseAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getResponseCode', 301); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertIdentical($page->getResponseCode(), 301); - } - - function testAuthenticationAccessors() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getAuthentication', 'Basic'); - $headers->setReturnValue('getRealm', 'Secret stuff'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getAuthentication(), 'Basic'); - $this->assertEqual($page->getRealm(), 'Secret stuff'); - } -} - -class TestOfHtmlStrippingAndNormalisation extends UnitTestCase { - - function testImageSuppressionWhileKeepingParagraphsAndAltText() { - $this->assertEqual( - SimplePage::normalise('

some text

bar'), - 'some text bar'); - } - - function testSpaceNormalisation() { - $this->assertEqual( - SimplePage::normalise("\nOne\tTwo \nThree\t"), - 'One Two Three'); - } - - function testMultilinesCommentSuppression() { - $this->assertEqual( - SimplePage::normalise(''), - ''); - } - - function testCommentSuppression() { - $this->assertEqual( - SimplePage::normalise(''), - ''); - } - - function testJavascriptSuppression() { - $this->assertEqual( - SimplePage::normalise(''), - ''); - $this->assertEqual( - SimplePage::normalise(''), - ''); - $this->assertEqual( - SimplePage::normalise(''), - ''); - } - - function testTagSuppression() { - $this->assertEqual( - SimplePage::normalise('Hello'), - 'Hello'); - } - - function testAdjoiningTagSuppression() { - $this->assertEqual( - SimplePage::normalise('HelloGoodbye'), - 'HelloGoodbye'); - } - - function testExtractImageAltTextWithDifferentQuotes() { - $this->assertEqual( - SimplePage::normalise('One\'Two\'Three'), - 'One Two Three'); - } - - function testExtractImageAltTextMultipleTimes() { - $this->assertEqual( - SimplePage::normalise('OneTwoThree'), - 'One Two Three'); - } - - function testHtmlEntityTranslation() { - $this->assertEqual( - SimplePage::normalise('<>"&''), - '<>"&\''); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/parse_error_test.php b/application/libraries/simpletest/test/parse_error_test.php deleted file mode 100644 index c3ffb3d4205..00000000000 --- a/application/libraries/simpletest/test/parse_error_test.php +++ /dev/null @@ -1,9 +0,0 @@ -addFile('test_with_parse_error.php'); -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/parsing_test.php b/application/libraries/simpletest/test/parsing_test.php deleted file mode 100644 index 2c5e6cafe1d..00000000000 --- a/application/libraries/simpletest/test/parsing_test.php +++ /dev/null @@ -1,642 +0,0 @@ -whenVisiting('http://host/', 'Raw HTML'); - $this->assertEqual($page->getRaw(), 'Raw HTML'); - } - - function testTextAccessor() { - $page = $this->whenVisiting('http://host/', 'Some "messy" HTML'); - $this->assertEqual($page->getText(), 'Some "messy" HTML'); - } - - function testFramesetAbsence() { - $page = $this->whenVisiting('http://here/', ''); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), false); - } - - function testPageWithNoUrlsGivesEmptyArrayOfLinks() { - $page = $this->whenVisiting('http://here/', '

Stuff

'); - $this->assertIdentical($page->getUrls(), array()); - } - - function testAddAbsoluteLink() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testUrlLabelsHaveHtmlTagsStripped() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testAddStrictRelativeLink() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddBareRelativeLink() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddRelativeLinkWithBaseTag() { - $raw = '' . - 'Label' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://www.lastcraft.com/stuff/somewhere.php'))); - } - - function testAddAbsoluteLinkWithBaseTag() { - $raw = '' . - 'Label' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://here.com/somewhere.php'))); - } - - function testCanFindLinkInsideForm() { - $raw = '
Label
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testCanGetLinksByIdOrLabel() { - $raw = 'Label'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - $this->assertFalse($page->getUrlById(0)); - $this->assertEqual( - $page->getUrlById(33), - new SimpleUrl('http://host/somewhere.php')); - } - - function testCanFindLinkByNormalisedLabel() { - $raw = 'Long & thin'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Long & thin'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testCanFindLinkByImageAltText() { - $raw = '<A picture>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - array_map(array($this, 'urlToString'), $page->getUrlsByLabel('')), - array('http://host/somewhere.php')); - } - - function testTitle() { - $page = $this->whenVisiting('http://host', - 'Me'); - $this->assertEqual($page->getTitle(), 'Me'); - } - - function testTitleWithEntityReference() { - $page = $this->whenVisiting('http://host', - 'Me&Me'); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testOnlyFramesInFramesetAreRecognised() { - $raw = - '' . - ' ' . - ' ' . - '' . - ''; - $page = $this->whenVisiting('http://here', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertSameFrameset($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/2.html'), - 2 => new SimpleUrl('http://here/3.html'))); - } - - function testReadsNamesInFrames() { - $raw = - '' . - ' ' . - ' ' . - ' ' . - ' ' . - ''; - $page = $this->whenVisiting('http://here', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertSameFrameset($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/1.html'), - 'A' => new SimpleUrl('http://here/2.html'), - 'B' => new SimpleUrl('http://here/3.html'), - 4 => new SimpleUrl('http://here/4.html'))); - } - - function testRelativeFramesRespectBaseTag() { - $raw = ''; - $page = $this->whenVisiting('http://here', $raw); - $this->assertSameFrameset( - $page->getFrameset(), - array(1 => new SimpleUrl('https://there.com/stuff/1.html'))); - } - - function testSingleFrameInNestedFrameset() { - $raw = '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical( - $page->getFrameset(), - array(1 => new SimpleUrl('http://host/a.html'))); - } - - function testFramesCollectedWithNestedFramesetTags() { - $raw = '' . - '' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - 2 => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'))); - } - - function testNamedFrames() { - $raw = '' . - '' . - '' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - '_one' => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'), - '_two' => new SimpleUrl('http://host/d.html'))); - } - - function testCanReadElementOfCompleteForm() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testCanReadElementOfUnclosedForm() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testCanReadElementByLabel() { - $raw = '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Where')), "Hello"); - } - - function testCanFindFormByLabel() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('submit'))); - $this->assertNull($page->getFormBySubmit(new SimpleByName('submit'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('Submit')), - 'SimpleForm'); - } - - function testConfirmSubmitAttributesAreCaseSensitive() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('S')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('S')), - 'SimpleForm'); - } - - function testCanFindFormByImage() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertIsA( - $page->getFormByImage(new SimpleByLabel('Label')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleByName('me')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleById(100)), - 'SimpleForm'); - } - - function testCanFindFormByButtonTag() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b'))); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('b')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('BBB')), - 'SimpleForm'); - } - - function testCanFindFormById() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormById(54)); - $this->assertIsA($page->getFormById(55), 'SimpleForm'); - } - - function testFormCanBeSubmitted() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $form = $page->getFormBySubmit(new SimpleByLabel('Submit')); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('s' => 'Submit'))); - } - - function testUnparsedTagDoesNotCrash() { - $raw = '
'; - $this->whenVisiting('http://host', $raw); - } - - function testReadingTextField() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testEntitiesAreDecodedInDefaultTextFieldValue() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testReadingTextFieldIsCaseInsensitive() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testSettingTextField() { - $raw = '
' . - '' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - $this->assertTrue($page->setField(new SimpleById(3), 'bbb')); - $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz')); - $this->assertNull($page->getField(new SimpleByName('z'))); - } - - function testSettingTextFieldByEnclosingLabel() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testLabelsWithoutForDoNotAttachToInputsWithNoId() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), 'one'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), 'two'); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text A'), '1')); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text B'), '2')); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), '1'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), '2'); - } - - function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByName('b')), 'B'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - } - - function testSettingTextFieldByExternalLabel() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testReadingTextArea() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testEntitiesAreDecodedInTextareaValue() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testNewlinesPreservedInTextArea() { - $raw = "
"; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), "hello\r\nworld"); - } - - function testWhitespacePreservedInTextArea() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), ' '); - } - - function testComplexWhitespaceInTextArea() { - $raw = "\n" . - " \n" . - " \n" . - "
\n". - " \n" . - "
\n" . - " \n" . - ""; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('c')), " "); - } - - function testSettingTextArea() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA'); - } - - function testDontIncludeTextAreaContentInLabel() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Text area C')), 'mouse'); - } - - function testSettingSelectionField() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc')); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testSelectionOptionsAreNormalised() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'Big bold'); - $this->assertTrue($page->setField(new SimpleByName('a'), 'small italic')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'small italic'); - } - - function testCanParseBlankOptions() { - $raw = '
- -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), '')); - } - - function testTwoSelectionFieldsAreIndependent() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testEmptyOptionDoesNotScrewUpTwoSelectionFields() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testSettingSelectionFieldByEnclosingLabel() { - $raw = '
' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B'); - } - - function testTwoSelectionFieldsWithLabelsAreIndependent() { - $raw = '
- - -
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled D'), 'd2')); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled H'), 'h1')); - $this->assertEqual($page->getField(new SimpleByLabel('Labelled D')), 'd2'); - } - - function testSettingRadioButtonByEnclosingLabel() { - $raw = '
' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a'); - $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b')); - $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b'); - } - - function testCanParseInputsWithAllKindsOfAttributeQuoting() { - $raw = '
' . - '' . - '' . - '' . - '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('first')), 'one'); - $this->assertEqual($page->getField(new SimpleByName('second')), false); - $this->assertEqual($page->getField(new SimpleByName('third')), 'three'); - } - - function urlToString($url) { - return $url->asString(); - } - - function assertSameFrameset($actual, $expected) { - $this->assertIdentical(array_map(array($this, 'urlToString'), $actual), - array_map(array($this, 'urlToString'), $expected)); - } -} - -class TestOfParsingUsingPhpParser extends TestOfParsing { - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimplePhpPageBuilder(); - return $builder->parse($response); - } - - function testNastyTitle() { - $page = $this->whenVisiting('http://host', - ' <b>Me&Me '); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testLabelShouldStopAtClosingLabelTag() { - $raw = '
stuff
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('startend')), 'stuff'); - } -} - -class TestOfParsingUsingTidyParser extends TestOfParsing { - - function skip() { - $this->skipUnless(extension_loaded('tidy'), 'Install \'tidy\' php extension to enable html tidy based parser'); - } - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimpleTidyPageBuilder(); - return $builder->parse($response); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/php_parser_test.php b/application/libraries/simpletest/test/php_parser_test.php deleted file mode 100644 index d95c7d06a60..00000000000 --- a/application/libraries/simpletest/test/php_parser_test.php +++ /dev/null @@ -1,489 +0,0 @@ -assertFalse($regex->match("Hello", $match)); - $this->assertEqual($match, ""); - } - - function testNoSubject() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("", $match)); - $this->assertEqual($match, ""); - } - - function testMatchAll() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("Hello", $match)); - $this->assertEqual($match, "Hello"); - } - - function testCaseSensitive() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "abc"); - } - - function testCaseInsensitive() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - } - - function testMatchMultiple() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $regex->addPattern("ABC"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - $this->assertFalse($regex->match("Hello", $match)); - } - - function testPatternLabels() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc", "letter"); - $regex->addPattern("123", "number"); - $this->assertIdentical($regex->match("abcdef", $match), "letter"); - $this->assertEqual($match, "abc"); - $this->assertIdentical($regex->match("0123456789", $match), "number"); - $this->assertEqual($match, "123"); - } -} - -class TestOfStateStack extends UnitTestCase { - - function testStartState() { - $stack = new SimpleStateStack("one"); - $this->assertEqual($stack->getCurrent(), "one"); - } - - function testExhaustion() { - $stack = new SimpleStateStack("one"); - $this->assertFalse($stack->leave()); - } - - function testStateMoves() { - $stack = new SimpleStateStack("one"); - $stack->enter("two"); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("three"); - $this->assertEqual($stack->getCurrent(), "three"); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("third"); - $this->assertEqual($stack->getCurrent(), "third"); - $this->assertTrue($stack->leave()); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "one"); - } -} - -class TestParser { - - function accept() { - } - - function a() { - } - - function b() { - } -} -Mock::generate('TestParser'); - -class TestOfLexer extends UnitTestCase { - - function testEmptyPage() { - $handler = new MockTestParser(); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("")); - } - - function testSinglePattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(1, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(2, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(3, "accept", array("yyy", LEXER_UNMATCHED)); - $handler->expectAt(4, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(5, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(7, "accept", array("z", LEXER_UNMATCHED)); - $handler->expectCallCount("accept", 8); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); - } - - function testMultiplePattern() { - $handler = new MockTestParser(); - $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); - for ($i = 0; $i < count($target); $i++) { - $handler->expectAt($i, "accept", array($target[$i], '*')); - } - $handler->expectCallCount("accept", count($target)); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $lexer->addPattern("b+"); - $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); - } -} - -class TestOfLexerModes extends UnitTestCase { - - function testIsolatedPattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("bxb", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "a", array("aaaa", LEXER_MATCHED)); - $handler->expectAt(7, "a", array("x", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 8); - $handler->setReturnValue("a", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); - } - - function testModeChange() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(0, "b", array(":", LEXER_ENTER)); - $handler->expectAt(1, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(2, "b", array("b", LEXER_MATCHED)); - $handler->expectAt(3, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(6, "b", array("bbb", LEXER_MATCHED)); - $handler->expectAt(7, "b", array("a", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 5); - $handler->expectCallCount("b", 8); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern(":", "a", "b"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); - } - - function testNesting() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("(", LEXER_ENTER)); - $handler->expectAt(1, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(2, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(3, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(4, "b", array(")", LEXER_EXIT)); - $handler->expectAt(4, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 6); - $handler->expectCallCount("b", 5); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern("(", "a", "b"); - $lexer->addPattern("b+", "b"); - $lexer->addExitPattern(")", "b"); - $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); - } - - function testSingular() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(2, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(3, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("b", LEXER_SPECIAL)); - $handler->expectAt(1, "b", array("bbb", LEXER_SPECIAL)); - $handler->expectCallCount("a", 4); - $handler->expectCallCount("b", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addSpecialPattern("b+", "a", "b"); - $this->assertTrue($lexer->parse("aabaaxxbbbxx")); - } - - function testUnwindTooFar() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array(")", LEXER_EXIT)); - $handler->expectCallCount("a", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addExitPattern(")", "a"); - $this->assertFalse($lexer->parse("aa)aa")); - } -} - -class TestOfLexerHandlers extends UnitTestCase { - - function testModeMapping() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("(", LEXER_ENTER)); - $handler->expectAt(2, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "a", array(")", LEXER_EXIT)); - $handler->expectAt(6, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 7); - $lexer = new SimpleLexer($handler, "mode_a"); - $lexer->addPattern("a+", "mode_a"); - $lexer->addEntryPattern("(", "mode_a", "mode_b"); - $lexer->addPattern("b+", "mode_b"); - $lexer->addExitPattern(")", "mode_b"); - $lexer->mapHandler("mode_a", "a"); - $lexer->mapHandler("mode_b", "a"); - $this->assertTrue($lexer->parse("aa(bbabb)b")); - } -} - -class TestOfSimpleHtmlLexer extends UnitTestCase { - - function &createParser() { - $parser = new MockSimpleHtmlSaxParser(); - $parser->setReturnValue('acceptStartToken', true); - $parser->setReturnValue('acceptEndToken', true); - $parser->setReturnValue('acceptAttributeToken', true); - $parser->setReturnValue('acceptEntityToken', true); - $parser->setReturnValue('acceptTextToken', true); - $parser->setReturnValue('ignore', true); - return $parser; - } - - function testNoContent() { - $parser = $this->createParser(); - $parser->expectNever('acceptStartToken'); - $parser->expectNever('acceptEndToken'); - $parser->expectNever('acceptAttributeToken'); - $parser->expectNever('acceptEntityToken'); - $parser->expectNever('acceptTextToken'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testUninteresting() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testSkipCss() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipJavaScript() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipHtmlComments() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testTagWithNoAttributes() { - $parser = $this->createParser(); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 2); - $parser->expectOnce('acceptTextToken', array('Hello', '*')); - $parser->expectOnce('acceptEndToken', array('', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('Hello')); - } - - function testTagWithAttributes() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('label', '*')); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('href', '*')); - $parser->expectAt(2, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 3); - $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*')); - $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*')); - $parser->expectAt(2, 'acceptAttributeToken', array('"', '*')); - $parser->expectCallCount('acceptAttributeToken', 3); - $parser->expectOnce('acceptEndToken', array('
', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('label')); - } -} - -class TestOfHtmlSaxParser extends UnitTestCase { - - function createListener() { - $listener = new MockSimplePhpPageBuilder(); - $listener->setReturnValue('startElement', true); - $listener->setReturnValue('addContent', true); - $listener->setReturnValue('endElement', true); - return $listener; - } - - function testFramesetTag() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('frameset', array())); - $listener->expectOnce('addContent', array('Frames')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('Frames')); - } - - function testTagWithUnquotedAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('name' => 'a.b.c', 'value' => 'd'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagInsideContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectAt(0, 'addContent', array('')); - $listener->expectAt(1, 'addContent', array('')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagWithInternalContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testLinkAddress() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testEncodedAttribute() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testTagWithId() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('id' => '0'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testTagWithEmptyAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('option', array('value' => '', 'selected' => ''))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('option')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testComplexTagWithLotsOfCaseVariations() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('a', array('href' => 'here.html', 'style' => "'cool'"))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testXhtmlSelfClosingTag() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testNestedFrameInFrameset() { - $listener = $this->createListener(); - $listener->expectAt(0, 'startElement', array('frameset', array())); - $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html'))); - $listener->expectCallCount('startElement', 2); - $listener->expectOnce('addContent', array('Hello')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse( - 'Hello')); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/reflection_php4_test.php b/application/libraries/simpletest/test/reflection_php4_test.php deleted file mode 100644 index 8ee211b961b..00000000000 --- a/application/libraries/simpletest/test/reflection_php4_test.php +++ /dev/null @@ -1,61 +0,0 @@ -assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfInterfacesAlwaysFalse() { - $reflection = new SimpleReflection('AnyOldThing'); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldChildThing'); - $this->assertEqual(strtolower($reflection->getParent()), 'anyoldthing'); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldThing'); - $methods = $reflection->getMethods(); - $this->assertEqualIgnoringCase($methods[0], 'aMethod'); - } - - function testNoInterfacesForPHP4() { - $reflection = new SimpleReflection('AnyOldThing'); - $this->assertEqual( - $reflection->getInterfaces(), - array()); - } - - function testMostGeneralPossibleSignature() { - $reflection = new SimpleReflection('AnyOldThing'); - $this->assertEqualIgnoringCase( - $reflection->getSignature('aMethod'), - 'function &aMethod()'); - } - - function assertEqualIgnoringCase($a, $b) { - return $this->assertEqual(strtolower($a), strtolower($b)); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/reflection_php5_test.php b/application/libraries/simpletest/test/reflection_php5_test.php deleted file mode 100644 index d9f46e6db78..00000000000 --- a/application/libraries/simpletest/test/reflection_php5_test.php +++ /dev/null @@ -1,263 +0,0 @@ -assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfAbstractClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertTrue($reflection->isAbstract()); - } - - function testDetectionOfFinalMethods() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertFalse($reflection->hasFinal()); - $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal'); - $this->assertTrue($reflection->hasFinal()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); - } - - function testInterfaceExistence() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertTrue($reflection->isInterface()); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testMethodsListFromInterface() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesASWell() { - $reflection = new SimpleReflection('AnyDescendentInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testCanSeparateInterfaceMethodsFromOthers() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesInAbstractClass() { - $reflection = new SimpleReflection('AnyAbstractImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testInterfaceHasOnlyItselfToImplement() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForClass() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForSubclass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testNoParameterCreationWhenNoInterface() { - $reflection = new SimpleReflection('AnyOldArgumentClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod($argument)', strtolower($function)); - } else { - $this->assertEqual('function aMethod($argument)', $function); - } - } - - function testParameterCreationWithoutTypeHinting() { - $reflection = new SimpleReflection('AnyOldArgumentImplementation'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testParameterCreationForTypeHinting() { - $reflection = new SimpleReflection('AnyOldTypeHintedClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testIssetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__isset'); - $this->assertEqual('function __isset($key)', $function); - } - - function testUnsetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__unset'); - $this->assertEqual('function __unset($key)', $function); - } - - function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { - $reflection = new SimpleReflection('AnyDescendentImplementation'); - $interfaces = $reflection->getInterfaces(); - $this->assertEqual(1, count($interfaces)); - $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); - } - - function testCreatingSignatureForAbstractMethod() { - $reflection = new SimpleReflection('AnotherOldAbstractClass'); - $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)'); - } - - function testCanProperlyGenerateStaticMethodSignatures() { - $reflection = new SimpleReflection('AnyOldClassWithStaticMethods'); - $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic')); - $this->assertEqual( - 'static function aStaticWithParameters($arg1, $arg2)', - $reflection->getSignature('aStaticWithParameters') - ); - } -} - -class TestOfReflectionWithTypeHints extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above'); - } - - function testParameterCreationForTypeHintingWithArray() { - eval('interface AnyOldArrayTypeHintedInterface { - function amethod(array $argument); - } - class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface { - function amethod(array $argument) {} - }'); - $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass'); - $function = $reflection->getSignature('amethod'); - $this->assertEqual('function amethod(array $argument)', $function); - } -} - -class TestOfAbstractsWithAbstractMethods extends UnitTestCase { - function testCanProperlyGenerateAbstractMethods() { - $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods'); - $this->assertEqual( - 'function anAbstract()', - $reflection->getSignature('anAbstract') - ); - $this->assertEqual( - 'function anAbstractWithParameter($foo)', - $reflection->getSignature('anAbstractWithParameter') - ); - $this->assertEqual( - 'function anAbstractWithMultipleParameters($foo, $bar)', - $reflection->getSignature('anAbstractWithMultipleParameters') - ); - } -} - -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/remote_test.php b/application/libraries/simpletest/test/remote_test.php deleted file mode 100644 index 5f3f96a4de9..00000000000 --- a/application/libraries/simpletest/test/remote_test.php +++ /dev/null @@ -1,19 +0,0 @@ -add(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); diff --git a/application/libraries/simpletest/test/shell_test.php b/application/libraries/simpletest/test/shell_test.php deleted file mode 100644 index d1d769a6795..00000000000 --- a/application/libraries/simpletest/test/shell_test.php +++ /dev/null @@ -1,38 +0,0 @@ -assertIdentical($shell->execute('echo Hello'), 0); - $this->assertPattern('/Hello/', $shell->getOutput()); - } - - function testBadCommand() { - $shell = new SimpleShell(); - $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); - } -} - -class TestOfShellTesterAndShell extends ShellTestCase { - - function testEcho() { - $this->assertTrue($this->execute('echo Hello')); - $this->assertExitCode(0); - $this->assertoutput('Hello'); - } - - function testFileExistence() { - $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); - $this->assertFileNotExists('wibble'); - } - - function testFilePatterns() { - $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php'); - $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/shell_tester_test.php b/application/libraries/simpletest/test/shell_tester_test.php deleted file mode 100644 index b12c602a39f..00000000000 --- a/application/libraries/simpletest/test/shell_tester_test.php +++ /dev/null @@ -1,42 +0,0 @@ -mock_shell; - } - - function testGenericEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } - - function testExitCode() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->expectOnce('execute', array('ls')); - $this->assertTrue($this->execute('ls')); - $this->assertExitCode(0); - } - - function testOutput() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutput("Line 1\nLine 2\n"); - } - - function testOutputPatterns() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutputPattern('/line/i'); - $this->assertNoOutputPattern('/line 2/'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/simpletest_test.php b/application/libraries/simpletest/test/simpletest_test.php deleted file mode 100644 index daa65c6f472..00000000000 --- a/application/libraries/simpletest/test/simpletest_test.php +++ /dev/null @@ -1,58 +0,0 @@ -fail('Should be ignored'); - } -} - -class ShouldNeverBeRunEither extends ShouldNeverBeRun { } - -class TestOfStackTrace extends UnitTestCase { - - function testCanFindAssertInTrace() { - $trace = new SimpleStackTrace(array('assert')); - $this->assertEqual( - $trace->traceMethod(array(array( - 'file' => '/my_test.php', - 'line' => 24, - 'function' => 'assertSomething'))), - ' at [/my_test.php line 24]'); - } -} - -class DummyResource { } - -class TestOfContext extends UnitTestCase { - - function testCurrentContextIsUnique() { - $this->assertSame( - SimpleTest::getContext(), - SimpleTest::getContext()); - } - - function testContextHoldsCurrentTestCase() { - $context = SimpleTest::getContext(); - $this->assertSame($this, $context->getTest()); - } - - function testResourceIsSingleInstanceWithContext() { - $context = new SimpleTestContext(); - $this->assertSame( - $context->get('DummyResource'), - $context->get('DummyResource')); - } - - function testClearingContextResetsResources() { - $context = new SimpleTestContext(); - $resource = $context->get('DummyResource'); - $context->clear(); - $this->assertClone($resource, $context->get('DummyResource')); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/site/file.html b/application/libraries/simpletest/test/site/file.html deleted file mode 100644 index cc41aee1b8b..00000000000 --- a/application/libraries/simpletest/test/site/file.html +++ /dev/null @@ -1,6 +0,0 @@ - - Link to SimpleTest - - Link to SimpleTest - - \ No newline at end of file diff --git a/application/libraries/simpletest/test/socket_test.php b/application/libraries/simpletest/test/socket_test.php deleted file mode 100644 index 729adda4960..00000000000 --- a/application/libraries/simpletest/test/socket_test.php +++ /dev/null @@ -1,25 +0,0 @@ -assertFalse($error->isError()); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $this->assertEqual($error->getError(), 'Ouch'); - } - - function testClearingError() { - $error = new SimpleStickyError(); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $error->clearError(); - $this->assertFalse($error->isError()); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/collector/collectable.1 b/application/libraries/simpletest/test/support/collector/collectable.1 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/application/libraries/simpletest/test/support/collector/collectable.2 b/application/libraries/simpletest/test/support/collector/collectable.2 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/application/libraries/simpletest/test/support/empty_test_file.php b/application/libraries/simpletest/test/support/empty_test_file.php deleted file mode 100644 index 31e3f7bed62..00000000000 --- a/application/libraries/simpletest/test/support/empty_test_file.php +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/failing_test.php b/application/libraries/simpletest/test/support/failing_test.php deleted file mode 100644 index 30f0d7507d9..00000000000 --- a/application/libraries/simpletest/test/support/failing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -assertEqual(1,2); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/latin1_sample b/application/libraries/simpletest/test/support/latin1_sample deleted file mode 100644 index 19035257766..00000000000 --- a/application/libraries/simpletest/test/support/latin1_sample +++ /dev/null @@ -1 +0,0 @@ -£¹²³¼½¾@¶øþðßæ«»¢µ \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/passing_test.php b/application/libraries/simpletest/test/support/passing_test.php deleted file mode 100644 index b7863216353..00000000000 --- a/application/libraries/simpletest/test/support/passing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -assertEqual(2,2); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/spl_examples.php b/application/libraries/simpletest/test/support/spl_examples.php deleted file mode 100644 index 45add356c44..00000000000 --- a/application/libraries/simpletest/test/support/spl_examples.php +++ /dev/null @@ -1,15 +0,0 @@ - \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/supplementary_upload_sample.txt b/application/libraries/simpletest/test/support/supplementary_upload_sample.txt deleted file mode 100644 index d8aa9e81013..00000000000 --- a/application/libraries/simpletest/test/support/supplementary_upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Some more text content \ No newline at end of file diff --git a/application/libraries/simpletest/test/support/test1.php b/application/libraries/simpletest/test/support/test1.php deleted file mode 100644 index b414586d642..00000000000 --- a/application/libraries/simpletest/test/support/test1.php +++ /dev/null @@ -1,7 +0,0 @@ -assertEqual(3,1+2, "pass1"); - } -} -?> diff --git a/application/libraries/simpletest/test/support/upload_sample.txt b/application/libraries/simpletest/test/support/upload_sample.txt deleted file mode 100644 index ec98d7c5e3f..00000000000 --- a/application/libraries/simpletest/test/support/upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Sample for testing file upload \ No newline at end of file diff --git a/application/libraries/simpletest/test/tag_test.php b/application/libraries/simpletest/test/tag_test.php deleted file mode 100644 index 5e8a377f089..00000000000 --- a/application/libraries/simpletest/test/tag_test.php +++ /dev/null @@ -1,554 +0,0 @@ - '1', 'b' => '')); - $this->assertEqual($tag->getTagName(), 'title'); - $this->assertIdentical($tag->getAttribute('a'), '1'); - $this->assertIdentical($tag->getAttribute('b'), ''); - $this->assertIdentical($tag->getAttribute('c'), false); - $this->assertIdentical($tag->getContent(), ''); - } - - function testTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testMessyTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testTagWithNoEnd() { - $tag = new SimpleTextTag(array()); - $this->assertFalse($tag->expectEndTag()); - } - - function testAnchorHref() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/')); - $this->assertEqual($tag->getHref(), 'http://here/'); - - $tag = new SimpleAnchorTag(array('href' => '')); - $this->assertIdentical($tag->getAttribute('href'), ''); - $this->assertIdentical($tag->getHref(), ''); - - $tag = new SimpleAnchorTag(array()); - $this->assertIdentical($tag->getAttribute('href'), false); - $this->assertIdentical($tag->getHref(), ''); - } - - function testIsIdMatchesIdAttribute() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7)); - $this->assertIdentical($tag->getAttribute('id'), '7'); - $this->assertTrue($tag->isId(7)); - } -} - -class TestOfWidget extends UnitTestCase { - - function testTextEmptyDefault() { - $tag = new SimpleTextTag(array('type' => 'text')); - $this->assertIdentical($tag->getDefault(), ''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSettingOfExternalLabel() { - $tag = new SimpleTextTag(array('type' => 'text')); - $tag->setLabel('it'); - $this->assertTrue($tag->isLabel('it')); - } - - function testTextDefault() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $this->assertEqual($tag->getDefault(), 'aaa'); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSettingTextValue() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $tag->setValue('bbb'); - $this->assertEqual($tag->getValue(), 'bbb'); - $tag->resetValue(); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testFailToSetHiddenValue() { - $tag = new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden')); - $this->assertFalse($tag->setValue('bbb')); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSubmitDefaults() { - $tag = new SimpleSubmitTag(array('type' => 'submit')); - $this->assertIdentical($tag->getName(), false); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertFalse($tag->setValue('Cannot set this')); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertEqual($tag->getLabel(), 'Submit'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectNever('add'); - $tag->write($encoding); - } - - function testPopulatedSubmit() { - $tag = new SimpleSubmitTag( - array('type' => 'submit', 'name' => 's', 'value' => 'Ok!')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'Ok!'); - $this->assertEqual($tag->getLabel(), 'Ok!'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'Ok!')); - $tag->write($encoding); - } - - function testImageSubmit() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getLabel(), 'Label'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectAt(0, 'add', array('s.x', 20)); - $encoding->expectAt(1, 'add', array('s.y', 30)); - $tag->write($encoding, 20, 30); - } - - function testImageSubmitTitlePreferredOverAltForLabel() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title')); - $this->assertEqual($tag->getLabel(), 'Title'); - } - - function testButton() { - $tag = new SimpleButtonTag( - array('type' => 'submit', 'name' => 's', 'value' => 'do')); - $tag->addContent('I am a button'); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'do'); - $this->assertEqual($tag->getLabel(), 'I am a button'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'do')); - $tag->write($encoding); - } -} - -class TestOfTextArea extends UnitTestCase { - - function testDefault() { - $tag = new SimpleTextAreaTag(array('name' => 'a')); - $tag->addContent('Some text'); - $this->assertEqual($tag->getName(), 'a'); - $this->assertEqual($tag->getDefault(), 'Some text'); - } - - function testWrapping() { - $tag = new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical')); - $tag->addContent("Lot's of text that should be wrapped"); - $this->assertEqual( - $tag->getDefault(), - "Lot's of\r\ntext that\r\nshould be\r\nwrapped"); - $tag->setValue("New long text\r\nwith two lines"); - $this->assertEqual( - $tag->getValue(), - "New long\r\ntext\r\nwith two\r\nlines"); - } - - function testWrappingRemovesLeadingcariageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical')); - $tag->addContent("\rStuff"); - $this->assertEqual($tag->getDefault(), 'Stuff'); - $tag->setValue("\nNew stuff\n"); - $this->assertEqual($tag->getValue(), "New stuff\r\n"); - } - - function testBreaksAreNewlineAndCarriageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '10')); - $tag->addContent("Some\nText\rwith\r\nbreaks"); - $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks"); - } -} - -class TestOfCheckbox extends UnitTestCase { - - function testCanSetCheckboxToNamedValueWithBooleanTrue() { - $tag = new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A')); - $this->assertEqual($tag->getValue(), false); - $tag->setValue(true); - $this->assertIdentical($tag->getValue(), 'A'); - } -} - -class TestOfSelection extends UnitTestCase { - - function testEmpty() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSingle() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array()); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleMappedDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '', 'value' => 'aaa')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testStartsWithDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testSettingOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSettingMappedOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => 'aaa')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => 'bbb', 'selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'aaa'); - $tag->setValue('ccc'); - $this->assertEqual($tag->getValue(), 'ccc'); - } - - function testSelectionDespiteSpuriousWhitespace() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent(' AAA '); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent(' BBB '); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent(' CCC '); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), ' BBB '); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), ' AAA '); - } - - function testFailToSetIllegalOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertFalse($tag->setValue('Not present')); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testNastyOptionValuesThatLookLikeFalse() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => '1')); - $a->addContent('One'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => '0')); - $b->addContent('Zero'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), '1'); - $tag->setValue('Zero'); - $this->assertIdentical($tag->getValue(), '0'); - } - - function testBlankOption() { - $tag = new SimpleSelectionTag(array('name' => 'A')); - $a = new SimpleOptionTag(array()); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('b'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), ''); - $tag->setValue('b'); - $this->assertIdentical($tag->getValue(), 'b'); - $tag->setValue(''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testMultipleDefaultWithNoSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array()); - $this->assertIdentical($tag->getValue(), array()); - } - - function testMultipleDefaultWithSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB')); - $this->assertIdentical($tag->getValue(), array('AAA', 'BBB')); - } - - function testSettingMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('selected' => '', 'value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc')); - $this->assertTrue($tag->setValue(array('BBB', 'ccc'))); - $this->assertIdentical($tag->getValue(), array('BBB', 'ccc')); - $this->assertTrue($tag->setValue(array())); - $this->assertIdentical($tag->getValue(), array()); - } - - function testFailToSetIllegalOptionsInMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertFalse($tag->setValue(array('CCC'))); - $this->assertTrue($tag->setValue(array('AAA', 'BBB'))); - $this->assertFalse($tag->setValue(array('AAA', 'CCC'))); - } -} - -class TestOfRadioGroup extends UnitTestCase { - - function testEmptyGroup() { - $group = new SimpleRadioGroup(); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - $this->assertFalse($group->setValue('a')); - } - - function testReadingSingleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'A'); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testReadingMultipleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testFailToSetUnlistedValue() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z'))); - $this->assertFalse($group->setValue('a')); - $this->assertIdentical($group->getValue(), false); - } - - function testSettingNewValueClearsTheOldOne() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testIsIdMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'id' => 'i1'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'id' => 'i2'))); - $this->assertFalse($group->isId('i0')); - $this->assertTrue($group->isId('i1')); - $this->assertTrue($group->isId('i2')); - } - - function testIsLabelMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $button1 = new SimpleRadioButtonTag(array('value' => 'A')); - $button1->setLabel('one'); - $group->addWidget($button1); - $button2 = new SimpleRadioButtonTag(array('value' => 'B')); - $button2->setLabel('two'); - $group->addWidget($button2); - $this->assertFalse($group->isLabel('three')); - $this->assertTrue($group->isLabel('one')); - $this->assertTrue($group->isLabel('two')); - } -} - -class TestOfTagGroup extends UnitTestCase { - - function testReadingMultipleCheckboxGroup() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testReadingMultipleUncheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - } - - function testReadingMultipleCheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'A', 'checked' => ''))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), array('A', 'B')); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingSingleValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - $this->assertTrue($group->setValue('B')); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testSettingMultipleValues() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(array('A', 'B'))); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingNoValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(false)); - $this->assertIdentical($group->getValue(), false); - } - - function testIsIdMatchesAnyIdInSet() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B'))); - $this->assertFalse($group->isId(0)); - $this->assertTrue($group->isId(1)); - $this->assertTrue($group->isId(2)); - } -} - -class TestOfUploadWidget extends UnitTestCase { - - function testValueIsFilePath() { - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt'); - } - - function testSubmitsFileContents() { - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('attach', array( - 'a', - 'Sample for testing file upload', - 'upload_sample.txt')); - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $upload->write($encoding); - } -} - -class TestOfLabelTag extends UnitTestCase { - - function testLabelShouldHaveAnEndTag() { - $label = new SimpleLabelTag(array()); - $this->assertTrue($label->expectEndTag()); - } - - function testContentIsTextOnly() { - $label = new SimpleLabelTag(array()); - $label->addContent('Here are words'); - $this->assertEqual($label->getText(), 'Here are words'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/test_with_parse_error.php b/application/libraries/simpletest/test/test_with_parse_error.php deleted file mode 100644 index 41a5832a5cb..00000000000 --- a/application/libraries/simpletest/test/test_with_parse_error.php +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/application/libraries/simpletest/test/unit_tester_test.php b/application/libraries/simpletest/test/unit_tester_test.php deleted file mode 100644 index ce9850f09ab..00000000000 --- a/application/libraries/simpletest/test/unit_tester_test.php +++ /dev/null @@ -1,61 +0,0 @@ -assertTrue($this->assertTrue(true)); - } - - function testAssertFalseReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertFalse(false)); - } - - function testAssertEqualReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertEqual(5, 5)); - } - - function testAssertIdenticalReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertIdentical(5, 5)); - } - - function testCoreAssertionsDoNotThrowErrors() { - $this->assertIsA($this, 'UnitTestCase'); - $this->assertNotA($this, 'WebTestCase'); - } - - function testReferenceAssertionOnObjects() { - $a = new ReferenceForTesting(); - $b = $a; - $this->assertSame($a, $b); - } - - function testReferenceAssertionOnScalars() { - $a = 25; - $b = &$a; - $this->assertReference($a, $b); - } - - function testCloneOnObjects() { - $a = new ReferenceForTesting(); - $b = new ReferenceForTesting(); - $this->assertClone($a, $b); - } - - function TODO_testCloneOnScalars() { - $a = 25; - $b = 25; - $this->assertClone($a, $b); - } - - function testCopyOnScalars() { - $a = 25; - $b = 25; - $this->assertCopy($a, $b); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/unit_tests.php b/application/libraries/simpletest/test/unit_tests.php deleted file mode 100644 index 9e621293f9e..00000000000 --- a/application/libraries/simpletest/test/unit_tests.php +++ /dev/null @@ -1,49 +0,0 @@ -TestSuite('Unit tests'); - $path = dirname(__FILE__); - $this->addFile($path . '/errors_test.php'); - $this->addFile($path . '/exceptions_test.php'); - $this->addFile($path . '/arguments_test.php'); - $this->addFile($path . '/autorun_test.php'); - $this->addFile($path . '/compatibility_test.php'); - $this->addFile($path . '/simpletest_test.php'); - $this->addFile($path . '/dumper_test.php'); - $this->addFile($path . '/expectation_test.php'); - $this->addFile($path . '/unit_tester_test.php'); - $this->addFile($path . '/reflection_php5_test.php'); - $this->addFile($path . '/mock_objects_test.php'); - $this->addFile($path . '/interfaces_test.php'); - $this->addFile($path . '/collector_test.php'); - $this->addFile($path . '/recorder_test.php'); - $this->addFile($path . '/adapter_test.php'); - $this->addFile($path . '/socket_test.php'); - $this->addFile($path . '/encoding_test.php'); - $this->addFile($path . '/url_test.php'); - $this->addFile($path . '/cookies_test.php'); - $this->addFile($path . '/http_test.php'); - $this->addFile($path . '/authentication_test.php'); - $this->addFile($path . '/user_agent_test.php'); - $this->addFile($path . '/php_parser_test.php'); - $this->addFile($path . '/parsing_test.php'); - $this->addFile($path . '/tag_test.php'); - $this->addFile($path . '/form_test.php'); - $this->addFile($path . '/page_test.php'); - $this->addFile($path . '/frames_test.php'); - $this->addFile($path . '/browser_test.php'); - $this->addFile($path . '/web_tester_test.php'); - $this->addFile($path . '/shell_tester_test.php'); - $this->addFile($path . '/xml_test.php'); - $this->addFile($path . '/../extensions/testdox/test.php'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/url_test.php b/application/libraries/simpletest/test/url_test.php deleted file mode 100644 index 80119afbdde..00000000000 --- a/application/libraries/simpletest/test/url_test.php +++ /dev/null @@ -1,515 +0,0 @@ -assertEqual($url->getScheme(), ''); - $this->assertEqual($url->getHost(), ''); - $this->assertEqual($url->getScheme('http'), 'http'); - $this->assertEqual($url->getHost('localhost'), 'localhost'); - $this->assertEqual($url->getPath(), ''); - } - - function testBasicParsing() { - $url = new SimpleUrl('https://www.lastcraft.com/test/'); - $this->assertEqual($url->getScheme(), 'https'); - $this->assertEqual($url->getHost(), 'www.lastcraft.com'); - $this->assertEqual($url->getPath(), '/test/'); - } - - function testRelativeUrls() { - $url = new SimpleUrl('../somewhere.php'); - $this->assertEqual($url->getScheme(), false); - $this->assertEqual($url->getHost(), false); - $this->assertEqual($url->getPath(), '../somewhere.php'); - } - - function testParseBareParameter() { - $url = new SimpleUrl('?a'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseEmptyParameter() { - $url = new SimpleUrl('?a='); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a='); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseParameterPair() { - $url = new SimpleUrl('?a=A'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X'); - } - - function testParseMultipleParameters() { - $url = new SimpleUrl('?a=A&b=B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X'); - } - - function testParsingParameterMixture() { - $url = new SimpleUrl('?a=A&b=&c'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X'); - } - - function testAddParametersFromScratch() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('b', 'B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('a', 'aaa'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa'); - } - - function testClearingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $url->clearRequest(); - $this->assertIdentical($url->getEncodedRequest(), ''); - } - - function testEncodingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|$%^&*()_+-='); - $this->assertIdentical( - $request = $url->getEncodedRequest(), - '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - } - - function testDecodingParameters() { - $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - $this->assertEqual( - $url->getEncodedRequest(), - '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|$%^&*()_+-=')); - } - - function testUrlInQueryDoesNotConfuseParsing() { - $url = new SimpleUrl('wibble/login.php?url=http://www.google.com/moo/'); - $this->assertFalse($url->getScheme()); - $this->assertFalse($url->getHost()); - $this->assertEqual($url->getPath(), 'wibble/login.php'); - $this->assertEqual($url->getEncodedRequest(), '?url=http://www.google.com/moo/'); - } - - function testSettingCordinates() { - $url = new SimpleUrl(''); - $url->setCoordinates('32', '45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), ''); - } - - function testParseCordinates() { - $url = new SimpleUrl('?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - } - - function testClearingCordinates() { - $url = new SimpleUrl('?32,45'); - $url->setCoordinates(); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - } - - function testParsingParameterCordinateMixture() { - $url = new SimpleUrl('?a=A&b=&c?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - } - - function testParsingParameterWithBadCordinates() { - $url = new SimpleUrl('?a=A&b=&c?32'); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32'); - } - - function testPageSplitting() { - $url = new SimpleUrl('./here/../there/somewhere.php'); - $this->assertEqual($url->getPath(), './here/../there/somewhere.php'); - $this->assertEqual($url->getPage(), 'somewhere.php'); - $this->assertEqual($url->getBasePath(), './here/../there/'); - } - - function testAbsolutePathPageSplitting() { - $url = new SimpleUrl("http://host.com/here/there/somewhere.php"); - $this->assertEqual($url->getPath(), "/here/there/somewhere.php"); - $this->assertEqual($url->getPage(), "somewhere.php"); - $this->assertEqual($url->getBasePath(), "/here/there/"); - } - - function testSplittingUrlWithNoPageGivesEmptyPage() { - $url = new SimpleUrl('/here/there/'); - $this->assertEqual($url->getPath(), '/here/there/'); - $this->assertEqual($url->getPage(), ''); - $this->assertEqual($url->getBasePath(), '/here/there/'); - } - - function testPathNormalisation() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1535407 - function testPathNormalisationWithSinglePeriod() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/./../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1852413 - function testHostnameExtractedFromUContainingAtSign() { - $url = new SimpleUrl("http://localhost/name@example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name@example.com"); - } - - function testHostnameInLocalhost() { - $url = new SimpleUrl("http://localhost/name/example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name/example.com"); - } - - function testUsernameAndPasswordAreUrlDecoded() { - $url = new SimpleUrl('http://' . urlencode('test@test') . - ':' . urlencode('$!�@*&%') . '@www.lastcraft.com'); - $this->assertEqual($url->getUsername(), 'test@test'); - $this->assertEqual($url->getPassword(), '$!�@*&%'); - } - - function testBlitz() { - $this->assertUrl( - "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor", - array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"), - array("a" => "1", "b" => "2")); - $this->assertUrl( - "username:password@www.somewhere.com/this/that/here.php?a=1", - array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false), - array("a" => "1")); - $this->assertUrl( - "username:password@somewhere.com:243?1,2", - array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false), - array(), - array(1, 2)); - $this->assertUrl( - "https://www.somewhere.com", - array("https", false, false, "www.somewhere.com", false, "/", "com", "", false)); - $this->assertUrl( - "username@www.somewhere.com:243#anchor", - array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor")); - $this->assertUrl( - "/this/that/here.php?a=1&b=2?3,4", - array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2"), - array(3, 4)); - $this->assertUrl( - "username@/here.php?a=1&b=2", - array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2")); - } - - function testAmbiguousHosts() { - $this->assertUrl( - "tigger", - array(false, false, false, false, false, "tigger", false, "", false)); - $this->assertUrl( - "/tigger", - array(false, false, false, false, false, "/tigger", false, "", false)); - $this->assertUrl( - "//tigger", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "//tigger/", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "tigger.com", - array(false, false, false, "tigger.com", false, "/", "com", "", false)); - $this->assertUrl( - "me.net/tigger", - array(false, false, false, "me.net", false, "/tigger", "net", "", false)); - } - - function testAsString() { - $this->assertPreserved('https://www.here.com'); - $this->assertPreserved('http://me:secret@www.here.com'); - $this->assertPreserved('http://here/there'); - $this->assertPreserved('http://here/there?a=A&b=B'); - $this->assertPreserved('http://here/there?a=1&a=2'); - $this->assertPreserved('http://here/there?a=1&a=2?9,8'); - $this->assertPreserved('http://host?a=1&a=2'); - $this->assertPreserved('http://host#stuff'); - $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6'); - $this->assertPreserved('http://www.here.com/?a=A__b=B'); - $this->assertPreserved('http://www.example.com:8080/'); - } - - function testUrlWithTwoSlashesInPath() { - $url = new SimpleUrl('/article/categoryedit/insert//'); - $this->assertEqual($url->getPath(), '/article/categoryedit/insert//'); - } - - function testUrlWithRequestKeyEncoded() { - $url = new SimpleUrl('/?foo%5B1%5D=bar'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar&a%5B1%5D=b%5B%5D'); - - $url = new SimpleUrl('/'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?a%5B1%5D=b%5B%5D'); - } - - function testUrlWithRequestKeyEncodedAndParamNamLookingLikePair() { - $url = new SimpleUrl('/'); - $url->addRequestParameter('foo[]=bar', ''); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - $url = new SimpleUrl('/?foo%5B%5D%3Dbar='); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - } - - function assertUrl($raw, $parts, $params = false, $coords = false) { - if (! is_array($params)) { - $params = array(); - } - $url = new SimpleUrl($raw); - $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); - $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); - $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); - $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); - $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); - $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); - $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); - $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); - $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); - if ($coords) { - $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); - $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); - } - } - - function assertPreserved($string) { - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - } -} - -class TestOfAbsoluteUrls extends UnitTestCase { - - function testDirectoriesAfterFilename() { - $string = '../../index.php/foo/bar'; - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - - $absolute = $url->makeAbsolute('http://www.domain.com/some/path/'); - $this->assertEqual($absolute->asString(), 'http://www.domain.com/index.php/foo/bar'); - } - - function testMakingAbsolute() { - $url = new SimpleUrl('../there/somewhere.php'); - $this->assertEqual($url->getPath(), '../there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPort(), 1234); - $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php'); - } - - function testMakingAnEmptyUrlAbsolute() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/page.html'); - } - - function testMakingAnEmptyUrlAbsoluteWithMissingPageName() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - } - - function testMakingAShortQueryUrlAbsolute() { - $url = new SimpleUrl('?a#b'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a'); - $this->assertEqual($absolute->getFragment(), 'b'); - } - - function testMakingADirectoryUrlAbsolute() { - $url = new SimpleUrl('hello/'); - $this->assertEqual($url->getPath(), 'hello/'); - $this->assertEqual($url->getBasePath(), 'hello/'); - $this->assertEqual($url->getPage(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/I/am/here/hello/'); - } - - function testMakingARootUrlAbsolute() { - $url = new SimpleUrl('/'); - $this->assertEqual($url->getPath(), '/'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/'); - } - - function testMakingARootPageUrlAbsolute() { - $url = new SimpleUrl('/here.html'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/here.html'); - } - - function testCarryAuthenticationFromRootPage() { - $url = new SimpleUrl('here.html'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/'); - $this->assertEqual($absolute->getPath(), '/here.html'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingCoordinateUrlAbsolute() { - $url = new SimpleUrl('?1,2'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getX(), 1); - $this->assertEqual($absolute->getY(), 2); - } - - function testMakingAbsoluteAppendedPath() { - $url = new SimpleUrl('./there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteBadlyFormedAppendedPath() { - $url = new SimpleUrl('there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f'); - $absolute = $url->makeAbsolute('http://host.com/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getPort(), 321); - $this->assertEqual($absolute->getPath(), '/stuff/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a=1'); - $this->assertEqual($absolute->getFragment(), 'f'); - } - - function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://www.lastcraft.com'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/here/'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() { - $url = new SimpleUrl('http://www.lastcraft.com'); - $absolute = $url->makeAbsolute('https://host.com:81/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertIdentical($absolute->getPort(), false); - $this->assertEqual($absolute->getPath(), '/'); - } -} - -class TestOfFrameUrl extends UnitTestCase { - - function testTargetAttachment() { - $url = new SimpleUrl('http://www.site.com/home.html'); - $this->assertIdentical($url->getTarget(), false); - $url->setTarget('A frame'); - $this->assertIdentical($url->getTarget(), 'A frame'); - } -} - -/** - * @note Based off of http://www.mozilla.org/quality/networking/testing/filetests.html - */ -class TestOfFileUrl extends UnitTestCase { - - function testMinimalUrl() { - $url = new SimpleUrl('file:///'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/'); - } - - function testUnixUrl() { - $url = new SimpleUrl('file:///fileInRoot'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/fileInRoot'); - } - - function testDOSVolumeUrl() { - $url = new SimpleUrl('file:///C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSVolumePromotion() { - $url = new SimpleUrl('file://C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSBackslashes() { - $url = new SimpleUrl('file:///C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSDirnameAfterFile() { - $url = new SimpleUrl('file://C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - -} - -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/user_agent_test.php b/application/libraries/simpletest/test/user_agent_test.php deleted file mode 100644 index 030abeb257d..00000000000 --- a/application/libraries/simpletest/test/user_agent_test.php +++ /dev/null @@ -1,348 +0,0 @@ -headers = new MockSimpleHttpHeaders(); - $this->response = new MockSimpleHttpResponse(); - $this->response->setReturnValue('isError', false); - $this->response->returns('getHeaders', new MockSimpleHttpHeaders()); - $this->request = new MockSimpleHttpRequest(); - $this->request->returns('fetch', $this->response); - } - - function testGetRequestWithoutIncidentGivesNoErrors() { - $url = new SimpleUrl('http://test:secret@this.com/page.html'); - $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $this->request); - $agent->__construct(); - - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A', 'b' => 'B'))); - $this->assertFalse($response->isError()); - } -} - -class TestOfAdditionalHeaders extends UnitTestCase { - - function testAdditionalHeaderAddedToRequest() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('User-Agent: SimpleTest')); - - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $agent->addHeader('User-Agent: SimpleTest'); - $response = $agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding()); - } -} - -class TestOfBrowserCookies extends UnitTestCase { - - private function createStandardResponse() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnValue("getContent", "stuff"); - $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders()); - return $response; - } - - private function createCookieSite($header_lines) { - $headers = new SimpleHttpHeaders($header_lines); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnReference("getHeaders", $headers); - $response->setReturnValue("getContent", "stuff"); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference("fetch", $response); - return $request; - } - - private function createMockedRequestUserAgent(&$request) { - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - return $agent; - } - - function testCookieJarIsSentToRequest() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectOnce('readCookiesFromJar', array($jar, '*')); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() { - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectNever('readCookiesFromJar'); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testReadingNewCookie() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testIgnoringNewCookieWhenCookiesDisabled() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false); - } - - function testOverwriteCookieThatAlreadyExists() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testClearCookieBySettingExpiry() { - $request = $this->createCookieSite('Set-cookie: a=b'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "b"); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testAgeingAndClearing() { - $request = $this->createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "A"); - $agent->ageCookies(2); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testReadingIncomingAndSettingNewCookies() { - $request = $this->createCookieSite('Set-cookie: a=AAA'); - $agent = $this->createMockedRequestUserAgent($request); - - $this->assertNull($agent->getBaseCookieValue("a", false)); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->setCookie("b", "BBB", "this.com", "this/path/"); - $this->assertEqual( - $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')), - "AAA"); - $this->assertEqual( - $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')), - "BBB"); - } -} - -class TestOfHttpRedirects extends UnitTestCase { - - function createRedirect($content, $redirect) { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('isRedirect', (boolean)$redirect); - $headers->setReturnValue('getLocation', $redirect); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnReference('getHeaders', $headers); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testDisabledRedirects() { - $agent = new MockRequestUserAgent(); - $agent->returns( - 'createHttpRequest', - $this->createRedirect('stuff', 'there.html')); - $agent->expectOnce('createHttpRequest'); - $agent->__construct(); - $agent->setMaximumRedirects(0); - $response = $agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'stuff'); - } - - function testSingleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testDoubleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 3); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'third'); - } - - function testSuccessAfterRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', false)); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testRedirectChangesPostToGet() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->expectAt(0, 'createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding'))); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectAt(1, 'createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding'))); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding()); - } -} - -class TestOfBadHosts extends UnitTestCase { - - private function createSimulatedBadHost() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('isError', true); - $response->setReturnValue('getError', 'Bad socket'); - $response->setReturnValue('getContent', false); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testUntestedHost() { - $request = $this->createSimulatedBadHost(); - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://this.host/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - } -} - -class TestOfAuthorisation extends UnitTestCase { - - function testAuthenticateHeaderAdded() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('Authorization: Basic ' . base64_encode('test:secret'))); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.host'), - new SimpleGetEncoding()); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/visual_test.php b/application/libraries/simpletest/test/visual_test.php deleted file mode 100644 index 6b9d085d67f..00000000000 --- a/application/libraries/simpletest/test/visual_test.php +++ /dev/null @@ -1,495 +0,0 @@ -a = $a; - } -} - -class PassingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->pass('Pass'); - } - - function testTrue() { - $this->assertTrue(true); - } - - function testFalse() { - $this->assertFalse(false); - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 25, 'My assert message : %s'); - } - - function testNull() { - $this->assertNull(null, "%s -> Pass"); - $this->assertNotNull(false, "%s -> Pass"); - } - - function testType() { - $this->assertIsA("hello", "string", "%s -> Pass"); - $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass"); - $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); - } - - function testTypeEquality() { - $this->assertEqual("0", 0, "%s -> Pass"); - } - - function testNullEquality() { - $this->assertNotEqual(null, 1, "%s -> Pass"); - $this->assertNotEqual(1, null, "%s -> Pass"); - } - - function testIntegerEquality() { - $this->assertNotEqual(1, 2, "%s -> Pass"); - } - - function testStringEquality() { - $this->assertEqual("a", "a", "%s -> Pass"); - $this->assertNotEqual("aa", "ab", "%s -> Pass"); - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass"); - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass"); - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertIdentical($a, $b, "%s -> Pass"); - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertNotIdentical($a, $b, "%s -> Pass"); - } - - function testNullIdentity() { - $this->assertNotIdentical(null, 1, "%s -> Pass"); - $this->assertNotIdentical(1, null, "%s -> Pass"); - } - - function testHashIdentity() { - } - - function testObjectEquality() { - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass"); - } - - function testObjectIndentity() { - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass"); - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertReference($a, $b, "%s -> Pass"); - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $b, "%s -> Pass"); - } - - function testPatterns() { - $this->assertPattern('/hello/i', "Hello there", "%s -> Pass"); - $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass"); - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text, $text); - } -} - -class FailingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->fail('Fail'); // Fail. - } - - function testTrue() { - $this->assertTrue(false); // Fail. - } - - function testFalse() { - $this->assertFalse(true); // Fail. - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 24, 'My assert message : %s'); // Fail. - } - - function testNull() { - $this->assertNull(false, "%s -> Fail"); // Fail. - $this->assertNotNull(null, "%s -> Fail"); // Fail. - } - - function testType() { - $this->assertIsA(14, "string", "%s -> Fail"); // Fail. - $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. - $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. - } - - function testTypeEquality() { - $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. - } - - function testNullEquality() { - $this->assertEqual(null, 1, "%s -> Fail"); // Fail. - $this->assertEqual(1, null, "%s -> Fail"); // Fail. - } - - function testIntegerEquality() { - $this->assertEqual(1, 2, "%s -> Fail"); // Fail. - } - - function testStringEquality() { - $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. - $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail. - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail. - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testNullIdentity() { - $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. - $this->assertIdentical(1, null, "%s -> Fail"); // Fail. - } - - function testHashIdentity() { - $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. - } - - function testObjectEquality() { - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. - } - - function testObjectIndentity() { - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail. - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertClone($a, $b, "%s -> Fail"); // Fail. - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $c, "%s -> Fail"); // Fail. - } - - function testPatterns() { - $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. - $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text . $text, $text . "a" . $text); // Fail. - } -} - -class Dummy { - function Dummy() { - } - - function a() { - } -} -Mock::generate('Dummy'); - -class TestOfMockObjectsOutput extends UnitTestCase { - - function testCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectCallCount('a', 1, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testMinimumCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testEmptyMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array()); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testEmptyMatchingWithCustomMessage() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(), 'My expectation message: %s'); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testNullMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(null)); - $dummy->a(null); - $dummy->a(); // Fail. - } - - function testBooleanMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(true, false)); - $dummy->a(true, false); - $dummy->a(true, true); // Fail. - } - - function testIntegerMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(32, 33)); - $dummy->a(32, 33); - $dummy->a(32, 34); // Fail. - } - - function testFloatMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(3.2, 3.3)); - $dummy->a(3.2, 3.3); - $dummy->a(3.2, 3.4); // Fail. - } - - function testStringMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('32', '33')); - $dummy->a('32', '33'); - $dummy->a('32', '34'); // Fail. - } - - function testEmptyMatchingWithCustomExpectationMessage() { - $dummy = &new MockDummy(); - $dummy->expect( - 'a', - array(new EqualExpectation('A', 'My part expectation message: %s')), - 'My expectation message: %s'); - $dummy->a('A'); - $dummy->a('B'); // Fail. - } - - function testArrayMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(array(32), array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } - - function testObjectMatching() { - $a = new Dummy(); - $a->a = 'a'; - $b = new Dummy(); - $b->b = 'b'; - $dummy = &new MockDummy(); - $dummy->expect('a', array($a, $b)); - $dummy->a($a, $b); - $dummy->a($a, $a); // Fail. - } - - function testBigList() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(false, 0, 1, 1.0)); - $dummy->a(false, 0, 1, 1.0); - $dummy->a(true, false, 2, 2.0); // Fail. - } -} - -class TestOfPastBugs extends UnitTestCase { - - function testMixedTypes() { - $this->assertEqual(array(), null, "%s -> Pass"); - $this->assertIdentical(array(), null, "%s -> Fail"); // Fail. - } - - function testMockWildcards() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('*', array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } -} - -class TestOfVisualShell extends ShellTestCase { - - function testDump() { - $this->execute('ls'); - $this->dumpOutput(); - $this->execute('dir'); - $this->dumpOutput(); - } - - function testDumpOfList() { - $this->execute('ls'); - $this->dump($this->getOutputAsList()); - } -} - -class PassesAsWellReporter extends HtmlReporter { - - protected function getCss() { - return parent::getCss() . ' .pass { color: darkgreen; }'; - } - - function paintPass($message) { - parent::paintPass($message); - print "Pass: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities($message) . "
\n"; - } - - function paintSignal($type, &$payload) { - print "$type: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities(serialize($payload)) . "
\n"; - } -} - -class TestOfSkippingNoMatterWhat extends UnitTestCase { - function skip() { - $this->skipIf(true, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingOrElse extends UnitTestCase { - function skip() { - $this->skipUnless(false, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingTwiceOver extends UnitTestCase { - function skip() { - $this->skipIf(true, 'First reason -> %s'); - $this->skipIf(true, 'Second reason -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestThatShouldNotBeSkipped extends UnitTestCase { - function skip() { - $this->skipIf(false); - $this->skipUnless(true); - } - - function testFail() { - $this->fail('We should see this message'); - } - - function testPass() { - $this->pass('We should see this message'); - } -} - -$test = &new TestSuite('Visual test with 46 passes, 47 fails and 0 exceptions'); -$test->add(new PassingUnitTestCaseOutput()); -$test->add(new FailingUnitTestCaseOutput()); -$test->add(new TestOfMockObjectsOutput()); -$test->add(new TestOfPastBugs()); -$test->add(new TestOfVisualShell()); -$test->add(new TestOfSkippingNoMatterWhat()); -$test->add(new TestOfSkippingOrElse()); -$test->add(new TestOfSkippingTwiceOver()); -$test->add(new TestThatShouldNotBeSkipped()); - -if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { - $reporter = new XmlReporter(); -} elseif (TextReporter::inCli()) { - $reporter = new TextReporter(); -} else { - $reporter = new PassesAsWellReporter(); -} -if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) { - $reporter->makeDry(); -} -exit ($test->run($reporter) ? 0 : 1); -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/web_tester_test.php b/application/libraries/simpletest/test/web_tester_test.php deleted file mode 100644 index 8c3bf1adf63..00000000000 --- a/application/libraries/simpletest/test/web_tester_test.php +++ /dev/null @@ -1,155 +0,0 @@ -assertTrue($expectation->test('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertFalse($expectation->test('A')); - } - - function testMatchesInteger() { - $expectation = new FieldExpectation('1'); - $this->assertTrue($expectation->test('1')); - $this->assertTrue($expectation->test(1)); - $this->assertTrue($expectation->test(array('1'))); - $this->assertTrue($expectation->test(array(1))); - } - - function testNonStringFailsExpectation() { - $expectation = new FieldExpectation('a'); - $this->assertFalse($expectation->test(null)); - } - - function testUnsetFieldCanBeTestedFor() { - $expectation = new FieldExpectation(false); - $this->assertTrue($expectation->test(false)); - } - - function testMultipleValuesCanBeInAnyOrder() { - $expectation = new FieldExpectation(array('a', 'b')); - $this->assertTrue($expectation->test(array('a', 'b'))); - $this->assertTrue($expectation->test(array('b', 'a'))); - $this->assertFalse($expectation->test(array('a', 'a'))); - $this->assertFalse($expectation->test('a')); - } - - function testSingleItemCanBeArrayOrString() { - $expectation = new FieldExpectation(array('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertTrue($expectation->test('a')); - } -} - -class TestOfHeaderExpectations extends UnitTestCase { - - function testExpectingOnlyTheHeaderName() { - $expectation = new HttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('a: B'), true); - $this->assertIdentical($expectation->test(' a : A '), true); - } - - function testHeaderValueAsWell() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), false); - } - - function testHeaderValueWithColons() { - $expectation = new HttpHeaderExpectation('a', 'A:B:C'); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('a: A:B'), false); - $this->assertIdentical($expectation->test('a: A:B:C'), true); - $this->assertIdentical($expectation->test('a: A:B:C:D'), false); - } - - function testMultilineSearch() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); - $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); - } - - function testMultilineSearchWithPadding() { - $expectation = new HttpHeaderExpectation('a', ' A '); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); - } - - function testPatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), true); - } - - function testCaseInsensitivePatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); - $this->assertIdentical($expectation->test('a: a'), true); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : BAB '), true); - $this->assertIdentical($expectation->test(' a : bab '), true); - } - - function testUnwantedHeader() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('stuff'), true); - $this->assertIdentical($expectation->test('b: B'), true); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('A: A'), false); - } - - function testMultilineUnwantedSearch() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); - } - - function testLocationHeaderSplitsCorrectly() { - $expectation = new HttpHeaderExpectation('Location', 'http://here/'); - $this->assertIdentical($expectation->test('Location: http://here/'), true); - } -} - -class TestOfTextExpectations extends UnitTestCase { - - function testMatchingSubString() { - $expectation = new TextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), false); - $this->assertIdentical($expectation->test('Wanted'), false); - $this->assertIdentical($expectation->test('wanted'), true); - $this->assertIdentical($expectation->test('the wanted text is here'), true); - } - - function testNotMatchingSubString() { - $expectation = new NoTextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('Wanted'), true); - $this->assertIdentical($expectation->test('wanted'), false); - $this->assertIdentical($expectation->test('the wanted text is here'), false); - } -} - -class TestOfGenericAssertionsInWebTester extends WebTestCase { - function testEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/test/xml_test.php b/application/libraries/simpletest/test/xml_test.php deleted file mode 100644 index f99e0dcd98b..00000000000 --- a/application/libraries/simpletest/test/xml_test.php +++ /dev/null @@ -1,187 +0,0 @@ - 2)); - $this->assertEqual($nesting->getSize(), 2); - } -} - -class TestOfXmlStructureParsing extends UnitTestCase { - function testValidXml() { - $listener = new MockSimpleScorer(); - $listener->expectNever('paintGroupStart'); - $listener->expectNever('paintGroupEnd'); - $listener->expectNever('paintCaseStart'); - $listener->expectNever('paintCaseEnd'); - $parser = new SimpleTestXmlParser($listener); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - } - - function testEmptyGroup() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintGroupStart', array('a_group', 7)); - $listener->expectOnce('paintGroupEnd', array('a_group')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyCase() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_case\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyMethod() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $listener->expectOnce('paintMethodStart', array('a_method')); - $listener->expectOnce('paintMethodEnd', array('a_method')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_method\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testNestedGroup() { - $listener = new MockSimpleScorer(); - $listener->expectAt(0, 'paintGroupStart', array('a_group', 7)); - $listener->expectAt(1, 'paintGroupStart', array('b_group', 3)); - $listener->expectCallCount('paintGroupStart', 2); - $listener->expectAt(0, 'paintGroupEnd', array('b_group')); - $listener->expectAt(1, 'paintGroupEnd', array('a_group')); - $listener->expectCallCount('paintGroupEnd', 2); - - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("b_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } -} - -class AnyOldSignal { - public $stuff = true; -} - -class TestOfXmlResultsParsing extends UnitTestCase { - - function sendValidStart(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $parser->parse("\n"); - $parser->parse("a_method\n"); - } - - function sendValidEnd(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testPass() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintPass', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFail() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFail', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testException() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintError', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSkip() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSkip', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSignal() { - $signal = new AnyOldSignal(); - $signal->stuff = "Hello"; - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSignal', array('a_signal', $signal)); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse( - "\n")); - $this->sendValidEnd($parser); - } - - function testMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintMessage', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFormattedMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("\n")); - $this->sendValidEnd($parser); - } -} -?> \ No newline at end of file diff --git a/application/libraries/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/application/third_party/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE similarity index 100% rename from application/libraries/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE rename to application/third_party/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE diff --git a/application/libraries/simpletest/LICENSE b/application/third_party/simpletest/LICENSE similarity index 100% rename from application/libraries/simpletest/LICENSE rename to application/third_party/simpletest/LICENSE diff --git a/application/libraries/simpletest/README b/application/third_party/simpletest/README similarity index 100% rename from application/libraries/simpletest/README rename to application/third_party/simpletest/README diff --git a/application/libraries/simpletest/VERSION b/application/third_party/simpletest/VERSION similarity index 100% rename from application/libraries/simpletest/VERSION rename to application/third_party/simpletest/VERSION diff --git a/application/libraries/simpletest/authentication.php b/application/third_party/simpletest/authentication.php similarity index 100% rename from application/libraries/simpletest/authentication.php rename to application/third_party/simpletest/authentication.php diff --git a/application/libraries/simpletest/autorun.php b/application/third_party/simpletest/autorun.php similarity index 100% rename from application/libraries/simpletest/autorun.php rename to application/third_party/simpletest/autorun.php diff --git a/application/libraries/simpletest/browser.php b/application/third_party/simpletest/browser.php similarity index 100% rename from application/libraries/simpletest/browser.php rename to application/third_party/simpletest/browser.php diff --git a/application/libraries/simpletest/collector.php b/application/third_party/simpletest/collector.php similarity index 100% rename from application/libraries/simpletest/collector.php rename to application/third_party/simpletest/collector.php diff --git a/application/libraries/simpletest/compatibility.php b/application/third_party/simpletest/compatibility.php similarity index 100% rename from application/libraries/simpletest/compatibility.php rename to application/third_party/simpletest/compatibility.php diff --git a/application/libraries/simpletest/cookies.php b/application/third_party/simpletest/cookies.php similarity index 100% rename from application/libraries/simpletest/cookies.php rename to application/third_party/simpletest/cookies.php diff --git a/application/libraries/simpletest/default_reporter.php b/application/third_party/simpletest/default_reporter.php similarity index 100% rename from application/libraries/simpletest/default_reporter.php rename to application/third_party/simpletest/default_reporter.php diff --git a/application/libraries/simpletest/detached.php b/application/third_party/simpletest/detached.php similarity index 100% rename from application/libraries/simpletest/detached.php rename to application/third_party/simpletest/detached.php diff --git a/application/libraries/simpletest/dumper.php b/application/third_party/simpletest/dumper.php similarity index 100% rename from application/libraries/simpletest/dumper.php rename to application/third_party/simpletest/dumper.php diff --git a/application/libraries/simpletest/eclipse.php b/application/third_party/simpletest/eclipse.php similarity index 100% rename from application/libraries/simpletest/eclipse.php rename to application/third_party/simpletest/eclipse.php diff --git a/application/libraries/simpletest/encoding.php b/application/third_party/simpletest/encoding.php similarity index 100% rename from application/libraries/simpletest/encoding.php rename to application/third_party/simpletest/encoding.php diff --git a/application/libraries/simpletest/errors.php b/application/third_party/simpletest/errors.php similarity index 100% rename from application/libraries/simpletest/errors.php rename to application/third_party/simpletest/errors.php diff --git a/application/libraries/simpletest/exceptions.php b/application/third_party/simpletest/exceptions.php similarity index 100% rename from application/libraries/simpletest/exceptions.php rename to application/third_party/simpletest/exceptions.php diff --git a/application/libraries/simpletest/expectation.php b/application/third_party/simpletest/expectation.php similarity index 100% rename from application/libraries/simpletest/expectation.php rename to application/third_party/simpletest/expectation.php diff --git a/application/libraries/simpletest/form.php b/application/third_party/simpletest/form.php similarity index 100% rename from application/libraries/simpletest/form.php rename to application/third_party/simpletest/form.php diff --git a/application/libraries/simpletest/frames.php b/application/third_party/simpletest/frames.php similarity index 100% rename from application/libraries/simpletest/frames.php rename to application/third_party/simpletest/frames.php diff --git a/application/libraries/simpletest/http.php b/application/third_party/simpletest/http.php similarity index 100% rename from application/libraries/simpletest/http.php rename to application/third_party/simpletest/http.php diff --git a/application/libraries/simpletest/invoker.php b/application/third_party/simpletest/invoker.php similarity index 100% rename from application/libraries/simpletest/invoker.php rename to application/third_party/simpletest/invoker.php diff --git a/application/libraries/simpletest/mock_objects.php b/application/third_party/simpletest/mock_objects.php similarity index 100% rename from application/libraries/simpletest/mock_objects.php rename to application/third_party/simpletest/mock_objects.php diff --git a/application/libraries/simpletest/page.php b/application/third_party/simpletest/page.php similarity index 100% rename from application/libraries/simpletest/page.php rename to application/third_party/simpletest/page.php diff --git a/application/libraries/simpletest/php_parser.php b/application/third_party/simpletest/php_parser.php similarity index 100% rename from application/libraries/simpletest/php_parser.php rename to application/third_party/simpletest/php_parser.php diff --git a/application/libraries/simpletest/reflection_php4.php b/application/third_party/simpletest/reflection_php4.php similarity index 100% rename from application/libraries/simpletest/reflection_php4.php rename to application/third_party/simpletest/reflection_php4.php diff --git a/application/libraries/simpletest/reflection_php5.php b/application/third_party/simpletest/reflection_php5.php similarity index 100% rename from application/libraries/simpletest/reflection_php5.php rename to application/third_party/simpletest/reflection_php5.php diff --git a/application/libraries/simpletest/remote.php b/application/third_party/simpletest/remote.php similarity index 100% rename from application/libraries/simpletest/remote.php rename to application/third_party/simpletest/remote.php diff --git a/application/libraries/simpletest/reporter.php b/application/third_party/simpletest/reporter.php similarity index 100% rename from application/libraries/simpletest/reporter.php rename to application/third_party/simpletest/reporter.php diff --git a/application/libraries/simpletest/scorer.php b/application/third_party/simpletest/scorer.php similarity index 100% rename from application/libraries/simpletest/scorer.php rename to application/third_party/simpletest/scorer.php diff --git a/application/libraries/simpletest/selector.php b/application/third_party/simpletest/selector.php similarity index 100% rename from application/libraries/simpletest/selector.php rename to application/third_party/simpletest/selector.php diff --git a/application/libraries/simpletest/shell_tester.php b/application/third_party/simpletest/shell_tester.php similarity index 100% rename from application/libraries/simpletest/shell_tester.php rename to application/third_party/simpletest/shell_tester.php diff --git a/application/libraries/simpletest/simpletest.php b/application/third_party/simpletest/simpletest.php similarity index 100% rename from application/libraries/simpletest/simpletest.php rename to application/third_party/simpletest/simpletest.php diff --git a/application/libraries/simpletest/socket.php b/application/third_party/simpletest/socket.php similarity index 100% rename from application/libraries/simpletest/socket.php rename to application/third_party/simpletest/socket.php diff --git a/application/libraries/simpletest/tag.php b/application/third_party/simpletest/tag.php similarity index 100% rename from application/libraries/simpletest/tag.php rename to application/third_party/simpletest/tag.php diff --git a/application/libraries/simpletest/test_case.php b/application/third_party/simpletest/test_case.php similarity index 100% rename from application/libraries/simpletest/test_case.php rename to application/third_party/simpletest/test_case.php diff --git a/application/libraries/simpletest/tidy_parser.php b/application/third_party/simpletest/tidy_parser.php similarity index 100% rename from application/libraries/simpletest/tidy_parser.php rename to application/third_party/simpletest/tidy_parser.php diff --git a/application/libraries/simpletest/unit_tester.php b/application/third_party/simpletest/unit_tester.php similarity index 100% rename from application/libraries/simpletest/unit_tester.php rename to application/third_party/simpletest/unit_tester.php diff --git a/application/libraries/simpletest/url.php b/application/third_party/simpletest/url.php similarity index 100% rename from application/libraries/simpletest/url.php rename to application/third_party/simpletest/url.php diff --git a/application/libraries/simpletest/user_agent.php b/application/third_party/simpletest/user_agent.php similarity index 100% rename from application/libraries/simpletest/user_agent.php rename to application/third_party/simpletest/user_agent.php diff --git a/application/libraries/simpletest/web_tester.php b/application/third_party/simpletest/web_tester.php similarity index 100% rename from application/libraries/simpletest/web_tester.php rename to application/third_party/simpletest/web_tester.php diff --git a/application/libraries/simpletest/xml.php b/application/third_party/simpletest/xml.php similarity index 100% rename from application/libraries/simpletest/xml.php rename to application/third_party/simpletest/xml.php