tests: add initial simpletest unit tests for the xmlrpc stuff
git-svn-id: https://svn.code.sf.net/p/postfixadmin/code/trunk@581 a1433add-5e2c-0410-b055-b7f2511e0802postfixadmin-2.3
@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
require_once('common.php');
|
||||
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('Zend/XmlRpc/Client.php');
|
||||
require_once('Zend/Http/Client.php');
|
||||
require_once('Zend/Registry.php');
|
||||
|
||||
class RemoteTest extends UnitTestCase {
|
||||
|
||||
protected $server_url = 'http://orange/david/postfixadmin/trunk/xmlrpc.php';
|
||||
protected $username = 'roger@example.com';
|
||||
protected $password = 'patchthedog';
|
||||
|
||||
/* xmlrpc objects... */
|
||||
protected $user;
|
||||
protected $vacation;
|
||||
protected $alias;
|
||||
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
|
||||
}
|
||||
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// ensure a user exists as per the above...
|
||||
|
||||
$table_vacation = table_by_key('vacation');
|
||||
$table_alias = table_by_key('alias');
|
||||
$table_mailbox = table_by_key('mailbox');
|
||||
$table_domain = table_by_key('domain');
|
||||
$username = escape_string($this->username);
|
||||
$password = escape_string(pacrypt($this->password));
|
||||
|
||||
db_query("DELETE FROM $table_vacation WHERE email = '$username'");
|
||||
db_query("DELETE FROM $table_alias WHERE domain = 'example.com'");
|
||||
db_query("DELETE FROM $table_mailbox WHERE domain = 'example.com'");
|
||||
db_query("DELETE FROM $table_domain WHERE domain = 'example.com'");
|
||||
|
||||
// create new db records..
|
||||
$result = db_query("INSERT INTO $table_domain (domain, aliases, mailboxes) VALUES ('example.com', 100, 100)");
|
||||
if($result['rows'] != 1) {
|
||||
die("Failed to add domain to db....");
|
||||
}
|
||||
|
||||
$result = db_query("INSERT INTO $table_mailbox (username, password, name, local_part, domain) VALUES ('$username', '$password', 'test user', 'roger', 'example.com')");
|
||||
if($result['rows'] != 1) {
|
||||
die("Failed to add user to db....");
|
||||
}
|
||||
|
||||
$result = db_query("INSERT INTO $table_alias (address, goto, domain) VALUES ('$username', '$username', 'example.com')");
|
||||
if($result['rows'] != 1) {
|
||||
die("Failed to add alias to db....");
|
||||
}
|
||||
|
||||
try {
|
||||
$this->xmlrpc_client = new Zend_XmlRpc_Client($this->server_url);
|
||||
$http_client = $this->xmlrpc_client->getHttpClient();
|
||||
$http_client->setCookieJar();
|
||||
|
||||
$login_object = $this->xmlrpc_client->getProxy('login');
|
||||
$success = $login_object->login($this->username, $this->password);
|
||||
|
||||
if(!$success) {
|
||||
var_dump($success);
|
||||
die("Failed to login to xmlrpc interface");
|
||||
}
|
||||
|
||||
$this->user = $this->xmlrpc_client->getProxy('user');
|
||||
$this->alias = $this->xmlrpc_client->getProxy('alias');
|
||||
$this->vacation = $this->xmlrpc_client->getProxy('vacation');
|
||||
}
|
||||
catch(Exception $e) {
|
||||
var_dump($e);
|
||||
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
|
||||
die("Error setting up..");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
<?php
|
||||
/**
|
||||
* Test for Postfixadmin - remote vacation stuff
|
||||
*
|
||||
* @package tests
|
||||
*/
|
||||
|
||||
require_once('RemoteTest.php');
|
||||
|
||||
class RemoteVacationTest extends RemoteTest {
|
||||
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
global $CONF;
|
||||
|
||||
// Ensure config.inc.php is vaguely correct.
|
||||
if($CONF['vacation'] != 'YES' || $CONF['vacation_control'] != "YES") {
|
||||
die("Cannot run tests; vacation not enabled - see config.inc.php");
|
||||
}
|
||||
if($CONF['vacation_domain'] != 'autoreply.example.com') {
|
||||
die("Cannot run tests; vacation_domain is not set to autoreply.example.com - see config.inc.php");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds the test recipient data to the database.
|
||||
*/
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
}
|
||||
public function tearDown() {
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testIsVacationSupported() {
|
||||
try {
|
||||
$this->assertTrue($this->vacation->isVacationSupported());
|
||||
}
|
||||
catch(Exception $e){
|
||||
var_dump($e);
|
||||
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
|
||||
die("fail..");
|
||||
}
|
||||
}
|
||||
|
||||
public function testCheckVacation() {
|
||||
$this->assertFalse($this->vacation->checkVacation());
|
||||
}
|
||||
|
||||
|
||||
public function testGetDetails() {
|
||||
$details = $this->vacation->getDetails();
|
||||
$this->assertFalse($details); // empty by default (thansk to tearDown/setUp);
|
||||
}
|
||||
|
||||
public function testSetAway() {
|
||||
try {
|
||||
$this->assertFalse($this->vacation->checkVacation());
|
||||
$this->assertTrue($this->vacation->setAway('zzzz', 'aaaa'));
|
||||
$this->assertTrue($this->vacation->checkVacation());
|
||||
}
|
||||
catch(Exception $e) {
|
||||
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
|
||||
}
|
||||
$details = $this->vacation->getDetails();
|
||||
$this->assertEqual($details['subject'], 'zzzz');
|
||||
$this->assertEqual($details['body'], 'aaaa');
|
||||
|
||||
$this->vacation->remove();
|
||||
$details = $this->vacation->getDetails();
|
||||
$this->assertEqual($details['subject'], 'zzzz');
|
||||
$this->assertEqual($details['body'], 'aaaa');
|
||||
|
||||
$this->vacation->setAway('subject', 'body');
|
||||
$details = $this->vacation->getDetails();
|
||||
$this->assertEqual($details['subject'], 'subject');
|
||||
$this->assertEqual($details['body'], 'body');
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
<?php
|
||||
|
||||
ini_set('include_path', ini_get('include_path') . ':' . dirname(__FILE__) . '/../');
|
||||
require_once(dirname(__FILE__) . '/../common.php');
|
@ -0,0 +1,15 @@
|
||||
<?php
|
||||
/**
|
||||
* Responsible for test suite...
|
||||
* @package tests
|
||||
*/
|
||||
require_once(dirname(__FILE__) . '/common.php');
|
||||
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('simpletest/unit_tester.php');
|
||||
|
||||
$test = new GroupTest('Postfixadmin XMLRPC Unit Tests');
|
||||
|
||||
$test->addTestFile('./RemoteVacationTest.php');
|
||||
|
||||
exit($test->run(new TextReporter()) ? 0 : 1);
|
@ -0,0 +1,37 @@
|
||||
BACKLOG
|
||||
This is backed up stuff that defines the 1.0.1 release.
|
||||
|
||||
$Id: BACKLOG,v 1.10 2006/11/20 23:44:36 lastcraft Exp $
|
||||
|
||||
Unit tester
|
||||
-----------
|
||||
|
||||
Reporter
|
||||
--------
|
||||
|
||||
Mock objects
|
||||
------------
|
||||
Fix new type hinting bug in PHP 5.0.2 and above (1).
|
||||
|
||||
Parser
|
||||
------
|
||||
Add U flag to regexes to allow unicode (3).
|
||||
|
||||
Browser
|
||||
-------
|
||||
Add a file() loading command (4).
|
||||
Change getUrls() to return more information (2).
|
||||
|
||||
Web tester
|
||||
----------
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
Extension docs (1).
|
||||
Integrate SpikeSource docs (4).
|
||||
Write Eclipse plug-in guide (4).
|
||||
Add page for projects that use or extend SimpleTest (2).
|
||||
|
||||
Build
|
||||
-----
|
||||
Integrate German documentation (2).
|
@ -0,0 +1,340 @@
|
||||
Simple Test interface changes
|
||||
=============================
|
||||
Because the SimpleTest tool set is still evolving it is likely that tests
|
||||
written with earlier versions will fail with the newest ones. The most
|
||||
dramatic changes are in the alpha releases. Here is a list of possible
|
||||
problems and their fixes...
|
||||
|
||||
Method setWildcard() removed in mocks
|
||||
-------------------------------------
|
||||
Even setWildcard() has been removed in 1.0.1beta now.
|
||||
If you want to test explicitely for a '*' string, then
|
||||
simply pass in new IdenticalExpectation('*') instead.
|
||||
|
||||
No method _getTest() on mocks
|
||||
-----------------------------
|
||||
This has finally been removed. It was a pretty esoteric
|
||||
flex point anyway. It was there to allow the mocks to
|
||||
work with other test tools, but no one does this.
|
||||
|
||||
No method assertError(), assertNoErrors(), swallowErrors()
|
||||
----------------------------------------------------------
|
||||
These have been deprecated in 1.0.1beta in favour of
|
||||
expectError() and expectException(). assertNoErrors() is
|
||||
redundant if you use expectError() as failures are now reported
|
||||
immediately.
|
||||
|
||||
No method TestCase::signal()
|
||||
----------------------------
|
||||
This has been deprecated in favour of triggering an error or
|
||||
throwing an exception. Deprecated as of 1.0.1beta.
|
||||
|
||||
No method TestCase::sendMessage()
|
||||
---------------------------------
|
||||
This has been deprecated as of 1.0.1beta.
|
||||
|
||||
Failure to connect now emits failures
|
||||
-------------------------------------
|
||||
It used to be that you would have to use the
|
||||
getTransferError() call on the web tester to see if
|
||||
there was a socket level error in a fetch. This check
|
||||
is now always carried out by the WebTestCase unless
|
||||
the fetch is prefaced with WebTestCase::ignoreErrors().
|
||||
The ignore directive only lasts for test case fetching
|
||||
action such as get() and click().
|
||||
|
||||
No method SimpleTestOptions::ignore()
|
||||
-------------------------------------
|
||||
This is deprecated in version 1.0.1beta and has been moved
|
||||
to SimpleTest::ignore() as that is more readable. In
|
||||
addition, parent classes are also ignored automatically.
|
||||
If you are using PHP5 you can skip this directive simply
|
||||
by marking your test case as abstract.
|
||||
|
||||
No method assertCopy()
|
||||
----------------------
|
||||
This is deprecated in 1.0.1 in favour of assertClone().
|
||||
The assertClone() method is slightly different in that
|
||||
the objects must be identical, but without being a
|
||||
reference. It is thus not a strict inversion of
|
||||
assertReference().
|
||||
|
||||
Constructor wildcard override has no effect in mocks
|
||||
----------------------------------------------------
|
||||
As of 1.0.1beta this is now set with setWildcard() instead
|
||||
of in the constructor.
|
||||
|
||||
No methods setStubBaseClass()/getStubBaseClass()
|
||||
------------------------------------------------
|
||||
As mocks are now used instead of stubs, these methods
|
||||
stopped working and are now removed as of the 1.0.1beta
|
||||
release. The mock objects may be freely used instead.
|
||||
|
||||
No method addPartialMockCode()
|
||||
------------------------------
|
||||
The ability to insert arbitrary partial mock code
|
||||
has been removed. This was a low value feature
|
||||
causing needless complications. It was removed
|
||||
in the 1.0.1beta release.
|
||||
|
||||
No method setMockBaseClass()
|
||||
----------------------------
|
||||
The ability to change the mock base class has been
|
||||
scheduled for removal and is deprecated since the
|
||||
1.0.1beta version. This was a rarely used feature
|
||||
except as a workaround for PHP5 limitations. As
|
||||
these limitations are being resolved it's hoped
|
||||
that the bundled mocks can be used directly.
|
||||
|
||||
No class Stub
|
||||
-------------
|
||||
Server stubs are deprecated from 1.0.1 as the mocks now
|
||||
have exactly the same interface. Just use mock objects
|
||||
instead.
|
||||
|
||||
No class SimpleTestOptions
|
||||
--------------------------
|
||||
This was replced by the shorter SimpleTest in 1.0.1beta1
|
||||
and is since deprecated.
|
||||
|
||||
No file simple_test.php
|
||||
-----------------------
|
||||
This was renamed test_case.php in 1.0.1beta to more accurately
|
||||
reflect it's purpose. This file should never be directly
|
||||
included in test suites though, as it's part of the
|
||||
underlying mechanics and has a tendency to be refactored.
|
||||
|
||||
No class WantedPatternExpectation
|
||||
---------------------------------
|
||||
This was deprecated in 1.0.1alpha in favour of the simpler
|
||||
name PatternExpectation.
|
||||
|
||||
No class NoUnwantedPatternExpectation
|
||||
-------------------------------------
|
||||
This was deprecated in 1.0.1alpha in favour of the simpler
|
||||
name NoPatternExpectation.
|
||||
|
||||
No method assertNoUnwantedPattern()
|
||||
-----------------------------------
|
||||
This has been renamed to assertNoPattern() in 1.0.1alpha and
|
||||
the old form is deprecated.
|
||||
|
||||
No method assertWantedPattern()
|
||||
-------------------------------
|
||||
This has been renamed to assertPattern() in 1.0.1alpha and
|
||||
the old form is deprecated.
|
||||
|
||||
No method assertExpectation()
|
||||
-----------------------------
|
||||
This was renamed as assert() in 1.0.1alpha and the old form
|
||||
has been deprecated.
|
||||
|
||||
No class WildcardExpectation
|
||||
----------------------------
|
||||
This was a mostly internal class for the mock objects. It was
|
||||
renamed AnythingExpectation to bring it closer to JMock and
|
||||
NMock in version 1.0.1alpha.
|
||||
|
||||
Missing UnitTestCase::assertErrorPattern()
|
||||
------------------------------------------
|
||||
This method is deprecated for version 1.0.1 onwards.
|
||||
This method has been subsumed by assertError() that can now
|
||||
take an expectation. Simply pass a PatternExpectation
|
||||
into assertError() to simulate the old behaviour.
|
||||
|
||||
No HTML when matching page elements
|
||||
-----------------------------------
|
||||
This behaviour has been switched to using plain text as if it
|
||||
were seen by the user of the browser. This means that HTML tags
|
||||
are suppressed, entities are converted and whitespace is
|
||||
normalised. This should make it easier to match items in forms.
|
||||
Also images are replaced with their "alt" text so that they
|
||||
can be matched as well.
|
||||
|
||||
No method SimpleRunner::_getTestCase()
|
||||
--------------------------------------
|
||||
This was made public as getTestCase() in 1.0RC2.
|
||||
|
||||
No method restartSession()
|
||||
--------------------------
|
||||
This was renamed to restart() in the WebTestCase, SimpleBrowser
|
||||
and the underlying SimpleUserAgent in 1.0RC2. Because it was
|
||||
undocumented anyway, no attempt was made at backward
|
||||
compatibility.
|
||||
|
||||
My custom test case ignored by tally()
|
||||
--------------------------------------
|
||||
The _assertTrue method has had it's signature changed due to a bug
|
||||
in the PHP 5.0.1 release. You must now use getTest() from within
|
||||
that method to get the test case. Mock compatibility with other
|
||||
unit testers is now deprecated as of 1.0.1alpha as PEAR::PHPUnit2
|
||||
should soon have mock support of it's own.
|
||||
|
||||
Broken code extending SimpleRunner
|
||||
----------------------------------
|
||||
This was replaced with SimpleScorer so that I could use the runner
|
||||
name in another class. This happened in RC1 development and there
|
||||
is no easy backward compatibility fix. The solution is simply to
|
||||
extend SimpleScorer instead.
|
||||
|
||||
Missing method getBaseCookieValue()
|
||||
-----------------------------------
|
||||
This was renamed getCurrentCookieValue() in RC1.
|
||||
|
||||
Missing files from the SimpleTest suite
|
||||
---------------------------------------
|
||||
Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant
|
||||
to point at the SimpleTest folder location before any of the toolset
|
||||
was loaded. This is no longer documented as it is now unnecessary
|
||||
for later versions. If you are using an earlier version you may
|
||||
need this constant. Consult the documentation that was bundled with
|
||||
the release that you are using or upgrade to Beta6 or later.
|
||||
|
||||
No method SimpleBrowser::getCurrentUrl()
|
||||
--------------------------------------
|
||||
This is replaced with the more versatile showRequest() for
|
||||
debugging. It only existed in this context for version Beta5.
|
||||
Later versions will have SimpleBrowser::getHistory() for tracking
|
||||
paths through pages. It is renamed as getUrl() since 1.0RC1.
|
||||
|
||||
No method Stub::setStubBaseClass()
|
||||
----------------------------------
|
||||
This method has finally been removed in 1.0RC1. Use
|
||||
SimpleTestOptions::setStubBaseClass() instead.
|
||||
|
||||
No class CommandLineReporter
|
||||
----------------------------
|
||||
This was renamed to TextReporter in Beta3 and the deprecated version
|
||||
was removed in 1.0RC1.
|
||||
|
||||
No method requireReturn()
|
||||
-------------------------
|
||||
This was deprecated in Beta3 and is now removed.
|
||||
|
||||
No method expectCookie()
|
||||
------------------------
|
||||
This method was abruptly removed in Beta4 so as to simplify the internals
|
||||
until another mechanism can replace it. As a workaround it is necessary
|
||||
to assert that the cookie has changed by setting it before the page
|
||||
fetch and then assert the desired value.
|
||||
|
||||
No method clickSubmitByFormId()
|
||||
-------------------------------
|
||||
This method had an incorrect name as no button was involved. It was
|
||||
renamed to submitByFormId() in Beta4 and the old version deprecated.
|
||||
Now removed.
|
||||
|
||||
No method paintStart() or paintEnd()
|
||||
------------------------------------
|
||||
You should only get this error if you have subclassed the lower level
|
||||
reporting and test runner machinery. These methods have been broken
|
||||
down into events for test methods, events for test cases and events
|
||||
for group tests. The new methods are...
|
||||
|
||||
paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart()
|
||||
paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd()
|
||||
|
||||
This change was made in Beta3, ironically to make it easier to subclass
|
||||
the inner machinery. Simply duplicating the code you had in the previous
|
||||
methods should provide a temporary fix.
|
||||
|
||||
No class TestDisplay
|
||||
--------------------
|
||||
This has been folded into SimpleReporter in Beta3 and is now deprecated.
|
||||
It was removed in RC1.
|
||||
|
||||
No method WebTestCase::fetch()
|
||||
------------------------------
|
||||
This was renamed get() in Alpha8. It is removed in Beta3.
|
||||
|
||||
No method submit()
|
||||
------------------
|
||||
This has been renamed clickSubmit() in Beta1. The old method was
|
||||
removed in Beta2.
|
||||
|
||||
No method clearHistory()
|
||||
------------------------
|
||||
This method is deprecated in Beta2 and removed in RC1.
|
||||
|
||||
No method getCallCount()
|
||||
------------------------
|
||||
This method has been deprecated since Beta1 and has now been
|
||||
removed. There are now more ways to set expectations on counts
|
||||
and so this method should be unecessery. Removed in RC1.
|
||||
|
||||
Cannot find file *
|
||||
------------------
|
||||
The following public name changes have occoured...
|
||||
|
||||
simple_html_test.php --> reporter.php
|
||||
simple_mock.php --> mock_objects.php
|
||||
simple_unit.php --> unit_tester.php
|
||||
simple_web.php --> web_tester.php
|
||||
|
||||
The old names were deprecated in Alpha8 and removed in Beta1.
|
||||
|
||||
No method attachObserver()
|
||||
--------------------------
|
||||
Prior to the Alpha8 release the old internal observer pattern was
|
||||
gutted and replaced with a visitor. This is to trade flexibility of
|
||||
test case expansion against the ease of writing user interfaces.
|
||||
|
||||
Code such as...
|
||||
|
||||
$test = &new MyTestCase();
|
||||
$test->attachObserver(new TestHtmlDisplay());
|
||||
$test->run();
|
||||
|
||||
...should be rewritten as...
|
||||
|
||||
$test = &new MyTestCase();
|
||||
$test->run(new HtmlReporter());
|
||||
|
||||
If you previously attached multiple observers then the workaround
|
||||
is to run the tests twice, once with each, until they can be combined.
|
||||
For one observer the old method is simulated in Alpha 8, but is
|
||||
removed in Beta1.
|
||||
|
||||
No class TestHtmlDisplay
|
||||
------------------------
|
||||
This class has been renamed to HtmlReporter in Alpha8. It is supported,
|
||||
but deprecated in Beta1 and removed in Beta2. If you have subclassed
|
||||
the display for your own design, then you will have to extend this
|
||||
class (HtmlReporter) instead.
|
||||
|
||||
If you have accessed the event queue by overriding the notify() method
|
||||
then I am afraid you are in big trouble :(. The reporter is now
|
||||
carried around the test suite by the runner classes and the methods
|
||||
called directly. In the unlikely event that this is a problem and
|
||||
you don't want to upgrade the test tool then simplest is to write your
|
||||
own runner class and invoke the tests with...
|
||||
|
||||
$test->accept(new MyRunner(new MyReporter()));
|
||||
|
||||
...rather than the run method. This should be easier to extend
|
||||
anyway and gives much more control. Even this method is overhauled
|
||||
in Beta3 where the runner class can be set within the test case. Really
|
||||
the best thing to do is to upgrade to this version as whatever you were
|
||||
trying to achieve before should now be very much easier.
|
||||
|
||||
Missing set options method
|
||||
--------------------------
|
||||
All test suite options are now in one class called SimpleTestOptions.
|
||||
This means that options are set differently...
|
||||
|
||||
GroupTest::ignore() --> SimpleTestOptions::ignore()
|
||||
Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass()
|
||||
|
||||
These changed in Alpha8 and the old versions are now removed in RC1.
|
||||
|
||||
No method setExpected*()
|
||||
------------------------
|
||||
The mock expectations changed their names in Alpha4 and the old names
|
||||
ceased to be supported in Alpha8. The changes are...
|
||||
|
||||
setExpectedArguments() --> expectArguments()
|
||||
setExpectedArgumentsSequence() --> expectArgumentsAt()
|
||||
setExpectedCallCount() --> expectCallCount()
|
||||
setMaximumCallCount() --> expectMaximumCallCount()
|
||||
|
||||
The parameters remained the same.
|
@ -0,0 +1,502 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
@ -0,0 +1,108 @@
|
||||
SimpleTest
|
||||
==========
|
||||
You probably got this package from...
|
||||
http://simpletest.sourceforge.net/projects/simpletest/
|
||||
|
||||
If there is no licence agreement with this package please download
|
||||
a version from the location above. You must read and accept that
|
||||
licence to use this software. The file is titled simply LICENSE.
|
||||
|
||||
What is it? It's a framework for unit testing, web site testing and
|
||||
mock objects for PHP 4.2.0+.
|
||||
|
||||
If you have used JUnit you will find this PHP unit testing version very
|
||||
similar. Also included is a mock objects and server stubs generator.
|
||||
The stubs can have return values set for different arguments, can have
|
||||
sequences set also by arguments and can return items by reference.
|
||||
The mocks inherit all of this functionality and can also have
|
||||
expectations set, again in sequences and for different arguments.
|
||||
|
||||
A web tester similar in concept to JWebUnit is also included. There is no
|
||||
JavaScript or tables support, but forms, authentication, cookies and
|
||||
frames are handled.
|
||||
|
||||
You can see a release schedule at http://www.lastcraft.com/overview.php
|
||||
which is also copied to the documentation folder with this release.
|
||||
A full PHPDocumenter API documentation exists at
|
||||
http://simpletest.sourceforge.net/.
|
||||
|
||||
The user interface is minimal
|
||||
in the extreme, but a lot of information flows from the test suite.
|
||||
After version 1.0 we will release a better web UI, but we are leaving XUL
|
||||
and GTk versions to volunteers as everybody has their own opinion
|
||||
on a good GUI, and we don't want to discourage development by shipping
|
||||
one with the toolkit.
|
||||
|
||||
You are looking at a first full release. The unit tests for SimpleTest
|
||||
itself can be run here...
|
||||
|
||||
simpletest/test/unit_tests.php
|
||||
|
||||
And tests involving live network connections as well are here...
|
||||
|
||||
simpletest/test/all_tests.php
|
||||
|
||||
The full tests will typically overrun the 8Mb limit usually allowed
|
||||
to a PHP process. A workaround is to run the tests on the command
|
||||
with a custom php.ini file if you do not have access to your server
|
||||
version.
|
||||
|
||||
You will have to edit the all_tests.php file if you are accesssing
|
||||
the internet through a proxy server. See the comments in all_tests.php
|
||||
for instructions.
|
||||
|
||||
The full tests read some test data from the LastCraft site. If the site
|
||||
is down or has been modified for a later version then you will get
|
||||
spurious errors. A unit_tests.php failure on the other hand would be
|
||||
very serious. As far as we know we haven't yet managed to check in any
|
||||
unit test failures so please correct us if you find one.
|
||||
|
||||
Even if all of the tests run please verify that your existing test suites
|
||||
also function as expected. If they don't see the file...
|
||||
|
||||
HELP_MY_TESTS_DONT_WORK_ANYMORE
|
||||
|
||||
This contains information on interface changes. It also points out
|
||||
deprecated interfaces so you should read this even if all of
|
||||
your current tests appear to run.
|
||||
|
||||
There is a documentation folder which contains the core reference information
|
||||
in English and French, although this information is fairly basic.
|
||||
You can find a tutorial on...
|
||||
|
||||
http://www.lastcraft.com/first_test_tutorial.php
|
||||
|
||||
...to get you started and this material will eventually become included
|
||||
with the project documentation. A French translation exists at...
|
||||
|
||||
http://www.onpk.net/index.php/2005/01/12/254-tutoriel-simpletest-decouvrir-les-tests-unitaires.
|
||||
|
||||
If you download and use and possibly even extend this tool, please let us
|
||||
know. Any feedback, even bad, is always welcome and we will work to get
|
||||
your suggestions into the next release. Ideally please send your
|
||||
comments to...
|
||||
|
||||
simpletest-support@lists.sourceforge.net
|
||||
|
||||
...so that others can read them too. We usually try to respond within 48
|
||||
hours.
|
||||
|
||||
There is no change log as yet except at Sourceforge. You can visit the
|
||||
release notes to see the completed TODO list after each cycle and also the
|
||||
status of any bugs, but if the bug is recent then it will be fixed in CVS only.
|
||||
The CVS check-ins always have all the tests passing and so CVS snapshots should
|
||||
be pretty usable, although the code may not look so good internally.
|
||||
|
||||
Oh, yes. It is called "Simple" because it should be simple to
|
||||
use. We intend to add a complete set of tools for a test first
|
||||
and "test as you code" type of development. "Simple" does not
|
||||
mean "Lite" in this context.
|
||||
|
||||
Thanks to everyone who has sent comments and offered suggestions. They
|
||||
really are invaluable, but sadly you are too many to mention in full.
|
||||
Thanks to all on the advanced PHP forum on SitePoint, especially Harry
|
||||
Feucks. Early adopters are always an inspiration.
|
||||
|
||||
yours Marcus Baker, Jason Sweat, Travis Swicegood and Perrick Penet.
|
||||
--
|
||||
marcus@lastcraft.com
|
@ -0,0 +1,32 @@
|
||||
TODO
|
||||
This is immediate stuff only for this iteration (1.0.1beta2) of 15 hours.
|
||||
|
||||
$Id: TODO,v 1.508 2007/01/16 23:35:21 lastcraft Exp $
|
||||
|
||||
Unit tester
|
||||
-----------
|
||||
Fix errors_test.php in PHP 5.2+ (2).
|
||||
|
||||
Reporter
|
||||
--------
|
||||
Dumper should be passed in testMessage() call to expectation (3).
|
||||
|
||||
Mock objects
|
||||
------------
|
||||
Mocks should inherit mocked class (9/4).
|
||||
|
||||
Parser
|
||||
------
|
||||
|
||||
Browser
|
||||
-------
|
||||
|
||||
Web tester
|
||||
----------
|
||||
|
||||
Documentation
|
||||
-------------
|
||||
Update roadmap (1).
|
||||
|
||||
Build
|
||||
-----
|
@ -0,0 +1 @@
|
||||
1.0.1beta2
|
@ -0,0 +1,238 @@
|
||||
<?php
|
||||
/**
|
||||
* Base include file for SimpleTest
|
||||
* @package SimpleTest
|
||||
* @subpackage WebTester
|
||||
* @version $Id: authentication.php,v 1.10 2005/07/26 01:27:18 lastcraft Exp $
|
||||
*/
|
||||
/**
|
||||
* include http class
|
||||
*/
|
||||
require_once(dirname(__FILE__) . '/http.php');
|
||||
|
||||
/**
|
||||
* Represents a single security realm's identity.
|
||||
* @package SimpleTest
|
||||
* @subpackage WebTester
|
||||
*/
|
||||
class SimpleRealm {
|
||||
var $_type;
|
||||
var $_root;
|
||||
var $_username;
|
||||
var $_password;
|
||||
|
||||
/**
|
||||
* Starts with the initial entry directory.
|
||||
* @param string $type Authentication type for this
|
||||
* realm. Only Basic authentication
|
||||
* is currently supported.
|
||||
* @param SimpleUrl $url Somewhere in realm.
|
||||
* @access public
|
||||
*/
|
||||
function SimpleRealm($type, $url) {
|
||||
$this->_type = $type;
|
||||
$this->_root = $url->getBasePath();
|
||||
$this->_username = false;
|
||||
$this->_password = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds another location to the realm.
|
||||
* @param SimpleUrl $url Somewhere in realm.
|
||||
* @access public
|
||||
*/
|
||||
function stretch($url) {
|
||||
$this->_root = $this->_getCommonPath($this->_root, $url->getPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the common starting path.
|
||||
* @param string $first Path to compare.
|
||||
* @param string $second Path to compare.
|
||||
* @return string Common directories.
|
||||
* @access private
|
||||
*/
|
||||
function _getCommonPath($first, $second) {
|
||||
$first = explode('/', $first);
|
||||
$second = explode('/', $second);
|
||||
for ($i = 0; $i < min(count($first), count($second)); $i++) {
|
||||
if ($first[$i] != $second[$i]) {
|
||||
return implode('/', array_slice($first, 0, $i)) . '/';
|
||||
}
|
||||
}
|
||||
return implode('/', $first) . '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the identity to try within this realm.
|
||||
* @param string $username Username in authentication dialog.
|
||||
* @param string $username Password in authentication dialog.
|
||||
* @access public
|
||||
*/
|
||||
function setIdentity($username, $password) {
|
||||
$this->_username = $username;
|
||||
$this->_password = $password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for current identity.
|
||||
* @return string Last succesful username.
|
||||
* @access public
|
||||
*/
|
||||
function getUsername() {
|
||||
return $this->_username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for current identity.
|
||||
* @return string Last succesful password.
|
||||
* @access public
|
||||
*/
|
||||
function getPassword() {
|
||||
return $this->_password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to see if the URL is within the directory
|
||||
* tree of the realm.
|
||||
* @param SimpleUrl $url URL to test.
|
||||
* @return boolean True if subpath.
|
||||
* @access public
|
||||
*/
|
||||
function isWithin($url) {
|
||||
if ($this->_isIn($this->_root, $url->getBasePath())) {
|
||||
return true;
|
||||
}
|
||||
if ($this->_isIn($this->_root, $url->getBasePath() . $url->getPage() . '/')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests to see if one string is a substring of
|
||||
* another.
|
||||
* @param string $part Small bit.
|
||||
* @param string $whole Big bit.
|
||||
* @return boolean True if the small bit is
|
||||
* in the big bit.
|
||||
* @access private
|
||||
*/
|
||||
function _isIn($part, $whole) {
|
||||
return strpos($whole, $part) === 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manages security realms.
|
||||
* @package SimpleTest
|
||||
* @subpackage WebTester
|
||||
*/
|
||||
class SimpleAuthenticator {
|
||||
var $_realms;
|
||||
|
||||
/**
|
||||
* Clears the realms.
|
||||
* @access public
|
||||
*/
|
||||
function SimpleAuthenticator() {
|
||||
$this->restartSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts with no realms set up.
|
||||
* @access public
|
||||
*/
|
||||
function restartSession() {
|
||||
$this->_realms = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new realm centered the current URL.
|
||||
* Browsers vary wildly on their behaviour in this
|
||||
* regard. Mozilla ignores the realm and presents
|
||||
* only when challenged, wasting bandwidth. IE
|
||||
* just carries on presenting until a new challenge
|
||||
* occours. SimpleTest tries to follow the spirit of
|
||||
* the original standards committee and treats the
|
||||
* base URL as the root of a file tree shaped realm.
|
||||
* @param SimpleUrl $url Base of realm.
|
||||
* @param string $type Authentication type for this
|
||||
* realm. Only Basic authentication
|
||||
* is currently supported.
|
||||
* @param string $realm Name of realm.
|
||||
* @access public
|
||||
*/
|
||||
function addRealm($url, $type, $realm) {
|
||||
$this->_realms[$url->getHost()][$realm] = new SimpleRealm($type, $url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current identity to be presented
|
||||
* against that realm.
|
||||
* @param string $host Server hosting realm.
|
||||
* @param string $realm Name of realm.
|
||||
* @param string $username Username for realm.
|
||||
* @param string $password Password for realm.
|
||||
* @access public
|
||||
*/
|
||||
function setIdentityForRealm($host, $realm, $username, $password) {
|
||||
if (isset($this->_realms[$host][$realm])) {
|
||||
$this->_realms[$host][$realm]->setIdentity($username, $password);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the name of the realm by comparing URLs.
|
||||
* @param SimpleUrl $url URL to test.
|
||||
* @return SimpleRealm Name of realm.
|
||||
* @access private
|
||||
*/
|
||||
function _findRealmFromUrl($url) {
|
||||
if (! isset($this->_realms[$url->getHost()])) {
|
||||
return false;
|
||||
}
|
||||
foreach ($this->_realms[$url->getHost()] as $name => $realm) {
|
||||
if ($realm->isWithin($url)) {
|
||||
return $realm;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presents the appropriate headers for this location.
|
||||
* @param SimpleHttpRequest $request Request to modify.
|
||||
* @param SimpleUrl $url Base of realm.
|
||||
* @access public
|
||||
*/
|
||||
function addHeaders(&$request, $url) {
|
||||
if ($url->getUsername() && $url->getPassword()) {
|
||||
$username = $url->getUsername();
|
||||
$password = $url->getPassword();
|
||||
} elseif ($realm = $this->_findRealmFromUrl($url)) {
|
||||
$username = $realm->getUsername();
|
||||
$password = $realm->getPassword();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
$this->addBasicHeaders($request, $username, $password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Presents the appropriate headers for this
|
||||
* location for basic authentication.
|
||||
* @param SimpleHttpRequest $request Request to modify.
|
||||
* @param string $username Username for realm.
|
||||
* @param string $password Password for realm.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function addBasicHeaders(&$request, $username, $password) {
|
||||
if ($username && $password) {
|
||||
$request->addHeaderLine(
|
||||
'Authorization: Basic ' . base64_encode("$username:$password"));
|
||||
}
|
||||
}
|
||||
}
|
||||
?>
|
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
/**
|
||||
* This file contains the following classes: {@link SimpleCollector},
|
||||
* {@link SimplePatternCollector}.
|
||||
*
|
||||
* @author Travis Swicegood <development@domain51.com>
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
* @version $Id: collector.php,v 1.11 2006/11/21 00:26:55 lastcraft Exp $
|
||||
*/
|
||||
|
||||
/**
|
||||
* The basic collector for {@link GroupTest}
|
||||
*
|
||||
* @see collect(), GroupTest::collect()
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
*/
|
||||
class SimpleCollector {
|
||||
|
||||
/**
|
||||
* Strips off any kind of slash at the end so as to normalise the path.
|
||||
* @param string $path Path to normalise.
|
||||
* @return string Path without trailing slash.
|
||||
*/
|
||||
function _removeTrailingSlash($path) {
|
||||
if (substr($path, -1) == DIRECTORY_SEPARATOR) {
|
||||
return substr($path, 0, -1);
|
||||
} elseif (substr($path, -1) == '/') {
|
||||
return substr($path, 0, -1);
|
||||
} else {
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans the directory and adds what it can.
|
||||
* @param object $test Group test with {@link GroupTest::addTestFile()} method.
|
||||
* @param string $path Directory to scan.
|
||||
* @see _attemptToAdd()
|
||||
*/
|
||||
function collect(&$test, $path) {
|
||||
$path = $this->_removeTrailingSlash($path);
|
||||
if ($handle = opendir($path)) {
|
||||
while (($entry = readdir($handle)) !== false) {
|
||||
$this->_handle($test, $path . DIRECTORY_SEPARATOR . $entry);
|
||||
}
|
||||
closedir($handle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method determines what should be done with a given file and adds
|
||||
* it via {@link GroupTest::addTestFile()} if necessary.
|
||||
*
|
||||
* This method should be overriden to provide custom matching criteria,
|
||||
* such as pattern matching, recursive matching, etc. For an example, see
|
||||
* {@link SimplePatternCollector::_handle()}.
|
||||
*
|
||||
* @param object $test Group test with {@link GroupTest::addTestFile()} method.
|
||||
* @param string $filename A filename as generated by {@link collect()}
|
||||
* @see collect()
|
||||
* @access protected
|
||||
*/
|
||||
function _handle(&$test, $file) {
|
||||
if (! is_dir($file)) {
|
||||
$test->addTestFile($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An extension to {@link SimpleCollector} that only adds files matching a
|
||||
* given pattern.
|
||||
*
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
* @see SimpleCollector
|
||||
*/
|
||||
class SimplePatternCollector extends SimpleCollector {
|
||||
var $_pattern;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $pattern Perl compatible regex to test name against
|
||||
* See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE}
|
||||
* for full documentation of valid pattern.s
|
||||
*/
|
||||
function SimplePatternCollector($pattern = '/php$/i') {
|
||||
$this->_pattern = $pattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to add files that match a given pattern.
|
||||
*
|
||||
* @see SimpleCollector::_handle()
|
||||
* @param object $test Group test with {@link GroupTest::addTestFile()} method.
|
||||
* @param string $path Directory to scan.
|
||||
* @access protected
|
||||
*/
|
||||
function _handle(&$test, $filename) {
|
||||
if (preg_match($this->_pattern, $filename)) {
|
||||
parent::_handle($test, $filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
?>
|
@ -0,0 +1,173 @@
|
||||
<?php
|
||||
/**
|
||||
* base include file for SimpleTest
|
||||
* @package SimpleTest
|
||||
* @version $Id: compatibility.php,v 1.11 2006/11/08 16:15:06 lastcraft Exp $
|
||||
*/
|
||||
|
||||
/**
|
||||
* Static methods for compatibility between different
|
||||
* PHP versions.
|
||||
* @package SimpleTest
|
||||
*/
|
||||
class SimpleTestCompatibility {
|
||||
|
||||
/**
|
||||
* Creates a copy whether in PHP5 or PHP4.
|
||||
* @param object $object Thing to copy.
|
||||
* @return object A copy.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function copy($object) {
|
||||
if (version_compare(phpversion(), '5') >= 0) {
|
||||
eval('$copy = clone $object;');
|
||||
return $copy;
|
||||
}
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity test. Drops back to equality + types for PHP5
|
||||
* objects as the === operator counts as the
|
||||
* stronger reference constraint.
|
||||
* @param mixed $first Test subject.
|
||||
* @param mixed $second Comparison object.
|
||||
* @return boolean True if identical.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function isIdentical($first, $second) {
|
||||
if ($first != $second) {
|
||||
return false;
|
||||
}
|
||||
if (version_compare(phpversion(), '5') >= 0) {
|
||||
return SimpleTestCompatibility::_isIdenticalType($first, $second);
|
||||
}
|
||||
return ($first === $second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive type test.
|
||||
* @param mixed $first Test subject.
|
||||
* @param mixed $second Comparison object.
|
||||
* @return boolean True if same type.
|
||||
* @access private
|
||||
* @static
|
||||
*/
|
||||
function _isIdenticalType($first, $second) {
|
||||
if (gettype($first) != gettype($second)) {
|
||||
return false;
|
||||
}
|
||||
if (is_object($first) && is_object($second)) {
|
||||
if (get_class($first) != get_class($second)) {
|
||||
return false;
|
||||
}
|
||||
return SimpleTestCompatibility::_isArrayOfIdenticalTypes(
|
||||
get_object_vars($first),
|
||||
get_object_vars($second));
|
||||
}
|
||||
if (is_array($first) && is_array($second)) {
|
||||
return SimpleTestCompatibility::_isArrayOfIdenticalTypes($first, $second);
|
||||
}
|
||||
if ($first !== $second) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive type test for each element of an array.
|
||||
* @param mixed $first Test subject.
|
||||
* @param mixed $second Comparison object.
|
||||
* @return boolean True if identical.
|
||||
* @access private
|
||||
* @static
|
||||
*/
|
||||
function _isArrayOfIdenticalTypes($first, $second) {
|
||||
if (array_keys($first) != array_keys($second)) {
|
||||
return false;
|
||||
}
|
||||
foreach (array_keys($first) as $key) {
|
||||
$is_identical = SimpleTestCompatibility::_isIdenticalType(
|
||||
$first[$key],
|
||||
$second[$key]);
|
||||
if (! $is_identical) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for two variables being aliases.
|
||||
* @param mixed $first Test subject.
|
||||
* @param mixed $second Comparison object.
|
||||
* @return boolean True if same.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function isReference(&$first, &$second) {
|
||||
if (version_compare(phpversion(), '5', '>=') && is_object($first)) {
|
||||
return ($first === $second);
|
||||
}
|
||||
if (is_object($first) && is_object($second)) {
|
||||
$id = uniqid("test");
|
||||
$first->$id = true;
|
||||
$is_ref = isset($second->$id);
|
||||
unset($first->$id);
|
||||
return $is_ref;
|
||||
}
|
||||
$temp = $first;
|
||||
$first = uniqid("test");
|
||||
$is_ref = ($first === $second);
|
||||
$first = $temp;
|
||||
return $is_ref;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to see if an object is a member of a
|
||||
* class hiearchy.
|
||||
* @param object $object Object to test.
|
||||
* @param string $class Root name of hiearchy.
|
||||
* @return boolean True if class in hiearchy.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function isA($object, $class) {
|
||||
if (version_compare(phpversion(), '5') >= 0) {
|
||||
if (! class_exists($class, false)) {
|
||||
if (function_exists('interface_exists')) {
|
||||
if (! interface_exists($class, false)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
eval("\$is_a = \$object instanceof $class;");
|
||||
return $is_a;
|
||||
}
|
||||
if (function_exists('is_a')) {
|
||||
return is_a($object, $class);
|
||||
}
|
||||
return ((strtolower($class) == get_class($object))
|
||||
or (is_subclass_of($object, $class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a socket timeout for each chunk.
|
||||
* @param resource $handle Socket handle.
|
||||
* @param integer $timeout Limit in seconds.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function setTimeout($handle, $timeout) {
|
||||
if (function_exists('stream_set_timeout')) {
|
||||
stream_set_timeout($handle, $timeout, 0);
|
||||
} elseif (function_exists('socket_set_timeout')) {
|
||||
socket_set_timeout($handle, $timeout, 0);
|
||||
} elseif (function_exists('set_socket_timeout')) {
|
||||
set_socket_timeout($handle, $timeout, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
?>
|
@ -0,0 +1,380 @@
|
||||
<?php
|
||||
/**
|
||||
* Base include file for SimpleTest
|
||||
* @package SimpleTest
|
||||
* @subpackage WebTester
|
||||
* @version $Id: cookies.php,v 1.4 2005/12/05 04:47:03 lastcraft Exp $
|
||||
*/
|
||||
|
||||
/**#@+
|
||||
* include other SimpleTest class files
|
||||
*/
|
||||
require_once(dirname(__FILE__) . '/url.php');
|
||||
/**#@-*/
|
||||
|
||||
/**
|
||||
* Cookie data holder. Cookie rules are full of pretty
|
||||
* arbitary stuff. I have used...
|
||||
* http://wp.netscape.com/newsref/std/cookie_spec.html
|
||||
* http://www.cookiecentral.com/faq/
|
||||
* @package SimpleTest
|
||||
* @subpackage WebTester
|
||||
*/
|
||||
class SimpleCookie {
|
||||
var $_host;
|
||||
var $_name;
|
||||
var $_value;
|
||||
var $_path;
|
||||
var $_expiry;
|
||||
var $_is_secure;
|
||||
|
||||
/**
|
||||
* Constructor. Sets the stored values.
|
||||
* @param string $name Cookie key.
|
||||
* @param string $value Value of cookie.
|
||||
* @param string $path Cookie path if not host wide.
|
||||
* @param string $expiry Expiry date as string.
|
||||
* @param boolean $is_secure Currently ignored.
|
||||
*/
|
||||
function SimpleCookie($name, $value = false, $path = false, $expiry = false, $is_secure = false) {
|
||||
$this->_host = false;
|
||||
$this->_name = $name;
|
||||
$this->_value = $value;
|
||||
$this->_path = ($path ? $this->_fixPath($path) : "/");
|
||||
$this->_expiry = false;
|
||||
if (is_string($expiry)) {
|
||||
$this->_expiry = strtotime($expiry);
|
||||
} elseif (is_integer($expiry)) {
|
||||
$this->_expiry = $expiry;
|
||||
}
|
||||
$this->_is_secure = $is_secure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the host. The cookie rules determine
|
||||
* that the first two parts are taken for
|
||||
* certain TLDs and three for others. If the
|
||||
* new host does not match these rules then the
|
||||
* call will fail.
|
||||
* @param string $host New hostname.
|
||||
* @return boolean True if hostname is valid.
|
||||
* @access public
|
||||
*/
|
||||
function setHost($host) {
|
||||
if ($host = $this->_truncateHost($host)) {
|
||||
$this->_host = $host;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for the truncated host to which this
|
||||
* cookie applies.
|
||||
* @return string Truncated hostname.
|
||||
* @access public
|
||||
*/
|
||||
function getHost() {
|
||||
return $this->_host;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for a cookie being valid for a host name.
|
||||
* @param string $host Host to test against.
|
||||
* @return boolean True if the cookie would be valid
|
||||
* here.
|
||||
*/
|
||||
function isValidHost($host) {
|
||||
return ($this->_truncateHost($host) === $this->getHost());
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts just the domain part that determines a
|
||||
* cookie's host validity.
|
||||
* @param string $host Host name to truncate.
|
||||
* @return string Domain or false on a bad host.
|
||||
* @access private
|
||||
*/
|
||||
function _truncateHost($host) {
|
||||
$tlds = SimpleUrl::getAllTopLevelDomains();
|
||||
if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) {
|
||||
return $matches[0];
|
||||
} elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) {
|
||||
return $matches[0];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for name.
|
||||
* @return string Cookie key.
|
||||
* @access public
|
||||
*/
|
||||
function getName() {
|
||||
return $this->_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for value. A deleted cookie will
|
||||
* have an empty string for this.
|
||||
* @return string Cookie value.
|
||||
* @access public
|
||||
*/
|
||||
function getValue() {
|
||||
return $this->_value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for path.
|
||||
* @return string Valid cookie path.
|
||||
* @access public
|
||||
*/
|
||||
function getPath() {
|
||||
return $this->_path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a path to see if the cookie applies
|
||||
* there. The test path must be longer or
|
||||
* equal to the cookie path.
|
||||
* @param string $path Path to test against.
|
||||
* @return boolean True if cookie valid here.
|
||||
* @access public
|
||||
*/
|
||||
function isValidPath($path) {
|
||||
return (strncmp(
|
||||
$this->_fixPath($path),
|
||||
$this->getPath(),
|
||||
strlen($this->getPath())) == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for expiry.
|
||||
* @return string Expiry string.
|
||||
* @access public
|
||||
*/
|
||||
function getExpiry() {
|
||||
if (! $this->_expiry) {
|
||||
return false;
|
||||
}
|
||||
return gmdate("D, d M Y H:i:s", $this->_expiry) . " GMT";
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to see if cookie is expired against
|
||||
* the cookie format time or timestamp.
|
||||
* Will give true for a session cookie.
|
||||
* @param integer/string $now Time to test against. Result
|
||||
* will be false if this time
|
||||
* is later than the cookie expiry.
|
||||
* Can be either a timestamp integer
|
||||
* or a cookie format date.
|
||||
* @access public
|
||||
*/
|
||||
function isExpired($now) {
|
||||
if (! $this->_expiry) {
|
||||
return true;
|
||||
}
|
||||
if (is_string($now)) {
|
||||
$now = strtotime($now);
|
||||
}
|
||||
return ($this->_expiry < $now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ages the cookie by the specified number of
|
||||
* seconds.
|
||||
* @param integer $interval In seconds.
|
||||
* @public
|
||||
*/
|
||||
function agePrematurely($interval) {
|
||||
if ($this->_expiry) {
|
||||
$this->_expiry -= $interval;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for the secure flag.
|
||||
* @return boolean True if cookie needs SSL.
|
||||
* @access public
|
||||
*/
|
||||
function isSecure() {
|
||||
return $this->_is_secure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a trailing and leading slash to the path
|
||||
* if missing.
|
||||
* @param string $path Path to fix.
|
||||
* @access private
|
||||
*/
|
||||
function _fixPath($path) {
|
||||
if (substr($path, 0, 1) != '/') {
|
||||
$path = '/' . $path;
|
||||
}
|
||||
if (substr($path, -1, 1) != '/') {
|
||||
$path .= '/';
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Repository for cookies. This stuff is a
|
||||
* tiny bit browser dependent.
|
||||
* @package SimpleTest
|
||||
* @subpackage WebTester
|
||||
*/
|
||||
class SimpleCookieJar {
|
||||
var $_cookies;
|
||||
|
||||
/**
|
||||
* Constructor. Jar starts empty.
|
||||
* @access public
|
||||
*/
|
||||
function SimpleCookieJar() {
|
||||
$this->_cookies = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes expired and temporary cookies as if
|
||||
* the browser was closed and re-opened.
|
||||
* @param string/integer $now Time to test expiry against.
|
||||
* @access public
|
||||
*/
|
||||
function restartSession($date = false) {
|
||||
$surviving_cookies = array();
|
||||
for ($i = 0; $i < count($this->_cookies); $i++) {
|
||||
if (! $this->_cookies[$i]->getValue()) {
|
||||
continue;
|
||||
}
|
||||
if (! $this->_cookies[$i]->getExpiry()) {
|
||||
continue;
|
||||
}
|
||||
if ($date && $this->_cookies[$i]->isExpired($date)) {
|
||||
continue;
|
||||
}
|
||||
$surviving_cookies[] = $this->_cookies[$i];
|
||||
}
|
||||
$this->_cookies = $surviving_cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ages all cookies in the cookie jar.
|
||||
* @param integer $interval The old session is moved
|
||||
* into the past by this number
|
||||
* of seconds. Cookies now over
|
||||
* age will be removed.
|
||||
* @access public
|
||||
*/
|
||||
function agePrematurely($interval) {
|
||||
for ($i = 0; $i < count($this->_cookies); $i++) {
|
||||
$this->_cookies[$i]->agePrematurely($interval);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets an additional cookie. If a cookie has
|
||||
* the same name and path it is replaced.
|
||||
* @param string $name Cookie key.
|
||||
* @param string $value Value of cookie.
|
||||
* @param string $host Host upon which the cookie is valid.
|
||||
* @param string $path Cookie path if not host wide.
|
||||
* @param string $expiry Expiry date.
|
||||
* @access public
|
||||
*/
|
||||
function setCookie($name, $value, $host = false, $path = '/', $expiry = false) {
|
||||
$cookie = new SimpleCookie($name, $value, $path, $expiry);
|
||||
if ($host) {
|
||||
$cookie->setHost($host);
|
||||
}
|
||||
$this->_cookies[$this->_findFirstMatch($cookie)] = $cookie;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a matching cookie to write over or the
|
||||
* first empty slot if none.
|
||||
* @param SimpleCookie $cookie Cookie to write into jar.
|
||||
* @return integer Available slot.
|
||||
* @access private
|
||||
*/
|
||||
function _findFirstMatch($cookie) {
|
||||
for ($i = 0; $i < count($this->_cookies); $i++) {
|
||||
$is_match = $this->_isMatch(
|
||||
$cookie,
|
||||
$this->_cookies[$i]->getHost(),
|
||||
$this->_cookies[$i]->getPath(),
|
||||
$this->_cookies[$i]->getName());
|
||||
if ($is_match) {
|
||||
return $i;
|
||||
}
|
||||
}
|
||||
return count($this->_cookies);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the most specific cookie value from the
|
||||
* browser cookies. Looks for the longest path that
|
||||
* matches.
|
||||
* @param string $host Host to search.
|
||||
* @param string $path Applicable path.
|
||||
* @param string $name Name of cookie to read.
|
||||
* @return string False if not present, else the
|
||||
* value as a string.
|
||||
* @access public
|
||||
*/
|
||||
function getCookieValue($host, $path, $name) {
|
||||
$longest_path = '';
|
||||
foreach ($this->_cookies as $cookie) {
|
||||
if ($this->_isMatch($cookie, $host, $path, $name)) {
|
||||
if (strlen($cookie->getPath()) > strlen($longest_path)) {
|
||||
$value = $cookie->getValue();
|
||||
$longest_path = $cookie->getPath();
|
||||
}
|
||||
}
|
||||
}
|
||||
return (isset($value) ? $value : false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests cookie for matching against search
|
||||
* criteria.
|
||||
* @param SimpleTest $cookie Cookie to test.
|
||||
* @param string $host Host must match.
|
||||
* @param string $path Cookie path must be shorter than
|
||||
* this path.
|
||||
* @param string $name Name must match.
|
||||
* @return boolean True if matched.
|
||||
* @access private
|
||||
*/
|
||||
function _isMatch($cookie, $host, $path, $name) {
|
||||
if ($cookie->getName() != $name) {
|
||||
return false;
|
||||
}
|
||||
if ($host && $cookie->getHost() && ! $cookie->isValidHost($host)) {
|
||||
return false;
|
||||
}
|
||||
if (! $cookie->isValidPath($path)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses a URL to sift relevant cookies by host and
|
||||
* path. Results are list of strings of form "name=value".
|
||||
* @param SimpleUrl $url Url to select by.
|
||||
* @return array Valid name and value pairs.
|
||||
* @access public
|
||||
*/
|
||||
function selectAsPairs($url) {
|
||||
$pairs = array();
|
||||
foreach ($this->_cookies as $cookie) {
|
||||
if ($this->_isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) {
|
||||
$pairs[] = $cookie->getName() . '=' . $cookie->getValue();
|
||||
}
|
||||
}
|
||||
return $pairs;
|
||||
}
|
||||
}
|
||||
?>
|
@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* base include file for SimpleTest
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
* @version $Id: detached.php,v 1.1 2005/12/08 19:35:06 lastcraft Exp $
|
||||
*/
|
||||
|
||||
/**#@+
|
||||
* include other SimpleTest class files
|
||||
*/
|
||||
require_once(dirname(__FILE__) . '/xml.php');
|
||||
require_once(dirname(__FILE__) . '/shell_tester.php');
|
||||
/**#@-*/
|
||||
|
||||
/**
|
||||
* Runs an XML formated test in a separate process.
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
*/
|
||||
class DetachedTestCase {
|
||||
var $_command;
|
||||
var $_dry_command;
|
||||
var $_size;
|
||||
|
||||
/**
|
||||
* Sets the location of the remote test.
|
||||
* @param string $command Test script.
|
||||
* @param string $dry_command Script for dry run.
|
||||
* @access public
|
||||
*/
|
||||
function DetachedTestCase($command, $dry_command = false) {
|
||||
$this->_command = $command;
|
||||
$this->_dry_command = $dry_command ? $dry_command : $command;
|
||||
$this->_size = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for the test name for subclasses.
|
||||
* @return string Name of the test.
|
||||
* @access public
|
||||
*/
|
||||
function getLabel() {
|
||||
return $this->_command;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the top level test for this class. Currently
|
||||
* reads the data as a single chunk. I'll fix this
|
||||
* once I have added iteration to the browser.
|
||||
* @param SimpleReporter $reporter Target of test results.
|
||||
* @returns boolean True if no failures.
|
||||
* @access public
|
||||
*/
|
||||
function run(&$reporter) {
|
||||
$shell = &new SimpleShell();
|
||||
$shell->execute($this->_command);
|
||||
$parser = &$this->_createParser($reporter);
|
||||
if (! $parser->parse($shell->getOutput())) {
|
||||
trigger_error('Cannot parse incoming XML from [' . $this->_command . ']');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor for the number of subtests.
|
||||
* @return integer Number of test cases.
|
||||
* @access public
|
||||
*/
|
||||
function getSize() {
|
||||
if ($this->_size === false) {
|
||||
$shell = &new SimpleShell();
|
||||
$shell->execute($this->_dry_command);
|
||||
$reporter = &new SimpleReporter();
|
||||
$parser = &$this->_createParser($reporter);
|
||||
if (! $parser->parse($shell->getOutput())) {
|
||||
trigger_error('Cannot parse incoming XML from [' . $this->_dry_command . ']');
|
||||
return false;
|
||||
}
|
||||
$this->_size = $reporter->getTestCaseCount();
|
||||
}
|
||||
return $this->_size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the XML parser.
|
||||
* @param SimpleReporter $reporter Target of test results.
|
||||
* @return SimpleTestXmlListener XML reader.
|
||||
* @access protected
|
||||
*/
|
||||
function &_createParser(&$reporter) {
|
||||
return new SimpleTestXmlParser($reporter);
|
||||
}
|
||||
}
|
||||
?>
|
@ -0,0 +1,336 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest documentation for testing log-in and authentication</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Authentication</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Authentication documentation</h1>
|
||||
<div class="content">
|
||||
|
||||
<p>
|
||||
One of the trickiest, and yet most important, areas
|
||||
of testing web sites is the security.
|
||||
Testing these schemes is one of the core goals of
|
||||
the SimpleTest web tester.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="basic">
|
||||
<h2>Basic HTTP authentication</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
If you fetch a page protected by basic authentication then
|
||||
rather than receiving content, you will instead get a 401
|
||||
header.
|
||||
We can illustrate this with this test...
|
||||
<pre>
|
||||
class AuthenticationTest extends WebTestCase {<strong>
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');
|
||||
$this->showHeaders();
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
This allows us to see the challenge header...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<pre style="background-color: lightgray; color: black">
|
||||
HTTP/1.1 401 Authorization Required
|
||||
Date: Sat, 18 Sep 2004 19:25:18 GMT
|
||||
Server: Apache/1.3.29 (Unix) PHP/4.3.4
|
||||
WWW-Authenticate: Basic realm="SimpleTest basic authentication"
|
||||
Connection: close
|
||||
Content-Type: text/html; charset=iso-8859-1
|
||||
</pre>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
We are trying to get away from visual inspection though, and so SimpleTest
|
||||
allows to make automated assertions against the challenge.
|
||||
Here is a thorough test of our header...
|
||||
<pre>
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');<strong>
|
||||
$this->assertAuthentication('Basic');
|
||||
$this->assertResponse(401);
|
||||
$this->assertRealm('SimpleTest basic authentication');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Any one of these tests would normally do on it's own depending
|
||||
on the amount of detail you want to see.
|
||||
</p>
|
||||
<p>
|
||||
One theme that runs through SimpleTest is the ability to use
|
||||
<span class="new_code">SimpleExpectation</span> objects wherever a simple
|
||||
match is not enough.
|
||||
If you want only an approximate match to the realm for
|
||||
example, you can do this...
|
||||
<pre>
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');
|
||||
$this->assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Most of the time we are not interested in testing the
|
||||
authentication itself, but want to get past it to test
|
||||
the pages underneath.
|
||||
As soon as the challenge has been issued we can reply with
|
||||
an authentication response...
|
||||
<pre>
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function testCanAuthenticate() {
|
||||
$this->get('http://www.lastcraft.com/protected/');<strong>
|
||||
$this->authenticate('Me', 'Secret');</strong>
|
||||
$this->assertTitle(...);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The username and password will now be sent with every
|
||||
subsequent request to that directory and subdirectories.
|
||||
You will have to authenticate again if you step outside
|
||||
the authenticated directory, but SimpleTest is smart enough
|
||||
to merge subdirectories into a common realm.
|
||||
</p>
|
||||
<p>
|
||||
You can shortcut this step further by encoding the log in
|
||||
details straight into the URL...
|
||||
<pre>
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function testCanReadAuthenticatedPages() {
|
||||
$this->get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
|
||||
$this->assertTitle(...);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
If your username or password has special characters, then you
|
||||
will have to URL encode them or the request will not be parsed
|
||||
correctly.
|
||||
Also this header will not be sent on subsequent requests if
|
||||
you request a page with a fully qualified URL.
|
||||
If you navigate with relative URLs though, the authentication
|
||||
information will be preserved.
|
||||
</p>
|
||||
<p>
|
||||
Only basic authentication is currently supported and this is
|
||||
only really secure in tandem with HTTPS connections.
|
||||
This is usually enough to protect test server from prying eyes,
|
||||
however.
|
||||
Digest authentication and NTLM authentication may be added
|
||||
in the future.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="cookies">
|
||||
<h2>Cookies</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Basic authentication doesn't give enough control over the
|
||||
user interface for web developers.
|
||||
More likely this functionality will be coded directly into
|
||||
the web architecture using cookies and complicated timeouts.
|
||||
</p>
|
||||
<p>
|
||||
Starting with a simple log-in form...
|
||||
<pre>
|
||||
<form>
|
||||
Username:
|
||||
<input type="text" name="u" value="" /><br />
|
||||
Password:
|
||||
<input type="password" name="p" value="" /><br />
|
||||
<input type="submit" value="Log in" />
|
||||
</form>
|
||||
</pre>
|
||||
Which looks like...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
Username:
|
||||
<input type="text" name="u" value="">
|
||||
<br>
|
||||
Password:
|
||||
<input type="password" name="p" value="">
|
||||
<br>
|
||||
<input type="submit" value="Log in">
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
Let's suppose that in fetching this page a cookie has been
|
||||
set with a session ID.
|
||||
We are not going to fill the form in yet, just test that
|
||||
we are tracking the user.
|
||||
Here is the test...
|
||||
<pre>
|
||||
class LogInTest extends WebTestCase {
|
||||
function testSessionCookieSetBeforeForm() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$this->assertCookie('SID');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
All we are doing is confirming that the cookie is set.
|
||||
As the value is likely to be rather cryptic it's not
|
||||
really worth testing this with...
|
||||
<pre>
|
||||
class LogInTest extends WebTestCase {
|
||||
function testSessionCookieIsCorrectPattern() {
|
||||
$this->get('http://www.my-site.com/login.php');
|
||||
$this->assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The rest of the test would be the same as any other form,
|
||||
but we might want to confirm that we still have the same
|
||||
cookie after log-in as before we entered.
|
||||
We wouldn't want to lose track of this after all.
|
||||
Here is a possible test for this...
|
||||
<pre>
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testSessionCookieSameAfterLogIn() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$session = $this->getCookie('SID');
|
||||
$this->setField('u', 'Me');
|
||||
$this->setField('p', 'Secret');
|
||||
$this->click('Log in');
|
||||
$this->assertText('Welcome Me');
|
||||
$this->assertCookie('SID', $session);</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
This confirms that the session identifier is maintained
|
||||
afer log-in.
|
||||
</p>
|
||||
<p>
|
||||
We could even attempt to spoof our own system by setting
|
||||
arbitrary cookies to gain access...
|
||||
<pre>
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testSessionCookieSameAfterLogIn() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$this->setCookie('SID', 'Some other session');
|
||||
$this->get('http://www.my-site.com/restricted.php');</strong>
|
||||
$this->assertText('Access denied');
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Is your site protected from this attack?
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="session">
|
||||
<h2>Browser sessions</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
If you are testing an authentication system a critical piece
|
||||
of behaviour is what happens when a user logs back in.
|
||||
We would like to simulate closing and reopening a browser...
|
||||
<pre>
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testLoseAuthenticationAfterBrowserClose() {
|
||||
$this->get('http://www.my-site.com/login.php');
|
||||
$this->setField('u', 'Me');
|
||||
$this->setField('p', 'Secret');
|
||||
$this->click('Log in');
|
||||
$this->assertText('Welcome Me');<strong>
|
||||
|
||||
$this->restart();
|
||||
$this->get('http://www.my-site.com/restricted.php');
|
||||
$this->assertText('Access denied');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The <span class="new_code">WebTestCase::restart()</span> method will
|
||||
preserve cookies that have unexpired timeouts, but throw away
|
||||
those that are temporary or expired.
|
||||
You can optionally specify the time and date that the restart
|
||||
happened.
|
||||
</p>
|
||||
<p>
|
||||
Expiring cookies can be a problem.
|
||||
After all, if you have a cookie that expires after an hour,
|
||||
you don't want to stall the test for an hour while the
|
||||
cookie passes it's timeout.
|
||||
</p>
|
||||
<p>
|
||||
To push the cookies over the hour limit you can age them
|
||||
before you restart the session...
|
||||
<pre>
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testLoseAuthenticationAfterOneHour() {
|
||||
$this->get('http://www.my-site.com/login.php');
|
||||
$this->setField('u', 'Me');
|
||||
$this->setField('p', 'Secret');
|
||||
$this->click('Log in');
|
||||
$this->assertText('Welcome Me');
|
||||
<strong>
|
||||
$this->ageCookies(3600);</strong>
|
||||
$this->restart();
|
||||
$this->get('http://www.my-site.com/restricted.php');
|
||||
$this->assertText('Access denied');
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
After the restart it will appear that cookies are an
|
||||
hour older and any that pass their expiry will have
|
||||
disappeared.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,391 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest documentation for the scriptable web browser component</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Scriptable browser</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>PHP Scriptable Web Browser</h1>
|
||||
<div class="content">
|
||||
|
||||
<p>
|
||||
SimpleTest's web browser component can be used not just
|
||||
outside of the <span class="new_code">WebTestCase</span> class, but also
|
||||
independently of the SimpleTest framework itself.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="scripting">
|
||||
<h2>The Scriptable Browser</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
You can use the web browser in PHP scripts to confirm
|
||||
services are up and running, or to extract information
|
||||
from them at a regular basis.
|
||||
For example, here is a small script to extract the current number of
|
||||
open PHP 5 bugs from the <a href="http://www.php.net/">PHP web site</a>...
|
||||
<pre>
|
||||
<strong><?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];
|
||||
?></strong>
|
||||
</pre>
|
||||
There are simpler methods to do this particular example in PHP
|
||||
of course.
|
||||
For example you can just use the PHP <span class="new_code">file()</span>
|
||||
command against what here is a pretty fixed page.
|
||||
However, using the web browser for scripts allows authentication,
|
||||
correct handling of cookies, automatic loading of frames, redirects,
|
||||
form submission and the ability to examine the page headers.
|
||||
Such methods are fragile against a site that is constantly
|
||||
evolving and you would want a more direct way of accessing
|
||||
data in a permanent set up, but for simple tasks this can provide
|
||||
a very rapid solution.
|
||||
</p>
|
||||
<p>
|
||||
All of the navigation methods used in the
|
||||
<a href="web_tester_documentation.html">WebTestCase</a>
|
||||
are present in the <span class="new_code">SimpleBrowser</span> class, but
|
||||
the assertions are replaced with simpler accessors.
|
||||
Here is a full list of the page navigation methods...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">addHeader($header)</span></td><td>Adds a header to every fetch</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">useProxy($proxy, $username, $password)</span></td><td>Use this proxy from now on</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">head($url, $parameters)</span></td><td>Perform a HEAD request</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">get($url, $parameters)</span></td><td>Fetch a page with GET</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">post($url, $parameters)</span></td><td>Fetch a page with POST</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickLink($label)</span></td><td>Follows a link by label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">isLink($label)</span></td><td>See if a link is present by label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickLinkById($id)</span></td><td>Follows a link by attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">isLinkById($id)</span></td><td>See if a link is present by attribut</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getUrl()</span></td><td>Current URL of page or frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getTitle()</span></td><td>Page title</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getContent()</span></td><td>Raw page or frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getContentAsText()</span></td><td>HTML removed except for alt text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">retry()</span></td><td>Repeat the last request</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">back()</span></td><td>Use the browser back button</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">forward()</span></td><td>Use the browser forward button</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">authenticate($username, $password)</span></td><td>Retry page or frame after a 401 response</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">restart($date)</span></td><td>Restarts the browser for a new session</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">ageCookies($interval)</span></td><td>Ages the cookies by the specified time</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setCookie($name, $value)</span></td><td>Sets an additional cookie</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getCookieValue($host, $path, $name)</span></td><td>Reads the most specific cookie</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getCurrentCookieValue($name)</span></td><td>Reads cookie for the current context</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
The methods <span class="new_code">SimpleBrowser::useProxy()</span> and
|
||||
<span class="new_code">SimpleBrowser::addHeader()</span> are special.
|
||||
Once called they continue to apply to all subsequent fetches.
|
||||
</p>
|
||||
<p>
|
||||
Navigating forms is similar to the
|
||||
<a href="form_testing_documentation.html">WebTestCase form navigation</a>...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">setField($name, $value)</span></td><td>Sets all form fields with that name</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setFieldById($id, $value)</span></td><td>Sets all form fields with that id</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getField($name)</span></td><td>Accessor for a form element value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getFieldById($id)</span></td><td>Accessor for a form element value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickSubmit($label)</span></td><td>Submits form by button label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickSubmitByName($name)</span></td><td>Submits form by button attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickSubmitById($id)</span></td><td>Submits form by button attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickImage($label, $x, $y)</span></td><td>Clicks the image by alt text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickImageByName($name, $x, $y)</span></td><td>Clicks the image by attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickImageById($id, $x, $y)</span></td><td>Clicks the image by attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">submitFormById($id)</span></td><td>Submits by the form tag attribute</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
At the moment there aren't any methods to list available forms
|
||||
and fields.
|
||||
This will probably be added to later versions of SimpleTest.
|
||||
</p>
|
||||
<p>
|
||||
Within a page, individual frames can be selected.
|
||||
If no selection is made then all the frames are merged together
|
||||
in one large conceptual page.
|
||||
The content of the current page will be a concatenation of all of the
|
||||
frames in the order that they were specified in the "frameset"
|
||||
tags.
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">getFrames()</span></td><td>A dump of the current frame structure</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getFrameFocus()</span></td><td>Current frame label or index</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setFrameFocusByIndex($choice)</span></td><td>Select a frame numbered from 1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setFrameFocus($name)</span></td><td>Select frame by label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clearFrameFocus()</span></td><td>Treat all the frames as a single page</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
When focused on a single frame, the content will come from
|
||||
that frame only.
|
||||
This includes links to click and forms to submit.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="debug">
|
||||
<h2>What went wrong?</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
All of this functionality is great when we actually manage to fetch pages,
|
||||
but that doesn't always happen.
|
||||
To help figure out what went wrong, the browser has some methods to
|
||||
aid in debugging...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">setConnectionTimeout($timeout)</span></td><td>Close the socket on overrun</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getRequest()</span></td><td>Raw request header of page or frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getHeaders()</span></td><td>Raw response header of page or frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getTransportError()</span></td><td>Any socket level errors in the last fetch</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getResponseCode()</span></td><td>HTTP response of page or frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getMimeType()</span></td><td>Mime type of page or frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getAuthentication()</span></td><td>Authentication type in 401 challenge header</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getRealm()</span></td><td>Authentication realm in 401 challenge header</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setMaximumRedirects($max)</span></td><td>Number of redirects before page is loaded anyway</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setMaximumNestedFrames($max)</span></td><td>Protection against recursive framesets</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">ignoreFrames()</span></td><td>Disables frames support</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">useFrames()</span></td><td>Enables frames support</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">ignoreCookies()</span></td><td>Disables sending and receiving of cookies</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">useCookies()</span></td><td>Enables cookie support</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
The methods <span class="new_code">SimpleBrowser::setConnectionTimeout()</span>
|
||||
<span class="new_code">SimpleBrowser::setMaximumRedirects()</span>,
|
||||
<span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>,
|
||||
<span class="new_code">SimpleBrowser::ignoreFrames()</span>,
|
||||
<span class="new_code">SimpleBrowser::useFrames()</span>,
|
||||
<span class="new_code">SimpleBrowser::ignoreCookies()</span> and
|
||||
<span class="new_code">SimpleBrowser::useCokies()</span> continue to apply
|
||||
to every subsequent request.
|
||||
The other methods are frames aware.
|
||||
This means that if you have an individual frame that is not
|
||||
loading, navigate to it using <span class="new_code">SimpleBrowser::setFrameFocus()</span>
|
||||
and you can then use <span class="new_code">SimpleBrowser::getRequest()</span>, etc to
|
||||
see what happened.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="unit">
|
||||
<h2>Complex unit tests with multiple browsers</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Anything that could be done in a
|
||||
<a href="web_tester_documentation.html">WebTestCase</a> can
|
||||
now be done in a <a href="unit_tester_documentation.html">UnitTestCase</a>.
|
||||
This means that we can freely mix domain object testing with the
|
||||
web interface...
|
||||
<pre>
|
||||
<strong>
|
||||
class TestOfRegistration extends UnitTestCase {
|
||||
function testNewUserAddedToAuthenticator() {</strong>
|
||||
$browser = &new SimpleBrowser();
|
||||
$browser->get('http://my-site.com/register.php');
|
||||
$browser->setField('email', 'me@here');
|
||||
$browser->setField('password', 'Secret');
|
||||
$browser->click('Register');
|
||||
<strong>
|
||||
$authenticator = &new Authenticator();
|
||||
$member = &$authenticator->findByEmail('me@here');
|
||||
$this->assertEqual($member->getPassword(), 'Secret');
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
While this may be a useful temporary expediency, I am not a fan
|
||||
of this type of testing.
|
||||
The testing has cut across application layers, make it twice as
|
||||
likely it will need refactoring when the code changes.
|
||||
</p>
|
||||
<p>
|
||||
A more useful case of where using the browser directly can be helpful
|
||||
is where the <span class="new_code">WebTestCase</span> cannot cope.
|
||||
An example is where two browsers are needed at the same time.
|
||||
</p>
|
||||
<p>
|
||||
For example, say we want to disallow multiple simultaneous
|
||||
usage of a site with the same username.
|
||||
This test case will do the job...
|
||||
<pre>
|
||||
class TestOfSecurity extends UnitTestCase {
|
||||
function testNoMultipleLoginsFromSameUser() {<strong>
|
||||
$first = &new SimpleBrowser();
|
||||
$first->get('http://my-site.com/login.php');
|
||||
$first->setField('name', 'Me');
|
||||
$first->setField('password', 'Secret');
|
||||
$first->click('Enter');
|
||||
$this->assertEqual($first->getTitle(), 'Welcome');
|
||||
|
||||
$second = &new SimpleBrowser();
|
||||
$second->get('http://my-site.com/login.php');
|
||||
$second->setField('name', 'Me');
|
||||
$second->setField('password', 'Secret');
|
||||
$second->click('Enter');
|
||||
$this->assertEqual($second->getTitle(), 'Access Denied');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
You can also use the <span class="new_code">SimpleBrowser</span> class
|
||||
directly when you want to write test cases using a different
|
||||
test tool than SimpleTest.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,121 @@
|
||||
body {
|
||||
padding-left: 3%;
|
||||
padding-right: 3%;
|
||||
}
|
||||
h1, h2, h3 {
|
||||
font-family: sans-serif;
|
||||
}
|
||||
h1 {
|
||||
text-align: center;
|
||||
}
|
||||
pre {
|
||||
font-family: courier, typewriter, monospace;
|
||||
font-size: 90%;
|
||||
border: 1px solid;
|
||||
border-color: #999966;
|
||||
background-color: #ffffcc;
|
||||
padding: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
}
|
||||
.code, .new_code, pre.new_code {
|
||||
font-family: courier, typewriter, monospace;
|
||||
font-weight: bold;
|
||||
}
|
||||
div.copyright {
|
||||
font-size: 80%;
|
||||
color: gray;
|
||||
}
|
||||
div.copyright a {
|
||||
margin-top: 1em;
|
||||
color: gray;
|
||||
}
|
||||
ul.api {
|
||||
border: 2px outset;
|
||||
border-color: gray;
|
||||
background-color: white;
|
||||
margin: 5px;
|
||||
margin-left: 5%;
|
||||
margin-right: 5%;
|
||||
}
|
||||
ul.api li {
|
||||
margin-top: 0.2em;
|
||||
margin-bottom: 0.2em;
|
||||
list-style: none;
|
||||
text-indent: -3em;
|
||||
padding-left: 1em;
|
||||
}
|
||||
div.demo {
|
||||
border: 4px ridge;
|
||||
border-color: gray;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
background-color: white;
|
||||
}
|
||||
div.demo span.fail {
|
||||
color: red;
|
||||
}
|
||||
div.demo span.pass {
|
||||
color: green;
|
||||
}
|
||||
div.demo h1 {
|
||||
font-size: 12pt;
|
||||
text-align: left;
|
||||
font-weight: bold;
|
||||
}
|
||||
div.menu {
|
||||
text-align: center;
|
||||
}
|
||||
table {
|
||||
border: 2px outset;
|
||||
border-color: gray;
|
||||
background-color: white;
|
||||
margin: 5px;
|
||||
margin-left: 5%;
|
||||
margin-right: 5%;
|
||||
}
|
||||
td {
|
||||
font-size: 90%;
|
||||
}
|
||||
.shell {
|
||||
color: white;
|
||||
}
|
||||
pre.shell {
|
||||
border: 4px ridge;
|
||||
border-color: gray;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
background-color: #000100;
|
||||
color: #99ff99;
|
||||
font-size: 90%;
|
||||
}
|
||||
pre.file {
|
||||
color: black;
|
||||
border: 1px solid;
|
||||
border-color: black;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
background-color: white;
|
||||
font-size: 90%;
|
||||
}
|
||||
form.demo {
|
||||
background-color: lightgray;
|
||||
border: 4px outset;
|
||||
border-color: lightgray;
|
||||
padding: 10px;
|
||||
margin-right: 40%;
|
||||
}
|
||||
dl, dd {
|
||||
margin: 10px;
|
||||
margin-left: 30px;
|
||||
}
|
||||
em {
|
||||
font-weight: bold;
|
||||
font-family: courier, typewriter, monospace;
|
||||
}
|
@ -0,0 +1,346 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>
|
||||
Extending the SimpleTest unit tester with additional expectation classes
|
||||
</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Expectations</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Expectation documentation</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="mock">
|
||||
<h2>More control over mock objects</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The default behaviour of the
|
||||
<a href="mock_objects_documentation.html">mock objects</a>
|
||||
in
|
||||
<a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a>
|
||||
is either an identical match on the argument or to allow any argument at all.
|
||||
For almost all tests this is sufficient.
|
||||
Sometimes, though, you want to weaken a test case.
|
||||
</p>
|
||||
<p>
|
||||
One place where a test can be too tightly coupled is with
|
||||
text matching.
|
||||
Suppose we have a component that outputs a helpful error
|
||||
message when something goes wrong.
|
||||
You want to test that the correct error was sent, but the actual
|
||||
text may be rather long.
|
||||
If you test for the text exactly, then every time the exact wording
|
||||
of the message changes, you will have to go back and edit the test suite.
|
||||
</p>
|
||||
<p>
|
||||
For example, suppose we have a news service that has failed
|
||||
to connect to its remote source.
|
||||
<pre>
|
||||
<strong>class NewsService {
|
||||
...
|
||||
function publish(&$writer) {
|
||||
if (! $this->isConnected()) {
|
||||
$writer->write('Cannot connect to news service "' .
|
||||
$this->_name . '" at this time. ' .
|
||||
'Please try again later.');
|
||||
}
|
||||
...
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
Here it is sending its content to a
|
||||
<span class="new_code">Writer</span> class.
|
||||
We could test this behaviour with a
|
||||
<span class="new_code">MockWriter</span> like so...
|
||||
<pre>
|
||||
class TestOfNewsService extends UnitTestCase {
|
||||
...
|
||||
function testConnectionFailure() {<strong>
|
||||
$writer = &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);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
This is a good example of a brittle test.
|
||||
If we decide to add additional instructions, such as
|
||||
suggesting an alternative news source, we will break
|
||||
our tests even though no underlying functionality
|
||||
has been altered.
|
||||
</p>
|
||||
<p>
|
||||
To get around this, we would like to do a regular expression
|
||||
test rather than an exact match.
|
||||
We can actually do this with...
|
||||
<pre>
|
||||
class TestOfNewsService extends UnitTestCase {
|
||||
...
|
||||
function testConnectionFailure() {
|
||||
$writer = &new MockWriter();<strong>
|
||||
$writer->expectOnce(
|
||||
'write',
|
||||
array(new PatternExpectation('/cannot connect/i')));</strong>
|
||||
|
||||
$service = &new NewsService('BBC News');
|
||||
$service->publish($writer);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Instead of passing in the expected parameter to the
|
||||
<span class="new_code">MockWriter</span> we pass an
|
||||
expectation class called
|
||||
<span class="new_code">WantedPatternExpectation</span>.
|
||||
The mock object is smart enough to recognise this as special
|
||||
and to treat it differently.
|
||||
Rather than simply comparing the incoming argument to this
|
||||
object, it uses the expectation object itself to
|
||||
perform the test.
|
||||
</p>
|
||||
<p>
|
||||
The <span class="new_code">WantedPatternExpectation</span> takes
|
||||
the regular expression to match in its constructor.
|
||||
Whenever a comparison is made by the <span class="new_code">MockWriter</span>
|
||||
against this expectation class, it will do a
|
||||
<span class="new_code">preg_match()</span> with this pattern.
|
||||
With our test case above, as long as "cannot connect"
|
||||
appears in the text of the string, the mock will issue a pass
|
||||
to the unit tester.
|
||||
The rest of the text does not matter.
|
||||
</p>
|
||||
<p>
|
||||
The possible expectation classes are...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">EqualExpectation</span></td><td>An equality, rather than the stronger identity comparison</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">NotEqualExpectation</span></td><td>An inequality comparison</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">IndenticalExpectation</span></td><td>The default mock object check which must match exactly</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">NotIndenticalExpectation</span></td><td>Inverts the mock object logic</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">PatternExpectation</span></td><td>Uses a Perl Regex to match a string</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">NoPatternExpectation</span></td><td>Passes only if failing a Perl Regex</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">IsAExpectation</span></td><td>Checks the type or class name only</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">NotAExpectation</span></td><td>Opposite of the <span class="new_code">IsAExpectation</span></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">MethodExistsExpectation</span></td><td>Checks a method is available on an object</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
Most take the expected value in the constructor.
|
||||
The exceptions are the pattern matchers, which take a regular expression,
|
||||
and the <span class="new_code">IsAExpectation</span> and <span class="new_code">NotAExpectation</span> which takes a type
|
||||
or class name as a string.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="behaviour">
|
||||
<h2>Using expectations to control stubs</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The expectation classes can be used not just for sending assertions
|
||||
from mock objects, but also for selecting behaviour for the
|
||||
<a href="mock_objects_documentation.html">mock objects</a>.
|
||||
Anywhere a list of arguments is given, a list of expectation objects
|
||||
can be inserted instead.
|
||||
</p>
|
||||
<p>
|
||||
Suppose we want an authorisation server mock to simulate a successful login
|
||||
only if it receives a valid session object.
|
||||
We can do this as follows...
|
||||
<pre>
|
||||
Mock::generate('Authorisation');
|
||||
<strong>
|
||||
$authorisation = new MockAuthorisation();
|
||||
$authorisation->setReturnValue(
|
||||
'isAllowed',
|
||||
true,
|
||||
array(new IsAExpectation('Session', 'Must be a session')));
|
||||
$authorisation->setReturnValue('isAllowed', false);</strong>
|
||||
</pre>
|
||||
We have set the default mock behaviour to return false when
|
||||
<span class="new_code">isAllowed</span> is called.
|
||||
When we call the method with a single parameter that
|
||||
is a <span class="new_code">Session</span> object, it will return true.
|
||||
We have also added a second parameter as a message.
|
||||
This will be displayed as part of the mock object
|
||||
failure message if this expectation is the cause of
|
||||
a failure.
|
||||
</p>
|
||||
<p>
|
||||
This kind of sophistication is rarely useful, but is included for
|
||||
completeness.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="extending">
|
||||
<h2>Creating your own expectations</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The expectation classes have a very simple structure.
|
||||
So simple that it is easy to create your own versions for
|
||||
commonly used test logic.
|
||||
</p>
|
||||
<p>
|
||||
As an example here is the creation of a class to test for
|
||||
valid IP addresses.
|
||||
In order to work correctly with the stubs and mocks the new
|
||||
expectation class should extend
|
||||
<span class="new_code">SimpleExpectation</span>...
|
||||
<pre>
|
||||
<strong>class ValidIp extends SimpleExpectation {
|
||||
|
||||
function test($ip) {
|
||||
return (ip2long($ip) != -1);
|
||||
}
|
||||
|
||||
function testMessage($ip) {
|
||||
return "Address [$ip] should be a valid IP address";
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
There are only two methods to implement.
|
||||
The <span class="new_code">test()</span> method should
|
||||
evaluate to true if the expectation is to pass, and
|
||||
false otherwise.
|
||||
The <span class="new_code">testMessage()</span> method
|
||||
should simply return some helpful text explaining the test
|
||||
that was carried out.
|
||||
</p>
|
||||
<p>
|
||||
This class can now be used in place of the earlier expectation
|
||||
classes.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="unit">
|
||||
<h2>Under the bonnet of the unit tester</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The <a href="http://sourceforge.net/projects/simpletest/">SimpleTest unit testing framework</a>
|
||||
also uses the expectation classes internally for the
|
||||
<a href="unit_test_documentation.html">UnitTestCase class</a>.
|
||||
We can also take advantage of these mechanisms to reuse our
|
||||
homebrew expectation classes within the test suites directly.
|
||||
</p>
|
||||
<p>
|
||||
The most crude way of doing this is to use the
|
||||
<span class="new_code">SimpleTest::assert()</span> method to
|
||||
test against it directly...
|
||||
<pre>
|
||||
<strong>class TestOfNetworking extends UnitTestCase {
|
||||
...
|
||||
function testGetValidIp() {
|
||||
$server = &new Server();
|
||||
$this->assert(
|
||||
new ValidIp(),
|
||||
$server->getIp(),
|
||||
'Server IP address->%s');
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
This is a little untidy compared with our usual
|
||||
<span class="new_code">assert...()</span> syntax.
|
||||
</p>
|
||||
<p>
|
||||
For such a simple case we would normally create a
|
||||
separate assertion method on our test case rather
|
||||
than bother using the expectation class.
|
||||
If we pretend that our expectation is a little more
|
||||
complicated for a moment, so that we want to reuse it,
|
||||
we get...
|
||||
<pre>
|
||||
class TestOfNetworking extends UnitTestCase {
|
||||
...<strong>
|
||||
function assertValidIp($ip, $message = '%s') {
|
||||
$this->assert(new ValidIp(), $ip, $message);
|
||||
}</strong>
|
||||
|
||||
function testGetValidIp() {
|
||||
$server = &new Server();<strong>
|
||||
$this->assertValidIp(
|
||||
$server->getIp(),
|
||||
'Server IP address->%s');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
It is unlikely we would ever need this degree of control
|
||||
over the testing machinery.
|
||||
It is rare to need the expectations for more than pattern
|
||||
matching.
|
||||
Also, complex expectation classes could make the tests
|
||||
harder to read and debug.
|
||||
These mechanisms are really of most use to authors of systems
|
||||
that will extend the test framework to create their own tool set.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,276 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>Simple Test documentation for testing HTML forms</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Testing forms</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Form testing documentation</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="submit">
|
||||
<h2>Submitting a simple form</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
When a page is fetched by the <span class="new_code">WebTestCase</span>
|
||||
using <span class="new_code">get()</span> or
|
||||
<span class="new_code">post()</span> the page content is
|
||||
automatically parsed.
|
||||
This results in any form controls that are inside <form> tags
|
||||
being available from within the test case.
|
||||
For example, if we have this snippet of HTML...
|
||||
<pre>
|
||||
<form>
|
||||
<input type="text" name="a" value="A default" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</pre>
|
||||
Which looks like this...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<input type="text" name="a" value="A default">
|
||||
<input type="submit" value="Go">
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
We can navigate to this code, via the
|
||||
<a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>
|
||||
site, with the following test...
|
||||
<pre>
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
<strong>
|
||||
function testDefaultValue() {
|
||||
$this->get('http://www.lastcraft.com/form_testing_documentation.php');
|
||||
$this->assertField('a', 'A default');
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
Immediately after loading the page all of the HTML controls are set at
|
||||
their default values just as they would appear in the web browser.
|
||||
The assertion tests that a HTML widget exists in the page with the
|
||||
name "a" and that it is currently set to the value
|
||||
"A default".
|
||||
As usual, we could use a pattern expectation instead if a fixed
|
||||
string.
|
||||
</p>
|
||||
<p>
|
||||
We could submit the form straight away, but first we'll change
|
||||
the value of the text field and only then submit it...
|
||||
<pre>
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
|
||||
function testDefaultValue() {
|
||||
$this->get('http://www.my-site.com/');
|
||||
$this->assertField('a', 'A default');<strong>
|
||||
$this->setField('a', 'New value');
|
||||
$this->click('Go');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Because we didn't specify a method attribute on the form tag, and
|
||||
didn't specify an action either, the test case will follow
|
||||
the usual browser behaviour of submitting the form data as a <em>GET</em>
|
||||
request back to the same location.
|
||||
SimpleTest tries to emulate typical browser behaviour as much as possible,
|
||||
rather than attempting to catch missing attributes on tags.
|
||||
This is because the target of the testing framework is the PHP application
|
||||
logic, not syntax or other errors in the HTML code.
|
||||
For HTML errors, other tools such as
|
||||
<a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> should be used.
|
||||
</p>
|
||||
<p>
|
||||
If a field is not present in any form, or if an option is unavailable,
|
||||
then <span class="new_code">WebTestCase::setField()</span> will return
|
||||
<span class="new_code">false</span>.
|
||||
For example, suppose we wish to verify that a "Superuser"
|
||||
option is not present in this form...
|
||||
<pre>
|
||||
<strong>Select type of user to add:</strong>
|
||||
<select name="type">
|
||||
<option>Subscriber</option>
|
||||
<option>Author</option>
|
||||
<option>Administrator</option>
|
||||
</select>
|
||||
</pre>
|
||||
Which looks like...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<strong>Select type of user to add:</strong>
|
||||
<select name="type">
|
||||
<option>Subscriber</option>
|
||||
<option>Author</option>
|
||||
<option>Administrator</option>
|
||||
</select>
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
The following test will confirm it...
|
||||
<pre>
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...
|
||||
function testNoSuperuserChoiceAvailable() {<strong>
|
||||
$this->get('http://www.lastcraft.com/form_testing_documentation.php');
|
||||
$this->assertFalse($this->setField('type', 'Superuser'));</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The selection will not be changed on a failure to set
|
||||
a widget value.
|
||||
</p>
|
||||
<p>
|
||||
Here is the full list of widgets currently supported...
|
||||
<ul>
|
||||
<li>Text fields, including hidden and password fields.</li>
|
||||
<li>Submit buttons including the button tag, although not yet reset buttons</li>
|
||||
<li>Text area. This includes text wrapping behaviour.</li>
|
||||
<li>Checkboxes, including multiple checkboxes in the same form.</li>
|
||||
<li>Drop down selections, including multiple selects.</li>
|
||||
<li>Radio buttons.</li>
|
||||
<li>Images.</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Although most standard HTML widgets are catered for by <em>SimpleTest</em>'s
|
||||
built in parser, it is unlikely that JavaScript will be implemented
|
||||
anytime soon.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="multiple">
|
||||
<h2>Fields with multiple values</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
SimpleTest can cope with two types of multivalue controls: Multiple
|
||||
selection drop downs, and multiple checkboxes with the same name
|
||||
within a form.
|
||||
The multivalue nature of these means that setting and testing
|
||||
are slightly different.
|
||||
Using checkboxes as an example...
|
||||
<pre>
|
||||
<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>
|
||||
</pre>
|
||||
Which renders as...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<strong>Create privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="c" checked>
|
||||
<br>
|
||||
<strong>Retrieve privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="r" checked>
|
||||
<br>
|
||||
<strong>Update privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="u" checked>
|
||||
<br>
|
||||
<strong>Destroy privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="d" checked>
|
||||
<br>
|
||||
<input type="submit" value="Enable Privileges">
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
If we wish to disable all but the retrieval privileges and
|
||||
submit this information we can do it like this...
|
||||
<pre>
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...<strong>
|
||||
function testDisableNastyPrivileges() {
|
||||
$this->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');
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
Instead of setting the field to a single value, we give it a list
|
||||
of values.
|
||||
We do the same when testing expected values.
|
||||
We can then write other test code to confirm the effect of this, perhaps
|
||||
by logging in as that user and attempting an update.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="raw">
|
||||
<h2>Raw posting</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
If you want to test a form handler, but have not yet written
|
||||
or do not have access to the form itself, you can create a
|
||||
form submission by hand.
|
||||
<pre>
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...<strong>
|
||||
function testAttemptedHack() {
|
||||
$this->post(
|
||||
'http://www.my-site.com/add_user.php',
|
||||
array('type' => 'superuser'));
|
||||
$this->assertNoText('user created');
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
By adding data to the <span class="new_code">WebTestCase::post()</span>
|
||||
method, we are attempting to fetch the page as a form submission.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,354 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest for PHP group test documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Group tests</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Group Test documentation</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="group">
|
||||
<h2>Grouping tests</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
To run test cases as part of a group the test cases should really
|
||||
be placed in files without the runner code...
|
||||
<pre>
|
||||
<strong><?php
|
||||
require_once('../classes/io.php');
|
||||
|
||||
class FileTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
|
||||
class SocketTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
?></strong>
|
||||
</pre>
|
||||
As many cases as needed can appear in a single file.
|
||||
They should include any code they need, such as the library
|
||||
being tested, but none of the simple test libraries.
|
||||
</p>
|
||||
<p>
|
||||
If you have extended any test cases, you can include them
|
||||
as well.
|
||||
<pre>
|
||||
<?php
|
||||
require_once('../classes/io.php');
|
||||
<strong>
|
||||
class MyFileTestCase extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
SimpleTest::ignore('MyFileTestCase');</strong>
|
||||
|
||||
class FileTester extends MyFileTestCase {
|
||||
...
|
||||
}
|
||||
|
||||
class SocketTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
The <span class="new_code">FileTester</span> class does
|
||||
not contain any actual tests, but is a base class for other
|
||||
test cases.
|
||||
For this reason we use the
|
||||
<span class="new_code">SimpleTestOptions::ignore()</span> directive
|
||||
to tell the upcoming group test to ignore it.
|
||||
This directive can appear anywhere in the file and works
|
||||
when a whole file of test cases is loaded (see below).
|
||||
We will call this sample <em>file_test.php</em>.
|
||||
</p>
|
||||
<p>
|
||||
Next we create a group test file, called say <em>group_test.php</em>.
|
||||
You will think of a better name I am sure.
|
||||
We will add the test file using a safe method...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('file_test.php');
|
||||
|
||||
$test = &new GroupTest('All file tests');
|
||||
$test->addTestCase(new FileTestCase());
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
</pre>
|
||||
This instantiates the test case before the test suite is
|
||||
run.
|
||||
This could get a little expensive with a large number of test
|
||||
cases, so another method is provided that will only
|
||||
instantiate the class when it is needed...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('file_test.php');
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestClass('FileTestCase');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
The problem with this method is that for every test case
|
||||
that we add we will have
|
||||
to <span class="new_code">require_once()</span> the test code
|
||||
file and manually instantiate each and every test case.
|
||||
We can save a lot of typing with...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestFile('file_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?&gt;
|
||||
</pre>
|
||||
What happens here is that the <span class="new_code">GroupTest</span>
|
||||
class has done the <span class="new_code">require_once()</span>
|
||||
for us.
|
||||
It then checks to see if any new test case classes
|
||||
have been created by the new file and automatically adds
|
||||
them to the group test.
|
||||
Now all we have to do is add each new file.
|
||||
</p>
|
||||
<p>
|
||||
There are two things that could go wrong and which require care...
|
||||
<ol>
|
||||
<li>
|
||||
The file could already have been parsed by PHP and so no
|
||||
new classes will have been added. You should make
|
||||
sure that the test cases are only included in this file
|
||||
and no others.
|
||||
</li>
|
||||
<li>
|
||||
New test case extension classes that get included will be
|
||||
placed in the group test and run also.
|
||||
You will need to add a <span class="new_code">SimpleTestOptions::ignore()</span>
|
||||
directive for these classes or make sure that they are included
|
||||
before the <span class="new_code">GroupTest::addTestFile()</span>
|
||||
line.
|
||||
</li>
|
||||
</ol>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="higher">
|
||||
<h2>Higher groupings</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The above method places all of the test cases into one large group.
|
||||
For larger projects though this may not be flexible enough; you
|
||||
may want to group the tests in all sorts of ways.
|
||||
</p>
|
||||
<p>
|
||||
To get a more flexible group test we can subclass
|
||||
<span class="new_code">GroupTest</span> and then instantiate it as needed...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
<strong>
|
||||
class FileGroupTest extends GroupTest {
|
||||
function FileGroupTest() {
|
||||
$this->GroupTest('All file tests');
|
||||
$this->addTestFile('file_test.php');
|
||||
}
|
||||
}</strong>
|
||||
?>
|
||||
</pre>
|
||||
This effectively names the test in the constructor and then
|
||||
adds our test cases and a single group below.
|
||||
Of course we can add more than one group at this point.
|
||||
We can now invoke the tests from a separate runner file...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('file_group_test.php');
|
||||
<strong>
|
||||
$test = &new FileGroupTest();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
</pre>
|
||||
...or we can group them into even larger group tests...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('file_group_test.php');
|
||||
<strong>
|
||||
$test = &new BigGroupTest('Big group');
|
||||
$test->addTestCase(new FileGroupTest());
|
||||
$test->addTestCase(...);
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
</pre>
|
||||
If we still wish to run the original group test and we
|
||||
don't want all of these little runner files, we can
|
||||
put the test runner code around guard bars when we create
|
||||
each group.
|
||||
<pre>
|
||||
<?php
|
||||
class FileGroupTest extends GroupTest {
|
||||
function FileGroupTest() {
|
||||
$this->GroupTest('All file tests');
|
||||
$test->addTestFile('file_test.php');
|
||||
}
|
||||
}
|
||||
<strong>
|
||||
if (! defined('RUNNER')) {
|
||||
define('RUNNER', true);</strong>
|
||||
$test = &new FileGroupTest();
|
||||
$test->run(new HtmlReporter());
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
This approach requires the guard to be set when including
|
||||
the group test file, but this is still less hassle than
|
||||
lots of separate runner files.
|
||||
You include the same guard on the top level tests to make sure
|
||||
that <span class="new_code">run()</span> will run once only
|
||||
from the top level script that has been invoked.
|
||||
<pre>
|
||||
<?php<strong>
|
||||
define('RUNNER', true);</strong>
|
||||
require_once('file_group_test.php');
|
||||
|
||||
$test = &new BigGroupTest('Big group');
|
||||
$test->addTestCase(new FileGroupTest());
|
||||
$test->addTestCase(...);
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
As with the normal test cases, a <span class="new_code">GroupTest</span> can
|
||||
be loaded with the <span class="new_code">GroupTest::addTestFile()</span> method.
|
||||
<pre>
|
||||
<?php
|
||||
define('RUNNER', true);
|
||||
|
||||
$test = &new BigGroupTest('Big group');<strong>
|
||||
$test->addTestFile('file_group_test.php');
|
||||
$test->addTestFile(...);</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="legacy">
|
||||
<h2>Integrating legacy test cases</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
If you already have unit tests for your code or are extending external
|
||||
classes that have tests, it is unlikely that all of the test cases
|
||||
are in SimpleTest format.
|
||||
Fortunately it is possible to incorporate test cases from other
|
||||
unit testers directly into SimpleTest group tests.
|
||||
</p>
|
||||
<p>
|
||||
Say we have the following
|
||||
<a href="http://sourceforge.net/projects/phpunit">PhpUnit</a>
|
||||
test case in the file <em>config_test.php</em>...
|
||||
<pre>
|
||||
<strong>class ConfigFileTest extends TestCase {
|
||||
function ConfigFileTest() {
|
||||
$this->TestCase('Config file test');
|
||||
}
|
||||
|
||||
function testContents() {
|
||||
$config = new ConfigFile('test.conf');
|
||||
$this->assertRegexp('/me/', $config->getValue('username'));
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
The group test can recognise this as long as we include
|
||||
the appropriate adapter class before we add the test
|
||||
file...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('simpletest/adapters/phpunit_test_case.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestFile('config_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
There are only two adapters, the other is for the
|
||||
<a href="http://pear.php.net/manual/en/package.php.phpunit.php">PEAR</a>
|
||||
1.0 unit tester...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('simpletest/adapters/pear_test_case.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestFile('some_pear_test_cases.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
The PEAR test cases can be freely mixed with SimpleTest
|
||||
ones even in the same test file,
|
||||
but you cannot use SimpleTest assertions in the legacy
|
||||
test case versions.
|
||||
This is done as a check that you are not accidently making
|
||||
your test cases completely dependent on SimpleTest.
|
||||
You may want to do a PEAR release of your library for example
|
||||
which would mean shipping it with valid PEAR::PhpUnit test
|
||||
cases.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,461 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>
|
||||
Download the Simple Test testing framework -
|
||||
Unit tests and mock objects for PHP
|
||||
</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<span class="chosen">SimpleTest</span>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Simple Test for PHP</h1>
|
||||
<div class="content">
|
||||
|
||||
|
||||
<p>
|
||||
The following assumes that you are familiar with the concept
|
||||
of unit testing as well as the PHP web development language.
|
||||
It is a guide for the impatient new user of
|
||||
<a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>.
|
||||
For fuller documentation, especially if you are new
|
||||
to unit testing see the ongoing
|
||||
<a href="unit_test_documentation.html">documentation</a>, and for
|
||||
example test cases see the
|
||||
<a href="http://www.lastcraft.com/first_test_tutorial.php">unit testing tutorial</a>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="unit">
|
||||
<h2>Using the tester quickly</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Amongst software testing tools, a unit tester is the one
|
||||
closest to the developer.
|
||||
In the context of agile development the test code sits right
|
||||
next to the source code as both are written simultaneously.
|
||||
In this context SimpleTest aims to be a complete PHP developer
|
||||
test solution and is called "Simple" because it
|
||||
should be easy to use and extend.
|
||||
It wasn't a good choice of name really.
|
||||
It includes all of the typical functions you would expect from
|
||||
<a href="http://www.junit.org/">JUnit</a> and the
|
||||
<a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>
|
||||
ports, but also adds
|
||||
<a href="http://www.mockobjects.com">mock objects</a>.
|
||||
It has some <a href="http://sourceforge.net/projects/jwebunit/">JWebUnit</a>
|
||||
functionality as well.
|
||||
This includes web page navigation, cookie testing and form submission.
|
||||
</p>
|
||||
<p>
|
||||
The quickest way to demonstrate is with an example.
|
||||
</p>
|
||||
<p>
|
||||
Let us suppose we are testing a simple file logging class called
|
||||
<span class="new_code">Log</span> in <em>classes/log.php</em>.
|
||||
We start by creating a test script which we will call
|
||||
<em>tests/log_test.php</em> and populate it as follows...
|
||||
<pre>
|
||||
<?php<strong>
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
}</strong>
|
||||
?>
|
||||
</pre>
|
||||
Here the <em>simpletest</em> folder is either local or in the path.
|
||||
You would have to edit these locations depending on where you
|
||||
placed the toolset.
|
||||
The <span class="new_code">TestOfLogging</span> is our frst test case and it's
|
||||
currently empty.
|
||||
</p>
|
||||
<p>
|
||||
Now we have five lines of scaffolding code and still no tests.
|
||||
However from this part on we get return on our investment very quickly.
|
||||
We'll assume that the <span class="new_code">Log</span> class
|
||||
takes the file name to write to in the constructor and we have
|
||||
a temporary folder in which to place this file...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
<strong>
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
When a test case runs it will search for any method that
|
||||
starts with the string <span class="new_code">test</span>
|
||||
and execute that method.
|
||||
We would normally have more than one test method of course.
|
||||
Assertions within the test methods trigger messages to the
|
||||
test framework which displays the result immediately.
|
||||
This immediate response is important, not just in the event
|
||||
of the code causing a crash, but also so that
|
||||
<span class="new_code">print</span> statements can display
|
||||
their content right next to the test case concerned.
|
||||
</p>
|
||||
<p>
|
||||
To see these results we have to actually run the tests.
|
||||
If this is the only test case we wish to run we can achieve
|
||||
it with...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));
|
||||
}
|
||||
}
|
||||
<strong>
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
On failure the display looks like this...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->True assertion failed.<br>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
...and if it passes like this...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>2</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
And if you get this...
|
||||
<div class="demo">
|
||||
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
|
||||
</div>
|
||||
it means you're missing the <em>classes/Log.php</em> file that could look like...
|
||||
<pre>
|
||||
<?php
|
||||
class Log {
|
||||
|
||||
function Log($file_path) {
|
||||
}
|
||||
|
||||
function message() {
|
||||
}
|
||||
}
|
||||
?>;
|
||||
</pre>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="group">
|
||||
<h2>Building group tests</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
It is unlikely in a real application that we will only ever run
|
||||
one test case.
|
||||
This means that we need a way of grouping cases into a test
|
||||
script that can, if need be, run every test in the application.
|
||||
</p>
|
||||
<p>
|
||||
Our first step is to strip the includes and to undo our
|
||||
previous hack...
|
||||
<pre>
|
||||
<?php<strong>
|
||||
require_once('../classes/log.php');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));<strong>
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
</pre>
|
||||
Next we create a new file called <em>tests/all_tests.php</em>
|
||||
and insert the following code...
|
||||
<pre>
|
||||
<strong><?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('All tests');
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
</pre>
|
||||
The method <span class="new_code">GroupTest::addTestFile()</span>
|
||||
will include the test case file and read any new classes created
|
||||
that are descended from <span class="new_code">SimpleTestCase</span>, of which
|
||||
<span class="new_code">UnitTestCase</span> is one example.
|
||||
Just the class names are stored for now, so that the test runner
|
||||
can instantiate the class when it works its way
|
||||
through your test suite.
|
||||
</p>
|
||||
<p>
|
||||
For this to work properly the test case file should not blindly include
|
||||
any other test case extensions that do not actually run tests.
|
||||
This could result in extra test cases being counted during the test
|
||||
run.
|
||||
Hardly a major problem, but to avoid this inconvenience simply add
|
||||
a <span class="new_code">SimpleTestOptions::ignore()</span> directive
|
||||
somewhere in the test case file.
|
||||
Also the test case file should not have been included
|
||||
elsewhere or no cases will be added to this group test.
|
||||
This would be a more serious error as if the test case classes are
|
||||
already loaded by PHP the <span class="new_code">GroupTest::addTestFile()</span>
|
||||
method will not detect them.
|
||||
</p>
|
||||
<p>
|
||||
To display the results it is necessary only to invoke
|
||||
<em>tests/all_tests.php</em> from the web server.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="mock">
|
||||
<h2>Using mock objects</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Let's move further into the future.
|
||||
</p>
|
||||
<p>
|
||||
Assume that our logging class is tested and completed.
|
||||
Assume also that we are testing another class that is
|
||||
required to write log messages, say a
|
||||
<span class="new_code">SessionPool</span>.
|
||||
We want to test a method that will probably end up looking
|
||||
like this...
|
||||
<pre>
|
||||
<strong>
|
||||
class SessionPool {
|
||||
...
|
||||
function logIn($username) {
|
||||
...
|
||||
$this->_log->message("User $username logged in.");
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
</strong>
|
||||
</pre>
|
||||
In the spirit of reuse we are using our
|
||||
<span class="new_code">Log</span> class.
|
||||
A conventional test case might look like this...
|
||||
<pre>
|
||||
<strong>
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/session_pool.php');
|
||||
|
||||
class TestOfSessionLogging extends UnitTestCase {
|
||||
|
||||
function setUp() {
|
||||
@unlink('/temp/test.log');
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
@unlink('/temp/test.log');
|
||||
}
|
||||
|
||||
function testLogInIsLogged() {
|
||||
$log = new Log('/temp/test.log');
|
||||
$session_pool = &new SessionPool($log);
|
||||
$session_pool->logIn('fred');
|
||||
$messages = file('/temp/test.log');
|
||||
$this->assertEqual($messages[0], "User fred logged in.\n");
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
</pre>
|
||||
This test case design is not all bad, but it could be improved.
|
||||
We are spending time fiddling with log files which are
|
||||
not part of our test. Worse, we have created close ties
|
||||
with the <span class="new_code">Log</span> class and
|
||||
this test.
|
||||
What if we don't use files any more, but use ths
|
||||
<em>syslog</em> library instead?
|
||||
Did you notice the extra carriage return in the message?
|
||||
Was that added by the logger?
|
||||
What if it also added a time stamp or other data?
|
||||
</p>
|
||||
<p>
|
||||
The only part that we really want to test is that a particular
|
||||
message was sent to the logger.
|
||||
We reduce coupling if we can pass in a fake logging class
|
||||
that simply records the message calls for testing, but
|
||||
takes no action.
|
||||
It would have to look exactly like our original though.
|
||||
</p>
|
||||
<p>
|
||||
If the fake object doesn't write to a file then we save on deleting
|
||||
the file before and after each test. We could save even more
|
||||
test code if the fake object would kindly run the assertion for us.
|
||||
<p>
|
||||
</p>
|
||||
Too good to be true?
|
||||
Luckily we can create such an object easily...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/session_pool.php');<strong>
|
||||
Mock::generate('Log');</strong>
|
||||
|
||||
class TestOfSessionLogging extends UnitTestCase {
|
||||
|
||||
function testLogInIsLogged() {<strong>
|
||||
$log = &new MockLog();
|
||||
$log->expectOnce('message', array('User fred logged in.'));</strong>
|
||||
$session_pool = &new SessionPool($log);
|
||||
$session_pool->logIn('fred');
|
||||
}
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
The test will be triggered when the call to
|
||||
<span class="new_code">message()</span> is invoked on the
|
||||
<span class="new_code">MockLog</span> object.
|
||||
The mock call will trigger a parameter comparison and then send the
|
||||
resulting pass or fail event to the test display.
|
||||
Wildcards can be included here too so as to prevent tests
|
||||
becoming too specific.
|
||||
</p>
|
||||
<p>
|
||||
If the mock reaches the end of the test case without the
|
||||
method being called, the <span class="new_code">expectOnce()</span>
|
||||
expectation will trigger a test failure.
|
||||
In other words the mocks can detect the absence of
|
||||
behaviour as well as the presence.
|
||||
</p>
|
||||
<p>
|
||||
The mock objects in the SimpleTest suite can have arbitrary
|
||||
return values set, sequences of returns, return values
|
||||
selected according to the incoming arguments, sequences of
|
||||
parameter expectations and limits on the number of times
|
||||
a method is to be invoked.
|
||||
</p>
|
||||
<p>
|
||||
For this test to run the mock objects library must have been
|
||||
included in the test suite, say in <em>all_tests.php</em>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="web">
|
||||
<h2>Web page testing</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
One of the requirements of web sites is that they produce web
|
||||
pages.
|
||||
If you are building a project top-down and you want to fully
|
||||
integrate testing along the way then you will want a way of
|
||||
automatically navigating a site and examining output for
|
||||
correctness.
|
||||
This is the job of a web tester.
|
||||
</p>
|
||||
<p>
|
||||
The web testing in SimpleTest is fairly primitive, there is
|
||||
no JavaScript for example.
|
||||
To give an idea here is a trivial example where a home
|
||||
page is fetched, from which we navigate to an "about"
|
||||
page and then test some client determined content.
|
||||
<pre>
|
||||
<?php<strong>
|
||||
require_once('simpletest/web_tester.php');</strong>
|
||||
require_once('simpletest/reporter.php');
|
||||
<strong>
|
||||
class TestOfAbout extends WebTestCase {
|
||||
|
||||
function setUp() {
|
||||
$this->get('http://test-server/index.php');
|
||||
$this->click('About');
|
||||
}
|
||||
|
||||
function testSearchEngineOptimisations() {
|
||||
$this->assertTitle('A long title about us for search engines');
|
||||
$this->assertPattern('/a popular keyphrase/i');
|
||||
}
|
||||
}</strong>
|
||||
$test = &new TestOfAbout();
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
With this code as an acceptance test you can ensure that
|
||||
the content always meets the specifications of both the
|
||||
developers and the other project stakeholders.
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"></a>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,727 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest for PHP mock objects documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Mock objects</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Mock objects documentation</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="what">
|
||||
<h2>What are mock objects?</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Mock objects have two roles during a test case: actor and critic.
|
||||
</p>
|
||||
<p>
|
||||
The actor behaviour is to simulate objects that are difficult to
|
||||
set up or time consuming to set up for a test.
|
||||
The classic example is a database connection.
|
||||
Setting up a test database at the start of each test would slow
|
||||
testing to a crawl and would require the installation of the
|
||||
database engine and test data on the test machine.
|
||||
If we can simulate the connection and return data of our
|
||||
choosing we not only win on the pragmatics of testing, but can
|
||||
also feed our code spurious data to see how it responds.
|
||||
We can simulate databases being down or other extremes
|
||||
without having to create a broken database for real.
|
||||
In other words, we get greater control of the test environment.
|
||||
</p>
|
||||
<p>
|
||||
If mock objects only behaved as actors they would simply be
|
||||
known as server stubs.
|
||||
This was originally a pattern named by Robert Binder (Testing
|
||||
object-oriented systems: models, patterns, and tools,
|
||||
Addison-Wesley) in 1999.
|
||||
</p>
|
||||
<p>
|
||||
A server stub is a simulation of an object or component.
|
||||
It should exactly replace a component in a system for test
|
||||
or prototyping purposes, but remain lightweight.
|
||||
This allows tests to run more quickly, or if the simulated
|
||||
class has not been written, to run at all.
|
||||
</p>
|
||||
<p>
|
||||
However, the mock objects not only play a part (by supplying chosen
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
In the case of an imaginary database connection they can
|
||||
test that the query, say SQL, was correctly formed by
|
||||
the object that is using the connection.
|
||||
Set them up with fairly tight expectations and you will
|
||||
hardly need manual assertions at all.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="creation">
|
||||
<h2>Creating mock objects</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
In the same way that we create server stubs, all we need is an
|
||||
existing class, say a database connection that looks like this...
|
||||
<pre>
|
||||
<strong>class DatabaseConnection {
|
||||
function DatabaseConnection() {
|
||||
}
|
||||
|
||||
function query() {
|
||||
}
|
||||
|
||||
function selectQuery() {
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
The class does not need to have been implemented yet.
|
||||
To create a mock version of the class we need to include the
|
||||
mock object library and run the generator...
|
||||
<pre>
|
||||
<strong>require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
|
||||
Mock::generate('DatabaseConnection');</strong>
|
||||
</pre>
|
||||
This generates a clone class called
|
||||
<span class="new_code">MockDatabaseConnection</span>.
|
||||
We can now create instances of the new class within
|
||||
our test case...
|
||||
<pre>
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
|
||||
Mock::generate('DatabaseConnection');
|
||||
<strong>
|
||||
class MyTestCase extends UnitTestCase {
|
||||
|
||||
function testSomething() {
|
||||
$connection = &new MockDatabaseConnection();
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
Unlike the generated stubs the mock constructor needs a reference
|
||||
to the test case so that it can dispatch passes and failures while
|
||||
checking its expectations.
|
||||
This means that mock objects can only be used within test cases.
|
||||
Despite this their extra power means that stubs are hardly ever used
|
||||
if mocks are available.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="stub">
|
||||
<h2>Mocks as actors</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The mock version of a class has all the methods of the original,
|
||||
so that operations like
|
||||
<span class="new_code">$connection->query()</span> are still
|
||||
legal.
|
||||
The return value will be <span class="new_code">null</span>,
|
||||
but we can change that with...
|
||||
<pre>
|
||||
<strong>$connection->setReturnValue('query', 37)</strong>
|
||||
</pre>
|
||||
Now every time we call
|
||||
<span class="new_code">$connection->query()</span> we get
|
||||
the result of 37.
|
||||
We can set the return value to anything, say a hash of
|
||||
imaginary database results or a list of persistent objects.
|
||||
Parameters are irrelevant here, we always get the same
|
||||
values back each time once they have been set up this way.
|
||||
That may not sound like a convincing replica of a
|
||||
database connection, but for the half a dozen lines of
|
||||
a test method it is usually all you need.
|
||||
</p>
|
||||
<p>
|
||||
We can also add extra methods to the mock when generating it
|
||||
and choose our own class name...
|
||||
<pre>
|
||||
<strong>Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));</strong>
|
||||
</pre>
|
||||
Here the mock will behave as if the <span class="new_code">setOptions()</span>
|
||||
existed in the original class.
|
||||
This is handy if a class has used the PHP <span class="new_code">overload()</span>
|
||||
mechanism to add dynamic methods.
|
||||
You can create a special mock to simulate this situation.
|
||||
</p>
|
||||
<p>
|
||||
Things aren't always that simple though.
|
||||
One common problem is iterators, where constantly returning
|
||||
the same value could cause an endless loop in the object
|
||||
being tested.
|
||||
For these we need to set up sequences of values.
|
||||
Let's say we have a simple iterator that looks like this...
|
||||
<pre>
|
||||
class Iterator {
|
||||
function Iterator() {
|
||||
}
|
||||
|
||||
function next() {
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
This is about the simplest iterator you could have.
|
||||
Assuming that this iterator only returns text until it
|
||||
reaches the end, when it returns false, we can simulate it
|
||||
with...
|
||||
<pre>
|
||||
Mock::generate('Iterator');
|
||||
|
||||
class IteratorTest extends UnitTestCase() {
|
||||
|
||||
function testASequence() {<strong>
|
||||
$iterator = &new MockIterator();
|
||||
$iterator->setReturnValue('next', false);
|
||||
$iterator->setReturnValueAt(0, 'next', 'First string');
|
||||
$iterator->setReturnValueAt(1, 'next', 'Second string');</strong>
|
||||
...
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
When <span class="new_code">next()</span> is called on the
|
||||
mock iterator it will first return "First string",
|
||||
on the second call "Second string" will be returned
|
||||
and on any other call <span class="new_code">false</span> will
|
||||
be returned.
|
||||
The sequenced return values take precedence over the constant
|
||||
return value.
|
||||
The constant one is a kind of default if you like.
|
||||
</p>
|
||||
<p>
|
||||
Another tricky situation is an overloaded
|
||||
<span class="new_code">get()</span> operation.
|
||||
An example of this is an information holder with name/value pairs.
|
||||
Say we have a configuration class like...
|
||||
<pre>
|
||||
class Configuration {
|
||||
function Configuration() {
|
||||
}
|
||||
|
||||
function getValue($key) {
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
This is a classic situation for using mock objects as
|
||||
actual configuration will vary from machine to machine,
|
||||
hardly helping the reliability of our tests if we use it
|
||||
directly.
|
||||
The problem though is that all the data comes through the
|
||||
<span class="new_code">getValue()</span> method and yet
|
||||
we want different results for different keys.
|
||||
Luckily the mocks have a filter system...
|
||||
<pre>
|
||||
<strong>$config = &new MockConfiguration();
|
||||
$config->setReturnValue('getValue', 'primary', array('db_host'));
|
||||
$config->setReturnValue('getValue', 'admin', array('db_user'));
|
||||
$config->setReturnValue('getValue', 'secret', array('db_password'));</strong>
|
||||
</pre>
|
||||
The extra parameter is a list of arguments to attempt
|
||||
to match.
|
||||
In this case we are trying to match only one argument which
|
||||
is the look up key.
|
||||
Now when the mock object has the
|
||||
<span class="new_code">getValue()</span> method invoked
|
||||
like this...
|
||||
<pre>
|
||||
$config->getValue('db_user')
|
||||
</pre>
|
||||
...it will return "admin".
|
||||
It finds this by attempting to match the calling arguments
|
||||
to its list of returns one after another until
|
||||
a complete match is found.
|
||||
</p>
|
||||
<p>
|
||||
You can set a default argument argument like so...
|
||||
<pre>
|
||||
<strong>
|
||||
$config->setReturnValue('getValue', false, array('*'));</strong>
|
||||
</pre>
|
||||
This is not the same as setting the return value without
|
||||
any argument requirements like this...
|
||||
<pre>
|
||||
<strong>
|
||||
$config->setReturnValue('getValue', false);</strong>
|
||||
</pre>
|
||||
In the first case it will accept any single argument,
|
||||
but exactly one is required.
|
||||
In the second case any number of arguments will do and
|
||||
it acts as a catchall after all other matches.
|
||||
Note that if we add further single parameter options after
|
||||
the wildcard in the first case, they will be ignored as the wildcard
|
||||
will match first.
|
||||
With complex parameter lists the ordering could be important
|
||||
or else desired matches could be masked by earlier wildcard
|
||||
ones.
|
||||
Declare the most specific matches first if you are not sure.
|
||||
</p>
|
||||
<p>
|
||||
There are times when you want a specific object to be
|
||||
dished out by the mock rather than a copy.
|
||||
The PHP4 copy semantics force us to use a different method
|
||||
for this.
|
||||
You might be simulating a container for example...
|
||||
<pre>
|
||||
class Thing {
|
||||
}
|
||||
|
||||
class Vector {
|
||||
function Vector() {
|
||||
}
|
||||
|
||||
function get($index) {
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
In this case you can set a reference into the mock's
|
||||
return list...
|
||||
<pre>
|
||||
$thing = &new Thing();<strong>
|
||||
$vector = &new MockVector();
|
||||
$vector->setReturnReference('get', $thing, array(12));</strong>
|
||||
</pre>
|
||||
With this arrangement you know that every time
|
||||
<span class="new_code">$vector->get(12)</span> is
|
||||
called it will return the same
|
||||
<span class="new_code">$thing</span> each time.
|
||||
This is compatible with PHP5 as well.
|
||||
</p>
|
||||
<p>
|
||||
These three factors, timing, parameters and whether to copy,
|
||||
can be combined orthogonally.
|
||||
For example...
|
||||
<pre>
|
||||
$complex = &new MockComplexThing();
|
||||
$stuff = &new Stuff();<strong>
|
||||
$complex->setReturnReferenceAt(3, 'get', $stuff, array('*', 1));</strong>
|
||||
</pre>
|
||||
This will return the <span class="new_code">$stuff</span> only on the third
|
||||
call and only if two parameters were set the second of
|
||||
which must be the integer 1.
|
||||
That should cover most simple prototyping situations.
|
||||
</p>
|
||||
<p>
|
||||
A final tricky case is one object creating another, known
|
||||
as a factory pattern.
|
||||
Suppose that on a successful query to our imaginary
|
||||
database, a result set is returned as an iterator with
|
||||
each call to <span class="new_code">next()</span> giving
|
||||
one row until false.
|
||||
This sounds like a simulation nightmare, but in fact it can all
|
||||
be mocked using the mechanics above.
|
||||
</p>
|
||||
<p>
|
||||
Here's how...
|
||||
<pre>
|
||||
Mock::generate('DatabaseConnection');
|
||||
Mock::generate('ResultIterator');
|
||||
|
||||
class DatabaseTest extends UnitTestCase {
|
||||
|
||||
function testUserFinder() {<strong>
|
||||
$result = &new MockResultIterator();
|
||||
$result->setReturnValue('next', false);
|
||||
$result->setReturnValueAt(0, 'next', array(1, 'tom'));
|
||||
$result->setReturnValueAt(1, 'next', array(3, 'dick'));
|
||||
$result->setReturnValueAt(2, 'next', array(6, 'harry'));
|
||||
|
||||
$connection = &new MockDatabaseConnection();
|
||||
$connection->setReturnValue('query', false);
|
||||
$connection->setReturnReference(
|
||||
'query',
|
||||
$result,
|
||||
array('select id, name from users'));</strong>
|
||||
|
||||
$finder = &new UserFinder($connection);
|
||||
$this->assertIdentical(
|
||||
$finder->findNames(),
|
||||
array('tom', 'dick', 'harry'));
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Now only if our
|
||||
<span class="new_code">$connection</span> is called with the correct
|
||||
<span class="new_code">query()</span> will the
|
||||
<span class="new_code">$result</span> be returned that is
|
||||
itself exhausted after the third call to <span class="new_code">next()</span>.
|
||||
This should be enough
|
||||
information for our <span class="new_code">UserFinder</span> class,
|
||||
the class actually
|
||||
being tested here, to come up with goods.
|
||||
A very precise test and not a real database in sight.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="expectations">
|
||||
<h2>Mocks as critics</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Although the server stubs approach insulates your tests from
|
||||
real world disruption, it is only half the benefit.
|
||||
You can have the class under test receiving the required
|
||||
messages, but is your new class sending correct ones?
|
||||
Testing this can get messy without a mock objects library.
|
||||
</p>
|
||||
<p>
|
||||
By way of example, suppose we have a
|
||||
<span class="new_code">SessionPool</span> class that we
|
||||
want to add logging to.
|
||||
Rather than grow the original class into something more
|
||||
complicated, we want to add this behaviour with a decorator (GOF).
|
||||
The <span class="new_code">SessionPool</span> code currently looks
|
||||
like this...
|
||||
<pre>
|
||||
<strong>class SessionPool {
|
||||
function SessionPool() {
|
||||
...
|
||||
}
|
||||
|
||||
function &findSession($cookie) {
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
|
||||
class Session {
|
||||
...
|
||||
}</strong>
|
||||
</php>
|
||||
While our logging code looks like this...
|
||||
<php><strong>
|
||||
class Log {
|
||||
function Log() {
|
||||
...
|
||||
}
|
||||
|
||||
function message() {
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
class LoggingSessionPool {
|
||||
function LoggingSessionPool(&$session_pool, &$log) {
|
||||
...
|
||||
}
|
||||
|
||||
function &findSession(\$cookie) {
|
||||
...
|
||||
}
|
||||
...
|
||||
}</strong>
|
||||
</pre>
|
||||
Out of all of this, the only class we want to test here
|
||||
is the <span class="new_code">LoggingSessionPool</span>.
|
||||
In particular we would like to check that the
|
||||
<span class="new_code">findSession()</span> method is
|
||||
called with the correct session ID in the cookie and that
|
||||
it sent the message "Starting session $cookie"
|
||||
to the logger.
|
||||
</p>
|
||||
<p>
|
||||
Despite the fact that we are testing only a few lines of
|
||||
production code, here is what we would have to do in a
|
||||
conventional test case:
|
||||
<ol>
|
||||
<li>Create a log object.</li>
|
||||
<li>Set a directory to place the log file.</li>
|
||||
<li>Set the directory permissions so we can write the log.</li>
|
||||
<li>Create a <span class="new_code">SessionPool</span> object.</li>
|
||||
<li>Hand start a session, which probably does lot's of things.</li>
|
||||
<li>Invoke <span class="new_code">findSession()</span>.</li>
|
||||
<li>Read the new Session ID (hope there is an accessor!).</li>
|
||||
<li>Raise a test assertion to confirm that the ID matches the cookie.</li>
|
||||
<li>Read the last line of the log file.</li>
|
||||
<li>Pattern match out the extra logging timestamps, etc.</li>
|
||||
<li>Assert that the session message is contained in the text.</li>
|
||||
</ol>
|
||||
It is hardly surprising that developers hate writing tests
|
||||
when they are this much drudgery.
|
||||
To make things worse, every time the logging format changes or
|
||||
the method of creating new sessions changes, we have to rewrite
|
||||
parts of this test even though this test does not officially
|
||||
test those parts of the system.
|
||||
We are creating headaches for the writers of these other classes.
|
||||
</p>
|
||||
<p>
|
||||
Instead, here is the complete test method using mock object magic...
|
||||
<pre>
|
||||
Mock::generate('Session');
|
||||
Mock::generate('SessionPool');
|
||||
Mock::generate('Log');
|
||||
|
||||
class LoggingSessionPoolTest extends UnitTestCase {
|
||||
...
|
||||
function testFindSessionLogging() {<strong>
|
||||
$session = &new MockSession();
|
||||
$pool = &new MockSessionPool();
|
||||
$pool->setReturnReference('findSession', $session);
|
||||
$pool->expectOnce('findSession', array('abc'));
|
||||
|
||||
$log = &new MockLog();
|
||||
$log->expectOnce('message', array('Starting session abc'));
|
||||
|
||||
$logging_pool = &new LoggingSessionPool($pool, $log);
|
||||
$this->assertReference($logging_pool->findSession('abc'), $session);</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
We start by creating a dummy session.
|
||||
We don't have to be too fussy about this as the check
|
||||
for which session we want is done elsewhere.
|
||||
We only need to check that it was the same one that came
|
||||
from the session pool.
|
||||
</p>
|
||||
<p>
|
||||
<span class="new_code">findSession()</span> is a factory
|
||||
method the simulation of which is described <a href="#stub">above</a>.
|
||||
The point of departure comes with the first
|
||||
<span class="new_code">expectOnce()</span> call.
|
||||
This line states that whenever
|
||||
<span class="new_code">findSession()</span> is invoked on the
|
||||
mock, it will test the incoming arguments.
|
||||
If it receives the single argument of a string "abc"
|
||||
then a test pass is sent to the unit tester, otherwise a fail is
|
||||
generated.
|
||||
This was the part where we checked that the right session was asked for.
|
||||
The argument list follows the same format as the one for setting
|
||||
return values.
|
||||
You can have wildcards and sequences and the order of
|
||||
evaluation is the same.
|
||||
</p>
|
||||
<p>
|
||||
We use the same pattern to set up the mock logger.
|
||||
We tell it that it should have
|
||||
<span class="new_code">message()</span> invoked
|
||||
once only with the argument "Starting session abc".
|
||||
By testing the calling arguments, rather than the logger output,
|
||||
we insulate the test from any display changes in the logger.
|
||||
</p>
|
||||
<p>
|
||||
We start to run our tests when we create the new
|
||||
<span class="new_code">LoggingSessionPool</span> and feed
|
||||
it our preset mock objects.
|
||||
Everything is now under our control.
|
||||
</p>
|
||||
<p>
|
||||
This is still quite a bit of test code, but the code is very
|
||||
strict.
|
||||
If it still seems rather daunting there is a lot less of it
|
||||
than if we tried this without mocks and this particular test,
|
||||
interactions rather than output, is always more work to set
|
||||
up.
|
||||
More often you will be testing more complex situations without
|
||||
needing this level or precision.
|
||||
Also some of this can be refactored into a test case
|
||||
<span class="new_code">setUp()</span> method.
|
||||
</p>
|
||||
<p>
|
||||
Here is the full list of expectations you can set on a mock object
|
||||
in <a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>...
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Expectation</th><th>Needs <span class="new_code">tally()</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">expect($method, $args)</span></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectAt($timing, $method, $args)</span></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectCallCount($method, $count)</span></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectMaximumCallCount($method, $count)</span></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectMinimumCallCount($method, $count)</span></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectNever($method)</span></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectOnce($method, $args)</span></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">expectAtLeastOnce($method, $args)</span></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
Where the parameters are...
|
||||
<dl>
|
||||
<dt class="new_code">$method</dt>
|
||||
<dd>The method name, as a string, to apply the condition to.</dd>
|
||||
<dt class="new_code">$args</dt>
|
||||
<dd>
|
||||
The arguments as a list. Wildcards can be included in the same
|
||||
manner as for <span class="new_code">setReturn()</span>.
|
||||
This argument is optional for <span class="new_code">expectOnce()</span>
|
||||
and <span class="new_code">expectAtLeastOnce()</span>.
|
||||
</dd>
|
||||
<dt class="new_code">$timing</dt>
|
||||
<dd>
|
||||
The only point in time to test the condition.
|
||||
The first call starts at zero.
|
||||
</dd>
|
||||
<dt class="new_code">$count</dt>
|
||||
<dd>The number of calls expected.</dd>
|
||||
</dl>
|
||||
The method <span class="new_code">expectMaximumCallCount()</span>
|
||||
is slightly different in that it will only ever generate a failure.
|
||||
It is silent if the limit is never reached.
|
||||
</p>
|
||||
<p>
|
||||
Like the assertions within test cases, all of the expectations
|
||||
can take a message override as an extra parameter.
|
||||
Also the original failure message can be embedded in the output
|
||||
as "%s".
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="approaches">
|
||||
<h2>Other approaches</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
There are three approaches to creating mocks including the one
|
||||
that SimpleTest employs.
|
||||
Coding them by hand using a base class, generating them to
|
||||
a file and dynamically generating them on the fly.
|
||||
</p>
|
||||
<p>
|
||||
Mock objects generated with <a href="simple_test.html">SimpleTest</a>
|
||||
are dynamic.
|
||||
They are created at run time in memory, using
|
||||
<span class="new_code">eval()</span>, rather than written
|
||||
out to a file.
|
||||
This makes the mocks easy to create, a one liner,
|
||||
especially compared with hand
|
||||
crafting them in a parallel class hierarchy.
|
||||
The problem is that the behaviour is usually set up in the tests
|
||||
themselves.
|
||||
If the original objects change the mock versions
|
||||
that the tests rely on can get out of sync.
|
||||
This can happen with the parallel hierarchy approach as well,
|
||||
but is far more quickly detected.
|
||||
</p>
|
||||
<p>
|
||||
The solution, of course, is to add some real integration
|
||||
tests.
|
||||
You don't need very many and the convenience gained
|
||||
from the mocks more than outweighs the small amount of
|
||||
extra testing.
|
||||
You cannot trust code that was only tested with mocks.
|
||||
</p>
|
||||
<p>
|
||||
If you are still determined to build static libraries of mocks
|
||||
because you want to simulate very specific behaviour, you can
|
||||
achieve the same effect using the SimpleTest class generator.
|
||||
In your library file, say <em>mocks/connection.php</em> for a
|
||||
database connection, create a mock and inherit to override
|
||||
special methods or add presets...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('../classes/connection.php');
|
||||
<strong>
|
||||
Mock::generate('Connection', 'BasicMockConnection');
|
||||
class MockConnection extends BasicMockConnection {
|
||||
function MockConnection() {
|
||||
$this->BasicMockConnection();
|
||||
$this->setReturn('query', false);
|
||||
}
|
||||
}</strong>
|
||||
?>
|
||||
</pre>
|
||||
The generate call tells the class generator to create
|
||||
a class called <span class="new_code">BasicMockConnection</span>
|
||||
rather than the usual <span class="new_code">MockConnection</span>.
|
||||
We then inherit from this to get our version of
|
||||
<span class="new_code">MockConnection</span>.
|
||||
By intercepting in this way we can add behaviour, here setting
|
||||
the default value of <span class="new_code">query()</span> to be false.
|
||||
By using the default name we make sure that the mock class
|
||||
generator will not recreate a different one when invoked elsewhere in the
|
||||
tests.
|
||||
It never creates a class if it already exists.
|
||||
As long as the above file is included first then all tests
|
||||
that generated <span class="new_code">MockConnection</span> should
|
||||
now be using our one instead.
|
||||
If we don't get the order right and the mock library
|
||||
creates one first then the class creation will simply fail.
|
||||
</p>
|
||||
<p>
|
||||
Use this trick if you find you have a lot of common mock behaviour
|
||||
or you are getting frequent integration problems at later
|
||||
stages of testing.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,406 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>
|
||||
Overview and feature list for the SimpleTest PHP unit tester and web tester
|
||||
</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<span class="chosen">Overview</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Overview of SimpleTest</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="summary">
|
||||
<h2>What is SimpleTest?</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The heart of SimpleTest is a testing framework built around
|
||||
test case classes.
|
||||
These are written as extensions of base test case classes,
|
||||
each extended with methods that actually contain test code.
|
||||
Top level test scripts then invoke the <span class="new_code">run()</span>
|
||||
methods on every one of these test cases in order.
|
||||
Each test method is written to invoke various assertions that
|
||||
the developer expects to be true such as
|
||||
<span class="new_code">assertEqual()</span>.
|
||||
If the expectation is correct, then a successful result is dispatched to the
|
||||
observing test reporter, but any failure triggers an alert
|
||||
and a description of the mismatch.
|
||||
</p>
|
||||
<p>
|
||||
A <a href="unit_test_documentation.html">test case</a> looks like this...
|
||||
<pre>
|
||||
<?php
|
||||
class <strong>MyTestCase</strong> extends UnitTestCase {
|
||||
<strong>
|
||||
function testLog() {
|
||||
$log = &new Log('my.log');
|
||||
$log->message('Hello');
|
||||
$this->assertTrue(file_exists('my.log'));
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
These tools are designed for the developer.
|
||||
Tests are written in the PHP language itself more or less
|
||||
as the application itself is built.
|
||||
The advantage of using PHP itself as the testing language is that
|
||||
there are no new languages to learn, testing can start straight away,
|
||||
and the developer can test any part of the code.
|
||||
Basically, all parts that can be accessed by the application code can also be
|
||||
accessed by the test code if they are in the same language.
|
||||
</p>
|
||||
<p>
|
||||
The simplest type of test case is the
|
||||
<a href="unit_tester_documentation.html">UnitTestCase</a>.
|
||||
This class of test case includes standard tests for equality,
|
||||
references and pattern matching.
|
||||
All these test the typical expectations of what you would
|
||||
expect the result of a function or method to be.
|
||||
This is by far the most common type of test in the daily
|
||||
routine of development, making up about 95% of test cases.
|
||||
</p>
|
||||
<p>
|
||||
The top level task of a web application though is not to
|
||||
produce correct output from its methods and objects, but
|
||||
to generate web pages.
|
||||
The <a href="web_tester_documentation.html">WebTestCase</a> class tests web
|
||||
pages.
|
||||
It simulates a web browser requesting a page, complete with
|
||||
cookies, proxies, secure connections, authentication, forms, frames and most
|
||||
navigation elements.
|
||||
With this type of test case, the developer can assert that
|
||||
information is present in the page and that forms and
|
||||
sessions are handled correctly.
|
||||
</p>
|
||||
<p>
|
||||
A <a href="web_tester_documentation.html">WebTestCase</a> looks like this...
|
||||
<pre>
|
||||
<?php
|
||||
class <strong>MySiteTest</strong> extends WebTestCase {
|
||||
<strong>
|
||||
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/');
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="features">
|
||||
<h2>Feature list</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The following is a very rough outline of past and future features
|
||||
and their expected point of release.
|
||||
I am afraid it is liable to change without warning as meeting the
|
||||
milestones rather depends on time available.
|
||||
Green stuff has been coded, but not necessarily released yet.
|
||||
If you have a pressing need for a green but unreleased feature
|
||||
then you should check-out the code from Sourceforge CVS directly.
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Feature</th><th>Description</th><th>Release</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Unit test case</td>
|
||||
<td>Core test case class and assertions</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Html display</td>
|
||||
<td>Simplest possible display</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Autoloading of test cases</td>
|
||||
<td>
|
||||
Reading a file with test cases and loading them into a
|
||||
group test automatically
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Mock objects</td>
|
||||
<td>
|
||||
Objects capable of simulating other objects removing
|
||||
test dependencies
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Web test case</td>
|
||||
<td>Allows link following and title tag matching</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Partial mocks</td>
|
||||
<td>
|
||||
Mocking parts of a class for testing less than a class
|
||||
or for complex simulations
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Web cookie handling</td>
|
||||
<td>Correct handling of cookies when fetching pages</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Following redirects</td>
|
||||
<td>Page fetching automatically follows 300 redirects</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Form parsing</td>
|
||||
<td>Ability to submit simple forms and read default form values</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Command line interface</td>
|
||||
<td>Test display without the need of a web browser</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Exposure of expectation classes</td>
|
||||
<td>Can create precise tests with mocks as well as test cases</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>XML output and parsing</td>
|
||||
<td>
|
||||
Allows multi host testing and the integration of acceptance
|
||||
testing extensions
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Browser component</td>
|
||||
<td>
|
||||
Exposure of lower level web browser interface for more
|
||||
detailed test cases
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>HTTP authentication</td>
|
||||
<td>
|
||||
Fetching protected web pages with basic authentication
|
||||
only
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>SSL support</td>
|
||||
<td>Can connect to https: pages</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Proxy support</td>
|
||||
<td>Can connect via. common proxies</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Frames support</td>
|
||||
<td>Handling of frames in web test cases</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>File upload testing</td>
|
||||
<td>Can simulate the input type file tag</td>
|
||||
<td style="color: green;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Mocking interfaces</td>
|
||||
<td>
|
||||
Can generate mock objects to interfaces as well as classes
|
||||
and class interfaces are carried for type hints
|
||||
</td>
|
||||
<td style="color: green;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Reporting machinery enhancements</td>
|
||||
<td>Improved message passing for better cooperation with IDEs</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Localisation</td>
|
||||
<td>Messages abstracted and code generated from XML</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Testing exceptions</td>
|
||||
<td>Similar to testing PHP errors</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>IFrame support</td>
|
||||
<td>Reads IFrame content that can be refreshed</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Improved mock interface</td>
|
||||
<td>More compact way of expressing mocks</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>HTML table assertions</td>
|
||||
<td>Can match table elements to numerical assertions</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>XPath searching of HTML elements</td>
|
||||
<td>More flexible content matching</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Alternate HTML parsers</td>
|
||||
<td>Can detect compiled parsers for performance improvements</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Javascript suport</td>
|
||||
<td>Use of PECL module to add Javascript</td>
|
||||
<td style="color: red;">3.0</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
PHP5 migraton will start straight after the version 1.0.1 series,
|
||||
whereupon PHP4 will no longer be supported.
|
||||
SimpleTest is currently compatible with PHP5, but will not
|
||||
make use of all of the new features until version 2.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="resources">
|
||||
<h2>Web resources for testing</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Process is at least as important as tools.
|
||||
The type of process that makes the heaviest use of a developer's
|
||||
testing tool is of course
|
||||
<a href="http://www.extremeprogramming.org/">Extreme Programming</a>.
|
||||
This is one of the
|
||||
<a href="http://www.agilealliance.com/articles/index">Agile Methodologies</a>
|
||||
which combine various practices to "flatten the cost curve" of software development.
|
||||
More extreme still is <a href="http://www.testdriven.com/modules/news/">Test Driven Development</a>,
|
||||
where you very strictly adhere to the rule of no coding until you have a test.
|
||||
If you're more of a planner or believe that experience trumps evolution,
|
||||
you may prefer the
|
||||
<a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a> approach.
|
||||
I haven't tried it, but even I can see that you will need test tools (see figure 9).
|
||||
</p>
|
||||
<p>
|
||||
Most unit testers clone <a href="http://www.junit.org/">JUnit</a> to some degree,
|
||||
as far as the interface at least. There is a wealth of information on the
|
||||
JUnit site including the
|
||||
<a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a>
|
||||
which contains plenty of general advice on testing.
|
||||
Once you get bitten by the bug you will certainly appreciate the phrase
|
||||
<a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">test infected</a>
|
||||
coined by Eric Gamma.
|
||||
If you are still reviewing which unit tester to use the main choices
|
||||
are <a href="http://phpunit.sourceforge.net/">PHPUnit</a>
|
||||
and <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>.
|
||||
They currently lack a lot of features found in
|
||||
<a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>, but the PEAR
|
||||
version at least has been upgraded for PHP5 and is recommended if you are porting
|
||||
existing <a href="http://www.junit.org/">JUnit</a> test cases.
|
||||
</p>
|
||||
<p>
|
||||
There is currently a sad lack of material on mock objects, which is a shame
|
||||
as unit testing without them is a lot more work.
|
||||
The <a href="http://www.sidewize.com/company/mockobjects.pdf">original mock objects paper</a>
|
||||
is very Java focused, but still worth a read.
|
||||
As a new technology there are plenty of discussions and debate on how to use mocks,
|
||||
often on Wikis such as
|
||||
<a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a>
|
||||
or <a href="http://www.mockobjects.com/MocksObjectsPaper.html">www.mockobjects.com</a>
|
||||
or <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>.
|
||||
Injecting mocks into a class is the main area of debate for which this
|
||||
<a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">paper on IBM</a>
|
||||
makes a good starting point.
|
||||
</p>
|
||||
<p>
|
||||
There are plenty of web testing tools, but the scriptable ones
|
||||
are mostly are written in Java and
|
||||
tutorials and advice are rather thin on the ground.
|
||||
The only hope is to look at the documentation for
|
||||
<a href="http://httpunit.sourceforge.net/">HTTPUnit</a>,
|
||||
<a href="http://htmlunit.sourceforge.net/">HTMLUnit</a>
|
||||
or <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> and hope for clues.
|
||||
There are some XML driven test frameworks, but again most
|
||||
require Java to run.
|
||||
</p>
|
||||
<p>
|
||||
A new generation of tools that run directly in the web browser
|
||||
are now available.
|
||||
These include
|
||||
<a href="http://www.openqa.org/selenium/">Selenium</a> and
|
||||
<a href="http://wtr.rubyforge.org/">Watir</a>.
|
||||
As SimpleTest does not support JavaScript you would probably
|
||||
have to look at these tools anyway if you have highly dynamic
|
||||
pages.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,423 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest for PHP partial mocks documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Partial mocks</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Partial mock objects documentation</h1>
|
||||
<div class="content">
|
||||
|
||||
<p>
|
||||
A partial mock is simply a pattern to alleviate a specific problem
|
||||
in testing with mock objects,
|
||||
that of getting mock objects into tight corners.
|
||||
It's quite a limited tool and possibly not even a good idea.
|
||||
It is included with SimpleTest because I have found it useful
|
||||
on more than one occasion and has saved a lot of work at that point.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="inject">
|
||||
<h2>The mock injection problem</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
When one object uses another it is very simple to just pass a mock
|
||||
version in already set up with its expectations.
|
||||
Things are rather tricker if one object creates another and the
|
||||
creator is the one you want to test.
|
||||
This means that the created object should be mocked, but we can
|
||||
hardly tell our class under test to create a mock instead.
|
||||
The tested class doesn't even know it is running inside a test
|
||||
after all.
|
||||
</p>
|
||||
<p>
|
||||
For example, suppose we are building a telnet client and it
|
||||
needs to create a network socket to pass its messages.
|
||||
The connection method might look something like...
|
||||
<pre>
|
||||
<strong><?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {
|
||||
$socket = &new Socket($ip, $port);
|
||||
$socket->read( ... );
|
||||
...
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
</pre>
|
||||
We would really like to have a mock object version of the socket
|
||||
here, what can we do?
|
||||
</p>
|
||||
<p>
|
||||
The first solution is to pass the socket in as a parameter,
|
||||
forcing the creation up a level.
|
||||
Having the client handle this is actually a very good approach
|
||||
if you can manage it and should lead to factoring the creation from
|
||||
the doing.
|
||||
In fact, this is one way in which testing with mock objects actually
|
||||
forces you to code more tightly focused solutions.
|
||||
They improve your programming.
|
||||
</p>
|
||||
<p>
|
||||
Here this would be...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
<strong>function &connect(&$socket, $username, $password) {
|
||||
$socket->read( ... );
|
||||
...
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
This means that the test code is typical for a test involving
|
||||
mock objects.
|
||||
<pre>
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new Telnet();
|
||||
$telnet->connect($socket, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
It is pretty obvious though that one level is all you can go.
|
||||
You would hardly want your top level application creating
|
||||
every low level file, socket and database connection ever
|
||||
needed.
|
||||
It wouldn't know the constructor parameters anyway.
|
||||
</p>
|
||||
<p>
|
||||
The next simplest compromise is to have the created object passed
|
||||
in as an optional parameter...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...<strong>
|
||||
function &connect($ip, $port, $username, $password, $socket = false) {
|
||||
if (!$socket) {
|
||||
$socket = &new Socket($ip, $port);
|
||||
}
|
||||
$socket->read( ... );</strong>
|
||||
...
|
||||
return $socket;
|
||||
}
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
For a quick solution this is usually good enough.
|
||||
The test now looks almost the same as if the parameter
|
||||
was formally passed...
|
||||
<pre>
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret', &$socket);
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The problem with this approach is its untidiness.
|
||||
There is test code in the main class and parameters passed
|
||||
in the test case that are never used.
|
||||
This is a quick and dirty approach, but nevertheless effective
|
||||
in most situations.
|
||||
</p>
|
||||
<p>
|
||||
The next method is to pass in a factory object to do the creation...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {<strong>
|
||||
function Telnet(&$network) {
|
||||
$this->_network = &$network;
|
||||
}</strong>
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {<strong>
|
||||
$socket = &$this->_network->createSocket($ip, $port);
|
||||
$socket->read( ... );</strong>
|
||||
...
|
||||
return $socket;
|
||||
}
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
This is probably the most highly factored answer as creation
|
||||
is now moved into a small specialist class.
|
||||
The networking factory can now be tested separately, but mocked
|
||||
easily when we are testing the telnet class...
|
||||
<pre>
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$network = &new MockNetwork($this);
|
||||
$network->setReturnReference('createSocket', $socket);
|
||||
$telnet = &new Telnet($network);
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The downside is that we are adding a lot more classes to the
|
||||
library.
|
||||
Also we are passing a lot of factories around which will
|
||||
make the code a little less intuitive.
|
||||
The most flexible solution, but the most complex.
|
||||
</p>
|
||||
<p>
|
||||
Is there a middle ground?
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="creation">
|
||||
<h2>Protected factory method</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
There is a way we can circumvent the problem without creating
|
||||
any new application classes, but it involves creating a subclass
|
||||
when we do the actual testing.
|
||||
Firstly we move the socket creation into its own method...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {<strong>
|
||||
$socket = &$this->_createSocket($ip, $port);</strong>
|
||||
$socket->read( ... );
|
||||
...
|
||||
}<strong>
|
||||
|
||||
function &_createSocket($ip, $port) {
|
||||
return new Socket($ip, $port);
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
</pre>
|
||||
This is the only change we make to the application code.
|
||||
</p>
|
||||
<p>
|
||||
For the test case we have to create a subclass so that
|
||||
we can intercept the socket creation...
|
||||
<pre>
|
||||
<strong>class TelnetTestVersion extends Telnet {
|
||||
var $_mock;
|
||||
|
||||
function TelnetTestVersion(&$mock) {
|
||||
$this->_mock = &$mock;
|
||||
$this->Telnet();
|
||||
}
|
||||
|
||||
function &_createSocket() {
|
||||
return $this->_mock;
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
Here I have passed the mock in the constructor, but a
|
||||
setter would have done just as well.
|
||||
Note that the mock was set into the object variable
|
||||
before the constructor was chained.
|
||||
This is necessary in case the constructor calls
|
||||
<span class="new_code">connect()</span>.
|
||||
Otherwise it could get a null value from
|
||||
<span class="new_code">_createSocket()</span>.
|
||||
</p>
|
||||
<p>
|
||||
After the completion of all of this extra work the
|
||||
actual test case is fairly easy.
|
||||
We just test our new class instead...
|
||||
<pre>
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($socket);
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The new class is very simple of course.
|
||||
It just sets up a return value, rather like a mock.
|
||||
It would be nice if it also checked the incoming parameters
|
||||
as well.
|
||||
Just like a mock.
|
||||
It seems we are likely to do this often, can
|
||||
we automate the subclass creation?
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="partial">
|
||||
<h2>A partial mock</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Of course the answer is "yes" or I would have stopped writing
|
||||
this by now!
|
||||
The previous test case was a lot of work, but we can
|
||||
generate the subclass using a similar approach to the mock objects.
|
||||
</p>
|
||||
<p>
|
||||
Here is the partial mock version of the test...
|
||||
<pre>
|
||||
<strong>Mock::generatePartial(
|
||||
'Telnet',
|
||||
'TelnetTestVersion',
|
||||
array('_createSocket'));</strong>
|
||||
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($this);
|
||||
$telnet->setReturnReference('_createSocket', $socket);
|
||||
$telnet->Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The partial mock is a subclass of the original with
|
||||
selected methods "knocked out" with test
|
||||
versions.
|
||||
The <span class="new_code">generatePartial()</span> call
|
||||
takes three parameters: the class to be subclassed,
|
||||
the new test class name and a list of methods to mock.
|
||||
</p>
|
||||
<p>
|
||||
Instantiating the resulting objects is slightly tricky.
|
||||
The only constructor parameter of a partial mock is
|
||||
the unit tester reference.
|
||||
As with the normal mock objects this is needed for sending
|
||||
test results in response to checked expectations.
|
||||
</p>
|
||||
<p>
|
||||
The original constructor is not run yet.
|
||||
This is necessary in case the constructor is going to
|
||||
make use of the as yet unset mocked methods.
|
||||
We set any return values at this point and then run the
|
||||
constructor with its normal parameters.
|
||||
This three step construction of "new", followed
|
||||
by setting up the methods, followed by running the constructor
|
||||
proper is what distinguishes the partial mock code.
|
||||
</p>
|
||||
<p>
|
||||
Apart from construction, all of the mocked methods have
|
||||
the same features as mock objects and all of the unmocked
|
||||
methods behave as before.
|
||||
We can set expectations very easily...
|
||||
<pre>
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($this);
|
||||
$telnet->setReturnReference('_createSocket', $socket);<strong>
|
||||
$telnet->expectOnce('_createSocket', array('127.0.0.1', 21));</strong>
|
||||
$telnet->Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...<strong>
|
||||
$telnet->tally();</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="less">
|
||||
<h2>Testing less than a class</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The mocked out methods don't have to be factory methods,
|
||||
they could be any sort of method.
|
||||
In this way partial mocks allow us to take control of any part of
|
||||
a class except the constructor.
|
||||
We could even go as far as to mock every method
|
||||
except one we actually want to test.
|
||||
</p>
|
||||
<p>
|
||||
This last situation is all rather hypothetical, as I haven't
|
||||
tried it.
|
||||
I am open to the possibility, but a little worried that
|
||||
forcing object granularity may be better for the code quality.
|
||||
I personally use partial mocks as a way of overriding creation
|
||||
or for occasional testing of the TemplateMethod pattern.
|
||||
</p>
|
||||
<p>
|
||||
It's all going to come down to the coding standards of your
|
||||
project to decide which mechanism you use.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,512 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest for PHP test runner and display documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Reporting</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Test reporter documentation</h1>
|
||||
<div class="content">
|
||||
|
||||
<p>
|
||||
SimpleTest pretty much follows the MVC pattern
|
||||
(Model-View-Controller).
|
||||
The reporter classes are the view and the model is your
|
||||
test cases and their hiearchy.
|
||||
The controller is mostly hidden from the user of
|
||||
SimpleTest unless you want to change how the test cases
|
||||
are actually run, in which case it is possible to
|
||||
override the runner objects from within the test case.
|
||||
As usual with MVC, the controller is mostly undefined
|
||||
and there are other places to control the test run.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="html">
|
||||
<h2>Reporting results in HTML</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The default test display is minimal in the extreme.
|
||||
It reports success and failure with the conventional red and
|
||||
green bars and shows a breadcrumb trail of test groups
|
||||
for every failed assertion.
|
||||
Here's a fail...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<span class="fail">Fail</span>: createnewfile->True assertion failed.<br>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
And here all tests passed...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
The good news is that there are several points in the display
|
||||
hiearchy for subclassing.
|
||||
</p>
|
||||
<p>
|
||||
For web page based displays there is the
|
||||
<span class="new_code">HtmlReporter</span> class with the following
|
||||
signature...
|
||||
<pre>
|
||||
class HtmlReporter extends SimpleReporter {
|
||||
public HtmlReporter($encoding) { ... }
|
||||
public makeDry(boolean $is_dry) { ... }
|
||||
public void paintHeader(string $test_name) { ... }
|
||||
public void sendNoCacheHeaders() { ... }
|
||||
public void paintFooter(string $test_name) { ... }
|
||||
public void paintGroupStart(string $test_name, integer $size) { ... }
|
||||
public void paintGroupEnd(string $test_name) { ... }
|
||||
public void paintCaseStart(string $test_name) { ... }
|
||||
public void paintCaseEnd(string $test_name) { ... }
|
||||
public void paintMethodStart(string $test_name) { ... }
|
||||
public void paintMethodEnd(string $test_name) { ... }
|
||||
public void paintFail(string $message) { ... }
|
||||
public void paintPass(string $message) { ... }
|
||||
public void paintError(string $message) { ... }
|
||||
public void paintException(string $message) { ... }
|
||||
public void paintMessage(string $message) { ... }
|
||||
public void paintFormattedMessage(string $message) { ... }
|
||||
protected string _getCss() { ... }
|
||||
public array getTestList() { ... }
|
||||
public integer getPassCount() { ... }
|
||||
public integer getFailCount() { ... }
|
||||
public integer getExceptionCount() { ... }
|
||||
public integer getTestCaseCount() { ... }
|
||||
public integer getTestCaseProgress() { ... }
|
||||
}
|
||||
</pre>
|
||||
Here is what some of these methods mean. First the display methods
|
||||
that you will probably want to override...
|
||||
<ul class="api">
|
||||
<li>
|
||||
<span class="new_code">HtmlReporter(string $encoding)</span>
|
||||
<br>
|
||||
is the constructor.
|
||||
Note that the unit test sets up the link to the display
|
||||
rather than the other way around.
|
||||
The display is a mostly passive receiver of test events.
|
||||
This allows easy adaption of the display for other test
|
||||
systems beside unit tests, such as monitoring servers.
|
||||
The encoding is the character encoding you wish to
|
||||
display the test output in.
|
||||
In order to correctly render debug output when
|
||||
using the web tester, this should match the encoding
|
||||
of the site you are trying to test.
|
||||
The available character set strings are described in
|
||||
the PHP <a href="http://www.php.net/manual/en/function.htmlentities.php">html_entities()</a>
|
||||
function.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">void paintHeader(string $test_name)</span>
|
||||
<br>
|
||||
is called once at the very start of the test when the first
|
||||
start event arrives.
|
||||
The first start event is usually delivered by the top level group
|
||||
test and so this is where <span class="new_code">$test_name</span>
|
||||
comes from.
|
||||
It paints the page titles, CSS, body tag, etc.
|
||||
It returns nothing (<span class="new_code">void</span>).
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">void paintFooter(string $test_name)</span>
|
||||
<br>
|
||||
Called at the very end of the test to close any tags opened
|
||||
by the page header.
|
||||
By default it also displays the red/green bar and the final
|
||||
count of results.
|
||||
Actually the end of the test happens when a test end event
|
||||
comes in with the same name as the one that started it all
|
||||
at the same level.
|
||||
The tests nest you see.
|
||||
Closing the last test finishes the display.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">void paintMethodStart(string $test_name)</span>
|
||||
<br>
|
||||
is called at the start of each test method.
|
||||
The name normally comes from method name.
|
||||
The other test start events behave the same way except
|
||||
that the group test one tells the reporter how large
|
||||
it is in number of held test cases.
|
||||
This is so that the reporter can display a progress bar
|
||||
as the runner churns through the test cases.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">void paintMethodEnd(string $test_name)</span>
|
||||
<br>
|
||||
backs out of the test started with the same name.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">void paintFail(string $message)</span>
|
||||
<br>
|
||||
paints a failure.
|
||||
By default it just displays the word fail, a breadcrumbs trail
|
||||
showing the current test nesting and the message issued by
|
||||
the assertion.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">void paintPass(string $message)</span>
|
||||
<br>
|
||||
by default does nothing.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">string _getCss()</span>
|
||||
<br>
|
||||
Returns the CSS styles as a string for the page header
|
||||
method.
|
||||
Additional styles have to be appended here if you are
|
||||
not overriding the page header.
|
||||
You will want to use this method in an overriden page header
|
||||
if you want to include the original CSS.
|
||||
</li>
|
||||
</ul>
|
||||
There are also some accessors to get information on the current
|
||||
state of the test suite.
|
||||
Use these to enrich the display...
|
||||
<ul class="api">
|
||||
<li>
|
||||
<span class="new_code">array getTestList()</span>
|
||||
<br>
|
||||
is the first convenience method for subclasses.
|
||||
Lists the current nesting of the tests as a list
|
||||
of test names.
|
||||
The first, most deeply nested test, is first in the
|
||||
list and the current test method will be last.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">integer getPassCount()</span>
|
||||
<br>
|
||||
returns the number of passes chalked up so far.
|
||||
Needed for the display at the end.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">integer getFailCount()</span>
|
||||
<br>
|
||||
is likewise the number of fails so far.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">integer getExceptionCount()</span>
|
||||
<br>
|
||||
is likewise the number of errors so far.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">integer getTestCaseCount()</span>
|
||||
<br>
|
||||
is the total number of test cases in the test run.
|
||||
This includes the grouping tests themselves.
|
||||
</li>
|
||||
<li>
|
||||
<span class="new_code">integer getTestCaseProgress()</span>
|
||||
<br>
|
||||
is the number of test cases completed so far.
|
||||
</li>
|
||||
</ul>
|
||||
One simple modification is to get the HtmlReporter to display
|
||||
the passes as well as the failures and errors...
|
||||
<pre>
|
||||
<strong>class ShowPasses extends HtmlReporter {
|
||||
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "&<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("-&gt;", $breadcrumb);
|
||||
print "-&gt;$message<br />\n";
|
||||
}
|
||||
|
||||
function _getCss() {
|
||||
return parent::_getCss() . ' .pass { color: green; }';
|
||||
}
|
||||
}</strong>
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
One method that was glossed over was the <span class="new_code">makeDry()</span>
|
||||
method.
|
||||
If you run this method, with no parameters, on the reporter
|
||||
before the test suite is run no actual test methods
|
||||
will be called.
|
||||
You will still get the events of entering and leaving the
|
||||
test methods and test cases, but no passes or failures etc,
|
||||
because the test code will not actually be executed.
|
||||
</p>
|
||||
<p>
|
||||
The reason for this is to allow for more sophistcated
|
||||
GUI displays that allow the selection of individual test
|
||||
cases.
|
||||
In order to build a list of possible tests they need a
|
||||
report on the test structure for drawing, say a tree view
|
||||
of the test suite.
|
||||
With a reporter set to dry run that just sends drawing events
|
||||
this is easily accomplished.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="other">
|
||||
<h2>Extending the reporter</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Rather than simply modifying the existing display, you might want to
|
||||
produce a whole new HTML look, or even generate text or XML.
|
||||
Rather than override every method in
|
||||
<span class="new_code">HtmlReporter</span> we can take one
|
||||
step up the class hiearchy to <span class="new_code">SimpleReporter</span>
|
||||
in the <em>simple_test.php</em> source file.
|
||||
</p>
|
||||
<p>
|
||||
A do nothing display, a blank canvas for your own creation, would
|
||||
be...
|
||||
<pre>
|
||||
<strong>require_once('simpletest/simple_test.php');</strong>
|
||||
|
||||
class MyDisplay extends SimpleReporter {<strong>
|
||||
</strong>
|
||||
function paintHeader($test_name) {
|
||||
}
|
||||
|
||||
function paintFooter($test_name) {
|
||||
}
|
||||
|
||||
function paintStart($test_name, $size) {<strong>
|
||||
parent::paintStart($test_name, $size);</strong>
|
||||
}
|
||||
|
||||
function paintEnd($test_name, $size) {<strong>
|
||||
parent::paintEnd($test_name, $size);</strong>
|
||||
}
|
||||
|
||||
function paintPass($message) {<strong>
|
||||
parent::paintPass($message);</strong>
|
||||
}
|
||||
|
||||
function paintFail($message) {<strong>
|
||||
parent::paintFail($message);</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
No output would come from this class until you add it.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="cli">
|
||||
<h2>The command line reporter</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
SimpleTest also ships with a minimal command line reporter.
|
||||
The interface mimics JUnit to some extent, but paints the
|
||||
failure messages as they arrive.
|
||||
To use the command line reporter simply substitute it
|
||||
for the HTML version...
|
||||
<pre>
|
||||
<?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(<strong>new TextReporter()</strong>);
|
||||
?>
|
||||
</pre>
|
||||
Then invoke the test suite from the command line...
|
||||
<pre class="shell">
|
||||
php file_test.php
|
||||
</pre>
|
||||
You will need the command line version of PHP installed
|
||||
of course.
|
||||
A passing test suite looks like this...
|
||||
<pre class="shell">
|
||||
File test
|
||||
OK
|
||||
Test cases run: 1/1, Failures: 0, Exceptions: 0
|
||||
</pre>
|
||||
A failure triggers a display like this...
|
||||
<pre class="shell">
|
||||
File test
|
||||
1) True assertion failed.
|
||||
in createnewfile
|
||||
FAILURES!!!
|
||||
Test cases run: 1/1, Failures: 1, Exceptions: 0
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
One of the main reasons for using a command line driven
|
||||
test suite is of using the tester as part of some automated
|
||||
process.
|
||||
To function properly in shell scripts the test script should
|
||||
return a non-zero exit code on failure.
|
||||
If a test suite fails the value <span class="new_code">false</span>
|
||||
is returned from the <span class="new_code">SimpleTest::run()</span>
|
||||
method.
|
||||
We can use that result to exit the script with the desired return
|
||||
code...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
<strong>exit ($test->run(new TextReporter()) ? 0 : 1);</strong>
|
||||
?>
|
||||
</pre>
|
||||
Of course we don't really want to create two test scripts,
|
||||
a command line one and a web browser one, for each test suite.
|
||||
The command line reporter includes a method to sniff out the
|
||||
run time environment...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
<strong>if (TextReporter::inCli()) {</strong>
|
||||
exit ($test->run(new TextReporter()) ? 0 : 1);
|
||||
<strong>}</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
This is the form used within SimpleTest itself.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="xml">
|
||||
<h2>Remote testing</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
SimpleTest ships with an <span class="new_code">XmlReporter</span> class
|
||||
used for internal communication.
|
||||
When run the output looks like...
|
||||
<pre class="shell">
|
||||
<?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>
|
||||
</pre>
|
||||
You can make use of this format with the parser
|
||||
supplied as part of SimpleTest itself.
|
||||
This is called <span class="new_code">SimpleTestXmlParser</span> and
|
||||
resides in <em>xml.php</em> within the SimpleTest package...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/xml.php');
|
||||
|
||||
...
|
||||
$parser = &new SimpleTestXmlParser(new HtmlReporter());
|
||||
$parser->parse($test_output);
|
||||
?>
|
||||
</pre>
|
||||
The <span class="new_code">$test_output</span> should be the XML format
|
||||
from the XML reporter, and could come from say a command
|
||||
line run of a test case.
|
||||
The parser sends events to the reporter just like any
|
||||
other test run.
|
||||
There are some odd occasions where this is actually useful.
|
||||
</p>
|
||||
<p>
|
||||
A problem with large test suites is thet they can exhaust
|
||||
the default 8Mb memory limit on a PHP process.
|
||||
By having the test groups output in XML and run in
|
||||
separate processes, the output can be reparsed to
|
||||
aggregate the results into a much smaller footprint top level
|
||||
test.
|
||||
</p>
|
||||
<p>
|
||||
Because the XML output can come from anywhere, this opens
|
||||
up the possibility of aggregating test runs from remote
|
||||
servers.
|
||||
A test case already exists to do this within the SimpleTest
|
||||
framework, but it is currently experimental...
|
||||
<pre>
|
||||
<?php
|
||||
<strong>require_once('../remote.php');</strong>
|
||||
require_once('../reporter.php');
|
||||
|
||||
$test_url = ...;
|
||||
$dry_url = ...;
|
||||
|
||||
$test = &new GroupTest('Remote tests');
|
||||
$test->addTestCase(<strong>new RemoteTestCase($test_url, $dry_url)</strong>);
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
</pre>
|
||||
The <span class="new_code">RemoteTestCase</span> takes the actual location
|
||||
of the test runner, basically a web page in XML format.
|
||||
It also takes the URL of a reporter set to do a dry run.
|
||||
This is so that progress can be reported upward correctly.
|
||||
The <span class="new_code">RemoteTestCase</span> can be added to test suites
|
||||
just like any other group test.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,390 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>SimpleTest for PHP regression test documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Unit tester</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="web_tester_documentation.html">Web tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>PHP Unit Test documentation</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="unit">
|
||||
<h2>Unit test cases</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
The core system is a regression testing framework built around
|
||||
test cases.
|
||||
A sample test case looks like this...
|
||||
<pre>
|
||||
<strong>class FileTestCase extends UnitTestCase {
|
||||
}</strong>
|
||||
</pre>
|
||||
If no test name is supplied when chaining the constructor then
|
||||
the class name will be taken instead.
|
||||
This will be the name displayed in the test results.
|
||||
</p>
|
||||
<p>
|
||||
Actual tests are added as methods in the test case whose names
|
||||
by default start with the string "test" and
|
||||
when the test case is invoked all such methods are run in
|
||||
the order that PHP introspection finds them.
|
||||
As many test methods can be added as needed.
|
||||
For example...
|
||||
<pre>
|
||||
require_once('../classes/writer.php');
|
||||
|
||||
class FileTestCase extends UnitTestCase {
|
||||
function FileTestCase() {
|
||||
$this->UnitTestCase('File test');
|
||||
}<strong>
|
||||
|
||||
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');
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
The constructor is optional and usually omitted.
|
||||
Without a name, the class name is taken as the name of the test case.
|
||||
</p>
|
||||
<p>
|
||||
Our only test method at the moment is <span class="new_code">testCreation()</span>
|
||||
where we check that a file has been created by our
|
||||
<span class="new_code">Writer</span> object.
|
||||
We could have put the <span class="new_code">unlink()</span>
|
||||
code into this method as well, but by placing it in
|
||||
<span class="new_code">setUp()</span> and
|
||||
<span class="new_code">tearDown()</span> we can use it with
|
||||
other test methods that we add.
|
||||
</p>
|
||||
<p>
|
||||
The <span class="new_code">setUp()</span> method is run
|
||||
just before each and every test method.
|
||||
<span class="new_code">tearDown()</span> is run just after
|
||||
each and every test method.
|
||||
</p>
|
||||
<p>
|
||||
You can place some test case set up into the constructor to
|
||||
be run once for all the methods in the test case, but
|
||||
you risk test inteference that way.
|
||||
This way is slightly slower, but it is safer.
|
||||
Note that if you come from a JUnit background this will not
|
||||
be the behaviour you are used to.
|
||||
JUnit surprisingly reinstantiates the test case for each test
|
||||
method to prevent such interference.
|
||||
SimpleTest requires the end user to use <span class="new_code">setUp()</span>, but
|
||||
supplies additional hooks for library writers.
|
||||
</p>
|
||||
<p>
|
||||
The means of reporting test results (see below) are by a
|
||||
visiting display class
|
||||
that is notified by various <span class="new_code">assert...()</span>
|
||||
methods.
|
||||
Here is the full list for the <span class="new_code">UnitTestCase</span>
|
||||
class, the default for SimpleTest...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">assertTrue($x)</span></td><td>Fail if $x is false</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertFalse($x)</span></td><td>Fail if $x is true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNull($x)</span></td><td>Fail if $x is set</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNotNull($x)</span></td><td>Fail if $x not set</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertIsA($x, $t)</span></td><td>Fail if $x is not the class or type $t</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNotA($x, $t)</span></td><td>Fail if $x is of the class or type $t</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertEqual($x, $y)</span></td><td>Fail if $x == $y is false</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNotEqual($x, $y)</span></td><td>Fail if $x == $y is true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertWithinMargin($x, $y, $m)</span></td><td>Fail if abs($x - $y) < $m is false</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertOutsideMargin($x, $y, $m)</span></td><td>Fail if abs($x - $y) < $m is true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertIdentical($x, $y)</span></td><td>Fail if $x == $y is false or a type mismatch</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNotIdentical($x, $y)</span></td><td>Fail if $x == $y is true and types match</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertReference($x, $y)</span></td><td>Fail unless $x and $y are the same variable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertCopy($x, $y)</span></td><td>Fail if $x and $y are the same variable</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertPattern($p, $x)</span></td><td>Fail unless the regex $p matches $x</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoPattern($p, $x)</span></td><td>Fail if the regex $p matches $x</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoErrors()</span></td><td>Fail if any PHP error occoured</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertError($x)</span></td><td>Fail if no PHP error or incorrect message/expectation</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertExpectation($e)</span></td><td>Fail on failed expectation object</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
All assertion methods can take an optional description to
|
||||
label the displayed result with.
|
||||
If omitted a default message is sent instead which is usually
|
||||
sufficient.
|
||||
This default message can still be embedded in your own message
|
||||
if you include "%s" within the string.
|
||||
All the assertions return true on a pass or false on failure.
|
||||
</p>
|
||||
<p>
|
||||
Some examples...
|
||||
<pre>
|
||||
<strong>$variable = null;
|
||||
$this->assertNull($variable, 'Should be cleared');</strong>
|
||||
</pre>
|
||||
...will pass and normally show no message.
|
||||
If you have
|
||||
<a href="http://www.lastcraft.com/display_subclass_tutorial.php">set up the tester to display passes</a>
|
||||
as well then the message will be displayed as is.
|
||||
<pre>
|
||||
<strong>$this->assertIdentical(0, false, 'Zero is not false [%s]');</strong>
|
||||
</pre>
|
||||
This will fail as it performs a type
|
||||
check as well as a comparison between the two values.
|
||||
The "%s" part is replaced by the default
|
||||
error message that would have been shown if we had not
|
||||
supplied our own.
|
||||
This also allows us to nest test messages.
|
||||
<pre>
|
||||
<strong>$a = 1;
|
||||
$b = $a;
|
||||
$this->assertReference($a, $b);</strong>
|
||||
</pre>
|
||||
Will fail as the variable <span class="new_code">$a</span> is a copy of <span class="new_code">$b</span>.
|
||||
<pre>
|
||||
<strong>$this->assertPattern('/hello/i', 'Hello world');</strong>
|
||||
</pre>
|
||||
This will pass as using a case insensitive match the string
|
||||
<span class="new_code">hello</span> is contained in <span class="new_code">Hello world</span>.
|
||||
<pre>
|
||||
<strong>trigger_error('Disaster');
|
||||
trigger_error('Catastrophe');
|
||||
$this->assertError();
|
||||
$this->assertError('Catastrophe');
|
||||
$this->assertNoErrors();</strong>
|
||||
</pre>
|
||||
This one takes some explanation as in fact they all pass!
|
||||
</p>
|
||||
<p>
|
||||
PHP errors in SimpleTest are trapped and placed in a queue.
|
||||
Here the first error check catches the "Disaster"
|
||||
message without checking the text and passes.
|
||||
This removes the error from the queue.
|
||||
The next error check tests not only the existence of the error,
|
||||
but also the text which here matches so another pass.
|
||||
With the queue now empty the last test will pass as well.
|
||||
If any unchecked errors are left at the end of a test method then
|
||||
an exception will be reported in the test.
|
||||
Note that SimpleTest cannot catch compile time PHP errors.
|
||||
</p>
|
||||
<p>
|
||||
The test cases also have some convenience methods for debugging
|
||||
code or extending the suite...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">setUp()</span></td><td>Runs this before each test method</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">tearDown()</span></td><td>Runs this after each test method</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">pass()</span></td><td>Sends a test pass</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">fail()</span></td><td>Sends a test failure</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">error()</span></td><td>Sends an exception event</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">sendMessage()</span></td><td>Sends a status message to those displays that support it</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">signal($type, $payload)</span></td><td>Sends a user defined message to the test reporter</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">dump($var)</span></td><td>Does a formatted <span class="new_code">print_r()</span> for quick and dirty debugging</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">swallowErrors()</span></td><td>Clears the error queue</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="extending_unit">
|
||||
<h2>Extending test cases</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Of course additional test methods can be added to create
|
||||
specific types of test case too so as to extend framework...
|
||||
<pre>
|
||||
require_once('simpletest/unit_tester.php');
|
||||
<strong>
|
||||
class FileTester extends UnitTestCase {
|
||||
function FileTester($name = false) {
|
||||
$this->UnitTestCase($name);
|
||||
}
|
||||
|
||||
function assertFileExists($filename, $message = '%s') {
|
||||
$this->assertTrue(
|
||||
file_exists($filename),
|
||||
sprintf($message, 'File [$filename] existence check'));
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
Here the SimpleTest library is held in a folder called
|
||||
<em>simpletest</em> that is local.
|
||||
Substitute your own path for this.
|
||||
</p>
|
||||
<p>
|
||||
This new case can be now be inherited just like
|
||||
a normal test case...
|
||||
<pre>
|
||||
class FileTestCase extends <strong>FileTester</strong> {
|
||||
|
||||
function setUp() {
|
||||
@unlink('../temp/test.txt');
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.txt');
|
||||
}
|
||||
|
||||
function testCreation() {
|
||||
$writer = &new FileWriter('../temp/test.txt');
|
||||
$writer->write('Hello');<strong>
|
||||
$this->assertFileExists('../temp/test.txt');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
If you want a test case that does not have all of the
|
||||
<span class="new_code">UnitTestCase</span> assertions,
|
||||
only your own and <span class="new_code">assertTrue()</span>,
|
||||
you need to extend the <span class="new_code">SimpleTestCase</span>
|
||||
class instead.
|
||||
It is found in <em>simple_test.php</em> rather than
|
||||
<em>unit_tester.php</em>.
|
||||
See <a href="group_test_documentation.html">later</a> if you
|
||||
want to incorporate other unit tester's
|
||||
test cases in your test suites.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="running_unit">
|
||||
<h2>Running a single test case</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
You won't often run single test cases except when bashing
|
||||
away at a module that is having difficulty and you don't
|
||||
want to upset the main test suite.
|
||||
Here is the scaffolding needed to run the a lone test case...
|
||||
<pre>
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');<strong>
|
||||
require_once('simpletest/reporter.php');</strong>
|
||||
require_once('../classes/writer.php');
|
||||
|
||||
class FileTestCase extends UnitTestCase {
|
||||
function FileTestCase() {
|
||||
$this->UnitTestCase('File test');
|
||||
}
|
||||
}<strong>
|
||||
|
||||
$test = &new FileTestCase();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
</pre>
|
||||
This script will run as is, but will output zero passes
|
||||
and zero failures until test methods are added.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,511 @@
|
||||
<html>
|
||||
<head>
|
||||
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>Simple Test for PHP web script testing documentation</title>
|
||||
<link rel="stylesheet" type="text/css" href="docs.css" title="Styles">
|
||||
</head>
|
||||
<body>
|
||||
<div class="menu_back">
|
||||
<div class="menu">
|
||||
<h2>
|
||||
<a href="index.html">SimpleTest</a>
|
||||
</h2>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="overview.html">Overview</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="unit_test_documentation.html">Unit tester</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="group_test_documentation.html">Group tests</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="mock_objects_documentation.html">Mock objects</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="partial_mocks_documentation.html">Partial mocks</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="reporter_documentation.html">Reporting</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="expectation_documentation.html">Expectations</a>
|
||||
</li>
|
||||
<li>
|
||||
<span class="chosen">Web tester</span>
|
||||
</li>
|
||||
<li>
|
||||
<a href="form_testing_documentation.html">Testing forms</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="authentication_documentation.html">Authentication</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="browser_documentation.html">Scriptable browser</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<h1>Web tester documentation</h1>
|
||||
<div class="content">
|
||||
<p>
|
||||
<a class="target" name="fetch">
|
||||
<h2>Fetching a page</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Testing classes is all very well, but PHP is predominately
|
||||
a language for creating functionality within web pages.
|
||||
How do we test the front end presentation role of our PHP
|
||||
applications?
|
||||
Well the web pages are just text, so we should be able to
|
||||
examine them just like any other test data.
|
||||
</p>
|
||||
<p>
|
||||
This leads to a tricky issue.
|
||||
If we test at too low a level, testing for matching tags
|
||||
in the page with pattern matching for example, our tests will
|
||||
be brittle.
|
||||
The slightest change in layout could break a large number of
|
||||
tests.
|
||||
If we test at too high a level, say using mock versions of a
|
||||
template engine, then we lose the ability to automate some classes
|
||||
of test.
|
||||
For example, the interaction of forms and navigation will
|
||||
have to be tested manually.
|
||||
These types of test are extremely repetitive and error prone.
|
||||
</p>
|
||||
<p>
|
||||
SimpleTest includes a special form of test case for the testing
|
||||
of web page actions.
|
||||
The <span class="new_code">WebTestCase</span> includes facilities
|
||||
for navigation, content and cookie checks and form handling.
|
||||
Usage of these test cases is similar to the
|
||||
<a href="unit_tester_documentation.html">UnitTestCase</a>...
|
||||
<pre>
|
||||
<strong>class TestOfLastcraft extends WebTestCase {
|
||||
}</strong>
|
||||
</pre>
|
||||
Here we are about to test the
|
||||
<a href="http://www/lastcraft.com/">Last Craft</a> site itself.
|
||||
If this test case is in a file called <em>lastcraft_test.php</em>
|
||||
then it can be loaded in a runner script just like unit tests...
|
||||
<pre>
|
||||
<?php<strong>
|
||||
require_once('simpletest/web_tester.php');</strong>
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('Web site tests');<strong>
|
||||
$test->addTestFile('lastcraft_test.php');</strong>
|
||||
exit ($test->run(new TextReporter()) ? 0 : 1);
|
||||
?>
|
||||
</pre>
|
||||
I am using the text reporter here to more clearly
|
||||
distinguish the web content from the test output.
|
||||
</p>
|
||||
<p>
|
||||
Nothing is being tested yet.
|
||||
We can fetch the home page by using the
|
||||
<span class="new_code">get()</span> method...
|
||||
<pre>
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
<strong>
|
||||
function testHomepage() {
|
||||
$this->assertTrue($this->get('http://www.lastcraft.com/'));
|
||||
}</strong>
|
||||
}
|
||||
</pre>
|
||||
The <span class="new_code">get()</span> method will
|
||||
return true only if page content was successfully
|
||||
loaded.
|
||||
It is a simple, but crude way to check that a web page
|
||||
was actually delivered by the web server.
|
||||
However that content may be a 404 response and yet
|
||||
our <span class="new_code">get()</span> method will still return true.
|
||||
</p>
|
||||
<p>
|
||||
Assuming that the web server for the Last Craft site is up
|
||||
(sadly not always the case), we should see...
|
||||
<pre class="shell">
|
||||
Web site tests
|
||||
OK
|
||||
Test cases run: 1/1, Failures: 0, Exceptions: 0
|
||||
</pre>
|
||||
All we have really checked is that any kind of page was
|
||||
returned.
|
||||
We don't yet know if it was the right one.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="content">
|
||||
<h2>Testing page content</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
To confirm that the page we think we are on is actually the
|
||||
page we are on, we need to verify the page content.
|
||||
<pre>
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {<strong>
|
||||
$this->get('http://www.lastcraft.com/');
|
||||
$this->assertTest('Why the last craft');</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The page from the last fetch is held in a buffer in
|
||||
the test case, so there is no need to refer to it directly.
|
||||
The pattern match is always made against the buffer.
|
||||
</p>
|
||||
<p>
|
||||
Here is the list of possible content assertions...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">assertTitle($title)</span></td><td>Pass if title is an exact match</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertPattern($pattern)</span></td><td>A Perl pattern match against the page content</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoPattern($pattern)</span></td><td>A Perl pattern match to not find content</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertText($text)</span></td><td>Pass if matches visible and "alt" text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoText($text)</span></td><td>Pass if doesn't match visible and "alt" text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertLink($label)</span></td><td>Pass if a link with this text is present</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoLink($label)</span></td><td>Pass if no link with this text is present</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertLinkById($id)</span></td><td>Pass if a link with this id attribute is present</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoLinkById($id)</span></td><td>Pass if no link with this id attribute is present</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertField($name, $value)</span></td><td>Pass if an input tag with this name has this value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertFieldById($id, $value)</span></td><td>Pass if an input tag with this id has this value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertResponse($codes)</span></td><td>Pass if HTTP response matches this list</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertMime($types)</span></td><td>Pass if MIME type is in this list</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertAuthentication($protocol)</span></td><td>Pass if the current challenge is this protocol</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoAuthentication()</span></td><td>Pass if there is no current challenge</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertRealm($name)</span></td><td>Pass if the current challenge realm matches</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertHeader($header, $content)</span></td><td>Pass if a header was fetched matching this value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoHeader($header)</span></td><td>Pass if a header was not fetched</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertCookie($name, $value)</span></td><td>Pass if there is currently a matching cookie</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">assertNoCookie($name)</span></td><td>Pass if there is currently no cookie of this name</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
As usual with the SimpleTest assertions, they all return
|
||||
false on failure and true on pass.
|
||||
They also allow an optional test message and you can embed
|
||||
the original test message inside using "%s" inside
|
||||
your custom message.
|
||||
</p>
|
||||
<p>
|
||||
So now we could instead test against the title tag with...
|
||||
<pre>
|
||||
<strong>$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');</strong>
|
||||
</pre>
|
||||
...or, if that is too long and fragile...
|
||||
<pre>
|
||||
<strong>$this->assertTitle(new PatternExpectation('/The Last Craft/'));</strong>
|
||||
</pre>
|
||||
As well as the simple HTML content checks we can check
|
||||
that the MIME type is in a list of allowed types with...
|
||||
<pre>
|
||||
<strong>$this->assertMime(array('text/plain', 'text/html'));</strong>
|
||||
</pre>
|
||||
More interesting is checking the HTTP response code.
|
||||
Like the MIME type, we can assert that the response code
|
||||
is in a list of allowed values...
|
||||
<pre>
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testRedirects() {
|
||||
$this->get('http://www.lastcraft.com/test/redirect.php');
|
||||
$this->assertResponse(200);</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
Here we are checking that the fetch is successful by
|
||||
allowing only a 200 HTTP response.
|
||||
This test will pass, but it is not actually correct to do so.
|
||||
There is no page, instead the server issues a redirect.
|
||||
The <span class="new_code">WebTestCase</span> will
|
||||
automatically follow up to three such redirects.
|
||||
The tests are more robust this way and we are usually
|
||||
interested in the interaction with the pages rather
|
||||
than their delivery.
|
||||
If the redirects are of interest then this ability must
|
||||
be disabled...
|
||||
<pre>
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {<strong>
|
||||
$this->setMaximumRedirects(0);</strong>
|
||||
$this->get('http://www.lastcraft.com/test/redirect.php');
|
||||
$this->assertResponse(200);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The assertion now fails as expected...
|
||||
<pre class="shell">
|
||||
Web site tests
|
||||
1) Expecting response in [200] got [302]
|
||||
in testhomepage
|
||||
in testoflastcraft
|
||||
in lastcraft_test.php
|
||||
FAILURES!!!
|
||||
Test cases run: 1/1, Failures: 1, Exceptions: 0
|
||||
</pre>
|
||||
We can modify the test to correctly assert redirects with...
|
||||
<pre>
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {
|
||||
$this->setMaximumRedirects(0);
|
||||
$this->get('http://www.lastcraft.com/test/redirect.php');
|
||||
$this->assertResponse(<strong>array(301, 302, 303, 307)</strong>);
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
This now passes.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="navigation">
|
||||
<h2>Navigating a web site</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Users don't often navigate sites by typing in URLs, but by
|
||||
clicking links and buttons.
|
||||
Here we confirm that the contact details can be reached
|
||||
from the home page...
|
||||
<pre>
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
...
|
||||
function testContact() {
|
||||
$this->get('http://www.lastcraft.com/');<strong>
|
||||
$this->clickLink('About');
|
||||
$this->assertTitle(new PatternExpectation('/About Last Craft/'));</strong>
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
The parameter is the text of the link.
|
||||
</p>
|
||||
<p>
|
||||
If the target is a button rather than an anchor tag, then
|
||||
<span class="new_code">clickSubmit()</span> can be used
|
||||
with the button title...
|
||||
<pre>
|
||||
<strong>$this->clickSubmit('Go!');</strong>
|
||||
</pre>
|
||||
If you are not sure or don't care, the usual case, then just
|
||||
use the <span class="new_code">click()</span> method...
|
||||
<pre>
|
||||
<strong>$this->click('Go!');</strong>
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
The list of navigation methods is...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">getUrl()</span></td><td>The current location</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">get($url, $parameters)</span></td><td>Send a GET request with these parameters</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">post($url, $parameters)</span></td><td>Send a POST request with these parameters</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">head($url, $parameters)</span></td><td>Send a HEAD request without replacing the page content</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">retry()</span></td><td>Reload the last request</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">back()</span></td><td>Like the browser back button</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">forward()</span></td><td>Like the browser forward button</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">authenticate($name, $password)</span></td><td>Retry after a challenge</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">restart()</span></td><td>Restarts the browser as if a new session</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getCookie($name)</span></td><td>Gets the cookie value for the current context</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">ageCookies($interval)</span></td><td>Ages current cookies prior to a restart</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clearFrameFocus()</span></td><td>Go back to treating all frames as one page</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickSubmit($label)</span></td><td>Click the first button with this label</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickSubmitByName($name)</span></td><td>Click the button with this name attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickSubmitById($id)</span></td><td>Click the button with this ID attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickImage($label, $x, $y)</span></td><td>Click an input tag of type image by title or alt text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickImageByName($name, $x, $y)</span></td><td>Click an input tag of type image by name</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickImageById($id, $x, $y)</span></td><td>Click an input tag of type image by ID attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">submitFormById($id)</span></td><td>Submit a form without the submit value</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickLink($label, $index)</span></td><td>Click an anchor by the visible label text</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">clickLinkById($id)</span></td><td>Click an anchor by the ID attribute</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">getFrameFocus()</span></td><td>The name of the currently selected frame</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setFrameFocusByIndex($choice)</span></td><td>Focus on a frame counting from 1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setFrameFocus($name)</span></td><td>Focus on a frame by name</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</p>
|
||||
<p>
|
||||
The parameters in the <span class="new_code">get()</span>, <span class="new_code">post()</span> or
|
||||
<span class="new_code">head()</span> methods are optional.
|
||||
The HTTP HEAD fetch does not change the browser context, only loads
|
||||
cookies.
|
||||
This can be useful for when an image or stylesheet sets a cookie
|
||||
for crafty robot blocking.
|
||||
</p>
|
||||
<p>
|
||||
The <span class="new_code">retry()</span>, <span class="new_code">back()</span> and
|
||||
<span class="new_code">forward()</span> commands work as they would on
|
||||
your web browser.
|
||||
They use the history to retry pages.
|
||||
This can be handy for checking the effect of hitting the
|
||||
back button on your forms.
|
||||
</p>
|
||||
<p>
|
||||
The frame methods need a little explanation.
|
||||
By default a framed page is treated just like any other.
|
||||
Content will be searced for throughout the entire frameset,
|
||||
so clicking a link will work no matter which frame
|
||||
the anchor tag is in.
|
||||
You can override this behaviour by focusing on a single
|
||||
frame.
|
||||
If you do that, all searches and actions will apply to that
|
||||
frame alone, such as authentication and retries.
|
||||
If a link or button is not in a focused frame then it cannot
|
||||
be clicked.
|
||||
</p>
|
||||
<p>
|
||||
Testing navigation on fixed pages only tells you when you
|
||||
have broken an entire script.
|
||||
For highly dynamic pages, such as for bulletin boards, this can
|
||||
be crucial for verifying the correctness of the application.
|
||||
For most applications though, the really tricky logic is usually in
|
||||
the handling of forms and sessions.
|
||||
Fortunately SimpleTest includes
|
||||
<a href="form_testing_documentation.html">tools for testing web forms</a>
|
||||
as well.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a class="target" name="request">
|
||||
<h2>Modifying the request</h2>
|
||||
</a>
|
||||
</p>
|
||||
<p>
|
||||
Although SimpleTest does not have the goal of testing networking
|
||||
problems, it does include some methods to modify and debug
|
||||
the requests it makes.
|
||||
Here is another method list...
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><span class="new_code">getTransportError()</span></td><td>The last socket error</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">showRequest()</span></td><td>Dump the outgoing request</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">showHeaders()</span></td><td>Dump the incoming headers</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">showSource()</span></td><td>Dump the raw HTML page content</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">ignoreFrames()</span></td><td>Do not load framesets</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setCookie($name, $value)</span></td><td>Set a cookie from now on</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">addHeader($header)</span></td><td>Always add this header to the request</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setMaximumRedirects($max)</span></td><td>Stop after this many redirects</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">setConnectionTimeout($timeout)</span></td><td>Kill the connection after this time between bytes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="new_code">useProxy($proxy, $name, $password)</span></td><td>Make requests via this proxy URL</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
These methods are principally for debugging.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
<div class="copyright">
|
||||
Copyright<br>Marcus Baker, Jason Sweat, Perrick Penet 2004
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,84 @@
|
||||
body {
|
||||
padding-left: 3%;
|
||||
padding-right: 3%;
|
||||
}
|
||||
pre {
|
||||
font-family: courier;
|
||||
font-size: 80%;
|
||||
border: 1px solid;
|
||||
background-color: #cccccc;
|
||||
padding: 5px;
|
||||
margin-left: 5%;
|
||||
margin-right: 8%;
|
||||
}
|
||||
.code, .new_code, pre.new_code {
|
||||
font-weight: bold;
|
||||
}
|
||||
div.copyright {
|
||||
font-size: 80%;
|
||||
color: gray;
|
||||
}
|
||||
div.copyright a {
|
||||
color: gray;
|
||||
}
|
||||
ul.api {
|
||||
padding-left: 0em;
|
||||
padding-right: 25%;
|
||||
}
|
||||
ul.api li {
|
||||
margin-top: 0.2em;
|
||||
margin-bottom: 0.2em;
|
||||
list-style: none;
|
||||
text-indent: -3em;
|
||||
padding-left: 3em;
|
||||
}
|
||||
div.demo {
|
||||
border: 4px ridge;
|
||||
border-color: gray;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
background-color: white;
|
||||
}
|
||||
div.demo span.fail {
|
||||
color: red;
|
||||
}
|
||||
div.demo span.pass {
|
||||
color: green;
|
||||
}
|
||||
div.demo h1 {
|
||||
font-size: 12pt;
|
||||
text-align: left;
|
||||
font-weight: bold;
|
||||
}
|
||||
table {
|
||||
border: 2px outset;
|
||||
border-color: gray;
|
||||
background-color: white;
|
||||
margin: 5px;
|
||||
margin-left: 5%;
|
||||
margin-right: 5%;
|
||||
}
|
||||
td {
|
||||
font-size: 80%;
|
||||
}
|
||||
.shell {
|
||||
color: white;
|
||||
}
|
||||
pre.shell {
|
||||
border: 4px ridge;
|
||||
border-color: gray;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
background-color: black;
|
||||
}
|
||||
form.demo {
|
||||
background-color: lightgray;
|
||||
border: 4px outset;
|
||||
border-color: lightgray;
|
||||
padding: 10px;
|
||||
margin-right: 40%;
|
||||
}
|
@ -0,0 +1 @@
|
||||
Output folder for Lastcraft site versions of documentation.
|
@ -0,0 +1 @@
|
||||
Répertoire utilisé pour l'extraction de la documentation au format du site onpk.net
|
@ -0,0 +1 @@
|
||||
Files here are generated from make_phpdoc_docs.sh
|
@ -0,0 +1 @@
|
||||
Output folder for SimpleTest.org site versions of content, documentation & tutorial.
|
After Width: | Height: | Size: 6.4 KiB |
After Width: | Height: | Size: 5.5 KiB |
After Width: | Height: | Size: 42 KiB |
After Width: | Height: | Size: 620 B |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 6.7 KiB |
After Width: | Height: | Size: 5.7 KiB |
After Width: | Height: | Size: 5.3 KiB |
After Width: | Height: | Size: 45 KiB |
After Width: | Height: | Size: 25 KiB |
After Width: | Height: | Size: 10 KiB |
@ -0,0 +1,174 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<title>SimpleTest - Unit Testing for PHP</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<link rel="stylesheet" type="text/css" href="simpletest.css" media="screen" title="Normal" />
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<div id="actions">
|
||||
<div id="logo">
|
||||
<a href="http://simpletest.org/index.html"><img name="simpletestlogo" src="images/simpletest-logo.png" width="335" height="127" border="0" id="simpletestlogo" alt="" /></a>
|
||||
</div>
|
||||
<div>
|
||||
<div>
|
||||
<a href="en/download.html"><img name="simpletestdownload" src="images/simpletest-download.png" width="305" height="109" border="0" id="simpletestdownload" alt="" /></a>
|
||||
<p>
|
||||
SimpleTest 1.0.1 beta release is the <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">latest version</a>.
|
||||
It's very stable although PHP5 users will find it doesn't
|
||||
run with E_STRICT : it's still fully PHP4 compatible.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<a href="en/start-testing.html"><img name="simpleteststarttesting" src="images/simpletest-start-testing.png" width="305" height="109" border="0" id="simpleteststarttesting" alt="" /></a>
|
||||
<p>
|
||||
Familiar with unit testing ? Just dive directly into SimpleTest with
|
||||
<a href="en/start-testing.html">the one-page starter</a> and
|
||||
<a href="http://simpletest.org/api/">the complete API</a>.
|
||||
<br />
|
||||
Otherwise see the ongoing
|
||||
<a href="en/overview.html">documentation</a>.
|
||||
<br />
|
||||
And for example test cases check out the
|
||||
<a href="en/first_test_tutorial.html">tutorial</a>.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<a href="en/support.html"><img name="simpletestsupport" src="images/simpletest-support.png" width="305" height="109" border="0" id="simpletestsupport" alt="" /></a>
|
||||
<p>
|
||||
Need help on your testing strategy ?
|
||||
Feel free to join the
|
||||
<a href="https://sourceforge.net/mail/?group_id=76550">SimpleTest support mailing-list</a>.
|
||||
</p>
|
||||
<p>
|
||||
If you need some new functionnality in SimpleTest, you may want to look at
|
||||
the <a href="https://sourceforge.net/tracker/?atid=547458&group_id=76550&func=browse">features tracker</a>.
|
||||
Also the <a href="https://sourceforge.net/tracker/?atid=547455&group_id=76550&func=browse">bug</a> and
|
||||
<a href="https://sourceforge.net/tracker/?group_id=76550&atid=547457">patches</a> trackers can be useful.
|
||||
</p>
|
||||
</div>
|
||||
<div id="credits">
|
||||
<a href="http://sourceforge.net/projects/simpletest">
|
||||
<img src="http://sourceforge.net/sflogo.php?group_id=76550&type=1" width="88" height="31" border="0" alt="SourceForge.net Logo" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="content">
|
||||
<p id="news">
|
||||
SimpleTest v1.0.1beta is <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">available for download</a>.
|
||||
</p>
|
||||
<p>
|
||||
The <strong>SimpleTest PHP unit tester</strong>
|
||||
is available for download from your nearest
|
||||
<a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
It is a PHP unit test and web test framework.
|
||||
Users of <a href="http://www.junit.org/">JUnit</a> will be
|
||||
familiar with most of the interface.
|
||||
The <a href="http://jwebunit.sourceforge.net/">JWebUnit</a>
|
||||
style functionality is more complete now.
|
||||
It has support for SSL, forms, frames, proxies and basic authentication.
|
||||
The current CVS code should become the 1.0.1 release real soon now and
|
||||
includes file upload and many small improvements.
|
||||
The idea is that common but fiddly PHP tasks, such as logging into a site,
|
||||
can be tested easily.
|
||||
</p>
|
||||
<h2>Screenshots</h2>
|
||||
<p>
|
||||
Here's what the result of your first test would look like :
|
||||
</p>
|
||||
<p>
|
||||
<img class="screenshot" alt="test with 1 pass" src="images/test-with-1-pass.png" border="0" id="test-with-1-pass" />
|
||||
</p>
|
||||
<p>
|
||||
Well not quite. In true TDD fashion, you should see a failing test case :
|
||||
</p>
|
||||
<p>
|
||||
<img class="screenshot" alt="test with 1 fail" src="images/test-with-1-fail.png" border="0" id="test-with-1-fail" />
|
||||
</p>
|
||||
<p>
|
||||
You may also prefer doing your testing with the command-line :
|
||||
</p>
|
||||
<p>
|
||||
<img alt="test in cli" src="images/test-in-cli.png" border="0" id="test-in-cli" />
|
||||
</p>
|
||||
<h2>Documentation</h2>
|
||||
<p>
|
||||
While (still) very scattered around different sites, the SimpleTest documentation is quite dense and thorough.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
in english there's <a href="en/first_test_tutorial.html">a tutorial</a>
|
||||
and <a href="en/unit_test_documentation.html">the official documentation</a>.
|
||||
</li>
|
||||
<li>
|
||||
<cite>en français, il y a aussi <a href="fr/first_test_tutorial.html">le tutoriel</a>
|
||||
et <a href="fr/unit_test_documentation.html">la documentation</a></cite>.
|
||||
</li>
|
||||
<li>
|
||||
a fully <a href="http://simpletest.org/api/">documentated API</a> is also generated with phpDocumentor.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
Other type of interesting stuff while starting out with Test Driven Development and SimpleTest include :
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="http://en.wikipedia.org/wiki/SimpleTest">Article on Wikipedia</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://www.developerspot.com/tutorials/php/test-driven-development/page1.html">Test Driven Development</a> :
|
||||
article by Marcus Baker (SimpleTest leader)
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://onpk.net/talks/fosdem2005/introduction_simpletest.html">Introduction to SimpleTest and TDD</a> :
|
||||
slides from a talk given at Fosdem, Brussels in 2005 by Perrick Penet
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://www.devpapers.com/article/303">Unit Testing in PHP using SimpleTest</a> :
|
||||
article by Saleh Jamal
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://drupal.org/simpletest">How to write automated tests</a> :
|
||||
in Drupal style (Module how-to's)
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://blog.casey-sweat.us/?p=72">Live TDD demo</a> :
|
||||
transcript of a presentation in London in 2006 by Jason E. Sweat
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
A couple of books do use SimpleTest quite extensively :
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>PHP|Architect's Guide to PHP Design Patterns</strong><br />
|
||||
by Jason E. Sweat<br />
|
||||
( <a href="http://www.phparch.com/shop_product.php?itemid=96">PHP|Architect</a> |
|
||||
<a href="http://www.amazon.com/gp/product/0973589825/102-3523235-1803315">Amazon</a> )
|
||||
</li>
|
||||
<li>
|
||||
<strong>The PHP Anthology: Object Oriented PHP Solutions</strong><br />
|
||||
by Harry Fuecks<br />
|
||||
( <a href="http://www.sitepoint.com/books/phpant1/">SitePoint</a> |
|
||||
<a href="http://www.amazon.com/gp/product/0957921845/102-3523235-1803315">Amazon</a> |
|
||||
<a href="http://developers.slashdot.org/article.pl?sid=04/08/04/1516258&tid=169&tid=192&tid=218&mode=nocomment">review on Slashdot</a> )
|
||||
</li>
|
||||
</ul>
|
||||
<h2>Contributing</h2>
|
||||
<p>
|
||||
For translators the documentation is available in XML format :
|
||||
we're always please to add new languages to our code base.
|
||||
</p>
|
||||
<p>
|
||||
And while we do try our best keeping this tool bug-free, detecting defects and
|
||||
submitting failing test cases and/or patches can come very handy ! Interested ?
|
||||
Drop by the <a href="https://sourceforge.net/mail/?group_id=76550">mailing-list</a>,
|
||||
most things tend to happen there...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,44 @@
|
||||
/* SimpleTest - Unit Testing for PHP */
|
||||
body { font-family : georgia, serif; }
|
||||
img { border : 0; }
|
||||
h1 { color : #009933; }
|
||||
blockquote { background: transparent url('images/quote.png') left top no-repeat; font-style : italic; padding-left : 40px; margin-left : 10px; }
|
||||
|
||||
#logo { margin-bottom : 20px; }
|
||||
#credits { margin-top : 40px; }
|
||||
#actions { position : absolute; top : 20px; left : 40px; width : 335px; }
|
||||
#actions div { width : 305px; }
|
||||
#content { position : absolute; top : 20px; left : 400px; padding-bottom : 50px; width : 491px; }
|
||||
#news { border : 2px solid #009933; padding : 20px; font-weight : bold; font-size : 18pt; width : 451px; }
|
||||
#news a { color : #009933; }
|
||||
|
||||
.screenshot { border : 1px solid #cccccc;}
|
||||
|
||||
div.demo {
|
||||
border: 4px ridge;
|
||||
border-color: gray;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
margin-left: 20px;
|
||||
margin-right: 40px;
|
||||
background-color: white;
|
||||
}
|
||||
div.demo span.fail {
|
||||
color: red;
|
||||
}
|
||||
div.demo span.pass {
|
||||
color: green;
|
||||
}
|
||||
div.demo h1 {
|
||||
color: black; font-size: 12pt;
|
||||
text-align: left;
|
||||
font-weight: bold;
|
||||
}
|
||||
pre {
|
||||
font-family: monospaced;
|
||||
border-left: 1px solid #999999;
|
||||
background-color: white;
|
||||
padding: 5px;
|
||||
margin-left: 5px;
|
||||
font-size : 10pt;
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="About Last Craft" here="About">
|
||||
<long_title>About Last Craft</long_title>
|
||||
<content>
|
||||
<section name="me" title="People">
|
||||
<p>
|
||||
<img src="../images/marcus.jpg" />
|
||||
At the moment this site is maintained by myself,
|
||||
<a href="mailto:marcus@lastcraft.com">Marcus Baker</a>
|
||||
and I am an <a href="marcus_cv.html">Object Oriented web developer</a>
|
||||
and father of two.
|
||||
I am currently a freelancer working as a senior developer for
|
||||
<a href="http://www.wordtracker.com">Wordtracker</a>
|
||||
and as a consultant to various smaller companies.
|
||||
Wordtracker is an internet statistics company with a huge database
|
||||
of search engine keyword popularity.
|
||||
The company software development is eXtreme Programming based.
|
||||
</p>
|
||||
<p>
|
||||
My wife <a href="mailto:aviva@lastcraft.com">Aviva Racher</a> is a
|
||||
microbiologist and Mother of the same two.
|
||||
</p>
|
||||
<p>
|
||||
Bryn was born on the 30th of July 2004.
|
||||
He is doing very well.
|
||||
</p>
|
||||
</section>
|
||||
<section name="issues" title="Issues">
|
||||
<p>
|
||||
Read the interview <a
|
||||
href="http://www.oreillynet.com/pub/a/patents/2000/05/24/PizzoFiles.html">
|
||||
Who's really being protected?</a> on the
|
||||
O'Reilly network if you have an interest in software patents.
|
||||
</p>
|
||||
</section>
|
||||
<section name="associations" title="Associations">
|
||||
<p>
|
||||
Besides working for Wordtracker, I also act as an independent
|
||||
consultant.
|
||||
Usually in relation to bringing agile development practices into an
|
||||
organisation.
|
||||
Clients include Waterscape and Amnesty International.
|
||||
</p>
|
||||
<p>
|
||||
I did a quick site for a graphic designer and illustrator friend of mine,
|
||||
<a href="http://www.dylanbeck.com/">Dylan Beck</a>.
|
||||
He has a very unique style.
|
||||
</p>
|
||||
<p>
|
||||
The <a href="om/">Ambassadors of Om</a> are a Jazz-Funk
|
||||
fusion (?) band with an internet presence going back over five
|
||||
years. Site includes samples, videos and links. The band is
|
||||
managed by guitarist and lead singer <a
|
||||
href="mailto:wahg@cwcom.net">Paul Grimes</a> who is a friend of ours.
|
||||
</p>
|
||||
<p>
|
||||
<a href="mailto:mark@leisurepursuits.demon.co.uk">
|
||||
Mark Eichner</a> is Aviva's uncle and run's the
|
||||
<a href="http://www.leisurepursuits.demon.co.uk">
|
||||
Leisure Pursuits</a>
|
||||
off-road driving school. Lots of wheels and mud!
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#me">Last Craft people</a>
|
||||
Myself and friends and relations.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#issues">Issues</a> that I care about.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#associations">Associated companies</a>
|
||||
and people.
|
||||
</link>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
<link>
|
||||
<a href="http://www.xpdeveloper.com/cgi-bin/wiki.cgi?MarcuS">Extreme Tuesday</a>
|
||||
Club is an informal meeting in London to promote
|
||||
<a href="http://www.extremeprogramming.org/">Extreme programming</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://www.phplondon.org/">PHPLondon</a>
|
||||
is a user group that meets the first thursday of every month.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://www.wordtracker.com">Wordtracker</a>
|
||||
crunches internet search data for web marketing.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
computer programmer,
|
||||
php programming,
|
||||
programming php,
|
||||
software development company,
|
||||
software development uk,
|
||||
php tutorial,
|
||||
bespoke software development uk,
|
||||
corporate web development,
|
||||
architecture,
|
||||
freelancer,
|
||||
php resources,
|
||||
wordtracker,
|
||||
web marketing,
|
||||
serach engines,
|
||||
web positioning,
|
||||
internet marketing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,316 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Authentication documentation" here="Authentication">
|
||||
<long_title>SimpleTest documentation for testing log-in and authentication</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
One of the trickiest, and yet most important, areas
|
||||
of testing web sites is the security.
|
||||
Testing these schemes is one of the core goals of
|
||||
the SimpleTest web tester.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="basic" title="Basic HTTP authentication">
|
||||
<p>
|
||||
If you fetch a page protected by basic authentication then
|
||||
rather than receiving content, you will instead get a 401
|
||||
header.
|
||||
We can illustrate this with this test...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {<strong>
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');
|
||||
$this->showHeaders();
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
This allows us to see the challenge header...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<pre style="background-color: lightgray; color: black"><![CDATA[
|
||||
HTTP/1.1 401 Authorization Required
|
||||
Date: Sat, 18 Sep 2004 19:25:18 GMT
|
||||
Server: Apache/1.3.29 (Unix) PHP/4.3.4
|
||||
WWW-Authenticate: Basic realm="SimpleTest basic authentication"
|
||||
Connection: close
|
||||
Content-Type: text/html; charset=iso-8859-1
|
||||
]]></pre>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
We are trying to get away from visual inspection though, and so SimpleTest
|
||||
allows to make automated assertions against the challenge.
|
||||
Here is a thorough test of our header...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');<strong>
|
||||
$this->assertAuthentication('Basic');
|
||||
$this->assertResponse(401);
|
||||
$this->assertRealm('SimpleTest basic authentication');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Any one of these tests would normally do on it's own depending
|
||||
on the amount of detail you want to see.
|
||||
</p>
|
||||
<p>
|
||||
One theme that runs through SimpleTest is the ability to use
|
||||
<code>SimpleExpectation</code> objects wherever a simple
|
||||
match is not enough.
|
||||
If you want only an approximate match to the realm for
|
||||
example, you can do this...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');
|
||||
$this->assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function testCanAuthenticate() {
|
||||
$this->get('http://www.lastcraft.com/protected/');<strong>
|
||||
$this->authenticate('Me', 'Secret');</strong>
|
||||
$this->assertTitle(...);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The username and password will now be sent with every
|
||||
subsequent request to that directory and subdirectories.
|
||||
You will have to authenticate again if you step outside
|
||||
the authenticated directory, but SimpleTest is smart enough
|
||||
to merge subdirectories into a common realm.
|
||||
</p>
|
||||
<p>
|
||||
You can shortcut this step further by encoding the log in
|
||||
details straight into the URL...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function testCanReadAuthenticatedPages() {
|
||||
$this->get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
|
||||
$this->assertTitle(...);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
If your username or password has special characters, then you
|
||||
will have to URL encode them or the request will not be parsed
|
||||
correctly.
|
||||
Also this header will not be sent on subsequent requests if
|
||||
you request a page with a fully qualified URL.
|
||||
If you navigate with relative URLs though, the authentication
|
||||
information will be preserved.
|
||||
</p>
|
||||
<p>
|
||||
Only basic authentication is currently supported and this is
|
||||
only really secure in tandem with HTTPS connections.
|
||||
This is usually enough to protect test server from prying eyes,
|
||||
however.
|
||||
Digest authentication and NTLM authentication may be added
|
||||
in the future.
|
||||
</p>
|
||||
</section>
|
||||
<section name="cookies" title="Cookies">
|
||||
<p>
|
||||
Basic authentication doesn't give enough control over the
|
||||
user interface for web developers.
|
||||
More likely this functionality will be coded directly into
|
||||
the web architecture using cookies and complicated timeouts.
|
||||
</p>
|
||||
<p>
|
||||
Starting with a simple log-in form...
|
||||
<pre><![CDATA[
|
||||
<form>
|
||||
Username:
|
||||
<input type="text" name="u" value="" /><br />
|
||||
Password:
|
||||
<input type="password" name="p" value="" /><br />
|
||||
<input type="submit" value="Log in" />
|
||||
</form>
|
||||
]]></pre>
|
||||
Which looks like...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
Username:
|
||||
<input type="text" name="u" value="" /><br />
|
||||
Password:
|
||||
<input type="password" name="p" value="" /><br />
|
||||
<input type="submit" value="Log in" />
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
Let's suppose that in fetching this page a cookie has been
|
||||
set with a session ID.
|
||||
We are not going to fill the form in yet, just test that
|
||||
we are tracking the user.
|
||||
Here is the test...
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
function testSessionCookieSetBeforeForm() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$this->assertCookie('SID');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
function testSessionCookieIsCorrectPattern() {
|
||||
$this->get('http://www.my-site.com/login.php');
|
||||
$this->assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The rest of the test would be the same as any other form,
|
||||
but we might want to confirm that we still have the same
|
||||
cookie after log-in as before we entered.
|
||||
We wouldn't want to lose track of this after all.
|
||||
Here is a possible test for this...
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testSessionCookieSameAfterLogIn() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$session = $this->getCookie('SID');
|
||||
$this->setField('u', 'Me');
|
||||
$this->setField('p', 'Secret');
|
||||
$this->click('Log in');
|
||||
$this->assertText('Welcome Me');
|
||||
$this->assertCookie('SID', $session);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
This confirms that the session identifier is maintained
|
||||
afer log-in.
|
||||
</p>
|
||||
<p>
|
||||
We could even attempt to spoof our own system by setting
|
||||
arbitrary cookies to gain access...
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testSessionCookieSameAfterLogIn() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$this->setCookie('SID', 'Some other session');
|
||||
$this->get('http://www.my-site.com/restricted.php');</strong>
|
||||
$this->assertText('Access denied');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Is your site protected from this attack?
|
||||
</p>
|
||||
</section>
|
||||
<section name="session" title="Browser sessions">
|
||||
<p>
|
||||
If you are testing an authentication system a critical piece
|
||||
of behaviour is what happens when a user logs back in.
|
||||
We would like to simulate closing and reopening a browser...
|
||||
<php><![CDATA[
|
||||
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');<strong>
|
||||
|
||||
$this->restart();
|
||||
$this->get('http://www.my-site.com/restricted.php');
|
||||
$this->assertText('Access denied');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The <code>WebTestCase::restart()</code> method will
|
||||
preserve cookies that have unexpired timeouts, but throw away
|
||||
those that are temporary or expired.
|
||||
You can optionally specify the time and date that the restart
|
||||
happened.
|
||||
</p>
|
||||
<p>
|
||||
Expiring cookies can be a problem.
|
||||
After all, if you have a cookie that expires after an hour,
|
||||
you don't want to stall the test for an hour while the
|
||||
cookie passes it's timeout.
|
||||
</p>
|
||||
<p>
|
||||
To push the cookies over the hour limit you can age them
|
||||
before you restart the session...
|
||||
<php><![CDATA[
|
||||
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');
|
||||
<strong>
|
||||
$this->ageCookies(3600);</strong>
|
||||
$this->restart();
|
||||
$this->get('http://www.my-site.com/restricted.php');
|
||||
$this->assertText('Access denied');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
After the restart it will appear that cookies are an
|
||||
hour older and any that pass their expiry will have
|
||||
disappeared.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Getting through <a href="#basic">Basic HTTP authentication</a>
|
||||
</link>
|
||||
<link>
|
||||
Testing <a href="#cookies">cookie based authentication</a>
|
||||
</link>
|
||||
<link>
|
||||
Managing <a href="#session">browser sessions</a> and timeouts
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
The <a href="http://simpletest.sourceforge.net/">developer's API for SimpleTest</a>
|
||||
gives full detail on the classes and assertions available.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming for clients,
|
||||
customer focused php,
|
||||
software development tools,
|
||||
acceptance testing framework,
|
||||
free php scripts,
|
||||
log in boxes,
|
||||
unit testing authentication systems,
|
||||
php resources,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
php testing,
|
||||
unit test resource,
|
||||
web testing,
|
||||
HTTP authentication,
|
||||
testing log in,
|
||||
authentication testing,
|
||||
security tests
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,72 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Books" here="Books">
|
||||
<long_title>Books in and around SimpleTest</long_title>
|
||||
<content>
|
||||
<section name="latest-recommandation" title="Latest recommandation">
|
||||
<p>
|
||||
From time to time a book is recommanded on the mailing-list, you can find it here
|
||||
with the original comments !
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215?ie=UTF8&tag=simpletest-21&"><img src="../images/book-domain-driven-design.jpg" alt="Domain-Driven Design: Tackling Complexity in the Heart of Software" /></a>
|
||||
</p>
|
||||
<blockquote>
|
||||
TDD is a lot about the mechanics of coding, but it says you are done
|
||||
when there is no duplication. DDD considers the code in constant churn,
|
||||
always renaming as the domain becomes clear and also feeding terms back
|
||||
into the domain as the code evolves.<br />
|
||||
<br />
|
||||
Anyways, it's a great book :) [<a href="http://sourceforge.net/mailarchive/message.php?msg_id=37546605">source</a>]
|
||||
</blockquote>
|
||||
</section>
|
||||
<section name="books-by-contributors" title="Books by contributors">
|
||||
<p>
|
||||
Two of SimpleTest contributors have written books about PHP. Both have a lot
|
||||
of examples with the SimpleTest Unit testing framework.
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://www.amazon.fr/gp/product/0973589825?ie=UTF8&tag=simpletest-21&linkCode=as2&camp=1642&creative=6746&creativeASIN=0973589825"><img src="../images/book-guide-to-php-design-patterns.jpg" alt="PHP|Architect's Guide to PHP Design Patterns" /></a>
|
||||
<br />
|
||||
<strong>PHP|Architect's Guide to PHP Design Patterns</strong><br />
|
||||
by Jason E. Sweat<br />
|
||||
(get it from : <a href="http://www.phparch.com/shop_product.php?itemid=96">PHP|Architect</a> |
|
||||
<a href="http://www.amazon.fr/gp/product/0973589825?ie=UTF8&tag=simpletest-21&linkCode=as2&camp=1642&creative=6746&creativeASIN=0973589825">Amazon</a> )
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://www.amazon.fr/gp/product/0957921845/402-9483515-6732155?ie=UTF8&tag=simpletest-21&linkCode=xm2&camp=1642&creativeASIN=0957921845"><img src="../images/book-the-php-anthology-object-oriented-php-solutions.jpg" alt="The PHP Anthology: Object Oriented PHP Solutions" /></a>
|
||||
<br />
|
||||
<strong>The PHP Anthology: Object Oriented PHP Solutions</strong><br />
|
||||
by Harry Fuecks<br />
|
||||
(get it from : <a href="http://www.sitepoint.com/books/phpant1/">SitePoint</a> |
|
||||
<a href="http://www.amazon.fr/gp/product/0957921845/402-9483515-6732155?ie=UTF8&tag=simpletest-21&linkCode=xm2&camp=1642&creativeASIN=0957921845">Amazon</a> |
|
||||
<a href="http://developers.slashdot.org/article.pl?sid=04/08/04/1516258&amp;tid=169&amp;tid=192&amp;tid=218&amp;mode=nocomment">review on Slashdot</a> )
|
||||
</p>
|
||||
</section>
|
||||
<section name="buying-books" title="Buying books">
|
||||
<p>
|
||||
One way to help the team of contributors is to buy books from this page through
|
||||
Amazon (with the <cite>simpletest-21</cite> tag). We all love reading stuff that's
|
||||
both interesting and challenging.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#latest-recommandation">Latest recommandation</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#books-by-contributors">Books by contributors</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#buying-books">Buying books</a>
|
||||
</link>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
</external>
|
||||
|
||||
<meta>
|
||||
<keywords>
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,408 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="The Application Boundary" here="Boundary classes">
|
||||
<long_title>
|
||||
PHP unit testing tutorial - Organising unit tests and boundary
|
||||
class test cases
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
You are probably thinking that we have well and truly exhausted
|
||||
the <code>Log</code> class by now and that there is
|
||||
really nothing more to add.
|
||||
Things are never that simple with object oriented programming, though.
|
||||
You think you understand a problem and then something comes a long
|
||||
that challenges your perspective and leads to an even deeper appreciation.
|
||||
I thought I understood the logging class and that only the first page
|
||||
of the tutorial would use it.
|
||||
After that I would move on to something more complicated.
|
||||
No one is more surprised than me that I still haven't got to
|
||||
the bottom of it.
|
||||
In fact I think I have only just figured out what a logger does.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="variation"><h2>Log variations</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Supposing that we do not want to log to a file at all.
|
||||
Perhaps we want to print to the screen, write the messages to a
|
||||
socket or send them to the Unix(tm) <em>syslog</em> daemon for
|
||||
dispatching across the network.
|
||||
How do we incorporate this variation?
|
||||
</p>
|
||||
<p>
|
||||
Simplest is to subclass the <code>Log</code>
|
||||
overriding the <code>message()</code> method
|
||||
with new versions.
|
||||
This will work in the short term, but there is actually something
|
||||
subtle, but deeply wrong with this.
|
||||
Suppose we do subclass and have loggers that write to files,
|
||||
the screen and the network.
|
||||
Three classes , but that is OK.
|
||||
Now suppose that we want a new logging class that adds message
|
||||
filtering by priority, letting only certain types of messages
|
||||
through according to some configuration file.
|
||||
</p>
|
||||
<p>
|
||||
We are stuck. If we subclass again, we have to do it for all
|
||||
three classes, giving us six classes.
|
||||
The amount of duplication is horrible.
|
||||
</p>
|
||||
<p>
|
||||
So are you now wishing that PHP had multiple inheritence?
|
||||
Well, here that would reduce the short term workload, but
|
||||
complicate what should be a very simple class.
|
||||
Multiple inheritance, even when supported, should be used
|
||||
extremely carefully as all sorts of complicated entanglements
|
||||
can result.
|
||||
Treat it as a loaded gun.
|
||||
In fact, our sudden need for it is telling us something else - perhaps
|
||||
that we have gone wrong on the conceptual level.
|
||||
</p>
|
||||
<p>
|
||||
What does a logger do?
|
||||
Does it send messages to a file?
|
||||
Does it send messages to a network?
|
||||
Does it send messages to a screen?
|
||||
Nope.
|
||||
It just sends messages (full stop).
|
||||
The target of those messages can be chosen when setting
|
||||
up the log, but after that the
|
||||
logger should be left to combine and format the message
|
||||
elements as that is its real job.
|
||||
We restricted ourselves by assuming that target was a filename.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="writer"><h2>Abstracting a file to a writer</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
The solution to this plight is a real classic.
|
||||
First we encapsulate the variation in a class as this will
|
||||
add a level of indirection.
|
||||
Instead of passing in the file name as a string we
|
||||
will pass the "thing that we will write to"
|
||||
which we will call a <code>Writer</code>.
|
||||
Back to the tests...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');<strong>
|
||||
require_once('../classes/writer.php');</strong>
|
||||
Mock::generate('Clock');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}
|
||||
function testCreatingNewFile() {<strong>
|
||||
$log = new Log(new FileWriter('../temp/test.log'));</strong>
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');
|
||||
}
|
||||
function testAppendingToFile() {<strong>
|
||||
$log = new Log(new FileWriter('../temp/test.log'));</strong>
|
||||
$log->message('Test line 1');
|
||||
$this->assertWantedPattern(
|
||||
'/Test line 1/',
|
||||
$this->getFileLine('../temp/test.log', 0));
|
||||
$log->message('Test line 2');
|
||||
$this->assertWantedPattern(
|
||||
'/Test line 2/',
|
||||
$this->getFileLine('../temp/test.log', 1));
|
||||
}
|
||||
function testTimestamps() {
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');<strong>
|
||||
$log = new Log(new FileWriter('../temp/test.log'));</strong>
|
||||
$log->message('Test line', &$clock);
|
||||
$this->assertWantedPattern(
|
||||
'/Timestamp/',
|
||||
$this->getFileLine('../temp/test.log', 0),
|
||||
'Found timestamp');
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
I am going to do this one step at a time so as not to get
|
||||
confused.
|
||||
I have replaced the file names with an imaginary
|
||||
<code>FileWriter</code> class from
|
||||
a file <em>classes/writer.php</em>.
|
||||
This will cause the tests to crash as we have not written
|
||||
the writer yet.
|
||||
Should we do that now?
|
||||
</p>
|
||||
<p>
|
||||
We could, but we don't have to.
|
||||
We do need to create the interface, though, or we won't be
|
||||
able to mock it.
|
||||
This makes <em>classes/writer.php</em> looks like...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class FileWriter {
|
||||
|
||||
function FileWriter($file_path) {
|
||||
}
|
||||
|
||||
function write($message) {
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
We need to modify the <code>Log</code> class
|
||||
as well...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/clock.php');<strong>
|
||||
require_once('../classes/writer.php');</strong>
|
||||
|
||||
class Log {<strong>
|
||||
var $_writer;</strong>
|
||||
|
||||
function Log(<strong>&$writer</strong>) {<strong>
|
||||
$this->_writer = &$writer;</strong>
|
||||
}
|
||||
|
||||
function message($message, $clock = false) {
|
||||
if (! is_object($clock)) {
|
||||
$clock = new Clock();
|
||||
}<strong>
|
||||
$this->_writer->write("[" . $clock->now() . "] $message");</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
There is not much that hasn't changed in our now even smaller
|
||||
class.
|
||||
The tests run, but fail at this point unless we add code to
|
||||
the writer.
|
||||
What do we do now?
|
||||
</p>
|
||||
<p>
|
||||
We could start writing tests and code the
|
||||
<code>FileWriter</code> class alongside, but
|
||||
while we were doing this our <code>Log</code>
|
||||
tests would be failing and disturbing our focus.
|
||||
In fact we do not have to.
|
||||
</p>
|
||||
<p>
|
||||
Part of our plan is to free the logging class from the file
|
||||
system and there is a way to do this.
|
||||
First we add a <em>tests/writer_test.php</em> so that
|
||||
we have somewhere to place our test code from <em>log_test.php</em>
|
||||
that we are going to shuffle around.
|
||||
I won't yet add it to the <em>all_tests.php</em> file
|
||||
though as it is the logging aspect we are tackling right now.
|
||||
</p>
|
||||
<p>
|
||||
Now I have done that (honest) we remove any
|
||||
tests from <em>log_test.php</em> that are not strictly logging
|
||||
related and move them to <em>writer_test.php</em> for later.
|
||||
We will also mock the writer so that it does not write
|
||||
out to real files...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');
|
||||
require_once('../classes/writer.php');
|
||||
Mock::generate('Clock');<strong>
|
||||
Mock::generate('FileWriter');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}<strong>
|
||||
function testWriting() {
|
||||
$clock = &new MockClock();
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$writer = &new MockFileWriter($this);
|
||||
$writer->expectArguments('write', array('[Timestamp] Test line'));
|
||||
$writer->expectCallCount('write', 1);
|
||||
$log = &new Log(\$writer);
|
||||
$log->message('Test line', &$clock);
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Yes that really is the whole test case and it really is that short.
|
||||
A lot has happened here...
|
||||
<ol>
|
||||
<li>
|
||||
The requirement to create the file only when needed has
|
||||
moved to the <code>FileWriter</code>.
|
||||
</li>
|
||||
<li>
|
||||
As we are dealing with mocks, no files are actually
|
||||
created and so I moved the
|
||||
<code>setUp()</code> and
|
||||
<code>tearDown()</code> off into the
|
||||
writing tests.
|
||||
</li>
|
||||
<li>
|
||||
The test now consists of sending a sample message and
|
||||
testing the format.
|
||||
</li>
|
||||
</ol>
|
||||
Hang on a minute, where are the assertions?
|
||||
</p>
|
||||
<p>
|
||||
The mock objects do much more than simply behave like other
|
||||
objects, they also run tests.
|
||||
The <code>expectArguments()</code>
|
||||
call told the mock to expect a single parameter of
|
||||
the string "[Timestamp] Test line" when
|
||||
the mock <code>write()</code> method is
|
||||
called.
|
||||
When that method is called the expected parameters are
|
||||
compared with this and either a pass or a fail is sent
|
||||
to the unit test as a result.
|
||||
</p>
|
||||
<p>
|
||||
The other expectation is that <code>write()</code>
|
||||
will be called only once.
|
||||
Simply setting this up is not enough.
|
||||
We can see all this in action by running the tests...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testwriting->Arguments for [write] were [String: [Timestamp] Test line]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testwriting->Expected call count for [write] was [1], but got [1]<br />
|
||||
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>4</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
</p>
|
||||
<p>
|
||||
We can actually shorten our test slightly more.
|
||||
The mock object expectation <code>expectOnce()</code>
|
||||
can actually combine the two seperate expectations...
|
||||
<php><![CDATA[
|
||||
function testWriting() {
|
||||
$clock = &new MockClock();
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$writer = &new MockFileWriter($this);<strong>
|
||||
$writer->expectOnce('write', array('[Timestamp] Test line'));</strong>
|
||||
$log = &new Log($writer);
|
||||
$log->message('Test line', &$clock);
|
||||
}
|
||||
]]></php>
|
||||
This can be an effective shorthand.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="boundary"><h2>Boundary classes</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Something very nice has happened to the logger besides merely
|
||||
getting smaller.
|
||||
</p>
|
||||
<p>
|
||||
The only things it depends on now are classes that we have written
|
||||
ourselves and
|
||||
in the tests these are mocked and so there are no dependencies
|
||||
on anything other than our own PHP code.
|
||||
No writing to files or waiting for clocks to tick over.
|
||||
This means that the <em>log_test.php</em> test case will
|
||||
run as fast as the processor will carry it.
|
||||
By contrast the <code>FileWriter</code>
|
||||
and <code>Clock</code> classes are very
|
||||
close to the system.
|
||||
This makes them harder to test as real data must be moved
|
||||
around and painstakingly confirmed, often by ad hoc tricks.
|
||||
</p>
|
||||
<p>
|
||||
Our last refactoring has helped a lot.
|
||||
The hard to test classes on the boundary of the application
|
||||
and the system are now smaller as the I/O code has
|
||||
been further separated from the application logic.
|
||||
They are direct mappings to PHP operations:
|
||||
<code>FileWriter::write()</code> maps
|
||||
to PHP <code>fwrite()</code> with the
|
||||
file opened for appending and
|
||||
<code>Clock::now()</code> maps to
|
||||
PHP <code>time()</code>.
|
||||
This makes debugging easier.
|
||||
It also means that these classes will change less often.
|
||||
</p>
|
||||
<p>
|
||||
If they don't change a lot then there is no reason to
|
||||
keep running the tests for them.
|
||||
This means that tests for the boundary classes can be moved
|
||||
off into there own test suite leaving the other unit tests
|
||||
to run at full speed.
|
||||
In fact this is what I tend to do and the test cases
|
||||
in <a href="simple_test.php">SimpleTest</a> itself are
|
||||
divided this way.
|
||||
</p>
|
||||
<p>
|
||||
That may not sound like much with one unit test and two
|
||||
boundary tests, but typical applications can have
|
||||
twenty boundary classes and two hundred application
|
||||
classes.
|
||||
To keep these running at full speed you will want
|
||||
to keep them separate.
|
||||
</p>
|
||||
<p>
|
||||
Besides, separating off decisions of which system components
|
||||
to use is good development.
|
||||
Perhaps all this mocking is
|
||||
<a href="improving_design_tutorial.php">improving our design</a>?
|
||||
</p>
|
||||
</content>
|
||||
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#variation">Handling variation</a> in our logger.
|
||||
</link>
|
||||
<link>
|
||||
Abstracting further with a <a href="#writer">mock Writer</a> class.
|
||||
</link>
|
||||
<link>
|
||||
Separating <a href="#boundary">Boundary class</a> tests
|
||||
cleans things up.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
This tutorial follows the <a href="mock_objects_tutorial.php">Mock objects</a> introduction.
|
||||
</link>
|
||||
<link>
|
||||
Next is <a href="improving_design_tutorial.php">test driven design</a>.
|
||||
</link>
|
||||
<link>
|
||||
You will need the <a href="simple_test.php">SimpleTest testing framework</a>
|
||||
to try these examples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
organizing unit tests,
|
||||
testing tips,
|
||||
development tricks,
|
||||
software architecture for testing,
|
||||
php example code,
|
||||
mock objects,
|
||||
junit port,
|
||||
test case examples,
|
||||
php testing,
|
||||
unit test tool,
|
||||
php test suite
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,264 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="PHP Scriptable Web Browser" here="Scriptable browser">
|
||||
<long_title>SimpleTest documentation for the scriptable web browser component</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
SimpleTest's web browser component can be used not just
|
||||
outside of the <code>WebTestCase</code> class, but also
|
||||
independently of the SimpleTest framework itself.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="scripting" title="The Scriptable Browser">
|
||||
<p>
|
||||
You can use the web browser in PHP scripts to confirm
|
||||
services are up and running, or to extract information
|
||||
from them at a regular basis.
|
||||
For example, here is a small script to extract the current number of
|
||||
open PHP 5 bugs from the <a href="http://www.php.net/">PHP web site</a>...
|
||||
<php><![CDATA[
|
||||
<strong><?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];
|
||||
?></strong>
|
||||
]]></php>
|
||||
There are simpler methods to do this particular example in PHP
|
||||
of course.
|
||||
For example you can just use the PHP <code>file()</code>
|
||||
command against what here is a pretty fixed page.
|
||||
However, using the web browser for scripts allows authentication,
|
||||
correct handling of cookies, automatic loading of frames, redirects,
|
||||
form submission and the ability to examine the page headers.
|
||||
Such methods are fragile against a site that is constantly
|
||||
evolving and you would want a more direct way of accessing
|
||||
data in a permanent set up, but for simple tasks this can provide
|
||||
a very rapid solution.
|
||||
</p>
|
||||
<p>
|
||||
All of the navigation methods used in the
|
||||
<a local="web_tester_documentation">WebTestCase</a>
|
||||
are present in the <code>SimpleBrowser</code> class, but
|
||||
the assertions are replaced with simpler accessors.
|
||||
Here is a full list of the page navigation methods...
|
||||
<table><tbody>
|
||||
<tr><td><code>addHeader($header)</code></td><td>Adds a header to every fetch</td></tr>
|
||||
<tr><td><code>useProxy($proxy, $username, $password)</code></td><td>Use this proxy from now on</td></tr>
|
||||
<tr><td><code>head($url, $parameters)</code></td><td>Perform a HEAD request</td></tr>
|
||||
<tr><td><code>get($url, $parameters)</code></td><td>Fetch a page with GET</td></tr>
|
||||
<tr><td><code>post($url, $parameters)</code></td><td>Fetch a page with POST</td></tr>
|
||||
<tr><td><code>clickLink($label)</code></td><td>Follows a link by label</td></tr>
|
||||
<tr><td><code>isLink($label)</code></td><td>See if a link is present by label</td></tr>
|
||||
<tr><td><code>clickLinkById($id)</code></td><td>Follows a link by attribute</td></tr>
|
||||
<tr><td><code>isLinkById($id)</code></td><td>See if a link is present by attribut</td></tr>
|
||||
<tr><td><code>getUrl()</code></td><td>Current URL of page or frame</td></tr>
|
||||
<tr><td><code>getTitle()</code></td><td>Page title</td></tr>
|
||||
<tr><td><code>getContent()</code></td><td>Raw page or frame</td></tr>
|
||||
<tr><td><code>getContentAsText()</code></td><td>HTML removed except for alt text</td></tr>
|
||||
<tr><td><code>retry()</code></td><td>Repeat the last request</td></tr>
|
||||
<tr><td><code>back()</code></td><td>Use the browser back button</td></tr>
|
||||
<tr><td><code>forward()</code></td><td>Use the browser forward button</td></tr>
|
||||
<tr><td><code>authenticate($username, $password)</code></td><td>Retry page or frame after a 401 response</td></tr>
|
||||
<tr><td><code>restart($date)</code></td><td>Restarts the browser for a new session</td></tr>
|
||||
<tr><td><code>ageCookies($interval)</code></td><td>Ages the cookies by the specified time</td></tr>
|
||||
<tr><td><code>setCookie($name, $value)</code></td><td>Sets an additional cookie</td></tr>
|
||||
<tr><td><code>getCookieValue($host, $path, $name)</code></td><td>Reads the most specific cookie</td></tr>
|
||||
<tr><td><code>getCurrentCookieValue($name)</code></td><td>Reads cookie for the current context</td></tr>
|
||||
</tbody></table>
|
||||
The methods <code>SimpleBrowser::useProxy()</code> and
|
||||
<code>SimpleBrowser::addHeader()</code> are special.
|
||||
Once called they continue to apply to all subsequent fetches.
|
||||
</p>
|
||||
<p>
|
||||
Navigating forms is similar to the
|
||||
<a local="form_testing_documentation">WebTestCase form navigation</a>...
|
||||
<table><tbody>
|
||||
<tr><td><code>setField($name, $value)</code></td><td>Sets all form fields with that name</td></tr>
|
||||
<tr><td><code>setFieldById($id, $value)</code></td><td>Sets all form fields with that id</td></tr>
|
||||
<tr><td><code>getField($name)</code></td><td>Accessor for a form element value</td></tr>
|
||||
<tr><td><code>getFieldById($id)</code></td><td>Accessor for a form element value</td></tr>
|
||||
<tr><td><code>clickSubmit($label)</code></td><td>Submits form by button label</td></tr>
|
||||
<tr><td><code>clickSubmitByName($name)</code></td><td>Submits form by button attribute</td></tr>
|
||||
<tr><td><code>clickSubmitById($id)</code></td><td>Submits form by button attribute</td></tr>
|
||||
<tr><td><code>clickImage($label, $x, $y)</code></td><td>Clicks the image by alt text</td></tr>
|
||||
<tr><td><code>clickImageByName($name, $x, $y)</code></td><td>Clicks the image by attribute</td></tr>
|
||||
<tr><td><code>clickImageById($id, $x, $y)</code></td><td>Clicks the image by attribute</td></tr>
|
||||
<tr><td><code>submitFormById($id)</code></td><td>Submits by the form tag attribute</td></tr>
|
||||
</tbody></table>
|
||||
At the moment there aren't any methods to list available forms
|
||||
and fields.
|
||||
This will probably be added to later versions of SimpleTest.
|
||||
</p>
|
||||
<p>
|
||||
Within a page, individual frames can be selected.
|
||||
If no selection is made then all the frames are merged together
|
||||
in one large conceptual page.
|
||||
The content of the current page will be a concatenation of all of the
|
||||
frames in the order that they were specified in the "frameset"
|
||||
tags.
|
||||
<table><tbody>
|
||||
<tr><td><code>getFrames()</code></td><td>A dump of the current frame structure</td></tr>
|
||||
<tr><td><code>getFrameFocus()</code></td><td>Current frame label or index</td></tr>
|
||||
<tr><td><code>setFrameFocusByIndex($choice)</code></td><td>Select a frame numbered from 1</td></tr>
|
||||
<tr><td><code>setFrameFocus($name)</code></td><td>Select frame by label</td></tr>
|
||||
<tr><td><code>clearFrameFocus()</code></td><td>Treat all the frames as a single page</td></tr>
|
||||
</tbody></table>
|
||||
When focused on a single frame, the content will come from
|
||||
that frame only.
|
||||
This includes links to click and forms to submit.
|
||||
</p>
|
||||
</section>
|
||||
<section name="debug" title="What went wrong?">
|
||||
<p>
|
||||
All of this functionality is great when we actually manage to fetch pages,
|
||||
but that doesn't always happen.
|
||||
To help figure out what went wrong, the browser has some methods to
|
||||
aid in debugging...
|
||||
<table><tbody>
|
||||
<tr><td><code>setConnectionTimeout($timeout)</code></td><td>Close the socket on overrun</td></tr>
|
||||
<tr><td><code>getRequest()</code></td><td>Raw request header of page or frame</td></tr>
|
||||
<tr><td><code>getHeaders()</code></td><td>Raw response header of page or frame</td></tr>
|
||||
<tr><td><code>getTransportError()</code></td><td>Any socket level errors in the last fetch</td></tr>
|
||||
<tr><td><code>getResponseCode()</code></td><td>HTTP response of page or frame</td></tr>
|
||||
<tr><td><code>getMimeType()</code></td><td>Mime type of page or frame</td></tr>
|
||||
<tr><td><code>getAuthentication()</code></td><td>Authentication type in 401 challenge header</td></tr>
|
||||
<tr><td><code>getRealm()</code></td><td>Authentication realm in 401 challenge header</td></tr>
|
||||
<tr><td><code>setMaximumRedirects($max)</code></td><td>Number of redirects before page is loaded anyway</td></tr>
|
||||
<tr><td><code>setMaximumNestedFrames($max)</code></td><td>Protection against recursive framesets</td></tr>
|
||||
<tr><td><code>ignoreFrames()</code></td><td>Disables frames support</td></tr>
|
||||
<tr><td><code>useFrames()</code></td><td>Enables frames support</td></tr>
|
||||
<tr><td><code>ignoreCookies()</code></td><td>Disables sending and receiving of cookies</td></tr>
|
||||
<tr><td><code>useCookies()</code></td><td>Enables cookie support</td></tr>
|
||||
</tbody></table>
|
||||
The methods <code>SimpleBrowser::setConnectionTimeout()</code>
|
||||
<code>SimpleBrowser::setMaximumRedirects()</code>,
|
||||
<code>SimpleBrowser::setMaximumNestedFrames()</code>,
|
||||
<code>SimpleBrowser::ignoreFrames()</code>,
|
||||
<code>SimpleBrowser::useFrames()</code>,
|
||||
<code>SimpleBrowser::ignoreCookies()</code> and
|
||||
<code>SimpleBrowser::useCokies()</code> 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 <code>SimpleBrowser::setFrameFocus()</code>
|
||||
and you can then use <code>SimpleBrowser::getRequest()</code>, etc to
|
||||
see what happened.
|
||||
</p>
|
||||
</section>
|
||||
<section name="unit" title="Complex unit tests with multiple browsers">
|
||||
<p>
|
||||
Anything that could be done in a
|
||||
<a local="web_tester_documentation">WebTestCase</a> can
|
||||
now be done in a <a local="unit_tester_documentation">UnitTestCase</a>.
|
||||
This means that we can freely mix domain object testing with the
|
||||
web interface...
|
||||
<php><![CDATA[<strong>
|
||||
class TestOfRegistration extends UnitTestCase {
|
||||
function testNewUserAddedToAuthenticator() {</strong>
|
||||
$browser = &new SimpleBrowser();
|
||||
$browser->get('http://my-site.com/register.php');
|
||||
$browser->setField('email', 'me@here');
|
||||
$browser->setField('password', 'Secret');
|
||||
$browser->click('Register');
|
||||
<strong>
|
||||
$authenticator = &new Authenticator();
|
||||
$member = &$authenticator->findByEmail('me@here');
|
||||
$this->assertEqual($member->getPassword(), 'Secret');
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
While this may be a useful temporary expediency, I am not a fan
|
||||
of this type of testing.
|
||||
The testing has cut across application layers, make it twice as
|
||||
likely it will need refactoring when the code changes.
|
||||
</p>
|
||||
<p>
|
||||
A more useful case of where using the browser directly can be helpful
|
||||
is where the <code>WebTestCase</code> cannot cope.
|
||||
An example is where two browsers are needed at the same time.
|
||||
</p>
|
||||
<p>
|
||||
For example, say we want to disallow multiple simultaneous
|
||||
usage of a site with the same username.
|
||||
This test case will do the job...
|
||||
<php><![CDATA[
|
||||
class TestOfSecurity extends UnitTestCase {
|
||||
function testNoMultipleLoginsFromSameUser() {<strong>
|
||||
$first = &new SimpleBrowser();
|
||||
$first->get('http://my-site.com/login.php');
|
||||
$first->setField('name', 'Me');
|
||||
$first->setField('password', 'Secret');
|
||||
$first->click('Enter');
|
||||
$this->assertEqual($first->getTitle(), 'Welcome');
|
||||
|
||||
$second = &new SimpleBrowser();
|
||||
$second->get('http://my-site.com/login.php');
|
||||
$second->setField('name', 'Me');
|
||||
$second->setField('password', 'Secret');
|
||||
$second->click('Enter');
|
||||
$this->assertEqual($second->getTitle(), 'Access Denied');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
You can also use the <code>SimpleBrowser</code> class
|
||||
directly when you want to write test cases using a different
|
||||
test tool than SimpleTest.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Using the bundled <a href="#scripting">web browser in scripts</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#debug">Debugging</a> failed pages
|
||||
</link>
|
||||
<link>
|
||||
Complex <a href="#unit">tests with multiple web browsers</a>
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
The <a href="http://simpletest.sourceforge.net/">developer's API for SimpleTest</a>
|
||||
gives full detail on the classes and assertions available.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
user agent,
|
||||
web browser php,
|
||||
fetching pages,
|
||||
spider scripts,
|
||||
software development,
|
||||
php programming for clients,
|
||||
customer focused php,
|
||||
software development tools,
|
||||
acceptance testing framework,
|
||||
free php scripts,
|
||||
log in boxes,
|
||||
unit testing authentication systems,
|
||||
php resources,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
php testing,
|
||||
unit test resource,
|
||||
web testing,
|
||||
HTTP authentication,
|
||||
testing log in,
|
||||
authentication testing,
|
||||
security tests
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,273 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Changing the test display" here="Showing passes">
|
||||
<long_title>PHP unit testing tutorial - Subclassing the test display</long_title>
|
||||
<content>
|
||||
<p>
|
||||
The display component of SimpleTest is actually the part
|
||||
to be developed last.
|
||||
Some of the following section will change in the future
|
||||
and hopefully more sophisticated display components will
|
||||
be written, but
|
||||
in the meantime if a minimal display is not enough, here
|
||||
is how to roll your own.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="passes"><h2>I want to see the passes!</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Oh all right then, here's how.
|
||||
</p>
|
||||
<p>
|
||||
We have to subclass the attached display, which in our case
|
||||
is currently <code>HtmlReporter</code>.
|
||||
The <code>HtmlReporter</code> class is in
|
||||
the file <em>simpletest/reporter.php</em> and currently has
|
||||
the following interface...
|
||||
<php><![CDATA[
|
||||
class HtmlReporter extends TestDisplay {
|
||||
public TestHtmlDisplay() { ... }
|
||||
public void paintHeader(string $test_name) { ... }
|
||||
public void paintFooter(string $test_name) { ... }
|
||||
public void paintStart(string $test_name, $size) { ... }
|
||||
public void paintEnd(string $test_name, $size) { ... }
|
||||
public void paintFail(string $message) { ... }
|
||||
public void paintPass(string $message) { ... }
|
||||
protected string _getCss() { ... }
|
||||
public array getTestList() { ... }
|
||||
public integer getPassCount() { ... }
|
||||
public integer getFailCount() { ... }
|
||||
public integer getTestCaseCount() { ... }
|
||||
public integer getTestCaseProgress { ... }
|
||||
}
|
||||
]]></php>
|
||||
Here is what the relevant methods mean.
|
||||
You can see the
|
||||
<a href="reporter_documentation.php#html">whole list here</a>
|
||||
if you are interested.
|
||||
<ul class="api">
|
||||
<li>
|
||||
<code>HtmlReporter()</code><br />
|
||||
is the constructor.
|
||||
Note that the unit test sets up the link to the display
|
||||
rather than the other way around.
|
||||
The display is a passive receiver of test events.
|
||||
This allows easy adaption of the display for other test
|
||||
systems beside unit tests, such as monitoring servers.
|
||||
It also means that the unit test can write to more than
|
||||
one display at a time.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintFail(string $message)</code><br />
|
||||
paints a failure.
|
||||
See below.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintPass(string $message)</code><br />
|
||||
by default does nothing.
|
||||
This is the method we will modify.
|
||||
</li>
|
||||
<li>
|
||||
<code>string _getCss()</code><br />
|
||||
returns the CSS styles as a string for the page header
|
||||
method.
|
||||
Additional styles have to be appended here.
|
||||
</li>
|
||||
<li>
|
||||
<code>array getTestList()</code><br />
|
||||
is a convenience method for subclasses.
|
||||
Lists the current nesting of the tests as a list
|
||||
of test names.
|
||||
The first, most deeply nested test, is first in the
|
||||
list and the current test method will be last.
|
||||
</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
To show the passes we just need the
|
||||
<code>paintPass()</code> method to behave
|
||||
just like <code>paintFail()</code>.
|
||||
Of course we won't modify the original.
|
||||
We'll subclass.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="subclass"><h2>A display subclass</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Firstly we'll create a <em>tests/show_passes.php</em> file
|
||||
in our logging project and then place in it this empty class...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
|
||||
class ShowPasses extends HtmlReporter {
|
||||
|
||||
function ShowPasses() {
|
||||
$this->HtmlReporter();
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
A quick peruse of the
|
||||
<a href="http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/simpletest/simpletest/reporter.php?content-type=text/vnd.viewcvs-markup">SimpleTest code base</a> shows the
|
||||
<code>paintFail()</code> implementation
|
||||
at the time of writing to look like this...
|
||||
<php><![CDATA[
|
||||
function paintFail($message) {
|
||||
parent::paintFail($message);
|
||||
print "<span class=\"fail\">Fail</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}
|
||||
]]></php>
|
||||
Essentially it chains to the parent's version, which we
|
||||
have to do also to preserve house keeping, and then
|
||||
prints a breadcrumbs trail calculated from the current test
|
||||
list.
|
||||
It drops the top level tests name, though.
|
||||
As it is the same on every test that would be a little bit too
|
||||
much information.
|
||||
Transposing this to our new class...
|
||||
<php><![CDATA[
|
||||
class ShowPasses extends HtmlReporter {
|
||||
|
||||
function ShowPasses() {
|
||||
$this->HtmlReporter();
|
||||
}
|
||||
<strong>
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
So far so good.
|
||||
Now to make use of our new class we have to modify our
|
||||
<em>tests/all_tests.php</em> file...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');<strong>
|
||||
require_once('show_passes.php');</strong>
|
||||
|
||||
$test = &new TestSuite('All tests');
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->addTestFile('clock_test.php');
|
||||
$test->run(<strong>new ShowPasses()</strong>);
|
||||
?>
|
||||
]]></php>
|
||||
We can run this to see the results of our handywork...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
|
||||
Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
|
||||
Pass: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
|
||||
Pass: log_test.php->Log class test->testcreatingnewfile->File created<br />
|
||||
Pass: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Nice, but no gold star.
|
||||
We have lost a little formatting here.
|
||||
The display does not have a CSS style for
|
||||
<code>span.pass</code>, but we can add this
|
||||
easily by overriding one more method...
|
||||
<php><![CDATA[
|
||||
class ShowPasses extends HtmlReporter {
|
||||
|
||||
function ShowPasses() {
|
||||
$this->HtmlReporter();
|
||||
}
|
||||
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}
|
||||
<strong>
|
||||
function _getCss() {
|
||||
return parent::_getCss() . ' .pass { color: green; }';
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
If you are adding the code as you go, you will see the style
|
||||
appended when you do view source on the test results page in your browser.
|
||||
To the eye the display itself should now look like this...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->File created<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Some people definitely prefer to see the passes being added
|
||||
as they are working on code; the feeling that you are getting
|
||||
work done is nice after all.
|
||||
Once you have to scroll up and down the page to find failures
|
||||
though, you soon come to realise its dark side.
|
||||
</p>
|
||||
<p>
|
||||
Try it both ways and see which you prefer.
|
||||
We'll leave it in for a bit anyhow when looking at the
|
||||
<a href="mock_objects_tutorial.php">mock objects coming up</a>.
|
||||
This is the first test tool that generates additional tests
|
||||
and it will be useful to see what is happening behind the scenes.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
How to Change the display to <a href="#passes">show test passes</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#subclass">Subclassing the <code>HtmlReporter</code> class</a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
The previous tutorial section was
|
||||
<a href="subclass_tutorial.php">subclassing the test case</a>.
|
||||
</link>
|
||||
<link>
|
||||
This section is very specific to
|
||||
<a href="simple_test.php">SimpleTest</a>.
|
||||
If you use another tool you will want to skip this.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development test first,
|
||||
php general programming advice,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php sample code,
|
||||
architecture,
|
||||
sample test cases,
|
||||
php simple test framework,
|
||||
php resources,
|
||||
php test case examples,
|
||||
phpunit,
|
||||
simpletest,
|
||||
unit test,
|
||||
php testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,98 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Downloading SimpleTest" here="Download SimpleTest">
|
||||
<long_title>Downloading SimpleTest</long_title>
|
||||
<content>
|
||||
<section name="current-release" title="Current release">
|
||||
<p>
|
||||
The current release is : <a href="http://prdownloads.sourceforge.net/simpletest/simpletest_1.0.1beta.tar.gz">SimpleTest v1.0.1beta</a>.
|
||||
</p>
|
||||
<p>
|
||||
You can download this version from
|
||||
<a href="http://sourceforge.net/project/showfiles.php?group_id=76550&package_id=159054&release_id=391231">SourceForget.net</a>
|
||||
and your local mirror. You may also want to look at
|
||||
the <a href="changelog.html">current changelog</a>.
|
||||
</p>
|
||||
<p>
|
||||
By the way, don't be scared away by the <quote>beta</quote> tag :
|
||||
quite a few users actually use SimpleTest straight from CVS.
|
||||
</p>
|
||||
</section>
|
||||
<section name="eclipse-release" title="Eclipse release">
|
||||
<p>
|
||||
If eclipse is your IDE / editor of choice, you might consider
|
||||
the <a href="http://sourceforge.net/project/showfiles.php?group_id=76550&package_id=159054&release_id=403632">Eclipse plugin</a>.
|
||||
</p>
|
||||
<p>
|
||||
For automatic "find and install", the URL is :
|
||||
<blockquote>http://simpletest.org/eclipse/</blockquote>
|
||||
</p>
|
||||
</section>
|
||||
<section name="packages" title="Packages">
|
||||
<p>
|
||||
SimpleTest has been packaged by the community to different flavours.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="http://packages.debian.org/unstable/web/php-simpletest">Debian package</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://www.pearified.com/index.php?package=SimpleTest">Pearified package</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://drupal.org/project/simpletest">Drupal module</a>
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
<cite>Note : careful, some versions are not always up-to-date.</cite>
|
||||
</p>
|
||||
</section>
|
||||
<section name="source" title="Source">
|
||||
<p>
|
||||
The source code is hosted on Sourceforge as well : you can browse
|
||||
the <a href="http://simpletest.cvs.sourceforge.net/simpletest/">CVS repository</a> there.
|
||||
</p>
|
||||
</section>
|
||||
<section name="older-stable-releases" title="Older stable releases">
|
||||
<ul>
|
||||
<li>
|
||||
<a href="http://prdownloads.sourceforge.net/simpletest/simpletest_1.0.tar.gz">1.0.0</a>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#current-release">Current release</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#eclipse-release">Eclipse release</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#packages">Packages</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#source">Source</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#older-stable-releases">Older stable releases</a>
|
||||
</link>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
</external>
|
||||
|
||||
<meta>
|
||||
<keywords>
|
||||
SimpleTest,
|
||||
download,
|
||||
source code,
|
||||
stable release,
|
||||
eclipse release,
|
||||
eclipse plugin,
|
||||
debian package,
|
||||
drupal module,
|
||||
pear channel,
|
||||
pearified package
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,338 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Expectation documentation" here="Expectations">
|
||||
<long_title>
|
||||
Extending the SimpleTest unit tester with additional expectation classes
|
||||
</long_title>
|
||||
<content>
|
||||
<section name="mock" title="More control over mock objects">
|
||||
<p>
|
||||
The default behaviour of the
|
||||
<a local="mock_objects_documentation">mock objects</a>
|
||||
in
|
||||
<a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a>
|
||||
is either an identical match on the argument or to allow any argument at all.
|
||||
For almost all tests this is sufficient.
|
||||
Sometimes, though, you want to weaken a test case.
|
||||
</p>
|
||||
<p>
|
||||
One place where a test can be too tightly coupled is with
|
||||
text matching.
|
||||
Suppose we have a component that outputs a helpful error
|
||||
message when something goes wrong.
|
||||
You want to test that the correct error was sent, but the actual
|
||||
text may be rather long.
|
||||
If you test for the text exactly, then every time the exact wording
|
||||
of the message changes, you will have to go back and edit the test suite.
|
||||
</p>
|
||||
<p>
|
||||
For example, suppose we have a news service that has failed
|
||||
to connect to its remote source.
|
||||
<php><![CDATA[
|
||||
<strong>class NewsService {
|
||||
...
|
||||
function publish(&$writer) {
|
||||
if (! $this->isConnected()) {
|
||||
$writer->write('Cannot connect to news service "' .
|
||||
$this->_name . '" at this time. ' .
|
||||
'Please try again later.');
|
||||
}
|
||||
...
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
Here it is sending its content to a
|
||||
<code>Writer</code> class.
|
||||
We could test this behaviour with a
|
||||
<code>MockWriter</code> like so...
|
||||
<php><![CDATA[
|
||||
class TestOfNewsService extends UnitTestCase {
|
||||
...
|
||||
function testConnectionFailure() {<strong>
|
||||
$writer = &new MockWriter();
|
||||
$writer->expectOnce('write', array(
|
||||
'Cannot connect to news service ' .
|
||||
'"BBC News" at this time. ' .
|
||||
'Please try again later.'));
|
||||
|
||||
$service = &new NewsService('BBC News');
|
||||
$service->publish($writer);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
This is a good example of a brittle test.
|
||||
If we decide to add additional instructions, such as
|
||||
suggesting an alternative news source, we will break
|
||||
our tests even though no underlying functionality
|
||||
has been altered.
|
||||
</p>
|
||||
<p>
|
||||
To get around this, we would like to do a regular expression
|
||||
test rather than an exact match.
|
||||
We can actually do this with...
|
||||
<php><![CDATA[
|
||||
class TestOfNewsService extends UnitTestCase {
|
||||
...
|
||||
function testConnectionFailure() {
|
||||
$writer = &new MockWriter();<strong>
|
||||
$writer->expectOnce(
|
||||
'write',
|
||||
array(new PatternExpectation('/cannot connect/i')));</strong>
|
||||
|
||||
$service = &new NewsService('BBC News');
|
||||
$service->publish($writer);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Instead of passing in the expected parameter to the
|
||||
<code>MockWriter</code> we pass an
|
||||
expectation class called
|
||||
<code>WantedPatternExpectation</code>.
|
||||
The mock object is smart enough to recognise this as special
|
||||
and to treat it differently.
|
||||
Rather than simply comparing the incoming argument to this
|
||||
object, it uses the expectation object itself to
|
||||
perform the test.
|
||||
</p>
|
||||
<p>
|
||||
The <code>WantedPatternExpectation</code> takes
|
||||
the regular expression to match in its constructor.
|
||||
Whenever a comparison is made by the <code>MockWriter</code>
|
||||
against this expectation class, it will do a
|
||||
<code>preg_match()</code> with this pattern.
|
||||
With our test case above, as long as "cannot connect"
|
||||
appears in the text of the string, the mock will issue a pass
|
||||
to the unit tester.
|
||||
The rest of the text does not matter.
|
||||
</p>
|
||||
<p>
|
||||
The possible expectation classes are...
|
||||
<table><tbody>
|
||||
<tr><td><code>AnythingExpectation</code></td><td>Will always match</td></tr>
|
||||
<tr><td><code>EqualExpectation</code></td><td>An equality, rather than the stronger identity comparison</td></tr>
|
||||
<tr><td><code>NotEqualExpectation</code></td><td>An inequality comparison</td></tr>
|
||||
<tr><td><code>IndenticalExpectation</code></td><td>The default mock object check which must match exactly</td></tr>
|
||||
<tr><td><code>NotIndenticalExpectation</code></td><td>Inverts the mock object logic</td></tr>
|
||||
<tr><td><code>WithinMarginExpectation</code></td><td>Compares a value to within a margin</td></tr>
|
||||
<tr><td><code>OutsideMarginExpectation</code></td><td>Checks that a value is out side the margin</td></tr>
|
||||
<tr><td><code>PatternExpectation</code></td><td>Uses a Perl Regex to match a string</td></tr>
|
||||
<tr><td><code>NoPatternExpectation</code></td><td>Passes only if failing a Perl Regex</td></tr>
|
||||
<tr><td><code>IsAExpectation</code></td><td>Checks the type or class name only</td></tr>
|
||||
<tr><td><code>NotAExpectation</code></td><td>Opposite of the <code>IsAExpectation</code></td></tr>
|
||||
<tr><td><code>MethodExistsExpectation</code></td><td>Checks a method is available on an object</td></tr>
|
||||
</tbody></table>
|
||||
Most take the expected value in the constructor.
|
||||
The exceptions are the pattern matchers, which take a regular expression,
|
||||
and the <code>IsAExpectation</code> and <code>NotAExpectation</code> which takes a type
|
||||
or class name as a string.
|
||||
</p>
|
||||
<p>
|
||||
Some examples...
|
||||
</p>
|
||||
<p>
|
||||
<php><![CDATA[
|
||||
$mock->expectOnce('method', array(new IdenticalExpectation(14)));
|
||||
]]></php>
|
||||
This is the same as <code>$mock->expectOnce('method', array(14))</code>.
|
||||
<php><![CDATA[
|
||||
$mock->expectOnce('method', array(new EqualExpectation(14)));
|
||||
]]></php>
|
||||
This is different from the previous version in that the string
|
||||
<code>"14"</code> as a parameter will also pass.
|
||||
Sometimes the additional type checks of SimpleTest are too restrictive.
|
||||
<php><![CDATA[
|
||||
$mock->expectOnce('method', array(new AnythingExpectation(14)));
|
||||
]]></php>
|
||||
This is the same as <code>$mock->expectOnce('method', array('*'))</code>.
|
||||
<php><![CDATA[
|
||||
$mock->expectOnce('method', array(new IdenticalExpectation('*')));
|
||||
]]></php>
|
||||
This is handy if you want to assert a literal <code>"*"</code>.
|
||||
<php><![CDATA[
|
||||
new NotIdenticalExpectation(14)
|
||||
]]></php>
|
||||
This matches on anything other than integer 14.
|
||||
Even the string <code>"14"</code> would pass.
|
||||
<php><![CDATA[
|
||||
new WithinMarginExpectation(14.0, 0.001)
|
||||
]]></php>
|
||||
This will accept any value from 13.999 to 14.001 inclusive.
|
||||
</p>
|
||||
</section>
|
||||
<section name="behaviour" title="Using expectations to control stubs">
|
||||
<p>
|
||||
The expectation classes can be used not just for sending assertions
|
||||
from mock objects, but also for selecting behaviour for the
|
||||
<a local="mock_objects_documentation">mock objects</a>.
|
||||
Anywhere a list of arguments is given, a list of expectation objects
|
||||
can be inserted instead.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
Mock::generate('Authorisation');
|
||||
<strong>
|
||||
$authorisation = new MockAuthorisation();
|
||||
$authorisation->setReturnValue(
|
||||
'isAllowed',
|
||||
true,
|
||||
array(new IsAExpectation('Session', 'Must be a session')));
|
||||
$authorisation->setReturnValue('isAllowed', false);</strong>
|
||||
]]></php>
|
||||
We have set the default mock behaviour to return false when
|
||||
<code>isAllowed</code> is called.
|
||||
When we call the method with a single parameter that
|
||||
is a <code>Session</code> object, it will return true.
|
||||
We have also added a second parameter as a message.
|
||||
This will be displayed as part of the mock object
|
||||
failure message if this expectation is the cause of
|
||||
a failure.
|
||||
</p>
|
||||
<p>
|
||||
This kind of sophistication is rarely useful, but is included for
|
||||
completeness.
|
||||
</p>
|
||||
</section>
|
||||
<section name="extending" title="Creating your own expectations">
|
||||
<p>
|
||||
The expectation classes have a very simple structure.
|
||||
So simple that it is easy to create your own versions for
|
||||
commonly used test logic.
|
||||
</p>
|
||||
<p>
|
||||
As an example here is the creation of a class to test for
|
||||
valid IP addresses.
|
||||
In order to work correctly with the stubs and mocks the new
|
||||
expectation class should extend
|
||||
<code>SimpleExpectation</code>...
|
||||
<php><![CDATA[
|
||||
<strong>class ValidIp extends SimpleExpectation {
|
||||
|
||||
function test($ip) {
|
||||
return (ip2long($ip) != -1);
|
||||
}
|
||||
|
||||
function testMessage($ip) {
|
||||
return "Address [$ip] should be a valid IP address";
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
There are only two methods to implement.
|
||||
The <code>test()</code> method should
|
||||
evaluate to true if the expectation is to pass, and
|
||||
false otherwise.
|
||||
The <code>testMessage()</code> method
|
||||
should simply return some helpful text explaining the test
|
||||
that was carried out.
|
||||
</p>
|
||||
<p>
|
||||
This class can now be used in place of the earlier expectation
|
||||
classes.
|
||||
</p>
|
||||
</section>
|
||||
<section name="unit" title="Under the bonnet of the unit tester">
|
||||
<p>
|
||||
The <a href="http://sourceforge.net/projects/simpletest/">SimpleTest unit testing framework</a>
|
||||
also uses the expectation classes internally for the
|
||||
<a local="unit_test_documentation">UnitTestCase class</a>.
|
||||
We can also take advantage of these mechanisms to reuse our
|
||||
homebrew expectation classes within the test suites directly.
|
||||
</p>
|
||||
<p>
|
||||
The most crude way of doing this is to use the
|
||||
<code>SimpleTest::assert()</code> method to
|
||||
test against it directly...
|
||||
<php><![CDATA[
|
||||
<strong>class TestOfNetworking extends UnitTestCase {
|
||||
...
|
||||
function testGetValidIp() {
|
||||
$server = &new Server();
|
||||
$this->assert(
|
||||
new ValidIp(),
|
||||
$server->getIp(),
|
||||
'Server IP address->%s');
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
This is a little untidy compared with our usual
|
||||
<code>assert...()</code> syntax.
|
||||
</p>
|
||||
<p>
|
||||
For such a simple case we would normally create a
|
||||
separate assertion method on our test case rather
|
||||
than bother using the expectation class.
|
||||
If we pretend that our expectation is a little more
|
||||
complicated for a moment, so that we want to reuse it,
|
||||
we get...
|
||||
<php><![CDATA[
|
||||
class TestOfNetworking extends UnitTestCase {
|
||||
...<strong>
|
||||
function assertValidIp($ip, $message = '%s') {
|
||||
$this->assert(new ValidIp(), $ip, $message);
|
||||
}</strong>
|
||||
|
||||
function testGetValidIp() {
|
||||
$server = &new Server();<strong>
|
||||
$this->assertValidIp(
|
||||
$server->getIp(),
|
||||
'Server IP address->%s');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
It is unlikely we would ever need this degree of control
|
||||
over the testing machinery.
|
||||
It is rare to need the expectations for more than pattern
|
||||
matching.
|
||||
Also, complex expectation classes could make the tests
|
||||
harder to read and debug.
|
||||
These mechanisms are really of most use to authors of systems
|
||||
that will extend the test framework to create their own tool set.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Using expectations for
|
||||
<a href="#mock">more precise testing with mock objects</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#behaviour">Changing mock object behaviour</a> with expectations
|
||||
</link>
|
||||
<link>
|
||||
<a href="#extending">Extending the expectations</a>
|
||||
</link>
|
||||
<link>
|
||||
Underneath SimpleTest <a href="#unit">uses expectation classes</a>
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
The expectations mimic the constraints in <a href="http://www.jmock.org/">JMock</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">Full API for SimpleTest</a>
|
||||
from the PHPDoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
mock objects,
|
||||
test driven development,
|
||||
inheritance of expectations,
|
||||
mock object constraints,
|
||||
advanced PHP unit testing,
|
||||
test first,
|
||||
test framework architecture
|
||||
expectations in simpletest
|
||||
test cases
|
||||
server stubs
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,458 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Creating a new test case" here="PHP unit testing">
|
||||
<long_title>PHP unit testing tutorial - Creating an example test case in PHP</long_title>
|
||||
<content>
|
||||
<p>
|
||||
If you are new to unit testing it is recommended that you
|
||||
actually try the code out as we go.
|
||||
There is actually not very much to type and you will get
|
||||
a feel for the rhythm of test first programming.
|
||||
</p>
|
||||
<p>
|
||||
To run the examples as is, you need an empty directory with the folders
|
||||
<em>classes</em>, <em>tests</em> and <em>temp</em>.
|
||||
Unpack the <a href="simple_test.php">SimpleTest</a> framework
|
||||
into the <em>tests</em> folder and make sure your web server
|
||||
can reach these locations.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="new"><h2>A new test case</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
The quick <a local="{{simple_test}}">introductory example</a>
|
||||
featured the unit testing of a simple log class.
|
||||
In this tutorial on Simple Test I am going to try to
|
||||
tell the whole story of developing this class.
|
||||
This PHP class is small and simple and in the course of
|
||||
this introduction will receive far more attention than
|
||||
it probably would in production.
|
||||
Yet even this tiny class contains some surprisingly difficult
|
||||
design decisions.
|
||||
</p>
|
||||
<p>
|
||||
Maybe they are too difficult?
|
||||
Rather than trying to design the whole thing up front
|
||||
I'll start with a known requirement, namely
|
||||
we want to write messages to a file.
|
||||
These messages must be appended to the file if it exists.
|
||||
Later we will want priorities and filters and things, but
|
||||
for now we will place the file writing requirement in
|
||||
the forefront of our thoughts.
|
||||
We will think of nothing else for fear of getting confused.
|
||||
OK, let's make a test...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase();
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
}
|
||||
}
|
||||
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
]]></php>
|
||||
Piece by piece here is what it all means.
|
||||
</p>
|
||||
<p>
|
||||
The <code>SIMPLE_TEST</code> constant
|
||||
is the path from this file to the Simple Test classes.
|
||||
The classes could be placed into the path in the
|
||||
<em>php.ini</em> file, but if you are using a shared
|
||||
hosting account you do not have access to this.
|
||||
To keep everybody happy this path is declared explicitely
|
||||
in the test script.
|
||||
Later we will see how it eventually ends up in only one
|
||||
place.
|
||||
</p>
|
||||
<p>
|
||||
Requiring the <em>unit_tester.php</em> library is pretty
|
||||
clear, but what is this <em>reporter.php</em>
|
||||
file?
|
||||
The Simple Test libraries are a toolkit for creating
|
||||
your own standardised test suite.
|
||||
They can be used "as is" without trouble, but consist
|
||||
of separate components that have to be assembled.
|
||||
<em>reporter.php</em> has a display component.
|
||||
It is probable that you will eventually write your own
|
||||
and so including the default set is optional.
|
||||
Simple test includes a usable, but basic, test display class
|
||||
called <code>HtmlReporter</code>.
|
||||
It can record test starts, ends, errors, passes and fails.
|
||||
It displays this information as quickly as possible in case
|
||||
the test code crashes the script and obscures the point of
|
||||
failure.
|
||||
</p>
|
||||
<p>
|
||||
The tests themselves are gathered in test case classes.
|
||||
This one is typical in extending
|
||||
<code>UnitTestCase</code>.
|
||||
When the test is run it will search for any method within
|
||||
that starts with the name "test" and run it.
|
||||
Our only test method at present is called
|
||||
<code>testCreatingNewFile()</code>.
|
||||
There is nothing in it yet.
|
||||
</p>
|
||||
<p>
|
||||
Now the empty method definition on its own does not do anything.
|
||||
We need to actually place some code inside it.
|
||||
The <code>UnitTestCase</code> class
|
||||
will typically generate test events when run and these events are
|
||||
sent to an observer.
|
||||
The <code>UnitTestCase::run()</code>
|
||||
method runs all of the tests in the class.
|
||||
</p>
|
||||
<p>
|
||||
Now to add test code...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');<strong>
|
||||
require_once('../classes/log.php');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase();
|
||||
}
|
||||
function testCreatingNewFile() {<strong>
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'));</strong>
|
||||
}
|
||||
}
|
||||
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
You are probably thinking that that is a lot of test code for
|
||||
just one test and I would agree.
|
||||
Don't worry.
|
||||
This is a fixed cost and from now on we can add tests
|
||||
pretty much as one liners.
|
||||
Even less when using some of the test artifacts that we
|
||||
will use later.
|
||||
</p>
|
||||
<p>
|
||||
Now comes the first of our decisions.
|
||||
Our test file is called <em>log_test.php</em> (any name
|
||||
is fine) and is in a folder called <em>tests</em> (anywhere is fine).
|
||||
We have called our code file <em>log.php</em> and this is
|
||||
the code we are going to test.
|
||||
I have placed it into a folder called <em>classes</em>, so that means
|
||||
we are building a class, yes?
|
||||
</p>
|
||||
<p>
|
||||
For this example I am, but the unit tester is not restricted
|
||||
to testing classes.
|
||||
It is just that object oriented code is easier to break
|
||||
down and redesign for testing.
|
||||
It is no accident that the fine grain testing style of unit
|
||||
tests has arisen from the object community.
|
||||
</p>
|
||||
<p>
|
||||
The test itself is minimal.
|
||||
It first deletes any previous test file that may have
|
||||
been left lying around.
|
||||
Design decisions now come in thick and fast.
|
||||
Our class is called <code>Log</code>
|
||||
and takes the file path in the constructor.
|
||||
We create a log and immediately send a message to
|
||||
it using a method named
|
||||
<code>message()</code>.
|
||||
Sadly, original naming is not a desirable characteristic
|
||||
of a software developer.
|
||||
</p>
|
||||
<p>
|
||||
The smallest unit of a...er...unit test is the assertion.
|
||||
Here we want to assert that the log file we just sent
|
||||
a message to was indeed created.
|
||||
<code>UnitTestCase::assertTrue()</code>
|
||||
will send a pass event if the condition evaluates to
|
||||
true and a fail event otherwise.
|
||||
We can have a variety of different assertions and even more
|
||||
if we extend our base test cases.
|
||||
Here is the base list...
|
||||
<table><tbody>
|
||||
<tr><td><code>assertTrue(\$x)</code></td><td>Fail if \$x is false</td></tr>
|
||||
<tr><td><code>assertFalse(\$x)</code></td><td>Fail if \$x is true</td></tr>
|
||||
<tr><td><code>assertNull(\$x)</code></td><td>Fail if \$x is set</td></tr>
|
||||
<tr><td><code>assertNotNull(\$x)</code></td><td>Fail if \$x not set</td></tr>
|
||||
<tr><td><code>assertIsA(\$x, \$t)</code></td><td>Fail if \$x is not the class or type \$t</td></tr>
|
||||
<tr><td><code>assertEqual(\$x, \$y)</code></td><td>Fail if \$x == \$y is false</td></tr>
|
||||
<tr><td><code>assertNotEqual(\$x, \$y)</code></td><td>Fail if \$x == \$y is true</td></tr>
|
||||
<tr><td><code>assertIdentical(\$x, \$y)</code></td><td>Fail if \$x === \$y is false</td></tr>
|
||||
<tr><td><code>assertNotIdentical(\$x, \$y)</code></td><td>Fail if \$x === \$y is true</td></tr>
|
||||
<tr><td><code>assertReference(\$x, \$y)</code></td><td>Fail unless \$x and \$y are the same variable</td></tr>
|
||||
<tr><td><code>assertCopy(\$x, \$y)</code></td><td>Fail if \$x and \$y are the same variable</td></tr>
|
||||
<tr><td><code>assertWantedPattern(\$p, \$x)</code></td><td>Fail unless the regex \$p matches \$x</td></tr>
|
||||
<tr><td><code>assertNoUnwantedPattern(\$p, \$x)</code></td><td>Fail if the regex \$p matches \$x</td></tr>
|
||||
<tr><td><code>assertNoErrors()</code></td><td>Fail if any PHP error occoured</td></tr>
|
||||
<tr><td><code>assertError(\$x)</code></td><td>Fail if no PHP error or incorrect message</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
<p>
|
||||
We are now ready to execute our test script by pointing the
|
||||
browser at it.
|
||||
What happens?
|
||||
It should crash...
|
||||
<div class="demo">
|
||||
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
|
||||
</div>
|
||||
The reason is that we have not yet created <em>log.php</em>.
|
||||
</p>
|
||||
<p>
|
||||
Hang on, that's silly!
|
||||
You aren't going to build a test without creating any of the
|
||||
code you are testing, surely...?
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="tdd"><h2>Test Driven Development</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Co-inventor of
|
||||
<a href="http://www.extremeprogramming.org/">Extreme Programming</a>,
|
||||
Kent Beck, has come up with another manifesto.
|
||||
The book is called
|
||||
<a href="http://www.amazon.com/exec/obidos/tg/detail/-/0321146530/ref=lib_dp_TFCV/102-2696523-7458519?v=glance&s=books&vi=reader#reader-link">Test driven development</a>
|
||||
or TDD and raises unit testing to a senior position in design.
|
||||
In a nutshell you write a small test first and
|
||||
then only get this passing by writing code.
|
||||
Any code.
|
||||
Just get it working.
|
||||
</p>
|
||||
<p>
|
||||
You write another test and get that passing.
|
||||
What you will now have is some duplication and generally lousy
|
||||
code.
|
||||
You re-arrange
|
||||
(refactor)
|
||||
that code while the tests are passing and thus while you cannot break
|
||||
anything.
|
||||
Once the code is as clean as possible you are ready to add more
|
||||
functionality.
|
||||
In turn you only achieve this by adding another test and starting the
|
||||
cycle again.
|
||||
</p>
|
||||
<p>
|
||||
This is a radical approach and one that I feel is incomplete.
|
||||
However it makes for a great way to explain a unit tester!
|
||||
We happen to have a failing, not to say crashing, test right now so
|
||||
let's write some code into <em>log.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
|
||||
class Log {
|
||||
|
||||
function Log($file_path) {
|
||||
}
|
||||
|
||||
function message($message) {
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
This is the minimum to avoid a PHP fatal error.
|
||||
We now get the respones...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->True assertion failed.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
And "testoflogging" has failed.
|
||||
PHP has this really annoying effect of reducing class and method
|
||||
names to lower case internally.
|
||||
SimpleTest uses these names by default to describe the tests, but
|
||||
we can replace them with our own...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {<strong>
|
||||
$this->UnitTestCase('Log class test');</strong>
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Should write this to a file');<strong>
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Giving...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->File created.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
There is not much we can do about the method name I am afraid.
|
||||
</p>
|
||||
<p>
|
||||
Test messages like this are a bit like code comments.
|
||||
Some organisations insist on them while others ban them as clutter
|
||||
and a waste of good typing.
|
||||
I am somewhere in the middle.
|
||||
</p>
|
||||
<p>
|
||||
To get the test passing we could just create the file in the
|
||||
<code>Log</code> constructor.
|
||||
This "faking it" technique is very useful for checking
|
||||
that your tests work when the going gets tough.
|
||||
This is especially so if you have had a run of test failures
|
||||
and just want to confirm that you haven't just missed something
|
||||
stupid.
|
||||
We are not going that slow, so...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class Log {<strong>
|
||||
var $_file_path;</strong>
|
||||
|
||||
function Log($file_path) {<strong>
|
||||
$this->_file_path = $file_path;</strong>
|
||||
}
|
||||
|
||||
function message($message) {<strong>
|
||||
$file = fopen($this->_file_path, 'a');
|
||||
fwrite($file, $message . "\n");
|
||||
fclose($file);</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
It took me no less than four failures to get to the next step.
|
||||
I had not created the temporary directory, I had not made it
|
||||
publicly writeable, I had one typo and I did not check in the
|
||||
new directory to CVS.
|
||||
Any one of these could have kept me busy for several hours if
|
||||
they had come to light later, but then that is what testing is for.
|
||||
With the necessary fixes we get...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Success!
|
||||
</p>
|
||||
<p>
|
||||
You may not like the rather minimal style of the display.
|
||||
Passes are not shown by default because generally you do
|
||||
not need more information when you actually understand what is
|
||||
going on.
|
||||
If you do not know what is going on then you should write another test.
|
||||
</p>
|
||||
<p>
|
||||
OK, this is a little strict.
|
||||
If you want to see the passes as well then you
|
||||
<a local="display_subclass_tutorial">can subclass the
|
||||
<code>HtmlReporter</code> class</a>
|
||||
and attach that to the test instead.
|
||||
Even I like the comfort factor sometimes.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="doc"><h2>Tests as Documentation</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
There is a subtlety here.
|
||||
We don't want the file created until we actually send
|
||||
a message.
|
||||
Rather than think about this too deeply we will just add
|
||||
another test for it...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');<strong>
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'No file created before first message');</strong>
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
...and find it already works...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>2</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Actually I knew it would.
|
||||
I am putting this test in to confirm this partly for peace of mind, but
|
||||
also to document the behaviour.
|
||||
That little extra test line says more in this context than
|
||||
a dozen lines of use case or a whole UML activity diagram.
|
||||
That the test suite acts as a source of documentation is a pleasant
|
||||
side effect of all these tests.
|
||||
</p>
|
||||
<p>
|
||||
Should we clean up the temporary file at the end of the test?
|
||||
I usually do this once I am finished with a test method
|
||||
and it is working.
|
||||
I don't want to check in code that leaves remnants of
|
||||
test files lying around after a test.
|
||||
I don't do it while I am writing the code, though.
|
||||
I probably should, but sometimes I need to see what is
|
||||
going on and there is that comfort thing again.
|
||||
</p>
|
||||
<p>
|
||||
In a real life project we usually have more than one test case,
|
||||
so we next have to look at
|
||||
<a local="group_test_tutorial">grouping tests into test suites</a>.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>Creating a <a href="#new">new test case</a>.</link>
|
||||
<link><a href="#tdd">Test driven development</a> in PHP.</link>
|
||||
<link><a href="#doc">Tests as documentation</a> is one of many side effects.</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
The <a href="http://junit.sourceforge.net/doc/faq/faq.htm">JUnit FAQ</a>
|
||||
has plenty of useful testing advice.
|
||||
</link>
|
||||
<link>
|
||||
<a href="group_test_tutorial.php">Next</a> is grouping test
|
||||
cases together.
|
||||
</link>
|
||||
<link>
|
||||
You will need the <a href="simple_test.php">SimpleTest testing framework</a>
|
||||
for these examples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php testing,
|
||||
unit test,
|
||||
automated php testing,
|
||||
test cases tutorial,
|
||||
explain unit test case,
|
||||
unit test example,
|
||||
unit test
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,254 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Form testing documentation" here="Testing forms">
|
||||
<long_title>Simple Test documentation for testing HTML forms</long_title>
|
||||
<content>
|
||||
<section name="submit" title="Submitting a simple form">
|
||||
<p>
|
||||
When a page is fetched by the <code>WebTestCase</code>
|
||||
using <code>get()</code> or
|
||||
<code>post()</code> 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...
|
||||
<pre><![CDATA[
|
||||
<form>
|
||||
<input type="text" name="a" value="A default" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
]]></pre>
|
||||
Which looks like this...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<input type="text" name="a" value="A default" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
We can navigate to this code, via the
|
||||
<a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>
|
||||
site, with the following test...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
<strong>
|
||||
function testDefaultValue() {
|
||||
$this->get('http://www.lastcraft.com/form_testing_documentation.php');
|
||||
$this->assertField('a', 'A default');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Immediately after loading the page all of the HTML controls are set at
|
||||
their default values just as they would appear in the web browser.
|
||||
The assertion tests that a HTML widget exists in the page with the
|
||||
name "a" and that it is currently set to the value
|
||||
"A default".
|
||||
As usual, we could use a pattern expectation instead if a fixed
|
||||
string.
|
||||
</p>
|
||||
<p>
|
||||
We could submit the form straight away, but first we'll change
|
||||
the value of the text field and only then submit it...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
|
||||
function testDefaultValue() {
|
||||
$this->get('http://www.my-site.com/');
|
||||
$this->assertField('a', 'A default');<strong>
|
||||
$this->setField('a', 'New value');
|
||||
$this->click('Go');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Because we didn't specify a method attribute on the form tag, and
|
||||
didn't specify an action either, the test case will follow
|
||||
the usual browser behaviour of submitting the form data as a <em>GET</em>
|
||||
request back to the same location.
|
||||
SimpleTest tries to emulate typical browser behaviour as much as possible,
|
||||
rather than attempting to catch missing attributes on tags.
|
||||
This is because the target of the testing framework is the PHP application
|
||||
logic, not syntax or other errors in the HTML code.
|
||||
For HTML errors, other tools such as
|
||||
<a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> should be used.
|
||||
</p>
|
||||
<p>
|
||||
If a field is not present in any form, or if an option is unavailable,
|
||||
then <code>WebTestCase::setField()</code> will return
|
||||
<code>false</code>.
|
||||
For example, suppose we wish to verify that a "Superuser"
|
||||
option is not present in this form...
|
||||
<pre><![CDATA[
|
||||
<strong>Select type of user to add:</strong>
|
||||
<select name="type">
|
||||
<option>Subscriber</option>
|
||||
<option>Author</option>
|
||||
<option>Administrator</option>
|
||||
</select>
|
||||
]]></pre>
|
||||
Which looks like...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<strong>Select type of user to add:</strong>
|
||||
<select name="type">
|
||||
<option>Subscriber</option>
|
||||
<option>Author</option>
|
||||
<option>Administrator</option>
|
||||
</select>
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
The following test will confirm it...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...
|
||||
function testNoSuperuserChoiceAvailable() {<strong>
|
||||
$this->get('http://www.lastcraft.com/form_testing_documentation.php');
|
||||
$this->assertFalse($this->setField('type', 'Superuser'));</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The selection will not be changed on a failure to set
|
||||
a widget value.
|
||||
</p>
|
||||
<p>
|
||||
Here is the full list of widgets currently supported...
|
||||
<ul>
|
||||
<li>Text fields, including hidden and password fields.</li>
|
||||
<li>Submit buttons including the button tag, although not yet reset buttons</li>
|
||||
<li>Text area. This includes text wrapping behaviour.</li>
|
||||
<li>Checkboxes, including multiple checkboxes in the same form.</li>
|
||||
<li>Drop down selections, including multiple selects.</li>
|
||||
<li>Radio buttons.</li>
|
||||
<li>Images.</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Although most standard HTML widgets are catered for by <em>SimpleTest</em>'s
|
||||
built in parser, it is unlikely that JavaScript will be implemented
|
||||
anytime soon.
|
||||
</p>
|
||||
</section>
|
||||
<section name="multiple" title="Fields with multiple values">
|
||||
<p>
|
||||
SimpleTest can cope with two types of multivalue controls: Multiple
|
||||
selection drop downs, and multiple checkboxes with the same name
|
||||
within a form.
|
||||
The multivalue nature of these means that setting and testing
|
||||
are slightly different.
|
||||
Using checkboxes as an example...
|
||||
<pre><![CDATA[
|
||||
<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>
|
||||
]]></pre>
|
||||
Which renders as...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<strong>Create privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="c" checked=""/><br/>
|
||||
<strong>Retrieve privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="r" checked=""/><br/>
|
||||
<strong>Update privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="u" checked=""/><br/>
|
||||
<strong>Destroy privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="d" checked=""/><br/>
|
||||
<input type="submit" value="Enable Privileges"/>
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
If we wish to disable all but the retrieval privileges and
|
||||
submit this information we can do it like this...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...<strong>
|
||||
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');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Instead of setting the field to a single value, we give it a list
|
||||
of values.
|
||||
We do the same when testing expected values.
|
||||
We can then write other test code to confirm the effect of this, perhaps
|
||||
by logging in as that user and attempting an update.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="raw"><h2>Raw posting</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
If you want to test a form handler, but have not yet written
|
||||
or do not have access to the form itself, you can create a
|
||||
form submission by hand.
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...<strong>
|
||||
function testAttemptedHack() {
|
||||
$this->post(
|
||||
'http://www.my-site.com/add_user.php',
|
||||
array('type' => 'superuser'));
|
||||
$this->assertNoText('user created');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
By adding data to the <code>WebTestCase::post()</code>
|
||||
method, we are attempting to fetch the page as a form submission.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Changing form values and successfully
|
||||
<a href="#submit">Submitting a simple form</a>
|
||||
</link>
|
||||
<link>
|
||||
Handling <a href="#multiple">widgets with multiple values</a>
|
||||
by setting lists.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#raw">Raw posting</a> when you don't have a button
|
||||
to click.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
The <a href="http://simpletest.sourceforge.net/">developer's API for SimpleTest</a>
|
||||
gives full detail on the classes and assertions available.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming for clients,
|
||||
customer focused php,
|
||||
software development tools,
|
||||
acceptance testing framework,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
php testing,
|
||||
unit test resource,
|
||||
web testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,299 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Taking control of testing" here="Taking control">
|
||||
<long_title>PHP unit testing tutorial - Isolating variables when testing</long_title>
|
||||
<content>
|
||||
<p>
|
||||
In order to test a code module you need very tight control
|
||||
of its environment.
|
||||
If anything can vary behind the scenes, for example a
|
||||
configuration file, then this could cause the tests
|
||||
to fail unexpectedly.
|
||||
This would not be a fair test of the code and could
|
||||
cause you to spend fruitless hours examining code that
|
||||
is actually working, rather than dealing with the configuration issue
|
||||
that actually failed the test.
|
||||
At the very least your test cases get more complicated in
|
||||
taking account the possible variations.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="time"><h2>Controlling time</h2></a>
|
||||
<p>
|
||||
</p>
|
||||
There are often a lot of obvious variables that could affect
|
||||
a unit test case, especially in the web development
|
||||
environment in which PHP usually operates.
|
||||
These include database set up, file permissions, network
|
||||
resources and configuration amongst others.
|
||||
The failure or misinstall of one of these components will
|
||||
break the test suite.
|
||||
Do we add tests to confirm these components are installed?
|
||||
This is a good idea, but if you place them into code module
|
||||
tests you will start to clutter you test code with detail
|
||||
that is irrelavent to the immediate task.
|
||||
They should be placed in their own test group.
|
||||
</p>
|
||||
<p>
|
||||
Another problem, though, is that our development machines
|
||||
must have every system component installed to be able
|
||||
to run the test suite.
|
||||
Your tests run slower too.
|
||||
</p>
|
||||
<p>
|
||||
When faced with this while coding we will often create wrapper
|
||||
versions of classes that deal with these resources.
|
||||
Ugly details of these resources are then coded once only.
|
||||
I like to call these classes "boundary classes"
|
||||
as they exist at the edges of the application,
|
||||
the interface of your application with the rest of the
|
||||
system.
|
||||
These boundary classes are best simulated during testing
|
||||
by simulated versions.
|
||||
These run faster as well and are often called
|
||||
"Server Stubs" or in more generic form
|
||||
"Mock Objects".
|
||||
It is a great time saver to wrap and stub out every such resource.
|
||||
</p>
|
||||
<p>
|
||||
One often neglected factor is time.
|
||||
For example, to test a session time-out coders will often
|
||||
temporarily set the session time limit to a small value, say two seconds,
|
||||
and then do a <code>sleep(3)</code>
|
||||
and assert that the session is now invalid.
|
||||
That adds three seconds to your test suite and is usually
|
||||
a lot of extra code making your session classes that maleable.
|
||||
Far simpler is to have a way to suddenly advance the clock.
|
||||
To control time.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="clock"><h2>A clock class</h2></a>
|
||||
Again we will design our clock wrapper by writing tests.
|
||||
Firstly we add a clock test case to our <em>tests/all_tests.php</em>
|
||||
test suite...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
require_once('log_test.php');<strong>
|
||||
require_once('clock_test.php');</strong>
|
||||
|
||||
$test = &new TestSuite('All tests');
|
||||
$test->addTestCase(new TestOfLogging());<strong>
|
||||
$test->addTestCase(new TestOfClock());</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Then we create the test case in the new file
|
||||
<em>tests/clock_test.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('../classes/clock.php');
|
||||
|
||||
class TestOfClock extends UnitTestCase {
|
||||
function TestOfClock() {
|
||||
$this->UnitTestCase('Clock class test');
|
||||
}
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertEqual($clock->now(), time(), 'Now is the right time');
|
||||
}
|
||||
function testClockAdvance() {
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Our only test at the moment is that our new
|
||||
<code>Clock</code> class acts
|
||||
as a simple PHP <code>time()</code>
|
||||
function substitute.
|
||||
The other method is a place holder.
|
||||
It's our <em>TODO</em> item if you like.
|
||||
We haven't done a test for it yet because that
|
||||
would spoil our rhythm.
|
||||
We will write the time shift functionality once we are green.
|
||||
At the moment we are obviously not green...
|
||||
<div class="demo">
|
||||
<br />
|
||||
<b>Fatal error</b>: Failed opening required '../classes/clock.php' (include_path='') in
|
||||
<b>/home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php</b> on line <b>2</b>
|
||||
<br />
|
||||
</div>
|
||||
We create a <em>classes/clock.php</em> file like so...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
class Clock {
|
||||
|
||||
function Clock() {
|
||||
}
|
||||
|
||||
function now() {
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
This regains our flow ready for coding.
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="fail">Fail</span>: Clock class test->testclocktellstime->[NULL: ] should be equal to [integer: 1050257362]<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">3/3 test cases complete.
|
||||
<strong>4</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
This is now easy to fix...
|
||||
<php><![CDATA[
|
||||
class Clock {
|
||||
|
||||
function Clock() {
|
||||
}
|
||||
|
||||
function now() {<strong>
|
||||
return time();</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
And now we are green...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>5</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
There is still a problem.
|
||||
The clock could roll over during the assertion causing the
|
||||
result to be out by one second.
|
||||
The chances are small, but if there were a lot of timing tests
|
||||
you would end up with a test suite that is erratic, severely
|
||||
limiting its usefulness.
|
||||
We will <a href="subclass_tutorial.php">tackle this shortly</a> and for now just jot it onto our
|
||||
"to do" list.
|
||||
</p>
|
||||
<p>
|
||||
The advancement test looks like this...
|
||||
<php><![CDATA[
|
||||
class TestOfClock extends UnitTestCase {
|
||||
function TestOfClock() {
|
||||
$this->UnitTestCase('Clock class test');
|
||||
}
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertEqual($clock->now(), time(), 'Now is the right time');
|
||||
}<strong>
|
||||
function testClockAdvance() {
|
||||
$clock = new Clock();
|
||||
$clock->advance(10);
|
||||
$this->assertEqual($clock->now(), time() + 10, 'Advancement');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
The code to get to green is straight forward and just involves adding
|
||||
a time offset.
|
||||
<php><![CDATA[
|
||||
class Clock {<strong>
|
||||
var $_offset;</strong>
|
||||
|
||||
function Clock() {<strong>
|
||||
$this->_offset = 0;</strong>
|
||||
}
|
||||
|
||||
function now() {
|
||||
return time()<strong> + $this->_offset</strong>;
|
||||
}
|
||||
<strong>
|
||||
function advance($offset) {
|
||||
$this->_offset += $offset;
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="tidy"><h2>Group test tidy up</h2></a>
|
||||
Our <em>all_tests.php</em> file has some repetition we could
|
||||
do without.
|
||||
We have to manually add our test cases from each included
|
||||
file.
|
||||
It is possible to remove it, but use of the following requires care.
|
||||
The <code>TestSuite</code> class has a
|
||||
convenience method called <code>addTestFile()</code>
|
||||
that takes a PHP file as a parameter.
|
||||
This mechanism makes a note of all the classes, requires in the
|
||||
file and then has a look at any newly created classes.
|
||||
If they are descendents of <code>TestCase</code>
|
||||
they are added as a new group test.
|
||||
</p>
|
||||
<p>
|
||||
Here is our refactored test suite using this method...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}<strong>
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');</strong>
|
||||
|
||||
$test = &new TestSuite('All tests');<strong>
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->addTestFile('clock_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
The pitfalls of this are...
|
||||
<ol>
|
||||
<li>
|
||||
If the test file has already been included,
|
||||
no new classes will be added to this group
|
||||
</li>
|
||||
<li>
|
||||
If the test file has other classes that are
|
||||
related to <code>TestCase</code>
|
||||
then these will be added to the group test as well.
|
||||
</li>
|
||||
</ol>
|
||||
In our tests we have only test cases in the test files and
|
||||
we removed their inclusion from the <em>all_tests.php</em>
|
||||
script and so we are OK.
|
||||
This is the usual situation.
|
||||
</p>
|
||||
<p>
|
||||
We should really fix the glitch with the possible
|
||||
clock rollover so we'll
|
||||
<a href="subclass_tutorial.php">do this next</a>.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link><a href="#time">Time</a> is an often neglected variable in tests.</link>
|
||||
<link>A <a href="#clock">clock class</a> allows us to alter time.</link>
|
||||
<link><a href="#tidy">Tidying the group test</a>.</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
The previous section is
|
||||
<a href="group_test_tutorial.php">grouping unit tests</a>.
|
||||
</link>
|
||||
<link>
|
||||
The next section is
|
||||
<a href="subclass_tutorial.php">subclassing test cases</a>.
|
||||
</link>
|
||||
<link>
|
||||
You will need
|
||||
<a href="simple_test.php">the SimpleTest unit tester</a>
|
||||
for the examples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php testing,
|
||||
unit test,
|
||||
php testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,330 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Test suite documentation" here="Group tests">
|
||||
<long_title>SimpleTest for PHP test suites</long_title>
|
||||
<content>
|
||||
<section name="group" title="Grouping tests into suites">
|
||||
<p>
|
||||
To run test cases as part of a group, the test cases should really
|
||||
be placed in files without the runner code...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('../classes/io.php');
|
||||
|
||||
class FileTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
|
||||
class SocketTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
As many cases as needed can appear in a single file.
|
||||
They should include any code they need, such as the library
|
||||
being tested, but none of the simple test libraries.
|
||||
</p>
|
||||
<p>
|
||||
If you have extended any test cases, you can include them
|
||||
as well. In PHP 4...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/io.php');
|
||||
<strong>
|
||||
class MyFileTestCase extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
SimpleTest::ignore('MyFileTestCase');</strong>
|
||||
|
||||
class FileTester extends MyFileTestCase { ... }
|
||||
|
||||
class SocketTester extends UnitTestCase { ... }
|
||||
?>
|
||||
]]></php>
|
||||
The <code>FileTester</code> class does
|
||||
not contain any actual tests, but is a base class for other
|
||||
test cases.
|
||||
For this reason we use the
|
||||
<code>SimpleTestOptions::ignore()</code> directive
|
||||
to tell the upcoming group test to ignore it.
|
||||
This directive can appear anywhere in the file and works
|
||||
when a whole file of test cases is loaded (see below).
|
||||
</p>
|
||||
<p>
|
||||
If you are using PHP 5, you do not need this special directive at all.
|
||||
Simply mark any test cases that should not be run as abstract...
|
||||
<php><![CDATA[
|
||||
<strong>abstract</strong> class MyFileTestCase extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
|
||||
class FileTester extends MyFileTestCase { ... }
|
||||
|
||||
class SocketTester extends UnitTestCase { ... }
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
We will call this sample <em>file_test.php</em>.
|
||||
Next we create a group test file, called say <em>my_group_test.php</em>.
|
||||
You will think of a better name I am sure.
|
||||
</p>
|
||||
<p>
|
||||
We will add the test file using a safe method...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('file_test.php');
|
||||
|
||||
$test = &new TestSuite('All file tests');
|
||||
$test->addTestCase(new FileTestCase());
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
This instantiates the test case before the test suite is
|
||||
run.
|
||||
This could get a little expensive with a large number of test
|
||||
cases, and can be surprising behaviour.
|
||||
</p>
|
||||
<p>
|
||||
The main problem is that for every test case
|
||||
that we add we will have
|
||||
to <code>require_once()</code> the test code
|
||||
file and manually instantiate each and every test case.
|
||||
</p>
|
||||
<p>
|
||||
We can save a lot of typing with...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new TestSuite('All file tests');<strong>
|
||||
$test->addTestFile('file_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
What happens here is that the <code>TestSuite</code>
|
||||
class has done the <code>require_once()</code>
|
||||
for us.
|
||||
It then checks to see if any new test case classes
|
||||
have been created by the new file and automatically adds
|
||||
them to the group test.
|
||||
Now all we have to do is add each new file.
|
||||
</p>
|
||||
<p>
|
||||
No only that, but you can guarantee that the constructor is run
|
||||
just before the first test method and, in PHP 5, the destructor
|
||||
is run just after the last test method.
|
||||
</p>
|
||||
<p>
|
||||
There are two things that could go wrong and which require care...
|
||||
<ol>
|
||||
<li>
|
||||
The file could already have been parsed by PHP, and so no
|
||||
new classes will have been added. You should make
|
||||
sure that the test cases are only included in this file
|
||||
and no others.
|
||||
</li>
|
||||
<li>
|
||||
New test case extension classes that get included will be
|
||||
placed in the group test and run also.
|
||||
You will need to add a <code>SimpleTestOptions::ignore()</code>
|
||||
directive for these classes, or make sure that they are included
|
||||
before the <code>TestSuite::addTestFile()</code>
|
||||
line, or make sure that they are abstract classes.
|
||||
</li>
|
||||
</ol>
|
||||
</p>
|
||||
</section>
|
||||
<section name="higher" title="Composite suites">
|
||||
<p>
|
||||
The above method places all of the test cases into one large group.
|
||||
For larger projects though this may not be flexible enough; you
|
||||
may want to group the tests in all sorts of ways.
|
||||
</p>
|
||||
<p>
|
||||
To get a more flexible group test we can subclass
|
||||
<code>TestSuite</code> and then instantiate it as needed...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
<strong>
|
||||
class FileTestSuite extends TestSuite {
|
||||
function FileTestSuite() {
|
||||
$this->TestSuite('All file tests');
|
||||
$this->addTestFile('file_test.php');
|
||||
}
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
This effectively names the test in the constructor and then
|
||||
adds our test cases and a single group below.
|
||||
Of course we can add more than one group at this point.
|
||||
We can now invoke the tests from a separate runner file...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('file_test_suite.php');
|
||||
<strong>
|
||||
$test = &new FileTestSuite();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
...or we can group them into even larger group tests.
|
||||
We can even mix groups and test cases freely as long as
|
||||
we are careful about double includes...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
<strong>
|
||||
$test = &new BigTestSuite('Big group');
|
||||
$test->addTestFile('file_test_suite.php');
|
||||
$test->addTestFile('some_test_case.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
In the event of a double include, ony the first instance
|
||||
of the test case will be run.
|
||||
</p>
|
||||
<p>
|
||||
If we still wish to run the original group test, and we
|
||||
don't want all of these little runner files, we can
|
||||
put the test runner code around guard bars when we create
|
||||
each group.
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class FileTestSuite extends TestSuite {
|
||||
function FileTestSuite() {
|
||||
$this->TestSuite('All file tests');
|
||||
$test->addTestFile('file_test.php');
|
||||
}
|
||||
}
|
||||
<strong>
|
||||
if (! defined('RUNNER')) {
|
||||
define('RUNNER', true);</strong>
|
||||
$test = &new FileTestSuite();
|
||||
$test->run(new HtmlReporter());
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
This approach requires the guard to be set when including
|
||||
the group test file, but this is still less hassle than
|
||||
lots of separate runner files.
|
||||
You include the same guard on the top level tests to make sure
|
||||
that <code>run()</code> will run once only
|
||||
from the top level script that has been invoked.
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
define('RUNNER', true);</strong>
|
||||
require_once('file_test_suite.php');
|
||||
|
||||
$test = &new BigTestSuite('Big group');
|
||||
$test->addTestCase(new FileTestSuite());
|
||||
$test->addTestCase(...);
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
As with the normal test cases, a <code>TestSuite</code> can
|
||||
be loaded with the <code>TestSuite::addTestFile()</code> method.
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
define('RUNNER', true);
|
||||
|
||||
$test = &new BigTestSuite('Big group');<strong>
|
||||
$test->addTestFile('file_test_suite.php');
|
||||
$test->addTestFile(...);</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="legacy" title="Integrating legacy test cases">
|
||||
<p>
|
||||
If you already have unit tests for your code or are extending external
|
||||
classes that have tests, it is unlikely that all of the test cases
|
||||
are in SimpleTest format.
|
||||
Fortunately it is possible to incorporate test cases from other
|
||||
unit testers directly into SimpleTest group tests.
|
||||
</p>
|
||||
<p>
|
||||
Say we have the following
|
||||
<a href="http://sourceforge.net/projects/phpunit">PhpUnit</a>
|
||||
test case in the file <em>config_test.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong>class ConfigFileTest extends TestCase {
|
||||
function ConfigFileTest() {
|
||||
$this->TestCase('Config file test');
|
||||
}
|
||||
|
||||
function testContents() {
|
||||
$config = new ConfigFile('test.conf');
|
||||
$this->assertRegexp('/me/', $config->getValue('username'));
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
The group test can recognise this as long as we include
|
||||
the appropriate adapter class before we add the test
|
||||
file...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('simpletest/adapters/phpunit_test_case.php');</strong>
|
||||
|
||||
$test = &new TestSuite('All file tests');<strong>
|
||||
$test->addTestFile('config_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
There are only two adapters, the other is for the
|
||||
<a href="http://pear.php.net/manual/en/package.php.phpunit.php">PEAR</a>
|
||||
1.0 unit tester...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('simpletest/adapters/pear_test_case.php');</strong>
|
||||
|
||||
$test = &new TestSuite('All file tests');<strong>
|
||||
$test->addTestFile('some_pear_test_cases.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
The PEAR test cases can be freely mixed with SimpleTest
|
||||
ones even in the same test file,
|
||||
but you cannot use SimpleTest assertions in the legacy
|
||||
test case versions.
|
||||
This is done as a check that you are not accidently making
|
||||
your test cases completely dependent on SimpleTest.
|
||||
You may want to do a PEAR release of your library for example,
|
||||
which would mean shipping it with valid PEAR::PhpUnit test
|
||||
cases.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Different ways to <a href="#group">group tests</a> together.
|
||||
</link>
|
||||
<link>
|
||||
Combining group tests into <a href="#higher">larger groups</a>.
|
||||
</link>
|
||||
<link>
|
||||
Integrating <a href="#legacy">legacy test cases</a> from other
|
||||
types of PHPUnit.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
php unit testing, test integration, documentation, marcus baker, simple test,
|
||||
simpletest documentation, phpunit, pear
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,237 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Grouping tests" here="Grouping tests">
|
||||
<long_title>
|
||||
PHP unit testing tutorial - Grouping together unit
|
||||
tests and examples of writing test cases
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Next up we will fill in some blanks and create a test suite.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="another"><h2>Another test</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Adding another test can be as simple as adding another method
|
||||
to a test case...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');<strong>
|
||||
@unlink('../temp/test.log');</strong>
|
||||
}<strong>
|
||||
function testAppendingToFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line 1');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 1/', $messages[0]);
|
||||
$log->message('Test line 2');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 2/', $messages[1]);
|
||||
@unlink('../temp/test.log');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
The <code>assertWantedPattern()</code>
|
||||
test case method uses Perl style regular expressions for
|
||||
matching.
|
||||
</p>
|
||||
<p>
|
||||
All we are doing in this new test method is writing a line to a file and
|
||||
reading it back twice over.
|
||||
We simply want to confirm that the logger appends the
|
||||
text rather than writing over the old file.
|
||||
A little pedantic, but hey, it's a tutorial!
|
||||
</p>
|
||||
<p>
|
||||
In fact this unit test actually passes straight away...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>4</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
The trouble is there is already a lot of repetition here,
|
||||
we have to delete the test file before and after every test.
|
||||
With outrageous plagarism from <a href="http://www.junit.org/">JUnit</a>,
|
||||
SimpleTest has <code>setUp()</code> and
|
||||
<code>tearDown()</code> methods
|
||||
which are run before and after every test respectively.
|
||||
File deletion is common to all the test methods so we
|
||||
should move that operation there.
|
||||
</p>
|
||||
<p>
|
||||
Our tests are green so we can refactor...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}<strong>
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function testCreatingNewFile() {</strong>
|
||||
$log = new Log('../temp/test.log');
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');<strong>
|
||||
}
|
||||
function testAppendingToFile() {</strong>
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line 1');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 1/', $messages[0]);
|
||||
$log->message('Test line 2');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 2/', $messages[1]);<strong>
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
The test stays green.
|
||||
We can add non-test methods to the test case as long as the method
|
||||
name does not start with the string "test".
|
||||
Only the methods that start "test" are run.
|
||||
This allows further optional refactoring...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}<strong>
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}</strong>
|
||||
function testCreatingNewFile() {
|
||||
$log = new Log('../temp/test.log');
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');
|
||||
}
|
||||
function testAppendingToFile() {
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line 1');<strong>
|
||||
$this->assertWantedPattern('/Test line 1/', $this->getFileLine('../temp/test.log', 0));</strong>
|
||||
$log->message('Test line 2');<strong>
|
||||
$this->assertWantedPattern('/Test line 2/', $this->getFileLine('../temp/test.log', 1));</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
It is a matter of taste whether you prefer this version
|
||||
to the previous one. There is a little more code, but
|
||||
the logic of the test is clearer.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="group"><h2>A group test</h2></a>
|
||||
A test case does not function alone for very long.
|
||||
When coding for real we usually want to run as many tests as
|
||||
quickly and as often as we can.
|
||||
This means grouping them together into test suites that
|
||||
could easily include every test in the application.
|
||||
</p>
|
||||
<p>
|
||||
Firstly we have to clean out the test running code from
|
||||
our existing test case...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
...
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
We no longer need the <code>SIMPLE_TEST</code>
|
||||
constant.
|
||||
Next we create a group test called <em>all_tests.php</em>
|
||||
in the <em>tests</em> folder...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
require_once('log_test.php');
|
||||
|
||||
$test = &new GroupTest('All tests');
|
||||
$test->addTestCase(new TestOfLogging());
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
]]></php>
|
||||
We hardly notice the difference when things work...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>4</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Group tests add to the test case count.
|
||||
Adding new test cases is very straight forward.
|
||||
Simply include the test cases file and add any contained test
|
||||
cases individually.
|
||||
You can also nest group tests within other group tests
|
||||
(although you should avoid loops).
|
||||
</p>
|
||||
<p>
|
||||
In the <a href="gain_control_tutorial.php">next page</a>
|
||||
we will add these more quickly.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#another">Adding another test</a> to the test case
|
||||
and refactoring.
|
||||
</link>
|
||||
<link>
|
||||
The crude way to <a href="#group">group unit tests</a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a href="gain_control_tutorial.php">Next</a> is controlling
|
||||
how the class under test interacts with the rest
|
||||
of the system.
|
||||
</link>
|
||||
<link>
|
||||
<a href="first_test_tutorial.php">Previous</a> is the creation
|
||||
of a first test.
|
||||
</link>
|
||||
<link>
|
||||
You need <a href="simple_test.php">SimpleTest</a> to run these examples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming in php,
|
||||
test first,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php testing,
|
||||
unit test,
|
||||
phpunit,
|
||||
PHP unit testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,197 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Top down and test driven" here="Top down testing">
|
||||
<long_title>
|
||||
PHP unit testing tutorial - Top down design
|
||||
test first with mock objects
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
<a class="target" name="mock"><h2>Mock now, code later</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
I lied.
|
||||
</p>
|
||||
<p>
|
||||
I haven't created a writer test at all, only the
|
||||
<code>FileWriter</code> interface that I showed
|
||||
earlier.
|
||||
In fact I'll go one step further away from a finished article and assume
|
||||
only an abstract writer in <em>classes/writer.php</em>...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class <strong>Writer</strong> {
|
||||
|
||||
function <strong>Writer()</strong> {
|
||||
}
|
||||
|
||||
function write($message) {
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
The corresponding test changes are...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');
|
||||
require_once('../classes/writer.php');
|
||||
Mock::generate('Clock');<strong>
|
||||
Mock::generate('Writer');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function testWriting() {
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$writer = &new <strong>MockWriter($this)</strong>;
|
||||
$writer->expectOnce('write', array('[Timestamp] Test line'));
|
||||
$log = &new Log($writer);
|
||||
$log->message('Test line', &$clock);
|
||||
$writer->tally();
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
In order to use the logging class we would need to code a file
|
||||
writer or other sort of writer, but at the moment we are only
|
||||
testing and so we do not yet need it.
|
||||
So, in other words, using mocks we can defer the creation of
|
||||
lower level objects until we feel like it.
|
||||
Not only can we design top down, but we can test top down too.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="bridge"><h2>Approaching the bridge</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Imagine for the moment that we had started the logging class
|
||||
from another direction.
|
||||
Pretend that we had coded just enough of the <code>Log</code>
|
||||
to realise we needed a <code>Writer</code> somehow.
|
||||
How would we have included it?
|
||||
</p>
|
||||
<p>
|
||||
Well, inheriting from the writer would not have allowed us to mock it
|
||||
from the testing point of view.
|
||||
From the design point of view we would have been restricted to
|
||||
just one writer without multiple inheritence.
|
||||
</p>
|
||||
<p>
|
||||
Creating the writer internally, rather than passing it in the constructor,
|
||||
by choosing a class name is possible, but we would have less control
|
||||
of the mock object set up.
|
||||
From the design point of view it would have been nearly impossible
|
||||
to pass parameters to the writer in all the different formats ever needed.
|
||||
You would have to have the writer restricted to say a hash or complicated
|
||||
string describing the target details.
|
||||
Needlessly complicated at best.
|
||||
</p>
|
||||
<p>
|
||||
Using a factory method to create the writer internally would be
|
||||
possible, but would mean subclassing it for testing so that the factory
|
||||
method could be replaced with one returning a mock.
|
||||
More work from the test point of view, although still possible.
|
||||
From the design point of view it would mean a new logger subclass
|
||||
for every type of writer that we want to use.
|
||||
This is called a parallel class hiearchy and obviously involves
|
||||
duplication.
|
||||
Yuk.
|
||||
</p>
|
||||
<p>
|
||||
At the other extreme, passing or creating the writer on every
|
||||
message would have been repetitive and reduced the
|
||||
<code>Log</code> class code to a single
|
||||
method, a sure sign that the whole class has become redundant.
|
||||
</p>
|
||||
<p>
|
||||
This tension between ease of testing and avoiding repetition
|
||||
has allowed us to find a flexible and clean design.
|
||||
Remember our brief yearning for multiple inheritence?
|
||||
We have replaced it with polymorphism (lots of writers) and separated the
|
||||
logging hierachy from the writing hierarchy.
|
||||
We connect the two through this simpler <code>Log</code>
|
||||
by aggregation.
|
||||
This trick is actually a design pattern called a "Bridge".
|
||||
</p>
|
||||
<p>
|
||||
So we have been pushed by test code (we haven't written much else yet)
|
||||
into a design pattern.
|
||||
Think about this for a second.
|
||||
Tests improve code quality, certainly in my case, but this is
|
||||
something far more profound and far more powerful.
|
||||
</p>
|
||||
<p>
|
||||
Testing has improved the design.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="design"><h2>Mock down design</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Creating a mock object is as easy as creating the interface in text
|
||||
form.
|
||||
If you have UML or other tools that create these interfaces for you,
|
||||
then you have an even more flexible route to quickly generate
|
||||
test objects.
|
||||
Even if you do not, you can switch from white board drawing, to
|
||||
writing a test case, to writing a mock, to generating an interface
|
||||
which takes us back to the whiteboard drawing again, fairly easily.
|
||||
Like refactoring, design, code and test become unified.
|
||||
</p>
|
||||
<p>
|
||||
Because mock objects work top down they can be bought into the design
|
||||
more quickly than normal refactoring, which requires at least
|
||||
partially working code before it kicks in.
|
||||
This means that the testing code interacts with the design faster
|
||||
and this means that the design quality goes up sooner.
|
||||
</p>
|
||||
<p>
|
||||
A unit tester is a coding tool.
|
||||
A unit tester with mock objects is a design tool.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#mock">Mock now</a>, code later.
|
||||
</link>
|
||||
<link>
|
||||
We derive <a href="#bridge">the bridge pattern</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#design">Designing and testing</a> hand in hand.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
This tutorial follows <a href="boundary_classes_tutorial.php">Boundary classes</a>.
|
||||
</link>
|
||||
<link>
|
||||
You will need the <a href="simple_test.php">SimpleTest testing framework</a>
|
||||
to try these examples.
|
||||
</link>
|
||||
<link>
|
||||
For more mock object discussion see the
|
||||
<a href="http://www.xpdeveloper.org/xpdwiki/Wiki.jsp?page=MockObjects">Extreme Tuesday Wiki</a>
|
||||
or the
|
||||
<a href="http://c2.com/cgi/wiki?MockObject">C2 Wiki</a>
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming tutorial,
|
||||
programming php test cases,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php code,
|
||||
architecture,
|
||||
php examples,
|
||||
mock object examples,
|
||||
junit style testing,
|
||||
php testing frameworks,
|
||||
unit test,
|
||||
mock objects in PHP,
|
||||
php testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,219 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="The Last Craft?" here="Last Craft">
|
||||
<long_title>
|
||||
The Last Craft? Web developer tutorials on PHP, Extreme programming
|
||||
and Object Oriented development
|
||||
</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
This site focuses mostly on developing with lightweight web technologies such as
|
||||
<a href="http://www.php.net/">PHP</a>,
|
||||
especially when applied with agile methodologies such as
|
||||
<a href="http://www.extremeprogramming.org/">XP</a>.
|
||||
No guarantee of quality is given or even intended.
|
||||
It is hoped only that what you find gives you ideas and enthusiasm
|
||||
from a fellow computer programmer.
|
||||
</p>
|
||||
<p>
|
||||
I've been a little busy of late with children (two versions).
|
||||
They take quite a chunk of your professional life and 100% of
|
||||
what's left!
|
||||
Hopefully the projects below should start to get back on track.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="what" title="Ongoing projects">
|
||||
<p>
|
||||
My latest project is <a href="cgreen.html">Cgreen</a>.
|
||||
It's a C unit tester.
|
||||
There are a couple of C unit testing tools out there already of course.
|
||||
What makes <em>Cgreen</em> different is that it is pure C99, includes
|
||||
a tutorial right here and has facilities for creating mock functions.
|
||||
Mock functions should lead to more decoupled C code if Mock objects are
|
||||
anything to go by.
|
||||
It's alpha status right now until I get feedback from other users.
|
||||
So if you want to be influential, try it out right now.
|
||||
The project has been mostly funded by <a href="http://www.wordtracker.com/">Wordtracker</a>,
|
||||
for which I am very grateful.
|
||||
</p>
|
||||
<p>
|
||||
Along with Jon Ramsey, I am a founder of
|
||||
<a href="http://www.phplondon.org/wiki/">PHP London</a>, a PHP user
|
||||
group not surprisingly based in London.
|
||||
It's going well.
|
||||
The networking meetings take place on the first Thursday of every month
|
||||
at a pub.
|
||||
</p>
|
||||
<p>
|
||||
In addition the group organises other events that include the 2nd
|
||||
<a href="http://phpconference.co.uk/">London UK PHP Conference</a>.
|
||||
This is a one day event on Friday the 23rd of February 2007 and costs only
|
||||
fifty quid.
|
||||
</p>
|
||||
<p>
|
||||
The <a local="simple_test">SimpleTest PHP unit tester</a>
|
||||
is available for download from your nearest
|
||||
<a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
It is a PHP unit test and web test framework.
|
||||
Users of <a href="http://www.junit.org/">JUnit</a> will be
|
||||
familiar with most of the interface.
|
||||
The <a href="http://jwebunit.sourceforge.net/">JWebUnit</a>
|
||||
style functionality is more complete now.
|
||||
It has support for SSL, forms, frames, proxies and basic authentication.
|
||||
The current CVS code should become the 1.0.1 release real soon now and
|
||||
includes file upload and many small improvements.
|
||||
The idea is that common but fiddly PHP tasks, such as logging into a site,
|
||||
can be tested easily.
|
||||
</p>
|
||||
<p>
|
||||
My most neglected project right now is a requirents testing
|
||||
and sign-off tool called
|
||||
<a href="http://sourceforge.net/projects/arbiter">Arbiter</a>.
|
||||
It's actually best described in this
|
||||
<a href="http://www.sitepoint.com/forums/showthread.php?t=193797">Sitepoint thread</a>,
|
||||
but basically think of it as a document driven FIT for small
|
||||
web projects only.
|
||||
The project is currently stalled due the birth of children and
|
||||
writing projects.
|
||||
</p>
|
||||
<p>
|
||||
Also on the subject of open source, <a href="http://www.wordtracker.com/">Wordtracker</a>
|
||||
have kindly agreed to publish some of their in house tools.
|
||||
A Wordtracker spin off is <a local="fakemail">fakeMail</a>.
|
||||
Testing applications that send e-mails can be a right royal pain because
|
||||
of all of the infrastructure involved.
|
||||
You will likely need an SMPT gateway that talks to a POP client that
|
||||
you can read the queue from.
|
||||
That's a lot of set up.
|
||||
<a local="fakemail">Fakemail acts as an SMTP gateway</a> on any port
|
||||
you define.
|
||||
When you send it a mail it simply copies that mail to the local file
|
||||
system in whatever directory you want.
|
||||
You then just have to look at the local file.
|
||||
It means that you must be able to configure your application to use
|
||||
a port other than 25, but that's not usualy difficult.
|
||||
</p>
|
||||
</section>
|
||||
<section name="why" title="Why the Last Craft?">
|
||||
<p>
|
||||
A craft is defined as...
|
||||
<div class="quotation">
|
||||
Art or skill; dexterity in particular manual employment;
|
||||
hence, the occupation or employment itself; manual art; a
|
||||
trade.
|
||||
</div>
|
||||
</p>
|
||||
<p>
|
||||
If you lose a screw or clasp from a hand made jewellery box it is hopeless to
|
||||
try to find a replacement. Nothing else is quite the same and the mechanism will
|
||||
fail to work. It may even cause more damage when applied. You need to find the original maker
|
||||
or someone of the same skill to make you another.
|
||||
Sound like software?
|
||||
Yet mechanical parts today are interchangeable.
|
||||
</p>
|
||||
<p>
|
||||
Writing software has resisted mass production.
|
||||
As soon as a part of it becomes
|
||||
routine it can be automated.
|
||||
Once it is you don't need a programmer any more.
|
||||
Routine programming jobs no longer exist.
|
||||
All that is left is the unsolved problems that require
|
||||
a higher level of skill in constructing their solutions.
|
||||
</p>
|
||||
<p>
|
||||
This dependency on the ability of the artisan, combined with nothing quite fitting
|
||||
together properly, is what gives software the pre-industrial feel.
|
||||
</p>
|
||||
</section>
|
||||
<section name="crc" title="The cards?">
|
||||
<p>
|
||||
The panel at the top is supposed to resemble a standard office index card.
|
||||
The way it is marked out is called a
|
||||
<a href="http://www.c2.com/doc/crc/draw.html">CRC card</a>.
|
||||
It stands for Classes, Responsibilities and
|
||||
Collaborations and is the cheapest software development tool you
|
||||
can find.
|
||||
You really do buy a pack of cards.
|
||||
<p>
|
||||
</p>
|
||||
The role is written at the top and would often be just a class
|
||||
name.
|
||||
The left side is the object's responsibilities and on the
|
||||
right collaborations (within the page I have treated these as
|
||||
internal links and external links repectively).
|
||||
A group of developers can point at, discuss and discard cards
|
||||
in the heat of design session.
|
||||
It makes it especially difficult for only one person to take charge
|
||||
of a discussion in the way you can with a UML tool or notepad.
|
||||
Try scribbling out five cards before someone gets a look in.
|
||||
</p>
|
||||
<p>
|
||||
Now nothing beats a whiteboard for collaboration, but if the level
|
||||
of detail is getting too high and you want a temporary record,
|
||||
give the CRC cards a try.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#what">Projects</a> under development.
|
||||
All free and open source software.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#why">Why Last Craft?</a>
|
||||
Odd name isn't it?
|
||||
</link>
|
||||
<link>
|
||||
<a href="#crc">Why this index card</a> at the top?
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a local="simple_test">SimpleTest</a> is a PHP unit test framework.
|
||||
</link>
|
||||
<link>
|
||||
My article on <a href="http://www.developerspot.com/tutorials/php/test-driven-development/page1.html">TDD</a>
|
||||
</link>
|
||||
<link>
|
||||
My article on the
|
||||
<a href="http://www.phppatterns.com/index.php/article/articleview/75/1/1/">Registry Pattern</a>.
|
||||
</link>
|
||||
<link>
|
||||
Site E-mail is
|
||||
<a href="http://spamcop.net">SpamCop</a>
|
||||
filtered which I cannot recommend enough.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
computer programmer,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
software development company,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
bespoke software development uk,
|
||||
corporate web development,
|
||||
architecture,
|
||||
php resources,
|
||||
wordtracker,
|
||||
xslt,
|
||||
java,
|
||||
bug tracker,
|
||||
bug reporting,
|
||||
unit test,
|
||||
php testing,
|
||||
test cases tutorial,
|
||||
explain unit test case,
|
||||
unit test example,
|
||||
xml
|
||||
</keywords>
|
||||
<description>
|
||||
A web site of software development tutorials and examples with an
|
||||
emphasis on web programming, testing, agile methodology and PHP
|
||||
development
|
||||
</description>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,54 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Introduction to SimpleTest" here="English version">
|
||||
<long_title>
|
||||
The Last Craft? Web developer tutorials on PHP, Extreme programming
|
||||
and Object Oriented development
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
The <a local="simple_test">SimpleTest PHP unit tester</a> is in
|
||||
the 1.0.1 release cycle and is available for download from your nearest <a
|
||||
href="http://souceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</p>
|
||||
<p>
|
||||
It is a PHP unit test, mock objects and web test framework.
|
||||
Users of <a href="http://www.junit.org/">JUnit</a> will be
|
||||
familiar with most of the interface.
|
||||
<a href="http://jwebunit.sourceforge.net/">JWebUnit</a>
|
||||
style functionality is more complete now.
|
||||
It has support for SSL, frames, proxies, basic authentication and the
|
||||
standard HTML controls.
|
||||
The idea is that common but fiddly PHP tasks, such as logging into a site,
|
||||
can be tested easily.
|
||||
</p>
|
||||
<p>
|
||||
There is currently no support for JavaScript in the web tester.
|
||||
For testing these elements we recommend
|
||||
<a href="http://www.edwardh.com/jsunit/">JSUnit</a>
|
||||
or
|
||||
<a href="http://selenium.thoughtworks.com/index.html">Selenium</a>.
|
||||
</p>
|
||||
</content>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
computer programmer,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
software development company,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
bespoke software development uk,
|
||||
corporate web development,
|
||||
architecture,
|
||||
php resources,
|
||||
unit test,
|
||||
php testing,
|
||||
test cases tutorial,
|
||||
explain unit test case,
|
||||
unit test example,
|
||||
xml
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,698 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Mock objects documentation" here="Mock objects">
|
||||
<long_title>SimpleTest for PHP mock objects documentation</long_title>
|
||||
<content>
|
||||
<section name="what" title="What are mock objects?">
|
||||
<p>
|
||||
Mock objects have two roles during a test case: actor and critic.
|
||||
</p>
|
||||
<p>
|
||||
The actor behaviour is to simulate objects that are difficult to
|
||||
set up or time consuming to set up for a test.
|
||||
The classic example is a database connection.
|
||||
Setting up a test database at the start of each test would slow
|
||||
testing to a crawl and would require the installation of the
|
||||
database engine and test data on the test machine.
|
||||
If we can simulate the connection and return data of our
|
||||
choosing we not only win on the pragmatics of testing, but can
|
||||
also feed our code spurious data to see how it responds.
|
||||
We can simulate databases being down or other extremes
|
||||
without having to create a broken database for real.
|
||||
In other words, we get greater control of the test environment.
|
||||
</p>
|
||||
<p>
|
||||
If mock objects only behaved as actors they would simply be
|
||||
known as server stubs.
|
||||
This was originally a pattern named by Robert Binder (Testing
|
||||
object-oriented systems: models, patterns, and tools,
|
||||
Addison-Wesley) in 1999.
|
||||
</p>
|
||||
<p>
|
||||
A server stub is a simulation of an object or component.
|
||||
It should exactly replace a component in a system for test
|
||||
or prototyping purposes, but remain lightweight.
|
||||
This allows tests to run more quickly, or if the simulated
|
||||
class has not been written, to run at all.
|
||||
</p>
|
||||
<p>
|
||||
However, the mock objects not only play a part (by supplying chosen
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
In the case of an imaginary database connection they can
|
||||
test that the query, say SQL, was correctly formed by
|
||||
the object that is using the connection.
|
||||
Set them up with fairly tight expectations and you will
|
||||
hardly need manual assertions at all.
|
||||
</p>
|
||||
</section>
|
||||
<section name="creation" title="Creating mock objects">
|
||||
<p>
|
||||
In the same way that we create server stubs, all we need is an
|
||||
existing class, say a database connection that looks like this...
|
||||
<php><![CDATA[
|
||||
<strong>class DatabaseConnection {
|
||||
function DatabaseConnection() {
|
||||
}
|
||||
|
||||
function query() {
|
||||
}
|
||||
|
||||
function selectQuery() {
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
The class does not need to have been implemented yet.
|
||||
To create a mock version of the class we need to include the
|
||||
mock object library and run the generator...
|
||||
<php><![CDATA[
|
||||
<strong>require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
|
||||
Mock::generate('DatabaseConnection');</strong>
|
||||
]]></php>
|
||||
This generates a clone class called
|
||||
<code>MockDatabaseConnection</code>.
|
||||
We can now create instances of the new class within
|
||||
our test case...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
|
||||
Mock::generate('DatabaseConnection');
|
||||
<strong>
|
||||
class MyTestCase extends UnitTestCase {
|
||||
|
||||
function testSomething() {
|
||||
$connection = &new MockDatabaseConnection();
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
Unlike the generated stubs the mock constructor needs a reference
|
||||
to the test case so that it can dispatch passes and failures while
|
||||
checking its expectations.
|
||||
This means that mock objects can only be used within test cases.
|
||||
Despite this their extra power means that stubs are hardly ever used
|
||||
if mocks are available.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="stub"><h2>Mocks as actors</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
The mock version of a class has all the methods of the original,
|
||||
so that operations like
|
||||
<code><![CDATA[$connection->query()]]></code> are still
|
||||
legal.
|
||||
The return value will be <code>null</code>,
|
||||
but we can change that with...
|
||||
<php><![CDATA[
|
||||
<strong>$connection->setReturnValue('query', 37)</strong>
|
||||
]]></php>
|
||||
Now every time we call
|
||||
<code><![CDATA[$connection->query()]]></code> we get
|
||||
the result of 37.
|
||||
We can set the return value to anything, say a hash of
|
||||
imaginary database results or a list of persistent objects.
|
||||
Parameters are irrelevant here, we always get the same
|
||||
values back each time once they have been set up this way.
|
||||
That may not sound like a convincing replica of a
|
||||
database connection, but for the half a dozen lines of
|
||||
a test method it is usually all you need.
|
||||
</p>
|
||||
<p>
|
||||
We can also add extra methods to the mock when generating it
|
||||
and choose our own class name...
|
||||
<php><![CDATA[
|
||||
<strong>Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));</strong>
|
||||
]]></php>
|
||||
Here the mock will behave as if the <code>setOptions()</code>
|
||||
existed in the original class.
|
||||
This is handy if a class has used the PHP <code>overload()</code>
|
||||
mechanism to add dynamic methods.
|
||||
You can create a special mock to simulate this situation.
|
||||
</p>
|
||||
<p>
|
||||
Things aren't always that simple though.
|
||||
One common problem is iterators, where constantly returning
|
||||
the same value could cause an endless loop in the object
|
||||
being tested.
|
||||
For these we need to set up sequences of values.
|
||||
Let's say we have a simple iterator that looks like this...
|
||||
<php><![CDATA[
|
||||
class Iterator {
|
||||
function Iterator() {
|
||||
}
|
||||
|
||||
function next() {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
Mock::generate('Iterator');
|
||||
|
||||
class IteratorTest extends UnitTestCase() {
|
||||
|
||||
function testASequence() {<strong>
|
||||
$iterator = &new MockIterator();
|
||||
$iterator->setReturnValue('next', false);
|
||||
$iterator->setReturnValueAt(0, 'next', 'First string');
|
||||
$iterator->setReturnValueAt(1, 'next', 'Second string');</strong>
|
||||
...
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
When <code>next()</code> is called on the
|
||||
mock iterator it will first return "First string",
|
||||
on the second call "Second string" will be returned
|
||||
and on any other call <code>false</code> will
|
||||
be returned.
|
||||
The sequenced return values take precedence over the constant
|
||||
return value.
|
||||
The constant one is a kind of default if you like.
|
||||
</p>
|
||||
<p>
|
||||
Another tricky situation is an overloaded
|
||||
<code>get()</code> operation.
|
||||
An example of this is an information holder with name/value pairs.
|
||||
Say we have a configuration class like...
|
||||
<php><![CDATA[
|
||||
class Configuration {
|
||||
function Configuration() {
|
||||
}
|
||||
|
||||
function getValue($key) {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
This is a classic situation for using mock objects as
|
||||
actual configuration will vary from machine to machine,
|
||||
hardly helping the reliability of our tests if we use it
|
||||
directly.
|
||||
The problem though is that all the data comes through the
|
||||
<code>getValue()</code> method and yet
|
||||
we want different results for different keys.
|
||||
Luckily the mocks have a filter system...
|
||||
<php><![CDATA[
|
||||
<strong>$config = &new MockConfiguration();
|
||||
$config->setReturnValue('getValue', 'primary', array('db_host'));
|
||||
$config->setReturnValue('getValue', 'admin', array('db_user'));
|
||||
$config->setReturnValue('getValue', 'secret', array('db_password'));</strong>
|
||||
]]></php>
|
||||
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
|
||||
<code>getValue()</code> method invoked
|
||||
like this...
|
||||
<php><![CDATA[
|
||||
$config->getValue('db_user')
|
||||
]]></php>
|
||||
...it will return "admin".
|
||||
It finds this by attempting to match the calling arguments
|
||||
to its list of returns one after another until
|
||||
a complete match is found.
|
||||
</p>
|
||||
<p>
|
||||
You can set a default argument argument like so...
|
||||
<php><![CDATA[<strong>
|
||||
$config->setReturnValue('getValue', false, array('*'));</strong>
|
||||
]]></php>
|
||||
This is not the same as setting the return value without
|
||||
any argument requirements like this...
|
||||
<php><![CDATA[<strong>
|
||||
$config->setReturnValue('getValue', false);</strong>
|
||||
]]></php>
|
||||
In the first case it will accept any single argument,
|
||||
but exactly one is required.
|
||||
In the second case any number of arguments will do and
|
||||
it acts as a catchall after all other matches.
|
||||
Note that if we add further single parameter options after
|
||||
the wildcard in the first case, they will be ignored as the wildcard
|
||||
will match first.
|
||||
With complex parameter lists the ordering could be important
|
||||
or else desired matches could be masked by earlier wildcard
|
||||
ones.
|
||||
Declare the most specific matches first if you are not sure.
|
||||
</p>
|
||||
<p>
|
||||
There are times when you want a specific object to be
|
||||
dished out by the mock rather than a copy.
|
||||
The PHP4 copy semantics force us to use a different method
|
||||
for this.
|
||||
You might be simulating a container for example...
|
||||
<php><![CDATA[
|
||||
class Thing {
|
||||
}
|
||||
|
||||
class Vector {
|
||||
function Vector() {
|
||||
}
|
||||
|
||||
function get($index) {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
In this case you can set a reference into the mock's
|
||||
return list...
|
||||
<php><![CDATA[
|
||||
$thing = &new Thing();<strong>
|
||||
$vector = &new MockVector();
|
||||
$vector->setReturnReference('get', $thing, array(12));</strong>
|
||||
]]></php>
|
||||
With this arrangement you know that every time
|
||||
<code><![CDATA[$vector->get(12)]]></code> is
|
||||
called it will return the same
|
||||
<code>$thing</code> each time.
|
||||
This is compatible with PHP5 as well.
|
||||
</p>
|
||||
<p>
|
||||
These three factors, timing, parameters and whether to copy,
|
||||
can be combined orthogonally.
|
||||
For example...
|
||||
<php><![CDATA[
|
||||
$complex = &new MockComplexThing();
|
||||
$stuff = &new Stuff();<strong>
|
||||
$complex->setReturnReferenceAt(3, 'get', $stuff, array('*', 1));</strong>
|
||||
]]></php>
|
||||
This will return the <code>$stuff</code> only on the third
|
||||
call and only if two parameters were set the second of
|
||||
which must be the integer 1.
|
||||
That should cover most simple prototyping situations.
|
||||
</p>
|
||||
<p>
|
||||
A final tricky case is one object creating another, known
|
||||
as a factory pattern.
|
||||
Suppose that on a successful query to our imaginary
|
||||
database, a result set is returned as an iterator with
|
||||
each call to <code>next()</code> giving
|
||||
one row until false.
|
||||
This sounds like a simulation nightmare, but in fact it can all
|
||||
be mocked using the mechanics above.
|
||||
</p>
|
||||
<p>
|
||||
Here's how...
|
||||
<php><![CDATA[
|
||||
Mock::generate('DatabaseConnection');
|
||||
Mock::generate('ResultIterator');
|
||||
|
||||
class DatabaseTest extends UnitTestCase {
|
||||
|
||||
function testUserFinder() {<strong>
|
||||
$result = &new MockResultIterator();
|
||||
$result->setReturnValue('next', false);
|
||||
$result->setReturnValueAt(0, 'next', array(1, 'tom'));
|
||||
$result->setReturnValueAt(1, 'next', array(3, 'dick'));
|
||||
$result->setReturnValueAt(2, 'next', array(6, 'harry'));
|
||||
|
||||
$connection = &new MockDatabaseConnection();
|
||||
$connection->setReturnValue('query', false);
|
||||
$connection->setReturnReference(
|
||||
'query',
|
||||
$result,
|
||||
array('select id, name from users'));</strong>
|
||||
|
||||
$finder = &new UserFinder($connection);
|
||||
$this->assertIdentical(
|
||||
$finder->findNames(),
|
||||
array('tom', 'dick', 'harry'));
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Now only if our
|
||||
<code>$connection</code> is called with the correct
|
||||
<code>query()</code> will the
|
||||
<code>$result</code> be returned that is
|
||||
itself exhausted after the third call to <code>next()</code>.
|
||||
This should be enough
|
||||
information for our <code>UserFinder</code> class,
|
||||
the class actually
|
||||
being tested here, to come up with goods.
|
||||
A very precise test and not a real database in sight.
|
||||
</p>
|
||||
</section>
|
||||
<section name="expectations" title="Mocks as critics">
|
||||
<p>
|
||||
Although the server stubs approach insulates your tests from
|
||||
real world disruption, it is only half the benefit.
|
||||
You can have the class under test receiving the required
|
||||
messages, but is your new class sending correct ones?
|
||||
Testing this can get messy without a mock objects library.
|
||||
</p>
|
||||
<p>
|
||||
By way of example, suppose we have a
|
||||
<code>SessionPool</code> class that we
|
||||
want to add logging to.
|
||||
Rather than grow the original class into something more
|
||||
complicated, we want to add this behaviour with a decorator (GOF).
|
||||
The <code>SessionPool</code> code currently looks
|
||||
like this...
|
||||
<php><![CDATA[
|
||||
<strong>class SessionPool {
|
||||
function SessionPool() {
|
||||
...
|
||||
}
|
||||
|
||||
function &findSession($cookie) {
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
|
||||
class Session {
|
||||
...
|
||||
}</strong>
|
||||
</php>
|
||||
While our logging code looks like this...
|
||||
<php><strong>
|
||||
class Log {
|
||||
function Log() {
|
||||
...
|
||||
}
|
||||
|
||||
function message() {
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
class LoggingSessionPool {
|
||||
function LoggingSessionPool(&$session_pool, &$log) {
|
||||
...
|
||||
}
|
||||
|
||||
function &findSession(\$cookie) {
|
||||
...
|
||||
}
|
||||
...
|
||||
}</strong>
|
||||
]]></php>
|
||||
Out of all of this, the only class we want to test here
|
||||
is the <code>LoggingSessionPool</code>.
|
||||
In particular we would like to check that the
|
||||
<code>findSession()</code> method is
|
||||
called with the correct session ID in the cookie and that
|
||||
it sent the message "Starting session $cookie"
|
||||
to the logger.
|
||||
</p>
|
||||
<p>
|
||||
Despite the fact that we are testing only a few lines of
|
||||
production code, here is what we would have to do in a
|
||||
conventional test case:
|
||||
<ol>
|
||||
<li>Create a log object.</li>
|
||||
<li>Set a directory to place the log file.</li>
|
||||
<li>Set the directory permissions so we can write the log.</li>
|
||||
<li>Create a <code>SessionPool</code> object.</li>
|
||||
<li>Hand start a session, which probably does lot's of things.</li>
|
||||
<li>Invoke <code>findSession()</code>.</li>
|
||||
<li>Read the new Session ID (hope there is an accessor!).</li>
|
||||
<li>Raise a test assertion to confirm that the ID matches the cookie.</li>
|
||||
<li>Read the last line of the log file.</li>
|
||||
<li>Pattern match out the extra logging timestamps, etc.</li>
|
||||
<li>Assert that the session message is contained in the text.</li>
|
||||
</ol>
|
||||
It is hardly surprising that developers hate writing tests
|
||||
when they are this much drudgery.
|
||||
To make things worse, every time the logging format changes or
|
||||
the method of creating new sessions changes, we have to rewrite
|
||||
parts of this test even though this test does not officially
|
||||
test those parts of the system.
|
||||
We are creating headaches for the writers of these other classes.
|
||||
</p>
|
||||
<p>
|
||||
Instead, here is the complete test method using mock object magic...
|
||||
<php><![CDATA[
|
||||
Mock::generate('Session');
|
||||
Mock::generate('SessionPool');
|
||||
Mock::generate('Log');
|
||||
|
||||
class LoggingSessionPoolTest extends UnitTestCase {
|
||||
...
|
||||
function testFindSessionLogging() {<strong>
|
||||
$session = &new MockSession();
|
||||
$pool = &new MockSessionPool();
|
||||
$pool->setReturnReference('findSession', $session);
|
||||
$pool->expectOnce('findSession', array('abc'));
|
||||
|
||||
$log = &new MockLog();
|
||||
$log->expectOnce('message', array('Starting session abc'));
|
||||
|
||||
$logging_pool = &new LoggingSessionPool($pool, $log);
|
||||
$this->assertReference($logging_pool->findSession('abc'), $session);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
We start by creating a dummy session.
|
||||
We don't have to be too fussy about this as the check
|
||||
for which session we want is done elsewhere.
|
||||
We only need to check that it was the same one that came
|
||||
from the session pool.
|
||||
</p>
|
||||
<p>
|
||||
<code>findSession()</code> is a factory
|
||||
method the simulation of which is described <a href="#stub">above</a>.
|
||||
The point of departure comes with the first
|
||||
<code>expectOnce()</code> call.
|
||||
This line states that whenever
|
||||
<code>findSession()</code> is invoked on the
|
||||
mock, it will test the incoming arguments.
|
||||
If it receives the single argument of a string "abc"
|
||||
then a test pass is sent to the unit tester, otherwise a fail is
|
||||
generated.
|
||||
This was the part where we checked that the right session was asked for.
|
||||
The argument list follows the same format as the one for setting
|
||||
return values.
|
||||
You can have wildcards and sequences and the order of
|
||||
evaluation is the same.
|
||||
</p>
|
||||
<p>
|
||||
We use the same pattern to set up the mock logger.
|
||||
We tell it that it should have
|
||||
<code>message()</code> invoked
|
||||
once only with the argument "Starting session abc".
|
||||
By testing the calling arguments, rather than the logger output,
|
||||
we insulate the test from any display changes in the logger.
|
||||
</p>
|
||||
<p>
|
||||
We start to run our tests when we create the new
|
||||
<code>LoggingSessionPool</code> and feed
|
||||
it our preset mock objects.
|
||||
Everything is now under our control.
|
||||
</p>
|
||||
<p>
|
||||
This is still quite a bit of test code, but the code is very
|
||||
strict.
|
||||
If it still seems rather daunting there is a lot less of it
|
||||
than if we tried this without mocks and this particular test,
|
||||
interactions rather than output, is always more work to set
|
||||
up.
|
||||
More often you will be testing more complex situations without
|
||||
needing this level or precision.
|
||||
Also some of this can be refactored into a test case
|
||||
<code>setUp()</code> method.
|
||||
</p>
|
||||
<p>
|
||||
Here is the full list of expectations you can set on a mock object
|
||||
in <a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>...
|
||||
<table><thead>
|
||||
<tr><th>Expectation</th><th>Needs <code>tally()</code></th></tr>
|
||||
</thead><tbody><tr>
|
||||
<td><code>expect($method, $args)</code></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectAt($timing, $method, $args)</code></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectCallCount($method, $count)</code></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectMaximumCallCount($method, $count)</code></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectMinimumCallCount($method, $count)</code></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectNever($method)</code></td>
|
||||
<td style="text-align: center">No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectOnce($method, $args)</code></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectAtLeastOnce($method, $args)</code></td>
|
||||
<td style="text-align: center">Yes</td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
Where the parameters are...
|
||||
<dl>
|
||||
<dt class="new_code">$method</dt>
|
||||
<dd>The method name, as a string, to apply the condition to.</dd>
|
||||
<dt class="new_code">$args</dt>
|
||||
<dd>
|
||||
The arguments as a list. Wildcards can be included in the same
|
||||
manner as for <code>setReturn()</code>.
|
||||
This argument is optional for <code>expectOnce()</code>
|
||||
and <code>expectAtLeastOnce()</code>.
|
||||
</dd>
|
||||
<dt class="new_code">$timing</dt>
|
||||
<dd>
|
||||
The only point in time to test the condition.
|
||||
The first call starts at zero.
|
||||
</dd>
|
||||
<dt class="new_code">$count</dt>
|
||||
<dd>The number of calls expected.</dd>
|
||||
</dl>
|
||||
The method <code>expectMaximumCallCount()</code>
|
||||
is slightly different in that it will only ever generate a failure.
|
||||
It is silent if the limit is never reached.
|
||||
</p>
|
||||
<p>
|
||||
Like the assertions within test cases, all of the expectations
|
||||
can take a message override as an extra parameter.
|
||||
Also the original failure message can be embedded in the output
|
||||
as "%s".
|
||||
</p>
|
||||
</section>
|
||||
<section name="approaches" title="Other approaches">
|
||||
<p>
|
||||
There are three approaches to creating mocks including the one
|
||||
that SimpleTest employs.
|
||||
Coding them by hand using a base class, generating them to
|
||||
a file and dynamically generating them on the fly.
|
||||
</p>
|
||||
<p>
|
||||
Mock objects generated with <a local="simple_test">SimpleTest</a>
|
||||
are dynamic.
|
||||
They are created at run time in memory, using
|
||||
<code>eval()</code>, rather than written
|
||||
out to a file.
|
||||
This makes the mocks easy to create, a one liner,
|
||||
especially compared with hand
|
||||
crafting them in a parallel class hierarchy.
|
||||
The problem is that the behaviour is usually set up in the tests
|
||||
themselves.
|
||||
If the original objects change the mock versions
|
||||
that the tests rely on can get out of sync.
|
||||
This can happen with the parallel hierarchy approach as well,
|
||||
but is far more quickly detected.
|
||||
</p>
|
||||
<p>
|
||||
The solution, of course, is to add some real integration
|
||||
tests.
|
||||
You don't need very many and the convenience gained
|
||||
from the mocks more than outweighs the small amount of
|
||||
extra testing.
|
||||
You cannot trust code that was only tested with mocks.
|
||||
</p>
|
||||
<p>
|
||||
If you are still determined to build static libraries of mocks
|
||||
because you want to simulate very specific behaviour, you can
|
||||
achieve the same effect using the SimpleTest class generator.
|
||||
In your library file, say <em>mocks/connection.php</em> for a
|
||||
database connection, create a mock and inherit to override
|
||||
special methods or add presets...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('../classes/connection.php');
|
||||
<strong>
|
||||
Mock::generate('Connection', 'BasicMockConnection');
|
||||
class MockConnection extends BasicMockConnection {
|
||||
function MockConnection() {
|
||||
$this->BasicMockConnection();
|
||||
$this->setReturn('query', false);
|
||||
}
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
The generate call tells the class generator to create
|
||||
a class called <code>BasicMockConnection</code>
|
||||
rather than the usual <code>MockConnection</code>.
|
||||
We then inherit from this to get our version of
|
||||
<code>MockConnection</code>.
|
||||
By intercepting in this way we can add behaviour, here setting
|
||||
the default value of <code>query()</code> to be false.
|
||||
By using the default name we make sure that the mock class
|
||||
generator will not recreate a different one when invoked elsewhere in the
|
||||
tests.
|
||||
It never creates a class if it already exists.
|
||||
As long as the above file is included first then all tests
|
||||
that generated <code>MockConnection</code> should
|
||||
now be using our one instead.
|
||||
If we don't get the order right and the mock library
|
||||
creates one first then the class creation will simply fail.
|
||||
</p>
|
||||
<p>
|
||||
Use this trick if you find you have a lot of common mock behaviour
|
||||
or you are getting frequent integration problems at later
|
||||
stages of testing.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#what">What are mock objects?</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#creation">Creating mock objects</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#stub">Mocks as actors</a> or stubs.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#expectations">Mocks as critics</a> with expectations.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#approaches">Other approaches</a> including mock libraries.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
The original
|
||||
<a href="http://www.mockobjects.com/">Mock objects</a> paper.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest home page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php testing,
|
||||
unit test,
|
||||
php testing,
|
||||
jmock,
|
||||
nmock
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,361 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Mock Objects" here="Using mock objects">
|
||||
<long_title>PHP unit testing tutorial - Using mock objects in PHP</long_title>
|
||||
<content>
|
||||
<p>
|
||||
<a class="target" name="refactor"><h2>Refactoring the tests again</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Before more functionality is added there is some refactoring
|
||||
to do.
|
||||
We are going to do some timing tests and so the
|
||||
<code>TimeTestCase</code> class definitely needs
|
||||
its own file.
|
||||
Let's say <em>tests/time_test_case.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase($test_name = '') {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, $message = '') {
|
||||
if (! $message) {
|
||||
$message = "Time [$time1] should match time [$time2]";
|
||||
}
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
We can then <code>require()</code> this file into
|
||||
the <em>all_tests.php</em> script.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="timestamp"><h2>Adding a timestamp to the Log</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
I don't know quite what the format of the log message should
|
||||
be for the test, so to check for a timestamp we could do the
|
||||
simplest possible thing, which is to look for a sequence of digits.
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');<strong>
|
||||
require_once('../classes/clock.php');
|
||||
|
||||
class TestOfLogging extends TimeTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->TimeTestCase('Log class test');
|
||||
}</strong>
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
...
|
||||
}
|
||||
function testAppendingToFile() {
|
||||
...
|
||||
}<strong>
|
||||
function testTimestamps() {
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line');
|
||||
$this->assertTrue(
|
||||
preg_match('/(\d+)/', $this->getFileLine('../temp/test.log', 0), $matches),
|
||||
'Found timestamp');
|
||||
$clock = new clock();
|
||||
$this->assertSameTime((integer)$matches[1], $clock->now(), 'Correct time');
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
The test case creates a new <code>Log</code>
|
||||
object and writes a message.
|
||||
We look for a digit sequence and then test it against the current
|
||||
time using our <code>Clock</code> object.
|
||||
Of course it doesn't work until we write the code.
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->File created<br />
|
||||
<span class="fail">Fail</span>: log_test.php->Log class test->testtimestamps->Found timestamp<br />
|
||||
<br />
|
||||
<b>Notice</b>: Undefined offset: 1 in <b>/home/marcus/projects/lastcraft/tutorial_tests/tests/log_test.php</b> on line <b>44</b><br />
|
||||
<span class="fail">Fail</span>: log_test.php->Log class test->testtimestamps->Correct time<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>2</strong> fails.</div>
|
||||
</div>
|
||||
The test suite is still showing the passes from our earlier
|
||||
modification.
|
||||
</p>
|
||||
<p>
|
||||
We can get the tests to pass simply by adding a timestamp
|
||||
when writing out to the file.
|
||||
Yes, of course all of this is trivial and
|
||||
I would not normally test this fanatically, but it is going
|
||||
to illustrate a more general problem.
|
||||
The <em>log.php</em> file becomes...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('../classes/clock.php');</strong>
|
||||
|
||||
class Log {
|
||||
var $_file_path;
|
||||
|
||||
function Log($file_path) {
|
||||
$this->_file_path = $file_path;
|
||||
}
|
||||
|
||||
function message($message) {<strong>
|
||||
$clock = new Clock();</strong>
|
||||
$file = fopen($this->_file_path, 'a');<strong>
|
||||
fwrite($file, "[" . $clock->now() . "] $message\n");</strong>
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
The tests should now pass.
|
||||
</p>
|
||||
<p>
|
||||
Our new test is full of problems, though.
|
||||
What if our time format changes to something else?
|
||||
Things are going to be a lot more complicated to test if this
|
||||
happens.
|
||||
It also means that any changes to the clock class time
|
||||
format will cause our logging tests to fail also.
|
||||
This means that our log tests are tangled up with the clock tests
|
||||
and extremely fragile.
|
||||
It lacks cohesion, which is the same as saying it is not
|
||||
tightly focused, testing facets of the clock as well as the log.
|
||||
Our problems are caused in part because the clock output
|
||||
is unpredictable when
|
||||
all we really want to test is that the logging message
|
||||
contains the output of
|
||||
<code>Clock::now()</code>.
|
||||
We don't
|
||||
really care about the contents of that method call.
|
||||
</p>
|
||||
<p>
|
||||
Can we make that call predictable?
|
||||
We could if we could get the log to use a dummy version
|
||||
of the clock for the duration of the test.
|
||||
The dummy clock class would have to behave the same way
|
||||
as the <code>Clock</code> class
|
||||
except for the fixed output from the
|
||||
<code>now()</code> method.
|
||||
Hey, that would even free us from using the
|
||||
<code>TimeTestCase</code> class!
|
||||
</p>
|
||||
<p>
|
||||
We could write such a class pretty easily although it is
|
||||
rather tedious work.
|
||||
We just create another clock class with same interface
|
||||
except that the <code>now()</code> method
|
||||
returns a value that we can change with some other setter method.
|
||||
That is quite a lot of work for a pretty minor test.
|
||||
</p>
|
||||
<p>
|
||||
Except that it is really no work at all.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="mock"><h2>A mock clock</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
To reach instant testing clock nirvana we need
|
||||
only three extra lines of code...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/mock_objects.php');
|
||||
]]></php>
|
||||
This includes the mock generator code.
|
||||
It is simplest to place this in the <em>all_tests.php</em>
|
||||
script as it gets used rather a lot.
|
||||
<php><![CDATA[
|
||||
Mock::generate('Clock');
|
||||
]]></php>
|
||||
This is the line that does the work.
|
||||
The code generator scans the class for all of its
|
||||
methods, creates code to generate an identically
|
||||
interfaced class, but with the name "Mock" added,
|
||||
and then <code>eval()</code>s the new code to
|
||||
create the new class.
|
||||
<php><![CDATA[
|
||||
$clock = &new MockClock($this);
|
||||
]]></php>
|
||||
This line can be added to any test method we are interested in.
|
||||
It creates the dummy clock ready to receive our instructions.
|
||||
</p>
|
||||
<p>
|
||||
Our test case is on the first steps of a radical clean up...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');<strong>
|
||||
Mock::generate('Clock');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}</strong>
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
...
|
||||
}
|
||||
function testAppendingToFile() {
|
||||
...
|
||||
}
|
||||
function testTimestamps() {<strong>
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line', &$clock);
|
||||
$this->assertWantedPattern(
|
||||
'/Timestamp/',
|
||||
$this->getFileLine('../temp/test.log', 0),
|
||||
'Found timestamp');</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
This test method creates a <code>MockClock</code>
|
||||
object and then sets the return value of the
|
||||
<code>now()</code> method to be the string
|
||||
"Timestamp".
|
||||
Every time we call <code>$clock->now()</code>
|
||||
it will return this string.
|
||||
This should be easy to spot.
|
||||
</p>
|
||||
<p>
|
||||
Next we create our log and send a message.
|
||||
We pass into the <code>message()</code>
|
||||
call the clock we would like to use.
|
||||
This means that we will have to add an optional parameter to
|
||||
the logging class to make testing possible...
|
||||
<php><![CDATA[
|
||||
class Log {
|
||||
var $_file_path;
|
||||
|
||||
function Log($file_path) {
|
||||
$this->_file_path = $file_path;
|
||||
}
|
||||
|
||||
function message($message, <strong>$clock = false</strong>) {<strong>
|
||||
if (!is_object($clock)) {
|
||||
$clock = new Clock();
|
||||
}</strong>
|
||||
$file = fopen($this->_file_path, 'a');
|
||||
fwrite($file, "[" . $clock->now() . "] $message\n");
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
All of the tests now pass and they test only the logging code.
|
||||
We can breathe easy again.
|
||||
</p>
|
||||
<p>
|
||||
Does that extra parameter in the <code>Log</code>
|
||||
class bother you?
|
||||
We have changed the interface just to facilitate testing after
|
||||
all.
|
||||
Are not interfaces the most important thing?
|
||||
Have we sullied our class with test code?
|
||||
</p>
|
||||
<p>
|
||||
Possibly, but consider this.
|
||||
Next chance you get, look at a circuit board, perhaps the motherboard
|
||||
of the computer you are looking at right now.
|
||||
On most boards you will find the odd empty hole, or solder
|
||||
joint with nothing attached or perhaps a pin or socket
|
||||
that has no obvious function.
|
||||
Chances are that some of these are for expansion and
|
||||
variations, but most of the remainder will be for testing.
|
||||
</p>
|
||||
<p>
|
||||
Think about that.
|
||||
The factories making the boards many times over wasting material
|
||||
on parts that do not add to the final function.
|
||||
If hardware engineers can make this sacrifice of elegance I am
|
||||
sure we can too.
|
||||
Our sacrifice wastes no materials after all.
|
||||
</p>
|
||||
<p>
|
||||
Still bother you?
|
||||
Actually it bothers me too, but not so much here.
|
||||
The number one priority is code that works, not prizes
|
||||
for minimalism.
|
||||
If it really bothers you, then move the creation of the clock
|
||||
into another protected factory method.
|
||||
Then subclass the clock for testing and override the
|
||||
factory method with one that returns the mock.
|
||||
Your tests are clumsier, but your interface is intact.
|
||||
</p>
|
||||
<p>
|
||||
Again I leave the decision to you.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#refactor">Refactoring the tests</a> so we can reuse
|
||||
our new time test.
|
||||
</link>
|
||||
<link>Adding <a href="#timestamp">Log timestamps</a>.</link>
|
||||
<link><a href="#mock">Mocking the clock</a> to make the test cohesive.</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
This follows the <a href="first_test_tutorial.php">unit test tutorial</a>.
|
||||
</link>
|
||||
<link>
|
||||
Next is distilling <a href="boundary_classes_tutorial.php">boundary classes</a>.
|
||||
</link>
|
||||
<link>
|
||||
You will need the <a href="simple_test.php">SimpleTest</a>
|
||||
tool to run the examples.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://www.mockobjects.com/">Mock objects</a> papers.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php testing,
|
||||
unit test,
|
||||
php testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,420 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Overview of SimpleTest" here="Overview">
|
||||
<long_title>
|
||||
Overview and feature list for the SimpleTest PHP unit tester and web tester
|
||||
</long_title>
|
||||
<content>
|
||||
<section name="summary" title="What is SimpleTest?">
|
||||
<p>
|
||||
The heart of SimpleTest is a testing framework built around
|
||||
test case classes.
|
||||
These are written as extensions of base test case classes,
|
||||
each extended with methods that actually contain test code.
|
||||
Top level test scripts then invoke the <code>run()</code>
|
||||
methods on every one of these test cases in order.
|
||||
Each test method is written to invoke various assertions that
|
||||
the developer expects to be true such as
|
||||
<code>assertEqual()</code>.
|
||||
If the expectation is correct, then a successful result is dispatched to the
|
||||
observing test reporter, but any failure triggers an alert
|
||||
and a description of the mismatch.
|
||||
</p>
|
||||
<p>
|
||||
A <a local="unit_test_documentation">test case</a> looks like this...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class <strong>MyTestCase</strong> extends UnitTestCase {
|
||||
<strong>
|
||||
function testLogWroteMessage() {
|
||||
$log = &new Log('my.log');
|
||||
$log->message('Hello');
|
||||
$this->assertTrue(file_exists('my.log'));
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
These tools are designed for the developer.
|
||||
Tests are written in the PHP language itself more or less
|
||||
as the application itself is built.
|
||||
The advantage of using PHP itself as the testing language is that
|
||||
there are no new languages to learn, testing can start straight away,
|
||||
and the developer can test any part of the code.
|
||||
Basically, all parts that can be accessed by the application code can also be
|
||||
accessed by the test code, if they are in the same programming language.
|
||||
</p>
|
||||
<p>
|
||||
The simplest type of test case is the
|
||||
<a local="unit_tester_documentation">UnitTestCase</a>.
|
||||
This class of test case includes standard tests for equality,
|
||||
references and pattern matching.
|
||||
All these test the typical expectations of what you would
|
||||
expect the result of a function or method to be.
|
||||
This is by far the most common type of test in the daily
|
||||
routine of development, making up about 95% of test cases.
|
||||
</p>
|
||||
<p>
|
||||
The top level task of a web application though is not to
|
||||
produce correct output from its methods and objects, but
|
||||
to generate web pages.
|
||||
The <a local="web_tester_documentation">WebTestCase</a> class tests web
|
||||
pages.
|
||||
It simulates a web browser requesting a page, complete with
|
||||
cookies, proxies, secure connections, authentication, forms, frames and most
|
||||
navigation elements.
|
||||
With this type of test case, the developer can assert that
|
||||
information is present in the page and that forms and
|
||||
sessions are handled correctly.
|
||||
</p>
|
||||
<p>
|
||||
A <a local="web_tester_documentation">WebTestCase</a> looks like this...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class <strong>MySiteTest</strong> extends WebTestCase {
|
||||
<strong>
|
||||
function testHomePage() {
|
||||
$this->get('http://www.my-site.com/index.php');
|
||||
$this->assertTitle('My Home Page');
|
||||
$this->clickLink('Contact');
|
||||
$this->assertTitle('Contact me');
|
||||
$this->assertPattern('/Email me at/');
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="features" title="Feature list">
|
||||
<p>
|
||||
The following is a very rough outline of past and future features
|
||||
and their expected point of release.
|
||||
I am afraid it is liable to change without warning as meeting the
|
||||
milestones rather depends on time available.
|
||||
Green stuff has been coded, but not necessarily released yet.
|
||||
If you have a pressing need for a green but unreleased feature
|
||||
then you should check-out the code from Sourceforge CVS directly.
|
||||
<table><thead>
|
||||
<tr><th>Feature</th><th>Description</th><th>Release</th></tr>
|
||||
</thead><tbody><tr>
|
||||
<td>Unit test case</td>
|
||||
<td>Core test case class and assertions</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Html display</td>
|
||||
<td>Simplest possible display</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Autoloading of test cases</td>
|
||||
<td>
|
||||
Reading a file with test cases and loading them into a
|
||||
group test automatically
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Mock objects</td>
|
||||
<td>
|
||||
Objects capable of simulating other objects removing
|
||||
test dependencies
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Web test case</td>
|
||||
<td>Allows link following and title tag matching</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Partial mocks</td>
|
||||
<td>
|
||||
Mocking parts of a class for testing less than a class
|
||||
or for complex simulations
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Web cookie handling</td>
|
||||
<td>Correct handling of cookies when fetching pages</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Following redirects</td>
|
||||
<td>Page fetching automatically follows 300 redirects</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Form parsing</td>
|
||||
<td>Ability to submit simple forms and read default form values</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Command line interface</td>
|
||||
<td>Test display without the need of a web browser</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Exposure of expectation classes</td>
|
||||
<td>Can create precise tests with mocks as well as test cases</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>XML output and parsing</td>
|
||||
<td>
|
||||
Allows multi host testing and the integration of acceptance
|
||||
testing extensions
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Browser component</td>
|
||||
<td>
|
||||
Exposure of lower level web browser interface for more
|
||||
detailed test cases
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>HTTP authentication</td>
|
||||
<td>
|
||||
Fetching protected web pages with basic authentication
|
||||
only
|
||||
</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>SSL support</td>
|
||||
<td>Can connect to https: pages</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Proxy support</td>
|
||||
<td>Can connect via. common proxies</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Frames support</td>
|
||||
<td>Handling of frames in web test cases</td>
|
||||
<td style="color: green;">1.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>File upload testing</td>
|
||||
<td>Can simulate the input type file tag</td>
|
||||
<td style="color: green;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Mocking interfaces</td>
|
||||
<td>
|
||||
Can generate mock objects to interfaces as well as classes
|
||||
and class interfaces are carried for type hints
|
||||
</td>
|
||||
<td style="color: green;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Testing exceptions</td>
|
||||
<td>Similar to testing PHP errors</td>
|
||||
<td style="color: green;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>HTML label support</td>
|
||||
<td>Can access all controls using the visual label</td>
|
||||
<td style="color: red;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Code coverage</td>
|
||||
<td>Reports using the bundled SpikeSource coverage tool</td>
|
||||
<td style="color: red;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Reporting machinery enhancements</td>
|
||||
<td>Improved message passing for better cooperation with IDEs</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Localisation</td>
|
||||
<td>Messages abstracted and code generated from XML</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>IFrame support</td>
|
||||
<td>Reads IFrame content that can be refreshed</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Improved mock interface</td>
|
||||
<td>More compact way of expressing mocks using fluent interfaces</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Assertion packs</td>
|
||||
<td>Can dynamically add assertions to test cases</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>HTML table assertions</td>
|
||||
<td>Can match table elements to numerical assertions</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>XPath searching of HTML elements</td>
|
||||
<td>More flexible content matching</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Alternate HTML parsers</td>
|
||||
<td>Can detect compiled parsers for performance improvements</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Javascript suport</td>
|
||||
<td>Use of PECL module to add Javascript</td>
|
||||
<td style="color: red;">3.0</td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
PHP5 migraton will start straight after the version 1.0.1 series,
|
||||
whereupon only PHP 5.1+ will be supported.
|
||||
SimpleTest is currently compatible with PHP 5, but will not
|
||||
make use of all of the new features until version 2.
|
||||
</p>
|
||||
</section>
|
||||
<section name="resources" title="Web resources for testing">
|
||||
<p>
|
||||
Process is at least as important as tools.
|
||||
The type of process that makes the heaviest use of a developer's
|
||||
testing tool is of course
|
||||
<a href="http://www.extremeprogramming.org/">Extreme Programming</a>.
|
||||
This is one of the
|
||||
<a href="http://www.agilealliance.com/articles/index">Agile Methodologies</a>
|
||||
which combine various practices to "flatten the cost curve" of software development.
|
||||
More extreme still is <a href="http://www.testdriven.com/modules/news/">Test Driven Development</a>,
|
||||
where you very strictly adhere to the rule of no coding until you have a test.
|
||||
If you're more of a planner, or believe that experience trumps evolution,
|
||||
you may prefer the
|
||||
<a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a> approach.
|
||||
I haven't tried it, but even I can see that you will need test tools (see figure 9).
|
||||
</p>
|
||||
<p>
|
||||
Most unit testers clone <a href="http://www.junit.org/">JUnit</a> to some degree,
|
||||
as far as the interface at least. There is a wealth of information on the
|
||||
JUnit site including the
|
||||
<a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a>
|
||||
which contains plenty of general advice on testing.
|
||||
Once you get bitten by the bug you will certainly appreciate the phrase
|
||||
<a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">test infected</a>
|
||||
coined by Eric Gamma.
|
||||
If you are still reviewing which unit tester to use the main choices
|
||||
are <a href="http://phpunit.sourceforge.net/">PHPUnit</a>
|
||||
and <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>.
|
||||
They currently lack a lot of features found in
|
||||
<a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>, but the PEAR
|
||||
version at least has been upgraded for PHP5 and is recommended if you are porting
|
||||
existing <a href="http://www.junit.org/">JUnit</a> test cases.
|
||||
</p>
|
||||
<p>
|
||||
There is currently a sad lack of material on mock objects, which is a shame
|
||||
as unit testing without them is a lot more work.
|
||||
The <a href="http://www.sidewize.com/company/mockobjects.pdf">original mock objects paper</a>
|
||||
is very Java focused, but still worth a read.
|
||||
As a new technology there are plenty of discussions and debate on how to use mocks,
|
||||
often on Wikis such as
|
||||
<a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a>
|
||||
or <a href="http://www.mockobjects.com/MocksObjectsPaper.html">www.mockobjects.com</a>
|
||||
or <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>.
|
||||
Injecting mocks into a class is the main area of debate for which this
|
||||
<a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">paper on IBM</a>
|
||||
makes a good starting point.
|
||||
</p>
|
||||
<p>
|
||||
There are plenty of web testing tools, but the scriptable ones
|
||||
are mostly are written in Java and
|
||||
tutorials and advice are rather thin on the ground.
|
||||
The only hope is to look at the documentation for
|
||||
<a href="http://httpunit.sourceforge.net/">HTTPUnit</a>,
|
||||
<a href="http://htmlunit.sourceforge.net/">HTMLUnit</a>
|
||||
or <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> and hope for clues.
|
||||
There are some XML driven test frameworks, but again most
|
||||
require Java to run.
|
||||
</p>
|
||||
<p>
|
||||
A new generation of tools that run directly in the web browser
|
||||
are now available.
|
||||
These include
|
||||
<a href="http://www.openqa.org/selenium/">Selenium</a> and
|
||||
<a href="http://wtr.rubyforge.org/">Watir</a>.
|
||||
As SimpleTest does not support JavaScript you would probably
|
||||
have to look at these tools anyway if you have highly dynamic
|
||||
pages.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#summary">Quick summary</a>
|
||||
of the SimpleTest tool for PHP.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#features">List of features</a>,
|
||||
both current ones and those planned.
|
||||
</link>
|
||||
<link>
|
||||
There are plenty of <a href="#resources">unit testing resources</a>
|
||||
on the web.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a local="unit_test_documentation">Documentation for SimpleTest</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://www.lastcraft.com/first_test_tutorial.php">How to write PHP test cases</a>
|
||||
is a fairly advanced tutorial.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">SimpleTest API</a> from phpdoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development tools,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
Tools for extreme programming,
|
||||
free php scripts,
|
||||
links of testing tools,
|
||||
php testing resources,
|
||||
mock objects,
|
||||
junit,
|
||||
jwebunit,
|
||||
htmlunit,
|
||||
itc,
|
||||
php testing links,
|
||||
unit test advice and documentation,
|
||||
extreme programming in php
|
||||
</keywords>
|
||||
</meta>
|
||||
<refsynopsisdiv>
|
||||
<authorgroup>
|
||||
<author>
|
||||
Marcus Baker
|
||||
<authorblurb>
|
||||
<para>Primary Developer</para><para>{@link mailto:marcus@lastcraft.com marcus@lastcraft.com}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
<author>
|
||||
Harry Fuecks
|
||||
<authorblurb>
|
||||
<para>Packager</para><para>{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
<author>
|
||||
Jason Sweat
|
||||
<authorblurb>
|
||||
<para>Documentation</para><para>{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
</authorgroup>
|
||||
</refsynopsisdiv>
|
||||
</page>
|
@ -0,0 +1,401 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Partial mock objects documentation" here="Partial mocks">
|
||||
<long_title>SimpleTest for PHP partial mocks documentation</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
A partial mock is simply a pattern to alleviate a specific problem
|
||||
in testing with mock objects,
|
||||
that of getting mock objects into tight corners.
|
||||
It's quite a limited tool and possibly not even a good idea.
|
||||
It is included with SimpleTest because I have found it useful
|
||||
on more than one occasion and has saved a lot of work at that point.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="inject" title="The mock injection problem">
|
||||
<p>
|
||||
When one object uses another it is very simple to just pass a mock
|
||||
version in already set up with its expectations.
|
||||
Things are rather tricker if one object creates another and the
|
||||
creator is the one you want to test.
|
||||
This means that the created object should be mocked, but we can
|
||||
hardly tell our class under test to create a mock instead.
|
||||
The tested class doesn't even know it is running inside a test
|
||||
after all.
|
||||
</p>
|
||||
<p>
|
||||
For example, suppose we are building a telnet client and it
|
||||
needs to create a network socket to pass its messages.
|
||||
The connection method might look something like...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {
|
||||
$socket = &new Socket($ip, $port);
|
||||
$socket->read( ... );
|
||||
...
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
We would really like to have a mock object version of the socket
|
||||
here, what can we do?
|
||||
</p>
|
||||
<p>
|
||||
The first solution is to pass the socket in as a parameter,
|
||||
forcing the creation up a level.
|
||||
Having the client handle this is actually a very good approach
|
||||
if you can manage it and should lead to factoring the creation from
|
||||
the doing.
|
||||
In fact, this is one way in which testing with mock objects actually
|
||||
forces you to code more tightly focused solutions.
|
||||
They improve your programming.
|
||||
</p>
|
||||
<p>
|
||||
Here this would be...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
<strong>function &connect(&$socket, $username, $password) {
|
||||
$socket->read( ... );
|
||||
...
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
This means that the test code is typical for a test involving
|
||||
mock objects.
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new Telnet();
|
||||
$telnet->connect($socket, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
It is pretty obvious though that one level is all you can go.
|
||||
You would hardly want your top level application creating
|
||||
every low level file, socket and database connection ever
|
||||
needed.
|
||||
It wouldn't know the constructor parameters anyway.
|
||||
</p>
|
||||
<p>
|
||||
The next simplest compromise is to have the created object passed
|
||||
in as an optional parameter...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...<strong>
|
||||
function &connect($ip, $port, $username, $password, $socket = false) {
|
||||
if (!$socket) {
|
||||
$socket = &new Socket($ip, $port);
|
||||
}
|
||||
$socket->read( ... );</strong>
|
||||
...
|
||||
return $socket;
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
For a quick solution this is usually good enough.
|
||||
The test now looks almost the same as if the parameter
|
||||
was formally passed...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret', &$socket);
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The problem with this approach is its untidiness.
|
||||
There is test code in the main class and parameters passed
|
||||
in the test case that are never used.
|
||||
This is a quick and dirty approach, but nevertheless effective
|
||||
in most situations.
|
||||
</p>
|
||||
<p>
|
||||
The next method is to pass in a factory object to do the creation...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {<strong>
|
||||
function Telnet(&$network) {
|
||||
$this->_network = &$network;
|
||||
}</strong>
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {<strong>
|
||||
$socket = &$this->_network->createSocket($ip, $port);
|
||||
$socket->read( ... );</strong>
|
||||
...
|
||||
return $socket;
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$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');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The downside is that we are adding a lot more classes to the
|
||||
library.
|
||||
Also we are passing a lot of factories around which will
|
||||
make the code a little less intuitive.
|
||||
The most flexible solution, but the most complex.
|
||||
</p>
|
||||
<p>
|
||||
Is there a middle ground?
|
||||
</p>
|
||||
</section>
|
||||
<section name="creation" title="Protected factory method">
|
||||
<p>
|
||||
There is a way we can circumvent the problem without creating
|
||||
any new application classes, but it involves creating a subclass
|
||||
when we do the actual testing.
|
||||
Firstly we move the socket creation into its own method...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {<strong>
|
||||
$socket = &$this->_createSocket($ip, $port);</strong>
|
||||
$socket->read( ... );
|
||||
...
|
||||
}<strong>
|
||||
|
||||
function &_createSocket($ip, $port) {
|
||||
return new Socket($ip, $port);
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
This is the only change we make to the application code.
|
||||
</p>
|
||||
<p>
|
||||
For the test case we have to create a subclass so that
|
||||
we can intercept the socket creation...
|
||||
<php><![CDATA[
|
||||
<strong>class TelnetTestVersion extends Telnet {
|
||||
var $_mock;
|
||||
|
||||
function TelnetTestVersion(&$mock) {
|
||||
$this->_mock = &$mock;
|
||||
$this->Telnet();
|
||||
}
|
||||
|
||||
function &_createSocket() {
|
||||
return $this->_mock;
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
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
|
||||
<code>connect()</code>.
|
||||
Otherwise it could get a null value from
|
||||
<code>_createSocket()</code>.
|
||||
</p>
|
||||
<p>
|
||||
After the completion of all of this extra work the
|
||||
actual test case is fairly easy.
|
||||
We just test our new class instead...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($socket);
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The new class is very simple of course.
|
||||
It just sets up a return value, rather like a mock.
|
||||
It would be nice if it also checked the incoming parameters
|
||||
as well.
|
||||
Just like a mock.
|
||||
It seems we are likely to do this often, can
|
||||
we automate the subclass creation?
|
||||
</p>
|
||||
</section>
|
||||
<section name="partial" title="A partial mock">
|
||||
<p>
|
||||
Of course the answer is "yes" or I would have stopped writing
|
||||
this by now!
|
||||
The previous test case was a lot of work, but we can
|
||||
generate the subclass using a similar approach to the mock objects.
|
||||
</p>
|
||||
<p>
|
||||
Here is the partial mock version of the test...
|
||||
<php><![CDATA[
|
||||
<strong>Mock::generatePartial(
|
||||
'Telnet',
|
||||
'TelnetTestVersion',
|
||||
array('_createSocket'));</strong>
|
||||
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($this);
|
||||
$telnet->setReturnReference('_createSocket', $socket);
|
||||
$telnet->Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The partial mock is a subclass of the original with
|
||||
selected methods "knocked out" with test
|
||||
versions.
|
||||
The <code>generatePartial()</code> call
|
||||
takes three parameters: the class to be subclassed,
|
||||
the new test class name and a list of methods to mock.
|
||||
</p>
|
||||
<p>
|
||||
Instantiating the resulting objects is slightly tricky.
|
||||
The only constructor parameter of a partial mock is
|
||||
the unit tester reference.
|
||||
As with the normal mock objects this is needed for sending
|
||||
test results in response to checked expectations.
|
||||
</p>
|
||||
<p>
|
||||
The original constructor is not run yet.
|
||||
This is necessary in case the constructor is going to
|
||||
make use of the as yet unset mocked methods.
|
||||
We set any return values at this point and then run the
|
||||
constructor with its normal parameters.
|
||||
This three step construction of "new", followed
|
||||
by setting up the methods, followed by running the constructor
|
||||
proper is what distinguishes the partial mock code.
|
||||
</p>
|
||||
<p>
|
||||
Apart from construction, all of the mocked methods have
|
||||
the same features as mock objects and all of the unmocked
|
||||
methods behave as before.
|
||||
We can set expectations very easily...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($this);
|
||||
$telnet->setReturnReference('_createSocket', $socket);<strong>
|
||||
$telnet->expectOnce('_createSocket', array('127.0.0.1', 21));</strong>
|
||||
$telnet->Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...<strong>
|
||||
$telnet->tally();</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="less" title="Testing less than a class">
|
||||
<p>
|
||||
The mocked out methods don't have to be factory methods,
|
||||
they could be any sort of method.
|
||||
In this way partial mocks allow us to take control of any part of
|
||||
a class except the constructor.
|
||||
We could even go as far as to mock every method
|
||||
except one we actually want to test.
|
||||
</p>
|
||||
<p>
|
||||
This last situation is all rather hypothetical, as I haven't
|
||||
tried it.
|
||||
I am open to the possibility, but a little worried that
|
||||
forcing object granularity may be better for the code quality.
|
||||
I personally use partial mocks as a way of overriding creation
|
||||
or for occasional testing of the TemplateMethod pattern.
|
||||
</p>
|
||||
<p>
|
||||
It's all going to come down to the coding standards of your
|
||||
project to decide which mechanism you use.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#inject">The mock injection problem</a>.
|
||||
</link>
|
||||
<link>
|
||||
Moving creation to a <a href="#creation">protected factory</a> method.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#partial">Partial mocks</a> generate subclasses.
|
||||
</link>
|
||||
<link>
|
||||
Partial mocks <a href="#less">test less than a class</a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">Full API for SimpleTest</a>
|
||||
from the PHPDoc.
|
||||
</link>
|
||||
<link>
|
||||
The protected factory is described in
|
||||
<a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">this paper from IBM</a>.
|
||||
This is the only formal comment I have seen on this problem.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
php software development,
|
||||
php test case development,
|
||||
database programming php,
|
||||
software development tools,
|
||||
php advanced tutorial,
|
||||
phpunit style scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php test framework,
|
||||
unit test,
|
||||
php testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,470 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Test reporter documentation" here="Reporting">
|
||||
<long_title>SimpleTest for PHP test runner and display documentation</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
SimpleTest pretty much follows the MVC pattern
|
||||
(Model-View-Controller).
|
||||
The reporter classes are the view and the model is your
|
||||
test cases and their hiearchy.
|
||||
The controller is mostly hidden from the user of
|
||||
SimpleTest unless you want to change how the test cases
|
||||
are actually run, in which case it is possible to
|
||||
override the runner objects from within the test case.
|
||||
As usual with MVC, the controller is mostly undefined
|
||||
and there are other places to control the test run.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="html" title="Reporting results in HTML">
|
||||
<p>
|
||||
The default test display is minimal in the extreme.
|
||||
It reports success and failure with the conventional red and
|
||||
green bars and shows a breadcrumb trail of test groups
|
||||
for every failed assertion.
|
||||
Here's a fail...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<span class="fail">Fail</span>: createnewfile->True assertion failed.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
And here all tests passed...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
The good news is that there are several points in the display
|
||||
hiearchy for subclassing.
|
||||
</p>
|
||||
<p>
|
||||
For web page based displays there is the
|
||||
<code>HtmlReporter</code> class with the following
|
||||
signature...
|
||||
<php><![CDATA[
|
||||
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() { ... }
|
||||
}
|
||||
]]></php>
|
||||
Here is what some of these methods mean. First the display methods
|
||||
that you will probably want to override...
|
||||
<ul class="api">
|
||||
<li>
|
||||
<code>HtmlReporter(string $encoding)</code><br />
|
||||
is the constructor.
|
||||
Note that the unit test sets up the link to the display
|
||||
rather than the other way around.
|
||||
The display is a mostly passive receiver of test events.
|
||||
This allows easy adaption of the display for other test
|
||||
systems beside unit tests, such as monitoring servers.
|
||||
The encoding is the character encoding you wish to
|
||||
display the test output in.
|
||||
In order to correctly render debug output when
|
||||
using the web tester, this should match the encoding
|
||||
of the site you are trying to test.
|
||||
The available character set strings are described in
|
||||
the PHP <a href="http://www.php.net/manual/en/function.htmlentities.php">html_entities()</a>
|
||||
function.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintHeader(string $test_name)</code><br />
|
||||
is called once at the very start of the test when the first
|
||||
start event arrives.
|
||||
The first start event is usually delivered by the top level group
|
||||
test and so this is where <code>$test_name</code>
|
||||
comes from.
|
||||
It paints the page titles, CSS, body tag, etc.
|
||||
It returns nothing (<code>void</code>).
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintFooter(string $test_name)</code><br />
|
||||
Called at the very end of the test to close any tags opened
|
||||
by the page header.
|
||||
By default it also displays the red/green bar and the final
|
||||
count of results.
|
||||
Actually the end of the test happens when a test end event
|
||||
comes in with the same name as the one that started it all
|
||||
at the same level.
|
||||
The tests nest you see.
|
||||
Closing the last test finishes the display.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintMethodStart(string $test_name)</code><br />
|
||||
is called at the start of each test method.
|
||||
The name normally comes from method name.
|
||||
The other test start events behave the same way except
|
||||
that the group test one tells the reporter how large
|
||||
it is in number of held test cases.
|
||||
This is so that the reporter can display a progress bar
|
||||
as the runner churns through the test cases.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintMethodEnd(string $test_name)</code><br />
|
||||
backs out of the test started with the same name.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintFail(string $message)</code><br />
|
||||
paints a failure.
|
||||
By default it just displays the word fail, a breadcrumbs trail
|
||||
showing the current test nesting and the message issued by
|
||||
the assertion.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintPass(string $message)</code><br />
|
||||
by default does nothing.
|
||||
</li>
|
||||
<li>
|
||||
<code>string _getCss()</code><br />
|
||||
Returns the CSS styles as a string for the page header
|
||||
method.
|
||||
Additional styles have to be appended here if you are
|
||||
not overriding the page header.
|
||||
You will want to use this method in an overriden page header
|
||||
if you want to include the original CSS.
|
||||
</li>
|
||||
</ul>
|
||||
There are also some accessors to get information on the current
|
||||
state of the test suite.
|
||||
Use these to enrich the display...
|
||||
<ul class="api">
|
||||
<li>
|
||||
<code>array getTestList()</code><br />
|
||||
is the first convenience method for subclasses.
|
||||
Lists the current nesting of the tests as a list
|
||||
of test names.
|
||||
The first, most deeply nested test, is first in the
|
||||
list and the current test method will be last.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getPassCount()</code><br />
|
||||
returns the number of passes chalked up so far.
|
||||
Needed for the display at the end.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getFailCount()</code><br />
|
||||
is likewise the number of fails so far.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getExceptionCount()</code><br />
|
||||
is likewise the number of errors so far.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getTestCaseCount()</code><br />
|
||||
is the total number of test cases in the test run.
|
||||
This includes the grouping tests themselves.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getTestCaseProgress()</code><br />
|
||||
is the number of test cases completed so far.
|
||||
</li>
|
||||
</ul>
|
||||
One simple modification is to get the HtmlReporter to display
|
||||
the passes as well as the failures and errors...
|
||||
<php><![CDATA[
|
||||
<strong>class ShowPasses extends HtmlReporter {
|
||||
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "&<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}
|
||||
|
||||
function _getCss() {
|
||||
return parent::_getCss() . ' .pass { color: green; }';
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
One method that was glossed over was the <code>makeDry()</code>
|
||||
method.
|
||||
If you run this method, with no parameters, on the reporter
|
||||
before the test suite is run no actual test methods
|
||||
will be called.
|
||||
You will still get the events of entering and leaving the
|
||||
test methods and test cases, but no passes or failures etc,
|
||||
because the test code will not actually be executed.
|
||||
</p>
|
||||
<p>
|
||||
The reason for this is to allow for more sophistcated
|
||||
GUI displays that allow the selection of individual test
|
||||
cases.
|
||||
In order to build a list of possible tests they need a
|
||||
report on the test structure for drawing, say a tree view
|
||||
of the test suite.
|
||||
With a reporter set to dry run that just sends drawing events
|
||||
this is easily accomplished.
|
||||
</p>
|
||||
</section>
|
||||
<section name="other" title="Extending the reporter">
|
||||
<p>
|
||||
Rather than simply modifying the existing display, you might want to
|
||||
produce a whole new HTML look, or even generate text or XML.
|
||||
Rather than override every method in
|
||||
<code>HtmlReporter</code> we can take one
|
||||
step up the class hiearchy to <code>SimpleReporter</code>
|
||||
in the <em>simple_test.php</em> source file.
|
||||
</p>
|
||||
<p>
|
||||
A do nothing display, a blank canvas for your own creation, would
|
||||
be...
|
||||
<php><![CDATA[
|
||||
<strong>require_once('simpletest/simple_test.php');</strong>
|
||||
|
||||
class MyDisplay extends SimpleReporter {<strong>
|
||||
</strong>
|
||||
function paintHeader($test_name) {
|
||||
}
|
||||
|
||||
function paintFooter($test_name) {
|
||||
}
|
||||
|
||||
function paintStart($test_name, $size) {<strong>
|
||||
parent::paintStart($test_name, $size);</strong>
|
||||
}
|
||||
|
||||
function paintEnd($test_name, $size) {<strong>
|
||||
parent::paintEnd($test_name, $size);</strong>
|
||||
}
|
||||
|
||||
function paintPass($message) {<strong>
|
||||
parent::paintPass($message);</strong>
|
||||
}
|
||||
|
||||
function paintFail($message) {<strong>
|
||||
parent::paintFail($message);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
No output would come from this class until you add it.
|
||||
</p>
|
||||
</section>
|
||||
<section name="cli" title="The command line reporter">
|
||||
<p>
|
||||
SimpleTest also ships with a minimal command line reporter.
|
||||
The interface mimics JUnit to some extent, but paints the
|
||||
failure messages as they arrive.
|
||||
To use the command line reporter simply substitute it
|
||||
for the HTML version...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new TestSuite('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
$test->run(<strong>new TextReporter()</strong>);
|
||||
?>
|
||||
]]></php>
|
||||
Then invoke the test suite from the command line...
|
||||
<pre class="shell">
|
||||
php file_test.php
|
||||
</pre>
|
||||
You will need the command line version of PHP installed
|
||||
of course.
|
||||
A passing test suite looks like this...
|
||||
<pre class="shell">
|
||||
File test
|
||||
OK
|
||||
Test cases run: 1/1, Failures: 0, Exceptions: 0
|
||||
</pre>
|
||||
A failure triggers a display like this...
|
||||
<pre class="shell">
|
||||
File test
|
||||
1) True assertion failed.
|
||||
in createnewfile
|
||||
FAILURES!!!
|
||||
Test cases run: 1/1, Failures: 1, Exceptions: 0
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
One of the main reasons for using a command line driven
|
||||
test suite is of using the tester as part of some automated
|
||||
process.
|
||||
To function properly in shell scripts the test script should
|
||||
return a non-zero exit code on failure.
|
||||
If a test suite fails the value <code>false</code>
|
||||
is returned from the <code>SimpleTest::run()</code>
|
||||
method.
|
||||
We can use that result to exit the script with the desired return
|
||||
code...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new TestSuite('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
<strong>exit ($test->run(new TextReporter()) ? 0 : 1);</strong>
|
||||
?>
|
||||
]]></php>
|
||||
Of course we don't really want to create two test scripts,
|
||||
a command line one and a web browser one, for each test suite.
|
||||
The command line reporter includes a method to sniff out the
|
||||
run time environment...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new TestSuite('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
<strong>if (TextReporter::inCli()) {</strong>
|
||||
exit ($test->run(new TextReporter()) ? 0 : 1);
|
||||
<strong>}</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
This is the form used within SimpleTest itself.
|
||||
</p>
|
||||
</section>
|
||||
<section name="xml" title="Remote testing">
|
||||
<p>
|
||||
SimpleTest ships with an <code>XmlReporter</code> class
|
||||
used for internal communication.
|
||||
When run the output looks like...
|
||||
<pre class="shell"><![CDATA[
|
||||
<?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>
|
||||
]]></pre>
|
||||
You can make use of this format with the parser
|
||||
supplied as part of SimpleTest itself.
|
||||
This is called <code>SimpleTestXmlParser</code> and
|
||||
resides in <em>xml.php</em> within the SimpleTest package...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/xml.php');
|
||||
|
||||
...
|
||||
$parser = &new SimpleTestXmlParser(new HtmlReporter());
|
||||
$parser->parse($test_output);
|
||||
?>
|
||||
]]></php>
|
||||
The <code>$test_output</code> should be the XML format
|
||||
from the XML reporter, and could come from say a command
|
||||
line run of a test case.
|
||||
The parser sends events to the reporter just like any
|
||||
other test run.
|
||||
There are some odd occasions where this is actually useful.
|
||||
</p>
|
||||
<p>
|
||||
A problem with large test suites is thet they can exhaust
|
||||
the default 8Mb memory limit on a PHP process.
|
||||
By having the test groups output in XML and run in
|
||||
separate processes, the output can be reparsed to
|
||||
aggregate the results into a much smaller footprint top level
|
||||
test.
|
||||
</p>
|
||||
<p>
|
||||
Because the XML output can come from anywhere, this opens
|
||||
up the possibility of aggregating test runs from remote
|
||||
servers.
|
||||
A test case already exists to do this within the SimpleTest
|
||||
framework, but it is currently experimental...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
<strong>require_once('../remote.php');</strong>
|
||||
require_once('../reporter.php');
|
||||
|
||||
$test_url = ...;
|
||||
$dry_url = ...;
|
||||
|
||||
$test = &new TestSuite('Remote tests');
|
||||
$test->addTestCase(<strong>new RemoteTestCase($test_url, $dry_url)</strong>);
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
The <code>RemoteTestCase</code> 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 <code>RemoteTestCase</code> can be added to test suites
|
||||
just like any other group test.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Displaying <a href="#html">results in HTML</a>
|
||||
</link>
|
||||
<link>
|
||||
Displaying and <a href="#other">reporting results</a>
|
||||
in other formats
|
||||
</link>
|
||||
<link>
|
||||
Using <a href="#cli">SimpleTest from the command line</a>
|
||||
</link>
|
||||
<link>
|
||||
Using <a href="#xml">Using XML</a> for remote testing
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
The <a href="http://simpletest.sourceforge.net/">developer's API for SimpleTest</a>
|
||||
gives full detail on the classes and assertions available.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
php unit testing,
|
||||
documentation,
|
||||
marcus baker,
|
||||
simple test,
|
||||
simpletest,
|
||||
remote testing,
|
||||
xml tests,
|
||||
automated testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,466 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Simple Test for PHP" here="SimpleTest">
|
||||
<long_title>
|
||||
Download the Simple Test testing framework -
|
||||
Unit tests and mock objects for PHP
|
||||
</long_title>
|
||||
<content>
|
||||
<news>
|
||||
1.0.1 release cycle started.
|
||||
Features include include file upload, better PHP5 support for
|
||||
mock objects, and HTML label support.
|
||||
There is also a big clean up of method names and some internals
|
||||
refactoring.
|
||||
</news>
|
||||
<introduction>
|
||||
<p>
|
||||
The following assumes that you are familiar with the concept
|
||||
of unit testing as well as the PHP web development language.
|
||||
It is a guide for the impatient new user of
|
||||
<a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>.
|
||||
For fuller documentation, especially if you are new
|
||||
to unit testing see the ongoing
|
||||
<a local="unit_test_documentation">documentation</a>, and for
|
||||
example test cases see the
|
||||
<a href="http://www.lastcraft.com/first_test_tutorial.php">unit testing tutorial</a>.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="unit" title="Using the tester quickly">
|
||||
<p>
|
||||
Amongst software testing tools, a unit tester is the one
|
||||
closest to the developer.
|
||||
In the context of agile development the test code sits right
|
||||
next to the source code as both are written simultaneously.
|
||||
In this context SimpleTest aims to be a complete PHP developer
|
||||
test solution and is called "Simple" because it
|
||||
should be easy to use and extend.
|
||||
It wasn't a good choice of name really.
|
||||
It includes all of the typical functions you would expect from
|
||||
<a href="http://www.junit.org/">JUnit</a> and the
|
||||
<a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>
|
||||
ports, but also adds
|
||||
<a href="http://www.mockobjects.com">mock objects</a>.
|
||||
It has some <a href="http://sourceforge.net/projects/jwebunit/">JWebUnit</a>
|
||||
functionality as well.
|
||||
This includes web page navigation, cookie testing and form submission.
|
||||
</p>
|
||||
<p>
|
||||
The quickest way to demonstrate is with an example.
|
||||
</p>
|
||||
<p>
|
||||
Let us suppose we are testing a simple file logging class called
|
||||
<code>Log</code> in <em>classes/log.php</em>.
|
||||
We start by creating a test script which we will call
|
||||
<em>tests/log_test.php</em> and populate it as follows...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
Here the <em>simpletest</em> folder is either local or in the path.
|
||||
You would have to edit these locations depending on where you
|
||||
placed the toolset.
|
||||
The <code>TestOfLogging</code> is our frst test case and it's
|
||||
currently empty.
|
||||
</p>
|
||||
<p>
|
||||
Now we have five lines of scaffolding code and still no tests.
|
||||
However from this part on we get return on our investment very quickly.
|
||||
We'll assume that the <code>Log</code> class
|
||||
takes the file name to write to in the constructor and we have
|
||||
a temporary folder in which to place this file...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
<strong>
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
When a test case runs it will search for any method that
|
||||
starts with the string <code>test</code>
|
||||
and execute that method.
|
||||
We would normally have more than one test method of course.
|
||||
Assertions within the test methods trigger messages to the
|
||||
test framework which displays the result immediately.
|
||||
This immediate response is important, not just in the event
|
||||
of the code causing a crash, but also so that
|
||||
<code>print</code> statements can display
|
||||
their content right next to the test case concerned.
|
||||
</p>
|
||||
<p>
|
||||
To see these results we have to actually run the tests.
|
||||
If this is the only test case we wish to run we can achieve
|
||||
it with...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));
|
||||
}
|
||||
}
|
||||
<strong>
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
On failure the display looks like this...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->True assertion failed.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
...and if it passes like this...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>2</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
And if you get this...
|
||||
<div class="demo">
|
||||
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
|
||||
</div>
|
||||
it means you're missing the <em>classes/Log.php</em> file that could look like...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class Log {
|
||||
|
||||
function Log($file_path) {
|
||||
}
|
||||
|
||||
function message() {
|
||||
}
|
||||
}
|
||||
?>;
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="group" title="Building group tests">
|
||||
<p>
|
||||
It is unlikely in a real application that we will only ever run
|
||||
one test case.
|
||||
This means that we need a way of grouping cases into a test
|
||||
script that can, if need be, run every test in the application.
|
||||
</p>
|
||||
<p>
|
||||
Our first step is to strip the includes and to undo our
|
||||
previous hack...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('../classes/log.php');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));<strong>
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Next we create a new file called <em>tests/all_tests.php</em>
|
||||
and insert the following code...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new TestSuite('All tests');
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
]]></php>
|
||||
The method <code>TestSuite::addTestFile()</code>
|
||||
will include the test case file and read any new classes created
|
||||
that are descended from <code>SimpleTestCase</code>, of which
|
||||
<code>UnitTestCase</code> is one example.
|
||||
Just the class names are stored for now, so that the test runner
|
||||
can instantiate the class when it works its way
|
||||
through your test suite.
|
||||
</p>
|
||||
<p>
|
||||
For this to work properly the test case file should not blindly include
|
||||
any other test case extensions that do not actually run tests.
|
||||
This could result in extra test cases being counted during the test
|
||||
run.
|
||||
Hardly a major problem, but to avoid this inconvenience simply add
|
||||
a <code>SimpleTestOptions::ignore()</code> directive
|
||||
somewhere in the test case file.
|
||||
Also the test case file should not have been included
|
||||
elsewhere or no cases will be added to this group test.
|
||||
This would be a more serious error as if the test case classes are
|
||||
already loaded by PHP the <code>TestSuite::addTestFile()</code>
|
||||
method will not detect them.
|
||||
</p>
|
||||
<p>
|
||||
To display the results it is necessary only to invoke
|
||||
<em>tests/all_tests.php</em> from the web server.
|
||||
</p>
|
||||
</section>
|
||||
<section name="mock" title="Using mock objects">
|
||||
<p>
|
||||
Let's move further into the future.
|
||||
</p>
|
||||
<p>
|
||||
Assume that our logging class is tested and completed.
|
||||
Assume also that we are testing another class that is
|
||||
required to write log messages, say a
|
||||
<code>SessionPool</code>.
|
||||
We want to test a method that will probably end up looking
|
||||
like this...
|
||||
<php><![CDATA[<strong>
|
||||
class SessionPool {
|
||||
...
|
||||
function logIn($username) {
|
||||
...
|
||||
$this->_log->message("User $username logged in.");
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
</strong>
|
||||
]]></php>
|
||||
In the spirit of reuse we are using our
|
||||
<code>Log</code> class.
|
||||
A conventional test case might look like this...
|
||||
<php><![CDATA[<strong>
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/session_pool.php');
|
||||
|
||||
class TestOfSessionLogging extends UnitTestCase {
|
||||
|
||||
function setUp() {
|
||||
@unlink('/temp/test.log');
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
@unlink('/temp/test.log');
|
||||
}
|
||||
|
||||
function testLogInIsLogged() {
|
||||
$log = new Log('/temp/test.log');
|
||||
$session_pool = &new SessionPool($log);
|
||||
$session_pool->logIn('fred');
|
||||
$messages = file('/temp/test.log');
|
||||
$this->assertEqual($messages[0], "User fred logged in.\n");
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
This test case design is not all bad, but it could be improved.
|
||||
We are spending time fiddling with log files which are
|
||||
not part of our test. Worse, we have created close ties
|
||||
with the <code>Log</code> class and
|
||||
this test.
|
||||
What if we don't use files any more, but use ths
|
||||
<em>syslog</em> library instead?
|
||||
Did you notice the extra carriage return in the message?
|
||||
Was that added by the logger?
|
||||
What if it also added a time stamp or other data?
|
||||
</p>
|
||||
<p>
|
||||
The only part that we really want to test is that a particular
|
||||
message was sent to the logger.
|
||||
We reduce coupling if we can pass in a fake logging class
|
||||
that simply records the message calls for testing, but
|
||||
takes no action.
|
||||
It would have to look exactly like our original though.
|
||||
</p>
|
||||
<p>
|
||||
If the fake object doesn't write to a file then we save on deleting
|
||||
the file before and after each test. We could save even more
|
||||
test code if the fake object would kindly run the assertion for us.
|
||||
<p>
|
||||
</p>
|
||||
Too good to be true?
|
||||
Luckily we can create such an object easily...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/session_pool.php');<strong>
|
||||
Mock::generate('Log');</strong>
|
||||
|
||||
class TestOfSessionLogging extends UnitTestCase {
|
||||
|
||||
function testLogInIsLogged() {<strong>
|
||||
$log = &new MockLog();
|
||||
$log->expectOnce('message', array('User fred logged in.'));</strong>
|
||||
$session_pool = &new SessionPool($log);
|
||||
$session_pool->logIn('fred');
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
The test will be triggered when the call to
|
||||
<code>message()</code> is invoked on the
|
||||
<code>MockLog</code> object.
|
||||
The mock call will trigger a parameter comparison and then send the
|
||||
resulting pass or fail event to the test display.
|
||||
Wildcards can be included here too so as to prevent tests
|
||||
becoming too specific.
|
||||
</p>
|
||||
<p>
|
||||
If the mock reaches the end of the test case without the
|
||||
method being called, the <code>expectOnce()</code>
|
||||
expectation will trigger a test failure.
|
||||
In other words the mocks can detect the absence of
|
||||
behaviour as well as the presence.
|
||||
</p>
|
||||
<p>
|
||||
The mock objects in the SimpleTest suite can have arbitrary
|
||||
return values set, sequences of returns, return values
|
||||
selected according to the incoming arguments, sequences of
|
||||
parameter expectations and limits on the number of times
|
||||
a method is to be invoked.
|
||||
</p>
|
||||
<p>
|
||||
For this test to run the mock objects library must have been
|
||||
included in the test suite, say in <em>all_tests.php</em>.
|
||||
</p>
|
||||
</section>
|
||||
<section name="web" title="Web page testing">
|
||||
<p>
|
||||
One of the requirements of web sites is that they produce web
|
||||
pages.
|
||||
If you are building a project top-down and you want to fully
|
||||
integrate testing along the way then you will want a way of
|
||||
automatically navigating a site and examining output for
|
||||
correctness.
|
||||
This is the job of a web tester.
|
||||
</p>
|
||||
<p>
|
||||
The web testing in SimpleTest is fairly primitive, there is
|
||||
no JavaScript for example.
|
||||
To give an idea here is a trivial example where a home
|
||||
page is fetched, from which we navigate to an "about"
|
||||
page and then test some client determined content.
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('simpletest/web_tester.php');</strong>
|
||||
require_once('simpletest/reporter.php');
|
||||
<strong>
|
||||
class TestOfAbout extends WebTestCase {
|
||||
|
||||
function setUp() {
|
||||
$this->get('http://test-server/index.php');
|
||||
$this->click('About');
|
||||
}
|
||||
|
||||
function testSearchEngineOptimisations() {
|
||||
$this->assertTitle('A long title about us for search engines');
|
||||
$this->assertPattern('/a popular keyphrase/i');
|
||||
}
|
||||
}</strong>
|
||||
$test = &new TestOfAbout();
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
With this code as an acceptance test you can ensure that
|
||||
the content always meets the specifications of both the
|
||||
developers and the other project stakeholders.
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"/></a>
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#unit">Using unit tester</a>
|
||||
with an example.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#group">Grouping tests</a>
|
||||
for testing with one click.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#mock">Using mock objects</a>
|
||||
to ease testing and gain tighter control.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#web">Testing web pages</a>
|
||||
at the browser level.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a href="https://sourceforge.net/project/showfiles.php?group_id=76550&release_id=153280">Download PHP Simple Test</a>
|
||||
from <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
The <a href="http://simpletest.sourceforge.net/">developer's API for SimpleTest</a>
|
||||
gives full detail on the classes and assertions available.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
mock objects,
|
||||
junit,
|
||||
php testing,
|
||||
php unit,
|
||||
methodology,
|
||||
test first,
|
||||
sourceforge,
|
||||
open source,
|
||||
unit test,
|
||||
web tester,
|
||||
web testing,
|
||||
html testing tools,
|
||||
testing web pages,
|
||||
php mock objects,
|
||||
navigating websites automatically,
|
||||
automated testing,
|
||||
web scripting,
|
||||
wget,
|
||||
curl testing,
|
||||
jmock for php,
|
||||
jwebunit,
|
||||
phpunit,
|
||||
php unit testing,
|
||||
php web testing,
|
||||
jason sweat,
|
||||
marcus baker,
|
||||
topstyle plug in,
|
||||
phpedit plug in
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,256 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Subclassing a unit test case" here="Reusing cases">
|
||||
<long_title>PHP unit testing tutorial - Subclassing a test case</long_title>
|
||||
<content>
|
||||
<p>
|
||||
<a class="target" name="time"><h2>A timing insensitive assertion</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
We left our clock test with a hole.
|
||||
If the PHP <code>time()</code>
|
||||
function rolled over during this comparison...
|
||||
<php><![CDATA[
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertEqual($clock->now(), time(), 'Now is the right time');
|
||||
}
|
||||
]]></php>
|
||||
...our test would be out by one second and would cause
|
||||
a false failure.
|
||||
Erratic behaviour of our test suite is not what we want when
|
||||
we could be running it a hundred times a day.
|
||||
</p>
|
||||
<p>
|
||||
We could rewrite the test as...
|
||||
<php><![CDATA[
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();<strong>
|
||||
$time1 = $clock->now();
|
||||
$time2 = time();
|
||||
$this->assertTrue($time1 == $time2) || ($time1 + 1 == $time2), 'Now is the right time');</strong>
|
||||
}
|
||||
]]></php>
|
||||
This is hardly a clear design though and we will have to repeat
|
||||
this for every timing test that we do.
|
||||
Repetition is public enemy number one and so we'll
|
||||
use this as incentive to factor out the new test code.
|
||||
<php><![CDATA[
|
||||
class TestOfClock extends UnitTestCase {
|
||||
function TestOfClock() {
|
||||
$this->UnitTestCase('Clock class test');
|
||||
}<strong>
|
||||
function assertSameTime($time1, $time2, $message) {
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}</strong>
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();<strong>
|
||||
$this->assertSameTime($clock->now(), time(), 'Now is the right time');</strong>
|
||||
}
|
||||
function testClockAdvance() {
|
||||
$clock = new Clock();
|
||||
$clock->advance(10);<strong>
|
||||
$this->assertSameTime($clock->now(), time() + 10, 'Advancement');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Of course each time I make one of these changes I rerun the
|
||||
tests to make sure we are still OK.
|
||||
Refactor on green.
|
||||
It's a lot safer.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="subclass"><h2>Reusing our assertion</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
It may be that we want more than one test case that is
|
||||
timing sensitive.
|
||||
Perhaps we are reading timestamps from database rows
|
||||
or other places that could allow an extra second to
|
||||
tick over.
|
||||
For these new test classes to take advantage of our new assertion
|
||||
we need to place it into a superclass.
|
||||
</p>
|
||||
<p>
|
||||
Here is the complete <em>clock_test.php</em> file after
|
||||
promoting our <code>assertSameTime()</code>
|
||||
method to its own superclass...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/clock.php');
|
||||
<strong>
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase($test_name) {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, $message) {
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
|
||||
class TestOfClock extends TimeTestCase {
|
||||
function TestOfClock() {
|
||||
$this->TimeTestCase('Clock class test');
|
||||
}</strong>
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertSameTime($clock->now(), time(), 'Now is the right time');
|
||||
}
|
||||
function testClockAdvance() {
|
||||
$clock = new Clock();
|
||||
$clock->advance(10);
|
||||
$this->assertSameTime($clock->now(), time() + 10, 'Advancement');
|
||||
}<strong>
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
Now we get the benefit of our new assertion every
|
||||
time we inherit from our own
|
||||
<code>TimeTestCase</code> class
|
||||
rather than the default
|
||||
<code>UnitTestCase</code>.
|
||||
This is very much how the JUnit tool was designed
|
||||
to be used and SimpleTest is a port of that interface.
|
||||
It is a testing framework from which your own test
|
||||
system can be grown.
|
||||
</p>
|
||||
<p>
|
||||
If we run the tests now we get a slight niggle...
|
||||
<div class="demo">
|
||||
<b>Warning</b>: Missing argument 1 for timetestcase()
|
||||
in <b>/home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php</b> on line <b>5</b><br />
|
||||
<h1>All tests</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
The reasons for this are quite tricky.
|
||||
</p>
|
||||
<p>
|
||||
Our subclass requires a constructor parameter that has
|
||||
not been supplied and yet it appears that we did
|
||||
supply it.
|
||||
When we inherited our new class we passed it in our own
|
||||
constructor.
|
||||
It's right here...
|
||||
<php><![CDATA[
|
||||
function TestOfClock() {
|
||||
$this->TimeTestCase('Clock class test');
|
||||
}
|
||||
]]></php>
|
||||
In fact we are right, that is not the problem.
|
||||
</p>
|
||||
<p>
|
||||
Remember when we built our <em>all_tests.php</em>
|
||||
group test by using the
|
||||
<code>addTestFile()</code> method.
|
||||
This method looks for test case classes, instantiates
|
||||
them if they are new and then runs all of their tests.
|
||||
What's happened is that it has found our
|
||||
test case extension as well.
|
||||
This is harmless as there are no test methods within it,
|
||||
that is, method names that start with the string
|
||||
"test".
|
||||
No extra tests are run.
|
||||
</p>
|
||||
<p>
|
||||
The trouble is that it instantiates the class and does this without
|
||||
the <code>$test_name</code> parameter
|
||||
which is what causes our warning.
|
||||
This parameter is not normally required of a test
|
||||
case and not normally of its assertions either.
|
||||
To make our extended test case match the
|
||||
<code>UnitTestCase</code> interface
|
||||
we must make these optional...
|
||||
<php><![CDATA[
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase(<strong>$test_name = false</strong>) {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, <strong>$message = false</strong>) {<strong>
|
||||
if (! $message) {
|
||||
$message = "Time [$time1] should match time [$time2]";
|
||||
}</strong>
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Of course it should still bother you that this class is
|
||||
instantiated by the test suite unnecessarily.
|
||||
Here is a modification to prevent it running...
|
||||
<php><![CDATA[
|
||||
<strong>SimpleTestOptions::ignore('TimeTestCase');</strong>
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase($test_name = false) {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, $message = '') {
|
||||
if (!$message) {
|
||||
$message = "Time [$time1] should match time [$time2]";
|
||||
}
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
This just tells SimpleTest to always ignore this class when
|
||||
building test suites.
|
||||
It can be included anywhere in the test case file.
|
||||
</p>
|
||||
<p>
|
||||
Six passes looks good, but does not tell the casual
|
||||
observer what has been tested.
|
||||
For that you have to look at the code.
|
||||
If that sounds like drudge to you and you would like this
|
||||
information displayed before you then we should go on
|
||||
to <a local="display_subclass_tutorial">show the passes</a> next.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
A <a href="#time">timing insensitive assertion</a>
|
||||
that allows a one second gain.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#subclass">Subclassing the test case</a>
|
||||
so as to reuse the test method.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
The previous section was
|
||||
<a local="gain_control_tutorial">controlling test variables</a>.
|
||||
</link>
|
||||
<link>
|
||||
The next tutorial section was
|
||||
<a local="display_subclass_tutorial">changing the test display</a>.
|
||||
</link>
|
||||
<link>
|
||||
You will need the
|
||||
<a local="simple_test">SimpleTest test tool</a> to run the
|
||||
sample code.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
test case example,
|
||||
programming php,
|
||||
software development tools,
|
||||
php tutorial,
|
||||
creating subclass,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
junit,
|
||||
phpunit style testing,
|
||||
unit test,
|
||||
php testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,53 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Support mailing list" here="Support mailing list">
|
||||
<long_title>Support mailing list</long_title>
|
||||
<content>
|
||||
<p>
|
||||
The <strong>simpletest-support</strong> mailing-list is probably the most active area
|
||||
around SimpleTest : help, advice, bugs and workarounds tend to happen most of the time.
|
||||
</p>
|
||||
<p>
|
||||
It's really <a href="https://lists.sourceforge.net/lists/listinfo/simpletest-support">easy to subscribe</a>
|
||||
and it's <a href="http://sourceforge.net/mailarchive/forum.php?forum=simpletest-support">fully searchable</a> too.
|
||||
</p>
|
||||
<p>
|
||||
At the last count, there were about 114 subscribers and 1908 message sent.
|
||||
That's anything between 1 and 4 messages per day on average.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#current-release">Current release</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#eclipse-release">Eclipse release</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#packages">Packages</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#source">Source</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#older-stable-releases">Older stable releases</a>
|
||||
</link>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
</external>
|
||||
|
||||
<meta>
|
||||
<keywords>
|
||||
SimpleTest,
|
||||
download,
|
||||
source code,
|
||||
stable release,
|
||||
eclipse release,
|
||||
eclipse plugin,
|
||||
debian package,
|
||||
drupal module,
|
||||
pear channel,
|
||||
pearified package
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,305 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="PHP Unit Test documentation" here="Unit tester">
|
||||
<long_title>SimpleTest for PHP regression test documentation</long_title>
|
||||
<content>
|
||||
<section name="unit" title="Unit test cases">
|
||||
<p>
|
||||
The core system is a regression testing framework built around
|
||||
test cases.
|
||||
A sample test case looks like this...
|
||||
<php><![CDATA[
|
||||
<strong>class FileTestCase extends UnitTestCase {
|
||||
}</strong>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
For example...
|
||||
<php><![CDATA[
|
||||
require_once('../classes/writer.php');
|
||||
|
||||
class FileTestCase extends UnitTestCase {
|
||||
function FileTestCase() {
|
||||
$this->UnitTestCase('File test');
|
||||
}<strong>
|
||||
|
||||
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');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
The constructor is optional and usually omitted.
|
||||
Without a name, the class name is taken as the name of the test case.
|
||||
</p>
|
||||
<p>
|
||||
Our only test method at the moment is <code>testCreation()</code>
|
||||
where we check that a file has been created by our
|
||||
<code>Writer</code> object.
|
||||
We could have put the <code>unlink()</code>
|
||||
code into this method as well, but by placing it in
|
||||
<code>setUp()</code> and
|
||||
<code>tearDown()</code> we can use it with
|
||||
other test methods that we add.
|
||||
</p>
|
||||
<p>
|
||||
The <code>setUp()</code> method is run
|
||||
just before each and every test method.
|
||||
<code>tearDown()</code> is run just after
|
||||
each and every test method.
|
||||
</p>
|
||||
<p>
|
||||
You can place some test case set up into the constructor to
|
||||
be run once for all the methods in the test case, but
|
||||
you risk test inteference that way.
|
||||
This way is slightly slower, but it is safer.
|
||||
Note that if you come from a JUnit background this will not
|
||||
be the behaviour you are used to.
|
||||
JUnit surprisingly reinstantiates the test case for each test
|
||||
method to prevent such interference.
|
||||
SimpleTest requires the end user to use <code>setUp()</code>, but
|
||||
supplies additional hooks for library writers.
|
||||
</p>
|
||||
<p>
|
||||
The means of reporting test results (see below) are by a
|
||||
visiting display class
|
||||
that is notified by various <code>assert...()</code>
|
||||
methods.
|
||||
Here is the full list for the <code>UnitTestCase</code>
|
||||
class, the default for SimpleTest...
|
||||
<table><tbody>
|
||||
<tr><td><code>assertTrue($x)</code></td><td>Fail if $x is false</td></tr>
|
||||
<tr><td><code>assertFalse($x)</code></td><td>Fail if $x is true</td></tr>
|
||||
<tr><td><code>assertNull($x)</code></td><td>Fail if $x is set</td></tr>
|
||||
<tr><td><code>assertNotNull($x)</code></td><td>Fail if $x not set</td></tr>
|
||||
<tr><td><code>assertIsA($x, $t)</code></td><td>Fail if $x is not the class or type $t</td></tr>
|
||||
<tr><td><code>assertNotA($x, $t)</code></td><td>Fail if $x is of the class or type $t</td></tr>
|
||||
<tr><td><code>assertEqual($x, $y)</code></td><td>Fail if $x == $y is false</td></tr>
|
||||
<tr><td><code>assertNotEqual($x, $y)</code></td><td>Fail if $x == $y is true</td></tr>
|
||||
<tr><td><code>assertWithinMargin($x, $y, $m)</code></td><td>Fail if abs($x - $y) < $m is false</td></tr>
|
||||
<tr><td><code>assertOutsideMargin($x, $y, $m)</code></td><td>Fail if abs($x - $y) < $m is true</td></tr>
|
||||
<tr><td><code>assertIdentical($x, $y)</code></td><td>Fail if $x == $y is false or a type mismatch</td></tr>
|
||||
<tr><td><code>assertNotIdentical($x, $y)</code></td><td>Fail if $x == $y is true and types match</td></tr>
|
||||
<tr><td><code>assertReference($x, $y)</code></td><td>Fail unless $x and $y are the same variable</td></tr>
|
||||
<tr><td><code>assertClone($x, $y)</code></td><td>Fail unless $x and $y are identical copies</td></tr>
|
||||
<tr><td><code>assertPattern($p, $x)</code></td><td>Fail unless the regex $p matches $x</td></tr>
|
||||
<tr><td><code>assertNoPattern($p, $x)</code></td><td>Fail if the regex $p matches $x</td></tr>
|
||||
<tr><td><code>expectError($x)</code></td><td>Swallows any upcoming matching error</td></tr>
|
||||
<tr><td><code>assert($e)</code></td><td>Fail on failed <a local="expectation_documentation">expectation</a> object $e</td></tr>
|
||||
</tbody></table>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Some examples...
|
||||
<php><![CDATA[
|
||||
$variable = null;
|
||||
<strong>$this->assertNull($variable, 'Should be cleared');</strong>
|
||||
]]></php>
|
||||
...will pass and normally show no message.
|
||||
If you have
|
||||
<a href="http://www.lastcraft.com/display_subclass_tutorial.php">set up the tester to display passes</a>
|
||||
as well then the message will be displayed as is.
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertIdentical(0, false, 'Zero is not false [%s]');</strong>
|
||||
]]></php>
|
||||
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.
|
||||
<php><![CDATA[
|
||||
$a = 1;
|
||||
$b = $a;
|
||||
<strong>$this->assertReference($a, $b);</strong>
|
||||
]]></php>
|
||||
Will fail as the variable <code>$a</code> is a copy of <code>$b</code>.
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertPattern('/hello/i', 'Hello world');</strong>
|
||||
]]></php>
|
||||
This will pass as using a case insensitive match the string
|
||||
<code>hello</code> is contained in <code>Hello world</code>.
|
||||
<php><![CDATA[
|
||||
<strong>$this->expectError();</strong>
|
||||
trigger_error('Catastrophe');
|
||||
]]></php>
|
||||
Here the check catches the "Catastrophe"
|
||||
message without checking the text and passes.
|
||||
This removes the error from the queue.
|
||||
<php><![CDATA[
|
||||
<strong>$this->expectError('Catastrophe');</strong>
|
||||
trigger_error('Catastrophe');
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Note that SimpleTest cannot catch compile time PHP errors.
|
||||
</p>
|
||||
<p>
|
||||
The test cases also have some convenience methods for debugging
|
||||
code or extending the suite...
|
||||
<table><tbody>
|
||||
<tr><td><code>setUp()</code></td><td>Runs this before each test method</td></tr>
|
||||
<tr><td><code>tearDown()</code></td><td>Runs this after each test method</td></tr>
|
||||
<tr><td><code>pass()</code></td><td>Sends a test pass</td></tr>
|
||||
<tr><td><code>fail()</code></td><td>Sends a test failure</td></tr>
|
||||
<tr><td><code>error()</code></td><td>Sends an exception event</td></tr>
|
||||
<tr><td><code>signal($type, $payload)</code></td><td>Sends a user defined message to the test reporter</td></tr>
|
||||
<tr><td><code>dump($var)</code></td><td>Does a formatted <code>print_r()</code> for quick and dirty debugging</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
</section>
|
||||
<section name="extending_unit" title="Extending test cases">
|
||||
<p>
|
||||
Of course additional test methods can be added to create
|
||||
specific types of test case, so as to extend framework...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/unit_tester.php');
|
||||
<strong>
|
||||
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'));
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Here the SimpleTest library is held in a folder called
|
||||
<em>simpletest</em> that is local.
|
||||
Substitute your own path for this.
|
||||
</p>
|
||||
<p>
|
||||
To prevent this test case being run accidently, it is
|
||||
advisable to mark it as <code>abstract</code>.
|
||||
</p>
|
||||
<p>
|
||||
This new case can be now be inherited just like
|
||||
a normal test case...
|
||||
<php><![CDATA[
|
||||
class FileTestCase extends <strong>FileTester</strong> {
|
||||
|
||||
function setUp() {
|
||||
@unlink('../temp/test.txt');
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.txt');
|
||||
}
|
||||
|
||||
function testCreation() {
|
||||
$writer = &new FileWriter('../temp/test.txt');
|
||||
$writer->write('Hello');<strong>
|
||||
$this->assertFileExists('../temp/test.txt');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
If you want a test case that does not have all of the
|
||||
<code>UnitTestCase</code> assertions,
|
||||
only your own and a few basics,
|
||||
you need to extend the <code>SimpleTestCase</code>
|
||||
class instead.
|
||||
It is found in <em>simple_test.php</em> rather than
|
||||
<em>unit_tester.php</em>.
|
||||
See <a local="group_test_documentation">later</a> if you
|
||||
want to incorporate other unit tester's
|
||||
test cases in your test suites.
|
||||
</p>
|
||||
</section>
|
||||
<section name="running_unit" title="Running a single test case">
|
||||
<p>
|
||||
You won't often run single test cases except when bashing
|
||||
away at a module that is having difficulty, and you don't
|
||||
want to upset the main test suite.
|
||||
Here is the scaffolding needed to run a lone test case...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');<strong>
|
||||
require_once('simpletest/reporter.php');</strong>
|
||||
require_once('../classes/writer.php');
|
||||
|
||||
class FileTestCase extends UnitTestCase {
|
||||
function FileTestCase() {
|
||||
$this->UnitTestCase('File test');
|
||||
}
|
||||
}<strong>
|
||||
|
||||
$test = &new FileTestCase();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
This script will run as is, but of course will output zero passes
|
||||
and zero failures until test methods are added.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#unit">Unit test cases</a> and basic assertions.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#extending_unit">Extending test cases</a> to
|
||||
customise them for your own project.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#running_unit">Running a single case</a> as
|
||||
a single script.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">Full API for SimpleTest</a>
|
||||
from the PHPDoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
php unit testing,
|
||||
test integration,
|
||||
documentation,
|
||||
marcus baker,
|
||||
simple test,
|
||||
simpletest documentation,
|
||||
phpunit,
|
||||
junit,
|
||||
xunit,
|
||||
agile web development,
|
||||
eXtreme Programming,
|
||||
Test Driven,
|
||||
TDD
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,374 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Web tester documentation" here="Web tester">
|
||||
<long_title>Simple Test for PHP web script testing documentation</long_title>
|
||||
<content>
|
||||
<section name="fetch" title="Fetching a page">
|
||||
<p>
|
||||
Testing classes is all very well, but PHP is predominately
|
||||
a language for creating functionality within web pages.
|
||||
How do we test the front end presentation role of our PHP
|
||||
applications?
|
||||
Well the web pages are just text, so we should be able to
|
||||
examine them just like any other test data.
|
||||
</p>
|
||||
<p>
|
||||
This leads to a tricky issue.
|
||||
If we test at too low a level, testing for matching tags
|
||||
in the page with pattern matching for example, our tests will
|
||||
be brittle.
|
||||
The slightest change in layout could break a large number of
|
||||
tests.
|
||||
If we test at too high a level, say using mock versions of a
|
||||
template engine, then we lose the ability to automate some classes
|
||||
of test.
|
||||
For example, the interaction of forms and navigation will
|
||||
have to be tested manually.
|
||||
These types of test are extremely repetitive and error prone.
|
||||
</p>
|
||||
<p>
|
||||
SimpleTest includes a special form of test case for the testing
|
||||
of web page actions.
|
||||
The <code>WebTestCase</code> includes facilities
|
||||
for navigation, content and cookie checks and form handling.
|
||||
Usage of these test cases is similar to the
|
||||
<a local="unit_tester_documentation">UnitTestCase</a>...
|
||||
<php><![CDATA[
|
||||
<strong>class TestOfLastcraft extends WebTestCase {
|
||||
}</strong>
|
||||
]]></php>
|
||||
Here we are about to test the
|
||||
<a href="http://www/lastcraft.com/">Last Craft</a> site itself.
|
||||
If this test case is in a file called <em>lastcraft_test.php</em>
|
||||
then it can be loaded in a runner script just like unit tests...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('simpletest/web_tester.php');</strong>
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new TestSuite('Web site tests');<strong>
|
||||
$test->addTestFile('lastcraft_test.php');</strong>
|
||||
exit ($test->run(new TextReporter()) ? 0 : 1);
|
||||
?>
|
||||
]]></php>
|
||||
I am using the text reporter here to more clearly
|
||||
distinguish the web content from the test output.
|
||||
</p>
|
||||
<p>
|
||||
Nothing is being tested yet.
|
||||
We can fetch the home page by using the
|
||||
<code>get()</code> method...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
<strong>
|
||||
function testHomepage() {
|
||||
$this->assertTrue($this->get('http://www.lastcraft.com/'));
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
The <code>get()</code> 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 <code>get()</code> method will still return true.
|
||||
</p>
|
||||
<p>
|
||||
Assuming that the web server for the Last Craft site is up
|
||||
(sadly not always the case), we should see...
|
||||
<pre class="shell">
|
||||
Web site tests
|
||||
OK
|
||||
Test cases run: 1/1, Failures: 0, Exceptions: 0
|
||||
</pre>
|
||||
All we have really checked is that any kind of page was
|
||||
returned.
|
||||
We don't yet know if it was the right one.
|
||||
</p>
|
||||
</section>
|
||||
<section name="content" title="Testing page content">
|
||||
<p>
|
||||
To confirm that the page we think we are on is actually the
|
||||
page we are on, we need to verify the page content.
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {<strong>
|
||||
$this->get('http://www.lastcraft.com/');
|
||||
$this->assertText('Why the last craft');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The page from the last fetch is held in a buffer in
|
||||
the test case, so there is no need to refer to it directly.
|
||||
The pattern match is always made against the buffer.
|
||||
</p>
|
||||
<p>
|
||||
Here is the list of possible content assertions...
|
||||
<table><tbody>
|
||||
<tr><td><code>assertTitle($title)</code></td><td>Pass if title is an exact match</td></tr>
|
||||
<tr><td><code>assertText($text)</code></td><td>Pass if matches visible and "alt" text</td></tr>
|
||||
<tr><td><code>assertNoText($text)</code></td><td>Pass if doesn't match visible and "alt" text</td></tr>
|
||||
<tr><td><code>assertPattern($pattern)</code></td><td>A Perl pattern match against the page content</td></tr>
|
||||
<tr><td><code>assertNoPattern($pattern)</code></td><td>A Perl pattern match to not find content</td></tr>
|
||||
<tr><td><code>assertLink($label)</code></td><td>Pass if a link with this text is present</td></tr>
|
||||
<tr><td><code>assertNoLink($label)</code></td><td>Pass if no link with this text is present</td></tr>
|
||||
<tr><td><code>assertLinkById($id)</code></td><td>Pass if a link with this id attribute is present</td></tr>
|
||||
<tr><td><code>assertNoLinkById($id)</code></td><td>Pass if no link with this id attribute is present</td></tr>
|
||||
<tr><td><code>assertField($name, $value)</code></td><td>Pass if an input tag with this name has this value</td></tr>
|
||||
<tr><td><code>assertFieldById($id, $value)</code></td><td>Pass if an input tag with this id has this value</td></tr>
|
||||
<tr><td><code>assertResponse($codes)</code></td><td>Pass if HTTP response matches this list</td></tr>
|
||||
<tr><td><code>assertMime($types)</code></td><td>Pass if MIME type is in this list</td></tr>
|
||||
<tr><td><code>assertAuthentication($protocol)</code></td><td>Pass if the current challenge is this protocol</td></tr>
|
||||
<tr><td><code>assertNoAuthentication()</code></td><td>Pass if there is no current challenge</td></tr>
|
||||
<tr><td><code>assertRealm($name)</code></td><td>Pass if the current challenge realm matches</td></tr>
|
||||
<tr><td><code>assertHeader($header, $content)</code></td><td>Pass if a header was fetched matching this value</td></tr>
|
||||
<tr><td><code>assertNoHeader($header)</code></td><td>Pass if a header was not fetched</td></tr>
|
||||
<tr><td><code>assertCookie($name, $value)</code></td><td>Pass if there is currently a matching cookie</td></tr>
|
||||
<tr><td><code>assertNoCookie($name)</code></td><td>Pass if there is currently no cookie of this name</td></tr>
|
||||
</tbody></table>
|
||||
As usual with the SimpleTest assertions, they all return
|
||||
false on failure and true on pass.
|
||||
They also allow an optional test message and you can embed
|
||||
the original test message inside using "%s" inside
|
||||
your custom message.
|
||||
</p>
|
||||
<p>
|
||||
So now we could instead test against the title tag with...
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');</strong>
|
||||
]]></php>
|
||||
...or, if that is too long and fragile...
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertTitle(new PatternExpectation('/The Last Craft/'));</strong>
|
||||
]]></php>
|
||||
As well as the simple HTML content checks we can check
|
||||
that the MIME type is in a list of allowed types with...
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertMime(array('text/plain', 'text/html'));</strong>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testRedirects() {
|
||||
$this->get('http://www.lastcraft.com/test/redirect.php');
|
||||
$this->assertResponse(200);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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 <code>WebTestCase</code> 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...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {<strong>
|
||||
$this->setMaximumRedirects(0);</strong>
|
||||
$this->get('http://www.lastcraft.com/test/redirect.php');
|
||||
$this->assertResponse(200);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The assertion now fails as expected...
|
||||
<pre class="shell">
|
||||
Web site tests
|
||||
1) Expecting response in [200] got [302]
|
||||
in testhomepage
|
||||
in testoflastcraft
|
||||
in lastcraft_test.php
|
||||
FAILURES!!!
|
||||
Test cases run: 1/1, Failures: 1, Exceptions: 0
|
||||
</pre>
|
||||
We can modify the test to correctly assert redirects with...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {
|
||||
$this->setMaximumRedirects(0);
|
||||
$this->get('http://www.lastcraft.com/test/redirect.php');
|
||||
$this->assertResponse(<strong>array(301, 302, 303, 307)</strong>);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
This now passes.
|
||||
</p>
|
||||
</section>
|
||||
<section name="navigation" title="Navigating a web site">
|
||||
<p>
|
||||
Users don't often navigate sites by typing in URLs, but by
|
||||
clicking links and buttons.
|
||||
Here we confirm that the contact details can be reached
|
||||
from the home page...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
...
|
||||
function testContact() {
|
||||
$this->get('http://www.lastcraft.com/');<strong>
|
||||
$this->clickLink('About');
|
||||
$this->assertTitle(new PatternExpectation('/About Last Craft/'));</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
The parameter is the text of the link.
|
||||
</p>
|
||||
<p>
|
||||
If the target is a button rather than an anchor tag, then
|
||||
<code>clickSubmit()</code> can be used
|
||||
with the button title...
|
||||
<php><![CDATA[
|
||||
<strong>$this->clickSubmit('Go!');</strong>
|
||||
]]></php>
|
||||
If you are not sure or don't care, the usual case, then just
|
||||
use the <code>click()</code> method...
|
||||
<php><![CDATA[
|
||||
<strong>$this->click('Go!');</strong>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
The list of navigation methods is...
|
||||
<table><tbody>
|
||||
<tr><td><code>getUrl()</code></td><td>The current location</td></tr>
|
||||
<tr><td><code>get($url, $parameters)</code></td><td>Send a GET request with these parameters</td></tr>
|
||||
<tr><td><code>post($url, $parameters)</code></td><td>Send a POST request with these parameters</td></tr>
|
||||
<tr><td><code>head($url, $parameters)</code></td><td>Send a HEAD request without replacing the page content</td></tr>
|
||||
<tr><td><code>retry()</code></td><td>Reload the last request</td></tr>
|
||||
<tr><td><code>back()</code></td><td>Like the browser back button</td></tr>
|
||||
<tr><td><code>forward()</code></td><td>Like the browser forward button</td></tr>
|
||||
<tr><td><code>authenticate($name, $password)</code></td><td>Retry after a challenge</td></tr>
|
||||
<tr><td><code>restart()</code></td><td>Restarts the browser as if a new session</td></tr>
|
||||
<tr><td><code>getCookie($name)</code></td><td>Gets the cookie value for the current context</td></tr>
|
||||
<tr><td><code>ageCookies($interval)</code></td><td>Ages current cookies prior to a restart</td></tr>
|
||||
<tr><td><code>clearFrameFocus()</code></td><td>Go back to treating all frames as one page</td></tr>
|
||||
<tr><td><code>clickSubmit($label)</code></td><td>Click the first button with this label</td></tr>
|
||||
<tr><td><code>clickSubmitByName($name)</code></td><td>Click the button with this name attribute</td></tr>
|
||||
<tr><td><code>clickSubmitById($id)</code></td><td>Click the button with this ID attribute</td></tr>
|
||||
<tr><td><code>clickImage($label, $x, $y)</code></td><td>Click an input tag of type image by title or alt text</td></tr>
|
||||
<tr><td><code>clickImageByName($name, $x, $y)</code></td><td>Click an input tag of type image by name</td></tr>
|
||||
<tr><td><code>clickImageById($id, $x, $y)</code></td><td>Click an input tag of type image by ID attribute</td></tr>
|
||||
<tr><td><code>submitFormById($id)</code></td><td>Submit a form without the submit value</td></tr>
|
||||
<tr><td><code>clickLink($label, $index)</code></td><td>Click an anchor by the visible label text</td></tr>
|
||||
<tr><td><code>clickLinkById($id)</code></td><td>Click an anchor by the ID attribute</td></tr>
|
||||
<tr><td><code>getFrameFocus()</code></td><td>The name of the currently selected frame</td></tr>
|
||||
<tr><td><code>setFrameFocusByIndex($choice)</code></td><td>Focus on a frame counting from 1</td></tr>
|
||||
<tr><td><code>setFrameFocus($name)</code></td><td>Focus on a frame by name</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
<p>
|
||||
The parameters in the <code>get()</code>, <code>post()</code> or
|
||||
<code>head()</code> methods are optional.
|
||||
The HTTP HEAD fetch does not change the browser context, only loads
|
||||
cookies.
|
||||
This can be useful for when an image or stylesheet sets a cookie
|
||||
for crafty robot blocking.
|
||||
</p>
|
||||
<p>
|
||||
The <code>retry()</code>, <code>back()</code> and
|
||||
<code>forward()</code> commands work as they would on
|
||||
your web browser.
|
||||
They use the history to retry pages.
|
||||
This can be handy for checking the effect of hitting the
|
||||
back button on your forms.
|
||||
</p>
|
||||
<p>
|
||||
The frame methods need a little explanation.
|
||||
By default a framed page is treated just like any other.
|
||||
Content will be searced for throughout the entire frameset,
|
||||
so clicking a link will work no matter which frame
|
||||
the anchor tag is in.
|
||||
You can override this behaviour by focusing on a single
|
||||
frame.
|
||||
If you do that, all searches and actions will apply to that
|
||||
frame alone, such as authentication and retries.
|
||||
If a link or button is not in a focused frame then it cannot
|
||||
be clicked.
|
||||
</p>
|
||||
<p>
|
||||
Testing navigation on fixed pages only tells you when you
|
||||
have broken an entire script.
|
||||
For highly dynamic pages, such as for bulletin boards, this can
|
||||
be crucial for verifying the correctness of the application.
|
||||
For most applications though, the really tricky logic is usually in
|
||||
the handling of forms and sessions.
|
||||
Fortunately SimpleTest includes
|
||||
<a local="form_testing_documentation">tools for testing web forms</a>
|
||||
as well.
|
||||
</p>
|
||||
</section>
|
||||
<section name="request" title="Modifying the request">
|
||||
<p>
|
||||
Although SimpleTest does not have the goal of testing networking
|
||||
problems, it does include some methods to modify and debug
|
||||
the requests it makes.
|
||||
Here is another method list...
|
||||
<table><tbody>
|
||||
<tr><td><code>getTransportError()</code></td><td>The last socket error</td></tr>
|
||||
<tr><td><code>showRequest()</code></td><td>Dump the outgoing request</td></tr>
|
||||
<tr><td><code>showHeaders()</code></td><td>Dump the incoming headers</td></tr>
|
||||
<tr><td><code>showSource()</code></td><td>Dump the raw HTML page content</td></tr>
|
||||
<tr><td><code>ignoreFrames()</code></td><td>Do not load framesets</td></tr>
|
||||
<tr><td><code>setCookie($name, $value)</code></td><td>Set a cookie from now on</td></tr>
|
||||
<tr><td><code>addHeader($header)</code></td><td>Always add this header to the request</td></tr>
|
||||
<tr><td><code>setMaximumRedirects($max)</code></td><td>Stop after this many redirects</td></tr>
|
||||
<tr><td><code>setConnectionTimeout($timeout)</code></td><td>Kill the connection after this time between bytes</td></tr>
|
||||
<tr><td><code>useProxy($proxy, $name, $password)</code></td><td>Make requests via this proxy URL</td></tr>
|
||||
</tbody></table>
|
||||
These methods are principally for debugging.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Successfully <a href="#fetch">fetching a web page</a>
|
||||
</link>
|
||||
<link>
|
||||
Testing the <a href="#content">page content</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#navigation">Navigating a web site</a>
|
||||
while testing
|
||||
</link>
|
||||
<link>
|
||||
<a href="#request">Raw request modifications</a> and debugging methods
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
The <a href="http://simpletest.sourceforge.net/">developer's API for SimpleTest</a>
|
||||
gives full detail on the classes and assertions available.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
software development,
|
||||
php programming for clients,
|
||||
customer focused php,
|
||||
software development tools,
|
||||
acceptance testing framework,
|
||||
free php scripts,
|
||||
architecture,
|
||||
php resources,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
php testing,
|
||||
unit test resource,
|
||||
web testing
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,252 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur l'authentification" here="L'authentification">
|
||||
<long_title>Documentation Simple Test : tester l'authentification</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="basique" title="Authentification HTTP basique">
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {<strong>
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');
|
||||
$this->showHeaders();
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Ce qui nous permet de voir les entêtes reçues...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<pre style="background-color: lightgray; color: black"><![CDATA[
|
||||
HTTP/1.1 401 Authorization Required
|
||||
Date: Sat, 18 Sep 2004 19:25:18 GMT
|
||||
Server: Apache/1.3.29 (Unix) PHP/4.3.4
|
||||
WWW-Authenticate: Basic realm="SimpleTest basic authentication"
|
||||
Connection: close
|
||||
Content-Type: text/html; charset=iso-8859-1
|
||||
]]></pre>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
Sauf que nous voulons é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...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function test401Header() {
|
||||
$this->get('http://www.lastcraft.com/protected/');<strong>
|
||||
$this->assertAuthentication('Basic');
|
||||
$this->assertResponse(401);
|
||||
$this->assertRealm('SimpleTest basic authentication');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
N'importe laquelle de ces assertions suffirait, tout dépend de la masse de détails que vous souhaitez voir.
|
||||
</p>
|
||||
<p>
|
||||
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 :
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function testAuthentication() {
|
||||
$this->get('http://www.lastcraft.com/protected/');<strong>
|
||||
$this->authenticate('Me', 'Secret');</strong>
|
||||
$this->assertTitle(...);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Vous pouvez gagner une ligne en définissant l'authentification au niveau de l'URL...
|
||||
<php><![CDATA[
|
||||
class AuthenticationTest extends WebTestCase {
|
||||
function testCanReadAuthenticatedPages() {
|
||||
$this->get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/');
|
||||
$this->assertTitle(...);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
<section name="cookies" title="Cookies">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Commençons par un simple formulaire de connexion...
|
||||
<pre><![CDATA[
|
||||
<form>
|
||||
Username:
|
||||
<input type="text" name="u" value="" /><br />
|
||||
Password:
|
||||
<input type="password" name="p" value="" /><br />
|
||||
<input type="submit" value="Log in" />
|
||||
</form>
|
||||
]]></pre>
|
||||
Lequel doit ressembler à...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
Username:
|
||||
<input type="text" name="u" value="" /><br />
|
||||
Password:
|
||||
<input type="password" name="p" value="" /><br />
|
||||
<input type="submit" value="Log in" />
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
Supposons que, durant le chargement de la page, un cookie ait é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...
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
function testSessionCookieSetBeforeForm() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$this->assertCookie('SID');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Nous nous contentons ici de vérifier que le cookie a bien été défini. Etant donné que sa valeur est plutôt énigmatique, elle ne vaut pas la peine d'être testée.
|
||||
</p>
|
||||
<p>
|
||||
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é :
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testSessionCookieSameAfterLogIn() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$session = $this->getCookie('SID');
|
||||
$this->setField('u', 'Me');
|
||||
$this->setField('p', 'Secret');
|
||||
$this->clickSubmit('Log in');
|
||||
$this->assertWantedPattern('/Welcome Me/');
|
||||
$this->assertCookie('SID', $session);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Ceci confirme que l'identifiant de session est identique avant et après la connexion.
|
||||
</p>
|
||||
<p>
|
||||
Nous pouvons même essayer de duper notre propre système en créant un cookie arbitraire pour se connecter...
|
||||
<php><![CDATA[
|
||||
class LogInTest extends WebTestCase {
|
||||
...
|
||||
function testSessionCookieSameAfterLogIn() {
|
||||
$this->get('http://www.my-site.com/login.php');<strong>
|
||||
$this->setCookie('SID', 'Some other session');
|
||||
$this->get('http://www.my-site.com/restricted.php');</strong>
|
||||
$this->assertWantedPattern('/Access denied/');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Votre site est-il protégé contre ce type d'attaque ?
|
||||
</p>
|
||||
</section>
|
||||
<section name="session" title="Sessions de navigateur">
|
||||
<p>
|
||||
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 :
|
||||
<php><![CDATA[
|
||||
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/');<strong>
|
||||
|
||||
$this->restart();
|
||||
$this->get('http://www.my-site.com/restricted.php');
|
||||
$this->assertWantedPattern('/Access denied/');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
La méthode <code>WebTestCase::restart()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
</p>
|
||||
<p>
|
||||
Afin de provoquer leur expiration, vous pouvez dater manuellement les cookies, avant le début de la session.
|
||||
<php><![CDATA[
|
||||
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/');
|
||||
<strong>
|
||||
$this->ageCookies(3600);</strong>
|
||||
$this->restart();
|
||||
$this->get('http://www.my-site.com/restricted.php');
|
||||
$this->assertWantedPattern('/Access denied/');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Passer au travers d'une <a href="#basique">authentification HTTP basique</a>
|
||||
</link>
|
||||
<link>
|
||||
Tester l'<a href="#cookies">authentification basée sur des cookies</a>
|
||||
</link>
|
||||
<link>
|
||||
Gérer les <a href="#session">sessions du navigateur</a> et les timeouts
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API du développeur pour SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
php orienté client,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressources php,
|
||||
objets fantaise,
|
||||
php testing,
|
||||
php unit,
|
||||
méthodologie,
|
||||
développement piloté par les tests,
|
||||
outils tests html,
|
||||
tester des web pages,
|
||||
php objets fantaise,
|
||||
naviguer automatiquement sur des sites web,
|
||||
test automatisé,
|
||||
scripting web,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
phpunit,
|
||||
php unit testing,
|
||||
php web testing,
|
||||
test unitaire de système d'authentification,
|
||||
authentification HTTP,
|
||||
test de connexion,
|
||||
test d'authentification,
|
||||
test de sécurité
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,75 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Livres" here="Livres">
|
||||
<long_title>Livres avec / à propos / pas loin de SimpleTest</long_title>
|
||||
<content>
|
||||
<section name="latest-recommandation" title="Dernière recommandation">
|
||||
<p>
|
||||
De temps en temsp, un livre est recommandé sur la mailing-list,
|
||||
vous le trouverez ci-dessous avec les commentaires originaux !
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215?ie=UTF8&tag=simpletest-21&"><img src="../images/book-domain-driven-design.jpg" alt="Domain-Driven Design: Tackling Complexity in the Heart of Software" /></a>
|
||||
</p>
|
||||
<blockquote>
|
||||
Le Développement Piloté par les Tests est principalement intéressé par
|
||||
les mécanismes pour coder, mais il dit que c'est fini quand il n'y plus
|
||||
de duplication. Le Développement Piloté par la Conception (DDD) considère
|
||||
que le code est constamment <strike>in churn</strike>, changeant de terminologie au
|
||||
fur et à mesure que le domaine devient plus clair, et aussi nourrisant le domaine
|
||||
avec des nouveaux termes quand le code évolue..<br />
|
||||
<br />
|
||||
Et puis, c'est un super bouquin :)
|
||||
[<a href="http://sourceforge.net/mailarchive/message.php?msg_id=37546605">source</a>]
|
||||
</blockquote>
|
||||
</section>
|
||||
<section name="books-by-contributors" title="Livres par des contributeurs">
|
||||
<p>
|
||||
Deux contributeurs de Simpletest ont écrit des livres sur PHP.
|
||||
Tous les deux ont de nombreux exemples avec le framework SimpleTest.
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://www.amazon.fr/gp/product/0973589825?ie=UTF8&tag=simpletest-21&linkCode=as2&camp=1642&creative=6746&creativeASIN=0973589825"><img src="../images/book-guide-to-php-design-patterns.jpg" alt="PHP|Architect's Guide to PHP Design Patterns" /></a>
|
||||
<br />
|
||||
<strong>PHP|Architect's Guide to PHP Design Patterns</strong><br />
|
||||
par Jason E. Sweat<br />
|
||||
(l'obtenir depuis : <a href="http://www.phparch.com/shop_product.php?itemid=96">PHP|Architect</a> |
|
||||
<a href="http://www.amazon.fr/gp/product/0973589825?ie=UTF8&tag=simpletest-21&linkCode=as2&camp=1642&creative=6746&creativeASIN=0973589825">Amazon</a> )
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://www.amazon.fr/gp/product/0957921845/402-9483515-6732155?ie=UTF8&tag=simpletest-21&linkCode=xm2&camp=1642&creativeASIN=0957921845"><img src="../images/book-the-php-anthology-object-oriented-php-solutions.jpg" alt="The PHP Anthology: Object Oriented PHP Solutions" /></a>
|
||||
<br />
|
||||
<strong>The PHP Anthology: Object Oriented PHP Solutions</strong><br />
|
||||
par Harry Fuecks<br />
|
||||
(l'obtenir depuis : <a href="http://www.sitepoint.com/books/phpant1/">SitePoint</a> |
|
||||
<a href="http://www.amazon.fr/gp/product/0957921845/402-9483515-6732155?ie=UTF8&tag=simpletest-21&linkCode=xm2&camp=1642&creativeASIN=0957921845">Amazon</a> |
|
||||
<a href="http://developers.slashdot.org/article.pl?sid=04/08/04/1516258&amp;tid=169&amp;tid=192&amp;tid=218&amp;mode=nocomment">critique sur Slashdot</a> )
|
||||
</p>
|
||||
</section>
|
||||
<section name="buying-books" title="Achter des livres">
|
||||
<p>
|
||||
Une manière d'aider l'équipe de contributeurs, c'est d'acheter des livres via
|
||||
cete page avec Amazon (avec le mot-clé <cite>simpletest-21</cite>).
|
||||
Nous adorons tous lire des trucs à la fois intéressants et stimulants.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#latest-recommandation">Latest recommandation</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#books-by-contributors">Books by contributors</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#buying-books">Buying books</a>
|
||||
</link>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
</external>
|
||||
|
||||
<meta>
|
||||
<keywords>
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,268 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Les frontières de l'application" here="Les frontières de l'application">
|
||||
<long_title>
|
||||
Tutorial de tests unitaires PHP - Organiser les tests unitaires et les scénarios de test de classe frontière
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Vous pensez probablement que nous avons désormais épuisé les modifications sur la classe <code>Log</code> et qu'il n'y a plus rien à ajouter. Sauf que les choses ne sont jamais simples avec la Programmation Orienté Objet. Vous pensez comprendre un problème et un nouveau cas arrive : il défie votre point de vue et vous conduit vers une analyse encore plus profonde. Je pensais comprendre la classe de log et que seule la première page du tutorial l'utiliserait. Après ça, je serais passé à quelque chose de plus compliqué. Personne n'est plus surpris que moi de ne pas l'avoir bouclée. En fait je pense que je viens à peine de me rendre compte de ce qu'un loggueur fait.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="variation"><h2>Variations sur un log</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Supposons que nous ne voulons plus seulement enregistrer les logs vers un fichier. Nous pourrions vouloir les afficher à l'écran, les envoyer au daemon <em>syslog</em> d'Unix(tm) via un socket. Comment s'accommoder de tels changements ?
|
||||
</p>
|
||||
<p>
|
||||
Le plus simple est de créer des sous-classes de <code>Log</code> qui écrasent la méthode <code>message()</code> avec les nouvelles versions. Ce système fonctionne bien à court terme, sauf qu'il a quelque chose de subtilement mais foncièrement erroné. Supposons que nous créions ces sous-classes et que nous ayons des loggueurs écrivant vers un fichier, sur l'écran et via le réseau. Trois classes en tout : ça fonctionne. Maintenant supposons que nous voulons ajouter une nouvelle classe de log qui ajoute un filtrage par priorité des messages, ne laissant passer que les messages d'un certain type, le tout suivant un fichier de configuration.
|
||||
</p>
|
||||
<p>
|
||||
Nous sommes coincés. Si nous créons de nouvelles sous-classes, nous devons le faire pour l'ensemble des trois classes, ce qui nous donnerait six classes. L'envergure de la duplication est horrible.
|
||||
</p>
|
||||
<p>
|
||||
Alors, est-ce que vous êtes en train de souhaiter que PHP ait l'héritage multiple ? Effectivement, cela réduirait l'ampleur de la tâche à court terme, mais aussi compliquerait quelque chose qui devrait être une classe très simple. L'héritage multiple, même supporté, devrait être utilisé avec le plus grand soin car toutes sortes d'enchevêtrements peuvent en découler. En fait ce soudain besoin nous dit quelque chose d'autre - peut-être que notre erreur si situe au niveau de la conception.
|
||||
</p>
|
||||
<p>
|
||||
Qu'est-ce que doit faire un loggueur ? Est-ce qu'il envoie un message vers un fichier ? A l'écran ? Via le réseau ? Non. Il envoie un message, point final. La cible de ses messages peut être sélectionnée à l'initialisation du log, mais après ça pas touche : le loggueur doit pouvoir combiner et formater les éléments du message puisque tel est son véritable boulot. Présumer que la cible fut un nom de fichier était une belle paire d'oeillères.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="scripteur"><h2>Abstraire un fichier vers un scripteur</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
La solution de cette mauvaise passe est un classique. Tout d'abord nous encapsulons la variation de la classe : cela ajoute un niveau d'indirection. Au lieu d'introduire le nom du fichier comme une chaîne, nous l'introduisons comme "cette chose vers laquelle on écrit" et que nous appelons un <code>Writer</code>. Retour aux tests...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');<strong>
|
||||
require_once('../classes/writer.php');</strong>
|
||||
Mock::generate('Clock');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}
|
||||
function testCreatingNewFile() {<strong>
|
||||
$log = new Log(new FileWriter('../temp/test.log'));</strong>
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');
|
||||
}
|
||||
function testAppendingToFile() {<strong>
|
||||
$log = new Log(new FileWriter('../temp/test.log'));</strong>
|
||||
$log->message('Test line 1');
|
||||
$this->assertWantedPattern(
|
||||
'/Test line 1/',
|
||||
$this->getFileLine('../temp/test.log', 0));
|
||||
$log->message('Test line 2');
|
||||
$this->assertWantedPattern(
|
||||
'/Test line 2/',
|
||||
$this->getFileLine('../temp/test.log', 1));
|
||||
}
|
||||
function testTimestamps() {
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');<strong>
|
||||
$log = new Log(new FileWriter('../temp/test.log'));</strong>
|
||||
$log->message('Test line', &$clock);
|
||||
$this->assertWantedPattern(
|
||||
'/Timestamp/',
|
||||
$this->getFileLine('../temp/test.log', 0),
|
||||
'Found timestamp');
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Je vais parcourir ces tests pas à pas pour ne pas ajouter trop de confusion. J'ai remplacé les noms de fichier par une classe imaginaire <code>FileWriter</code> en provenance d'un fichier <em>classes/writer.php</em>. Par conséquent les tests devraient planter puisque nous n'avons pas encore écrit ce scripteur. Doit-on le faire maintenant ?
|
||||
</p>
|
||||
<p>
|
||||
Nous pourrions, mais ce n'est pas obligé. Par contre nous avons besoin de créer l'interface, ou alors il ne sera pas possible de la simuler. Au final <em>classes/writer.php</em> ressemble à...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class FileWriter {
|
||||
|
||||
function FileWriter($file_path) {
|
||||
}
|
||||
|
||||
function write($message) {
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Nous avons aussi besoin de modifier la classe <code>Log</code>...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/clock.php');<strong>
|
||||
require_once('../classes/writer.php');</strong>
|
||||
|
||||
class Log {<strong>
|
||||
var $_writer;</strong>
|
||||
|
||||
function Log(<strong>&$writer</strong>) {<strong>
|
||||
$this->_writer = &$writer;</strong>
|
||||
}
|
||||
|
||||
function message($message, $clock = false) {
|
||||
if (! is_object($clock)) {
|
||||
$clock = new Clock();
|
||||
}<strong>
|
||||
$this->_writer->write("[" . $clock->now() . "] $message");</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Il n'y a pas grand chose qui n'ait pas changé y compris dans la plus petite de nos classes. Désormais les tests s'exécutent mais ne passent pas, à moins que nous ajoutions du code dans le scripteur. Alors que faisons nous ?
|
||||
</p>
|
||||
<p>
|
||||
Nous pourrions commencer par écrire des tests et développer la classe <code>FileWriter</code> parallèlement, mais lors de cette étape nos tests de <code>Log</code> continueraient d'échouer et de nous distraire. En fait nous n'en avons pas besoin.
|
||||
</p>
|
||||
<p>
|
||||
Une partie de notre objectif est de libérer la classe du loggueur de l'emprise du système de fichiers et il existe un moyen d'y arriver. Tout d'abord nous créons le fichier <em>tests/writer_test.php</em> de manière à avoir un endroit pour placer notre code test en provenance de <em>log_test.php</em> et que nous allons brasser. Sauf que je ne vais pas l'ajouter dans le fichier <em>all_tests.php</em> pour l'instant puisque qu'il s'agit de la partie de log que nous sommes en train d'aborder.
|
||||
</p>
|
||||
<p>
|
||||
Nous enlevons tous les test de <em>log_test.php</em> qui ne sont pas strictement en lien avec le journal et nous les gardons bien précieusement dans <em>writer_test.php</em> pour plus tard. Nous allons aussi simuler le scripteur pour qu'il n'écrive pas réellement dans un fichier...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');
|
||||
require_once('../classes/writer.php');
|
||||
Mock::generate('Clock');<strong>
|
||||
Mock::generate('FileWriter');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}<strong>
|
||||
function testWriting() {
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$writer = &new MockFileWriter($this);
|
||||
$writer->expectArguments('write', array('[Timestamp] Test line'));
|
||||
$writer->expectCallCount('write', 1);
|
||||
$log = &new Log($writer);
|
||||
$log->message('Test line', &$clock);
|
||||
$writer->tally();
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Eh oui c'est tout : il s'agit bien de l'ensemble du scénario de test et c'est normal qu'il soit aussi court. Pas mal de choses se sont passées...
|
||||
<ol>
|
||||
<li>
|
||||
La nécessité de créer le fichier uniquement si nécessaire a été déplacée vers le <code>FileWriter</code>.
|
||||
</li>
|
||||
<li>
|
||||
Étant donné que nous travaillons avec des objets fantaisie, aucun fichier n'a été créé et donc <code>setUp()</code> et <code>tearDown()</code> passent dans les tests du scripteur.
|
||||
</li>
|
||||
<li>
|
||||
Désormais le test consiste simplement dans l'envoi d'un message type et du test de son format.
|
||||
</li>
|
||||
</ol>
|
||||
Attendez un instant, où sont les assertions ?
|
||||
</p>
|
||||
<p>
|
||||
Les objets fantaisie font beaucoup plus que se comporter comme des objets, ils exécutent aussi des test. L'appel <code>expectArguments()</code> dit à l'objet fantaisie d'attendre un seul paramètre de la chaîne "[Timestamp] Test" quand la méthode fantaise <code>write()</code> est appelée. Lorsque cette méthode est appelée les paramètres attendus sont comparés avec ceci et un succès ou un échec est renvoyé comme résultat au test unitaire. C'est pourquoi un nouvel objet fantaisie a une référence vers <code>$this</code> dans son constructeur, il a besoin de ce <code>$this</code> pour l'envoi de son propre résultat.
|
||||
</p>
|
||||
<p>
|
||||
L'autre attente, c'est que le <code>write</code> ne soit appelé qu'une seule et unique fois. Juste l'initialiser ne serait pas suffisant. L'objet fantaisie attendrait une éternité si la méthode n'était jamais appelée et par conséquent n'enverrait jamais le message d'erreur à la fin du test. Pour y faire face, l'appel <code>tally()</code> lui dit de vérifier le nombre d'appel à ce moment là. Nous pouvons voir tout ça en lançant les tests...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testwriting->Arguments for [write] were [String: [Timestamp] Test line]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testwriting->Expected call count for [write] was [1], but got [1]<br />
|
||||
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>4</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
</p>
|
||||
<p>
|
||||
En fait nous pouvons encore raccourcir nos tests. L'attente de l'objet fantaisie <code>expectOnce()</code> peut combiner les deux attentes séparées.
|
||||
<php><![CDATA[
|
||||
function testWriting() {
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$writer = &new MockFileWriter($this);<strong>
|
||||
$writer->expectOnce('write', array('[Timestamp] Test line'));</strong>
|
||||
$log = &new Log($writer);
|
||||
$log->message('Test line', &$clock);
|
||||
$writer->tally();
|
||||
}
|
||||
]]></php>
|
||||
Cela peut être une abréviation utile.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="frontiere"><h2>Classes frontières</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Quelque chose de très agréable est arrivée au loggueur en plus de devenir purement et simplement plus court.
|
||||
</p>
|
||||
<p>
|
||||
Les seules choses dont il dépend sont maintenant des classes que nous avons écrites nous-même et qui dans les tests sont simulées : donc aucune dépendance hormis notre propre code PHP. Pas de fichier à écrire ni de déclenchement via une horloge à attendre. Cela veut dire que le scénario de test <em>log_test.php</em> va s'exécuter aussi vite que le processeur le permet. Par contraste les classes <code>FileWriter</code> et <code>Clock</code> sont très proches du système. Plus difficile à tester puisque de vraies données doivent être déplacées et validées avec soin, souvent par des astuces ad hoc.
|
||||
</p>
|
||||
<p>
|
||||
Notre dernière factorisation a beaucoup aidé. Les classes aux frontières de l'application et du système, celles qui sont difficiles à tester, sont désormais plus courtes étant donné que le code d'I/O a été éloigné encore plus de la logique applicative. Il existe des liens directs vers des opérations PHP : <code>FileWriter::write()</code> s'apparente à l'équivalent PHP <code>fwrite()</code> avec le fichier ouvert pour l'ajout et <code>Clock::now()</code> s'apparente lui aussi à un équivalent PHP <code>time()</code>. Primo le débogage devient plus simple. Secundo ces classes devraient bouger moins souvent.
|
||||
</p>
|
||||
<p>
|
||||
Si elles ne changent pas beaucoup alors il n'y a aucune raison pour continuer à en exécuter les tests. Cela veut dire que les tests pour les classes frontières peuvent être déplacées vers leur propre suite de tests, laissant les autres tourner à plein régime. En fait c'est comme ça que j'ai tendance à travailler et les scénarios de test de <a href="simple_test.php">SimpleTest</a> lui-même sont divisés de cette manière.
|
||||
</p>
|
||||
<p>
|
||||
Peut-être que ça ne vous paraît pas beaucoup avec un test unitaire et deux tests aux frontières, mais une application typique peut contenir vingt classes de frontière et deux cent classes d'application. Pour continuer leur exécution à toute vitesse, vous voudrez les tenir séparées.
|
||||
</p>
|
||||
<p>
|
||||
De plus, un bon développement passe par des décisions de tri entre les composants à utiliser. Peut-être, qui sait, tous ces simulacres pourront <a href="improving_design_tutorial.php">améliorer votre conception</a>.
|
||||
</p>
|
||||
</content>
|
||||
|
||||
<internal>
|
||||
<link>
|
||||
<a name="#variation">Variations</a> sur un log
|
||||
</link>
|
||||
<link>
|
||||
Abstraire un niveau supplémentaire via une classe <a name="#scripteur">fantaisie d'un scripteur</a>
|
||||
</link>
|
||||
<link>
|
||||
Séparer les tests des <a name="#frontiere">classes frontières</a> pour un petit nettoyage
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
Ce tutorial suit l'introduction aux <a href="mock_objects_tutorial.php">objets fantaisies</a>.
|
||||
</link>
|
||||
<link>
|
||||
Ensuite vient la <a href="improving_design_tutorial.php">conception pilotée par les tests</a>.
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin du <a href="simple_test.php">framework de test SimpleTest</a> pour essayer ces exemples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
organisation de tests unitaires,
|
||||
conseil de test,
|
||||
astuce de développement,
|
||||
architecture logicielle pour des tests,
|
||||
exemple de code php,
|
||||
objets fantaisie,
|
||||
port de junit,
|
||||
exemples de scénarios de test,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,199 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur le navigateur scriptable" here="Le navigateur scriptable">
|
||||
<long_title>Documentation SimpleTest : le composant de navigation web scriptable</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
Le composant de navigation web de SimpleTest peut être utilisé non seulement à l'extérieur de la classe <code>WebTestCase</code>, mais aussi indépendamment du framework SimpleTest lui-même.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="script" title="Le navigateur scriptable">
|
||||
<p>
|
||||
Vous pouvez utiliser le navigateur web dans des scripts PHP pour confirmer que des services marchent bien comme il faut ou pour extraire des informations à 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 <a href="http://www.php.net/">site web PHP</a>...
|
||||
<php><![CDATA[
|
||||
<?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];
|
||||
?>
|
||||
]]></php>
|
||||
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 <code>file()</code> sur ce qui est ici une page fixe. Cependant, en utilisant des scripts avec le navigateur web vous vous autorisez l'authentification, la gestion des cookies, le chargement automatique des fenêtres, les redirections, la transmission de formulaires et la capacité d'examiner les entêtes. De telles méthodes sont fragiles dans un site en constante évolution et vous voudrez employer une méthode plus directe pour accéder aux données de façon permanente, mais pour des tâches simples cette technique peut s'avérer une solution très rapide.
|
||||
</p>
|
||||
<p>
|
||||
Toutes les méthode de navigation utilisées dans <a local="web_tester_documentation">WebTestCase</a> sont présente dans la classe <code>SimpleBrowser</code>, mais les assertions sont remplacées par de simples accesseurs. Voici une liste complète des méthodes de navigation de page à page...
|
||||
<table><tbody>
|
||||
<tr><td><code>addHeader($header)</code></td><td>Ajouter une entête à chaque téléchargement</td></tr>
|
||||
<tr><td><code>useProxy($proxy, $username, $password)</code></td><td>Utilise ce proxy à partir de maintenant</td></tr>
|
||||
<tr><td><code>head($url, $parameters)</code></td><td>Effectue une requête HEAD</td></tr>
|
||||
<tr><td><code>get($url, $parameters)</code></td><td>Télécharge une page avec un GET</td></tr>
|
||||
<tr><td><code>post($url, $parameters)</code></td><td>Télécharge une page avec un POST</td></tr>
|
||||
<tr><td><code>clickLink($label)</code></td><td>Suit un lien par son étiquette</td></tr>
|
||||
<tr><td><code>isLink($label)</code></td><td>Vérifie si un lien avec cette étiquette existe</td></tr>
|
||||
<tr><td><code>clickLinkById($id)</code></td><td>Suit un lien par son attribut d'identification</td></tr>
|
||||
<tr><td><code>isLinkById($id)</code></td><td>Vérifie si un lien avec cet attribut d'identification existe</td></tr>
|
||||
<tr><td><code>getUrl()</code></td><td>La page ou la fenêtre URL en cours</td></tr>
|
||||
<tr><td><code>getTitle()</code></td><td>Le titre de la page</td></tr>
|
||||
<tr><td><code>getContent()</code></td><td>Le page ou la fenêtre brute</td></tr>
|
||||
<tr><td><code>getContentAsText()</code></td><td>Sans code HTML à l'exception du text "alt"</td></tr>
|
||||
<tr><td><code>retry()</code></td><td>Répète la dernière requête</td></tr>
|
||||
<tr><td><code>back()</code></td><td>Utilise le bouton "précédent" du navigateur</td></tr>
|
||||
<tr><td><code>forward()</code></td><td>Utilise le bouton "suivant" du navigateur</td></tr>
|
||||
<tr><td><code>authenticate($username, $password)</code></td><td>Retente la page ou la fenêtre après une réponse 401</td></tr>
|
||||
<tr><td><code>restart($date)</code></td><td>Relance le navigateur pour une nouvelle session</td></tr>
|
||||
<tr><td><code>ageCookies($interval)</code></td><td>Change la date des cookies</td></tr>
|
||||
<tr><td><code>setCookie($name, $value)</code></td><td>Lance un nouveau cookie</td></tr>
|
||||
<tr><td><code>getCookieValue($host, $path, $name)</code></td><td>Lit le cookie le plus spécifique</td></tr>
|
||||
<tr><td><code>getCurrentCookieValue($name)</code></td><td>Lit le contenue du cookie en cours</td></tr>
|
||||
</tbody></table>
|
||||
Les méthode <code>SimpleBrowser::useProxy()</code> et <code>SimpleBrowser::addHeader()</code> sont spéciales. Une fois appelées, elles continuent à s'appliquer sur les téléchargements suivants.
|
||||
</p>
|
||||
<p>
|
||||
Naviguer dans les formulaires est similaire à la <a local="form_testing_documentation">navigation des formulaires via WebTestCase</a>...
|
||||
<table><tbody>
|
||||
<tr><td><code>setField($name, $value)</code></td><td>Modifie tous les champs avec ce nom</td></tr>
|
||||
<tr><td><code>setFieldById($id, $value)</code></td><td>Modifie tous les champs avec cet identifiant</td></tr>
|
||||
<tr><td><code>getField($name)</code></td><td>Accesseur de la valeur d'un élément de formulaire</td></tr>
|
||||
<tr><td><code>getFieldById($id)</code></td><td>Accesseur de la valeur de l'élément de formulaire avec cet identifiant</td></tr>
|
||||
<tr><td><code>clickSubmit($label)</code></td><td>Transmet le formulaire avec l'étiquette de son bouton</td></tr>
|
||||
<tr><td><code>clickSubmitByName($name)</code></td><td>Transmet le formulaire avec l'attribut de son bouton</td></tr>
|
||||
<tr><td><code>clickSubmitById($id)</code></td><td>Transmet le formulaire avec l'identifiant de son bouton</td></tr>
|
||||
<tr><td><code>clickImage($label, $x, $y)</code></td><td>Clique sur l'image par son texte alternatif</td></tr>
|
||||
<tr><td><code>clickImageByName($name, $x, $y)</code></td><td>Clique sur l'image par son attribut</td></tr>
|
||||
<tr><td><code>clickImageById($id, $x, $y)</code></td><td>Clique sur l'image par son identifiant</td></tr>
|
||||
<tr><td><code>submitFormById($id)</code></td><td>Transmet le formulaire par son identifiant propre</td></tr>
|
||||
</tbody></table>
|
||||
Au jourd d'aujourd'hui il n'existe aucune méthode pour lister les formulaires et les champs disponibles : ce sera probablement ajouté dans des versions successives de SimpleTest.
|
||||
</p>
|
||||
<p>
|
||||
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".
|
||||
<table><tbody>
|
||||
<tr><td><code>getFrames()</code></td><td>Un déchargement de la structure de la fenêtre courante</td></tr>
|
||||
<tr><td><code>getFrameFocus()</code></td><td>L'index ou l'étiquette de la fenêtre en courante</td></tr>
|
||||
<tr><td><code>setFrameFocusByIndex($choice)</code></td><td>Sélectionne la fenêtre numérotée à partir de 1</td></tr>
|
||||
<tr><td><code>setFrameFocus($name)</code></td><td>Sélectionne une fenêtre par son étiquette</td></tr>
|
||||
<tr><td><code>clearFrameFocus()</code></td><td>Traite toutes les fenêtres comme une seule page</td></tr>
|
||||
</tbody></table>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
<section name="deboguer" title="Où sont les erreurs ?">
|
||||
<p>
|
||||
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.
|
||||
<table><tbody>
|
||||
<tr><td><code>setConnectionTimeout($timeout)</code></td><td>Ferme la socket avec un délai trop long</td></tr>
|
||||
<tr><td><code>getRequest()</code></td><td>L'entête de la requête brute de la page ou de la fenêtre</td></tr>
|
||||
<tr><td><code>getHeaders()</code></td><td>L'entête de réponse de la page ou de la fenêtre</td></tr>
|
||||
<tr><td><code>getTransportError()</code></td><td>N'importe quel erreur au niveau de la socket dans le dernier téléchargement</td></tr>
|
||||
<tr><td><code>getResponseCode()</code></td><td>La réponse HTTP de la page ou de la fenêtre</td></tr>
|
||||
<tr><td><code>getMimeType()</code></td><td>Le type Mime de la page our de la fenêtre</td></tr>
|
||||
<tr><td><code>getAuthentication()</code></td><td>Le type d'authentification dans l'entête d'une provocation 401</td></tr>
|
||||
<tr><td><code>getRealm()</code></td><td>Le realm d'authentification dans l'entête d'une provocation 401</td></tr>
|
||||
<tr><td><code>setMaximumRedirects($max)</code></td><td>Nombre de redirections avant que la page ne soit chargée automatiquement</td></tr>
|
||||
<tr><td><code>setMaximumNestedFrames($max)</code></td><td>Protection contre des framesets récursifs</td></tr>
|
||||
<tr><td><code>ignoreFrames()</code></td><td>Neutralise le support des fenêtres</td></tr>
|
||||
<tr><td><code>useFrames()</code></td><td>Autorise le support des fenêtres</td></tr>
|
||||
</tbody></table>
|
||||
Les méthodes <code>SimpleBrowser::setConnectionTimeout()</code>, <code>SimpleBrowser::setMaximumRedirects()</code>,<code>SimpleBrowser::setMaximumNestedFrames()</code>, <code>SimpleBrowser::ignoreFrames()</code> et <code>SimpleBrowser::useFrames()</code> 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 <code>SimpleBrowser::setFrameFocus()</code> : ensuite on utilisera <code>SimpleBrowser::getRequest()</code>, etc. pour voir ce qui se passe.
|
||||
</p>
|
||||
</section>
|
||||
<section name="unit" title="Tests unitaires complexes avec des navigateurs multiples">
|
||||
<p>
|
||||
Tout ce qui peut être fait dans <a local="web_tester_documentation">WebTestCase</a> peut maintenant être fait dans un <a local="unit_tester_documentation">UnitTestCase</a>. Ce qui revient à dire que nous pouvons librement mélanger des tests sur des objets de domaine avec l'interface web...
|
||||
<php><![CDATA[
|
||||
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');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Un cas plus utile d'utilisation directe du navigateur est le moment où le <code>WebTestCase</code> ne peut plus suivre. Un exemple ? Quand deux navigateurs doivent être utilisés en même temps.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
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');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Vous pouvez aussi utiliser la classe <code>SimpleBrowser</code> quand vous souhaitez écrire des scénarios de test en utilisant un autre outil que SimpleTest.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Utiliser le <a href="#scripting">navigateur web dans des scripts</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#deboguer">Déboguer</a> les erreurs sur les pages
|
||||
</link>
|
||||
<link>
|
||||
<a href="#unit">Tests complexes avec des navigateurs web multiples</a>
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API de développeur pour SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php pour des clients,
|
||||
php centré autour du client,
|
||||
outils de développement logiciel,
|
||||
framework de test de recette,
|
||||
scripts php gratuits,
|
||||
test unitaire de systèmes d'authentification,
|
||||
ressources php,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
test php,
|
||||
ressource de test unitaire,
|
||||
test web,
|
||||
authentification HTTP,
|
||||
tester la connection,
|
||||
tester l'authentification,
|
||||
tests de sécurité
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,214 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Changer l'affichage du test" here="Changer l'affichage du test">
|
||||
<long_title>Tutorial de test unitaire en PHP - Sous-classer l'affichage du test</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Le composant affichage de SimpleTest est en fait la dernière partie à développer. Des morceaux de la section suivante changeront prochainement et -- avec optimisme -- des composants d'affichage plus sophistiqués seront écrits, mais pour l'instant si un affichage minime n'est pas suffisant, voici comment réaliser le votre.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="succès"><h2>Je veux voir les succès !</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Bon d'accord, voici comment.
|
||||
</p>
|
||||
<p>
|
||||
Nous devons créer une sous-classe de l'affichage utilisée, dans notre cas il s'agit de <code>HtmlReporter</code>. La classe <code>HtmlReporter</code> est situé dans le fichier <em>simpletest/reporter.php</em> : pour l'instant elle a l'interface suivante...
|
||||
<php><![CDATA[
|
||||
class HtmlReporter extends TestDisplay {
|
||||
public TestHtmlDisplay() { ... }
|
||||
public void paintHeader(string $test_name) { ... }
|
||||
public void paintFooter(string $test_name) { ... }
|
||||
public void paintStart(string $test_name, $size) { ... }
|
||||
public void paintEnd(string $test_name, $size) { ... }
|
||||
public void paintFail(string $message) { ... }
|
||||
public void paintPass(string $message) { ... }
|
||||
protected string _getCss() { ... }
|
||||
public array getTestList() { ... }
|
||||
public integer getPassCount() { ... }
|
||||
public integer getFailCount() { ... }
|
||||
public integer getTestCaseCount() { ... }
|
||||
public integer getTestCaseProgress { ... }
|
||||
}
|
||||
]]></php>
|
||||
Voici ce que les méthodes pertinentes veulent dire. Vous pouvez consulter la <a href="reporter_documentation.php#html">liste complète ici</a> si cela vous intéresse.
|
||||
<ul class="api">
|
||||
<li>
|
||||
<code>HtmlReporter()</code><br />
|
||||
est le constructeur. Notez qu'un test unitaire initie le lien vers l'affichage plutôt que l'inverse. L'affichage est un réceptacle passif des évènements de test. Cela permet une adaptation facile de l'affichage pour d'autres systèmes de test en dehors des tests unitaires comme la surveillance de serveurs par exemple. Autre avantage, un test unitaire peut écrire vers plus d'un affichage à la fois.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintFail(string $message)</code><br />
|
||||
peint un échec. Voir ci-dessous.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintPass(string \$message)</code><br />
|
||||
ne fait rien par défaut. C'est cette méthode que nous allons modifier.
|
||||
</li>
|
||||
<li>
|
||||
<code>string _getCss()</code><br />
|
||||
renvoie le style CSS - via une chaîne - pour la méthode d'entête de la page. Des styles complémentaires peuvent être ajoutés ici.
|
||||
</li>
|
||||
<li>
|
||||
<code>array getTestList()</code><br />
|
||||
est une méthode commode pour des sous-classes. Elle liste l'emboîtement courant des tests via une liste de noms de test. Le premier, le test emboîté le plus profondément, est le premier dans la liste et la méthode du test courant sera la dernière.
|
||||
</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Pour afficher les succès nous avons juste besoin que la méthode <code>paintPass()</code> se comporte comme <code>paintFail()</code>. Bien sûr nous n'allons pas modifier l'original. Nous allons juste créer une sous-classe.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="sous-classe"><h2>Une sous-classe d'affichage</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Premièrement nous allons créer un fichier <em>tests/show_passes.php</em> dans notre projet de log et y placer cette classe vide...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
|
||||
class ShowPasses extends HtmlReporter {
|
||||
|
||||
function ShowPasses() {
|
||||
$this->HtmlReporter();
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Une rapide mais attentive lecture du <a href="http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/simpletest/simpletest/reporter.php?content-type=text/vnd.viewcvs-markup">code de SimpleTest</a> indique que l'implémentation de <code>paintFail()</code> ressemble à...
|
||||
<php><![CDATA[
|
||||
function paintFail($message) {
|
||||
parent::paintFail($message);
|
||||
print "<span class=\"fail\">Fail</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}
|
||||
]]></php>
|
||||
Essentiellement elle s'enchaîne à la version du parent, que nous devons aussi réaliser pour garantir le ménage, et ensuite imprime une trace calculée à partir de la liste des tests courants. Par contre elle perd au passage le nom du test du premier niveau. Etant donné qu'il est identique pour chaque test, ce serait un peu trop d'informations. En la transposant dans notre nouvelle classe...
|
||||
<php><![CDATA[
|
||||
class ShowPasses extends HtmlReporter {
|
||||
|
||||
function ShowPasses() {
|
||||
$this->HtmlReporter();
|
||||
}
|
||||
<strong>
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Pour l'instant tout roule. Maintenant pour utiliser notre nouvelle classe, nous allons modifier notre fichier <em>tests/all_tests.php</em>...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');<strong>
|
||||
require_once('show_passes.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All tests');
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->addTestFile('clock_test.php');
|
||||
$test->run(<strong>new ShowPasses()</strong>);
|
||||
?>
|
||||
]]></php>
|
||||
Nous pouvons le lancer pour voir le résultat de notre bricolage...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
|
||||
Pass: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
|
||||
Pass: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
|
||||
Pass: log_test.php->Log class test->testcreatingnewfile->File created<br />
|
||||
Pass: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
Pass: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Joli, mais pas encore digne d'une médaille d'or. Nous avons perdu un peu d'information au passage. L'affichage du <code>span.pass</code> n'est pas stylé en CSS, mais nous pouvons l'ajouter en modifiant une autre méthode...
|
||||
<php><![CDATA[
|
||||
class ShowPasses extends HtmlReporter {
|
||||
|
||||
function ShowPasses() {
|
||||
$this->HtmlReporter();
|
||||
}
|
||||
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}
|
||||
<strong>
|
||||
function _getCss() {
|
||||
return parent::_getCss() . ' .pass { color: green; }';
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Si vous ajoutez le code au fur et à mesure, vous verrez l'ajout du style dans le code source du résultat via le navigateur. A l'oeil, l'affichage devrait ressembler à...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->File created<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Certains préfèrent voir les succès quand ils travaillent sur le code; le sentiment de travail achevé est sympathique après tout. Une fois que vous commencez à naviguer de haut en bas pour trouver les erreurs, assez vite vous en comprendrez le côté obscur.
|
||||
</p>
|
||||
<p>
|
||||
Essayez les deux méthodes pour déterminer votre préférence. Nous allons le laisser tel que pour l'étape qui approche : <a href="mock_objects_tutorial.php">les objets fantaisie</a>. Il s'agit du premier outil de test qui ajoute des tests additionnels : il sera utile de voir ce qui se passe dans les coulisses.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Comment changer l'affichage pour <a href="#succès">afficher les passages avec succès</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#sous-classe">Sous classer la classe <code>HtmlReporter</code></a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La section précédente : <a href="subclass_tutorial.php">sous-classer les scénarios de test</a>
|
||||
</link>
|
||||
<link>
|
||||
Cette section est très spécifique à <a href="simple_test.php">SimpleTest</a>. Si vous utilisez un autre outil, n'hésitez pas à sauter pardessus.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel piloté par les tests,
|
||||
conseil pour programmer en php,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
exemple de scénario de test,
|
||||
framework de tests unitaires,
|
||||
ressources php,
|
||||
exemple de code php,
|
||||
junit,
|
||||
phpunit,
|
||||
simpletest,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,100 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Télécharger SimpleTest" here="Télécharger SimpleTest">
|
||||
<long_title>Télécharger SimpleTest</long_title>
|
||||
<content>
|
||||
<section name="current-release" title="Version courante">
|
||||
<p>
|
||||
La version courante est :
|
||||
<a href="http://prdownloads.sourceforge.net/simpletest/simpletest_1.0.1beta.tar.gz">SimpleTest v1.0.1beta</a>.
|
||||
</p>
|
||||
<p>
|
||||
Vous pouvez télécharger cette version depuis
|
||||
<a href="http://sourceforge.net/project/showfiles.php?group_id=76550&package_id=159054&release_id=391231">SourceForget.net</a>
|
||||
et votre miroir le plus proche. Vous pouvez aussi jeter un oeil du côté
|
||||
du <a href="changelog.html">changelog actuel</a>.
|
||||
</p>
|
||||
<p>
|
||||
Au fait, ne soyez pas effrayé par le mot <quote>beta</quote> :
|
||||
pas mal d'utilisateurs vont même jusqu'à utiliser la version CVS.
|
||||
</p>
|
||||
</section>
|
||||
<section name="eclipse-release" title="Paquet Eclipse">
|
||||
<p>
|
||||
Si Eclipse est votre IDE / éditeur de prédilection, vous aurez
|
||||
peut-être envie d'utiliser le
|
||||
<a href="http://sourceforge.net/project/showfiles.php?group_id=76550&package_id=159054&release_id=403632">plugin Eclipse</a>.
|
||||
</p>
|
||||
<p>
|
||||
Pour utilser les procédures automatiques, l'URL est :
|
||||
<blockquote>http://simpletest.org/eclipse/</blockquote>
|
||||
</p>
|
||||
</section>
|
||||
<section name="packages" title="Autres paquets">
|
||||
<p>
|
||||
SimpleTest a été packagé par la communauté avec d'autres parfums encore.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<a href="http://packages.debian.org/unstable/web/php-simpletest">paquet Debian</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://www.pearified.com/index.php?package=SimpleTest">paquet Pearified</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="http://drupal.org/project/simpletest">module Drupal</a>
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
<cite>Attention : certains paquets ne sont pas toujours très à jour.</cite>
|
||||
</p>
|
||||
</section>
|
||||
<section name="source" title="Source">
|
||||
<p>
|
||||
Le code source est hébergé par SourceForge : vous pouvez l'étudier / le butiner
|
||||
via le <a href="http://simpletest.cvs.sourceforge.net/simpletest/">CVS repository</a>.
|
||||
</p>
|
||||
</section>
|
||||
<section name="older-stable-releases" title="Autres versions stables">
|
||||
<ul>
|
||||
<li>
|
||||
<a href="http://prdownloads.sourceforge.net/simpletest/simpletest_1.0.tar.gz">1.0.0</a>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#current-release">Version courante</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#eclipse-release">Paquet Eclipse</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#packages">Autres paquets</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#source">Source</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#older-stable-releases">Autres versions stables</a>
|
||||
</link>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
</external>
|
||||
|
||||
<meta>
|
||||
<keywords>
|
||||
SimpleTest,
|
||||
download,
|
||||
source code,
|
||||
stable release,
|
||||
eclipse release,
|
||||
eclipse plugin,
|
||||
debian package,
|
||||
drupal module,
|
||||
pear channel,
|
||||
pearified package
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,213 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur les attentes" here="Les attentes">
|
||||
<long_title>Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires</long_title>
|
||||
<content>
|
||||
<section name="fantaisie" title="Plus de contrôle sur les objets fantaisie">
|
||||
<p>
|
||||
Le comportement par défaut des <a local="mock_objects_documentation">objets fantaisie</a> dans <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a> est soit une correspondance identique sur l'argument, soit l'acceptation de n'importe quel argument. Pour la plupart des tests, c'est suffisant. Cependant il est parfois nécessaire de ramollir un scénario de test.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Voici un cas concret, nous avons un service d'actualités qui a échoué dans sa tentative de connexion à sa source distante.
|
||||
<php><![CDATA[
|
||||
<strong>class NewsService {
|
||||
...
|
||||
function publish(&$writer) {
|
||||
if (! $this->isConnected()) {
|
||||
$writer->write('Cannot connect to news service "' .
|
||||
$this->_name . '" at this time. ' .
|
||||
'Please try again later.');
|
||||
}
|
||||
...
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
Là il envoie son contenu vers un classe <code>Writer</code>. Nous pourrions tester ce comportement avec un <code>MockWriter</code>...
|
||||
<php><![CDATA[
|
||||
class TestOfNewsService extends UnitTestCase {
|
||||
...
|
||||
function testConnectionFailure() {<strong>
|
||||
$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();</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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é.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TestOfNewsService extends UnitTestCase {
|
||||
...
|
||||
function testConnectionFailure() {
|
||||
$writer = &new MockWriter($this);<strong>
|
||||
$writer->expectOnce(
|
||||
'write',
|
||||
array(new WantedPatternExpectation('/cannot connect/i')));</strong>
|
||||
|
||||
$service = &new NewsService('BBC News');
|
||||
$service->publish($writer);
|
||||
|
||||
$writer->tally();
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Plutôt que de transmettre le paramètre attendu au <code>MockWriter</code>, nous envoyons une classe d'attente appelée <code>WantedPatternExpectation</code>. 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.
|
||||
</p>
|
||||
<p>
|
||||
<code>WantedPatternExpectation</code> utilise l'expression rationnelle pour la comparaison avec son constructeur. A chaque fois qu'une comparaison est fait à travers <code>MockWriter</code> par rapport à cette classe attente, elle fera un <code>preg_match()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Les classes attente possibles sont...
|
||||
<table><tbody>
|
||||
<tr><td><code>EqualExpectation</code></td><td>Une égalité, plutôt que la plus forte comparaison à l'identique</td></tr>
|
||||
<tr><td><code>NotEqualExpectation</code></td><td>Une comparaison sur la non-égalité</td></tr>
|
||||
<tr><td><code>IndenticalExpectation</code></td><td>La vérification par défaut de l'objet fantaisie qui doit correspondre exactement</td></tr>
|
||||
<tr><td><code>NotIndenticalExpectation</code></td><td>Inverse la logique de l'objet fantaisie</td></tr>
|
||||
<tr><td><code>WantedPatternExpectation</code></td><td>Utilise une expression rationnelle Perl pour comparer une chaîne</td></tr>
|
||||
<tr><td><code>NoUnwantedPatternExpectation</code></td><td>Passe seulement si l'expression rationnelle Perl échoue</td></tr>
|
||||
<tr><td><code>IsAExpectation</code></td><td>Vérifie le type ou le nom de la classe uniquement</td></tr>
|
||||
<tr><td><code>NotAExpectation</code></td><td>L'opposé de <code>IsAExpectation</code></td></tr>
|
||||
<tr><td><code>MethodExistsExpectation</code></td><td>Vérifie si la méthode est disponible sur un objet</td></tr>
|
||||
</tbody></table>
|
||||
La plupart utilisent la valeur attendue dans le constructeur. Les exceptions sont les vérifications sur motif, qui utilisent une expression rationnelle, ainsi que <code>IsAExpectation</code> et <code>NotAExpectation</code>, qui prennent un type ou un nom de classe comme chaîne.
|
||||
</p>
|
||||
</section>
|
||||
<section name="comportement" title="Utiliser les attentes pour contrôler les bouchons serveur">
|
||||
<p>
|
||||
Les classes attente peuvent servir à autre chose que l'envoi d'assertions depuis les objets fantaisie, afin de choisir le comportement d'un <a local="mock_objects_documentation">objet fantaisie</a> ou celui d'un <a local="server_stubs_documentation">bouchon serveur</a>. A chaque fois qu'une liste d'arguments est donnée, une liste d'objets d'attente peut être insérée à la place.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
Stub::generate('Authorisation');
|
||||
<strong>
|
||||
$authorisation = new StubAuthorisation();
|
||||
$authorisation->setReturnValue(
|
||||
'isAllowed',
|
||||
true,
|
||||
array(new IsAExpectation('Session', 'Must be a session')));
|
||||
$authorisation->setReturnValue('isAllowed', false);</strong>
|
||||
]]></php>
|
||||
Le comportement par défaut du bouchon serveur est défini pour renvoyer <code>false</code> quand <code>isAllowed</code> est appelé. Lorsque nous appelons cette méthode avec un unique paramètre qui est un objet <code>Session</code>, il renverra <code>true</code>. 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.
|
||||
</p>
|
||||
<p>
|
||||
Ce niveau de sophistication est rarement utile : il n'est inclut que pour être complet.
|
||||
</p>
|
||||
</section>
|
||||
<section name="etendre" title="Créer vos propres attentes">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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 <code>SimpleExpectation</code>...
|
||||
<php><![CDATA[
|
||||
<strong>class ValidIp extends SimpleExpectation {
|
||||
|
||||
function test($ip) {
|
||||
return (ip2long($ip) != -1);
|
||||
}
|
||||
|
||||
function testMessage($ip) {
|
||||
return "Address [$ip] should be a valid IP address";
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
Il n'y a véritablement que deux méthodes à mettre en place. La méthode <code>test()</code> devrait renvoyer un <code>true</code> si l'attente doit passer, et une erreur <code>false</code> dans le cas contraire. La méthode <code>testMessage()</code> ne devrait renvoyer que du texte utile à la compréhension du test en lui-même.
|
||||
</p>
|
||||
<p>
|
||||
Cette classe peut désormais être employée à la place des classes d'attente précédentes.
|
||||
</p>
|
||||
</section>
|
||||
<section name="unitaire" title="Sous le capot du testeur unitaire">
|
||||
<p>
|
||||
Le <a href="http://sourceforge.net/projects/simpletest/">framework de test unitaire SimpleTest</a> utilise aussi dans son coeur des classes d'attente pour la <a local="unit_test_documentation">classe UnitTestCase</a>. 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.
|
||||
</p>
|
||||
<p>
|
||||
La méthode la plus directe est d'utiliser la méthode <code>SimpleTest::assertExpectation()</code> pour effectuer le test...
|
||||
<php><![CDATA[
|
||||
<strong>class TestOfNetworking extends UnitTestCase {
|
||||
...
|
||||
function testGetValidIp() {
|
||||
$server = &new Server();
|
||||
$this->assertExpectation(
|
||||
new ValidIp(),
|
||||
$server->getIp(),
|
||||
'Server IP address->%s');
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
C'est plutôt sale par rapport à notre syntaxe habituelle du type <code>assert...()</code>.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TestOfNetworking extends UnitTestCase {
|
||||
...<strong>
|
||||
function assertValidIp($ip, $message = '%s') {
|
||||
$this->assertExpectation(new ValidIp(), $ip, $message);
|
||||
}</strong>
|
||||
|
||||
function testGetValidIp() {
|
||||
$server = &new Server();<strong>
|
||||
$this->assertValidIp(
|
||||
$server->getIp(),
|
||||
'Server IP address->%s');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Il est peu probable que nous ayons besoin de ce niveau de contrôle sur la machinerie de test. Il est assez rare que le besoin d'une attente dépasse le stade de la reconnaissance d'un motif. De plus, les classes d'attente complexes peuvent rendre les tests difficiles à lire et à déboguer. Ces mécanismes sont véritablement là pour les auteurs de système qui étendront le framework de test pour leurs propres outils de test.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Utiliser les attentes <a href="#fantaisie">pour des tests plus précis avec des objets fantaisie</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#comportement">Changer le comportement d'un objet fantaisie</a> avec des attentes
|
||||
</link>
|
||||
<link>
|
||||
<a href="#etendre">Créer des attentes</a>
|
||||
</link>
|
||||
<link>
|
||||
Par dessous SimpleTest <a href="#unitaire">utilise des classes d'attente</a>
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
Les attentes imitent les contraintes dans <a href="http://www.jmock.org/">JMock</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API complète pour SimpleTest</a> réalisé avec PHPDoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
objets fantaisie,
|
||||
développement piloté par les tests,
|
||||
héritage des attentes,
|
||||
contraintes d'objet fantaisie,
|
||||
test unitaire avancé en PHP,
|
||||
test en premier,
|
||||
architecture de framework de test
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,285 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Créer un nouveau de scénario de test" here="Tutorial : les tests unitaires en PHP">
|
||||
<long_title>Tutorial sur les tests unitaires en PHP - Créer un exemple de scénario de test en PHP</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Si vous débutez avec les tests unitaires, il est recommandé d'essayer le code au fur et à mesure. Il n'y pas grand chose à taper et vous sentirez le rythme de la programmation pilotée par les tests.
|
||||
</p>
|
||||
<p>
|
||||
Pour exécuter les exemples tels quels, vous aurez besoin de créer un nouveau répertoire et d'y installer trois dossiers : <em>classes</em>, <em>tests</em> et <em>temp</em>. Dézippez le framework <a href="simple_test.php">SimpleTest</a> dans le dossier <em>tests</em> et assurez vous que votre serveur web puisse atteindre ces endroits.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="nouveau"><h2>Un nouveau scénario de test</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
L'exemple dans <a local="{{simple_test}}">l'introduction rapide</a> comprenait les tests unitaires d'une simple classe de log. Dans ce tutorial à propos de Simple Test, je vais essayer de raconter toute l'histoire du développement de cette classe. Cette classe PHP est courte et simple : au cours de cette introduction, elle recevra beaucoup plus d'attention que dans le cadre d'un développement de production. Nous verrons que derrière son apparente simplicité se cachent des choix de conception étonnamment difficiles.
|
||||
</p>
|
||||
<p>
|
||||
Peut-être que ces choix sont trop difficiles ? Plutôt que d'essayer de penser à tout en amont, je vais commencer par poser une exigence : nous voulons écrire des messages dans un fichier. Ces messages doivent être ajoutés en fin de fichier s'il existe. Plus tard nous aurons besoin de priorités, de filtres et d'autres choses encore, mais nous plaçons l'écriture dans un fichier au coeur de nos préoccupations. Nous ne penserons à rien d'autres par peur de confusion. OK, commençons par écrire un test...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase();
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
}
|
||||
}
|
||||
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
]]></php>
|
||||
Pas à pas, voici ce qu'il veut dire.
|
||||
</p>
|
||||
<p>
|
||||
La constante <code>SIMPLE_TEST</code> contient le chemin vers les classes de Simple Test à partir de ce fichier. Les classes pourraient être placées dans le path du fichier <em>php.ini</em> mais si vous êtes sur un serveur mutualisé, vous n'y aurez probablement pas accès. Pour que tout le monde soit content, le chemin est déclaré explicitement dans le script de test. Plus tard nous verrons comment tout finira au même endroit.
|
||||
</p>
|
||||
<p>
|
||||
Demander la librairie <em>unit_tester.php</em> est assez évident mais qu'est-ce que ce fichier <em>reporter.php</em> ? Les librairies Simple Test sont une boîte à outils pour créer votre propre suite de tests standardisés. Elles peuvent être utilisées "telles quelles" sans problème, mais elles sont constituées de plusieurs éléments qui ont besoin d'être assemblés les uns aux autres. Le composant pour l'affichage est situé dans <em>reporter.php</em>. Probablement qu'un jour vous écrirez le vôtre : c'est pourquoi son inclusion est optionnelle. Simple Test contient une classe d'affichage, fonctionnelle mais basique : elle s'appelle <code>HtmlReporter</code>. Elle peut enregistrer des informations sur les tests : début, fin, erreur, réussite ou échec. Elle affiche cette information le plus rapidement possible au cas où le code de test planterait et masquerait le lieu de l'échec.
|
||||
</p>
|
||||
<p>
|
||||
Les tests eux-mêmes sont rassemblés dans une classe de scénario de test. Cette dernière est typiquement une extension de la classe <code>UnitTestCase</code>. Quand le test est exécuté, elle cherche les méthodes commençant par "test" et les lancent. Notre seule méthode de test pour l'instant est appellée <code>testCreatingNewFile()</code> mais elle est encore vide.
|
||||
</p>
|
||||
<p>
|
||||
Une méthode vide ne fait rien. Nous avons besoin d'y placer du code. La classe <code>UnitTestCase</code> génère des évènements de test à son exécution : ces évènements sont envoyés vers un observateur. La méthode <code>UnitTestCase::run()</code> lancent tous les tests de la classe.
|
||||
</p>
|
||||
<p>
|
||||
Et pour ajouter du code de test...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');<strong>
|
||||
require_once('../classes/log.php');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase();
|
||||
}
|
||||
function testCreatingNewFile() {<strong>
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'));</strong>
|
||||
}
|
||||
}
|
||||
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
Vous pensez probablement que ça représente beaucoup de code pour un unique test et je suis d'accord avec vous. Ne vous inquiétez pas. Il s'agit d'un coût fixe et à partir de maintenant nous pouvons ajouter des tests : une ligne ou presque à chaque fois. Parfois moins en utilisant des artefacts de test que nous découvrirons plus tard.
|
||||
</p>
|
||||
<p>
|
||||
Nous devons maintenant prendre nos premières décisions. Notre fichier de test s'appelle <em>log_test.php</em> (n'importe quel nom ferait l'affaire) : nous le plaçons dans un dossier appelé <em>tests</em> (partout ailleurs serait aussi bien). Notre fichier de code s'appelle <em>log.php</em> : c'est son contenu que nous allons tester. Je l'ai placé dans notre dossier <em>classes</em> : cela veut-il dire que nous construisons une classe ?
|
||||
</p>
|
||||
<p>
|
||||
Pour cet exemple, la réponse est oui, mais le testeur unitaire n'est pas restreint aux tests de classe. C'est juste que le code orienté objet est plus facile à dépecer et à remodeler. Ce n'est pas par hasard si la conduite de tests fins via les tests unitaires est apparue au sein de la communauté OO.
|
||||
</p>
|
||||
<p>
|
||||
Le test en lui-même est minimal. Tout d'abord il élimine tout autre fichier de test qui serait encore présent. Les décisions de conception arrivent ensuite en rafale. Notre classe s'appelle <code>Log</code> : elle passe le chemin du fichier au constructeur. Nous créons le log et nous lui envoyons aussitôt un message en utilisant la méthode <code>message()</code>. L'originalité dans le nommage n'est pas une caractéristique désirable chez un développeur informatique : c'est triste mais c'est comme ça.
|
||||
</p>
|
||||
<p>
|
||||
La plus petite unité d'un test mmm... heu... unitaire est l'assertion. Ici nous voulons nous assurer que le fichier log auquel nous venons d'envoyer un message a bel et bien été créé. <code>UnitTestCase::assertTrue()</code> enverra un évènement réussite si la condition évaluée est vraie ou un échec dans le cas contraire. Nous pouvons avoir un ensemble d'assertions différentes et encore plus si nous étendons nos scénarios de test classique. Voici la liste...
|
||||
<table><tbody>
|
||||
<tr><td><code>assertTrue($x)</code></td><td>Echoue si $x est faux</td></tr>
|
||||
<tr><td><code>assertFalse($x)</code></td><td>Echoue si $x est vrai</td></tr>
|
||||
<tr><td><code>assertNull($x)</code></td><td>Echoue si $x est initialisé</td></tr>
|
||||
<tr><td><code>assertNotNull($x)</code></td><td>Echoue si $x n'est pas initialisé</td></tr>
|
||||
<tr><td><code>assertIsA($x, $t)</code></td><td>Echoue si $x n'est pas de la classe ou du type $t</td></tr>
|
||||
<tr><td><code>assertEqual($x, $y)</code></td><td>Echoue si $x == $y est faux</td></tr>
|
||||
<tr><td><code>assertNotEqual($x, $y)</code></td><td>Echoue si $x == $y est vrai</td></tr>
|
||||
<tr><td><code>assertIdentical($x, $y)</code></td><td>Echoue si $x === $y est faux</td></tr>
|
||||
<tr><td><code>assertNotIdentical($x, $y)</code></td><td>Echoue si $x === $y est vrai</td></tr>
|
||||
<tr><td><code>assertReference($x, $y)</code></td><td>Echoue sauf si $x et $y sont la même variable</td></tr>
|
||||
<tr><td><code>assertCopy($x, $y)</code></td><td>Echoue si $x et $y sont la même variable</td></tr>
|
||||
<tr><td><code>assertWantedPattern($p, $x)</code></td><td>Echoue sauf si l'expression rationnelle $p capture $x</td></tr>
|
||||
<tr><td><code>assertNoUnwantedPattern($p, $x)</code></td><td>Echoue si l'expression rationnelle $p capture $x</td></tr>
|
||||
<tr><td><code>assertNoErrors()</code></td><td>Echoue si une erreur PHP arrive</td></tr>
|
||||
<tr><td><code>assertError($x)</code></td><td>Echoue si aucune erreur ou message incorrect de PHP n'arrive</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
<p>
|
||||
Nous sommes désormais prêt à lancer notre script de test en le passant dans le navigateur. Qu'est-ce qui devrait arriver ? Il devrait planter...
|
||||
<div class="demo">
|
||||
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
|
||||
</div>
|
||||
La raison ? Nous n'avons pas encore créé <em>log.php</em>.
|
||||
</p>
|
||||
<p>
|
||||
Mais attendez une minute, c'est idiot ! Ne me dites pas qu'il faut créer un test sans écrire le code à tester auparavant...
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="tdd"><h2>Développement piloté par les tests</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Co-inventeur de l'<a href="http://www.extremeprogramming.org/">Extreme Programming</a>, Kent Beck a lancé un autre manifeste. Le livre est appelé <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0321146530/ref=lib_dp_TFCV/102-2696523-7458519?v=glance&s=books&vi=reader#reader-link">Test Driven Development</a> (Développement Piloté par les Tests)
|
||||
ou TDD et élève les tests unitaires à une position élevée de la conception. En quelques mots, vous écrivez d'abord un petit test et seulement ensuite le code qui passe ce test. N'importe quel bout de code. Juste pour qu'il passe.
|
||||
</p>
|
||||
<p>
|
||||
Vous écrivez un autre test et puis de nouveau du code qui passe. Vous aurez alors un peu de duplication et généralement du code pas très propre. Vous remaniez (factorisez) ce code-là en vous assurant que les tests continuent à passer : vous ne pouvez rien casser. Une fois que le code est le plus propre possible vous êtes prêt à ajouter des nouvelles fonctionnalités. Il suffit juste de rajouter des nouveaux tests et de recommencer le cycle une nouvelle fois.
|
||||
|
||||
</p>
|
||||
<p>
|
||||
Il s'agit d'une approche assez radicale et j'ai parfois l'impression qu'elle est incomplète. Mais il s'agit d'un moyen efficace pour expliquer un testeur unitaire ! Il se trouve que nous avons un test qui échoue, pour ne pas dire qu'il plante : l'heure est venue d'écrire du code dans <em>log.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
|
||||
class Log {
|
||||
|
||||
function Log($file_path) {
|
||||
}
|
||||
|
||||
function message($message) {
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Il s'agit là du minimum que nous puissions faire pour éviter une erreur fatale de PHP. Et maintenant la réponse devient...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->True assertion failed.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
"testoflogging" a échoué. Parmi les défauts de PHP on trouve cette fâcheuse tendance à transformer intérieurement les noms de classes et de méthodes en minuscules. SimpleTest utilise ces noms par défaut pour décrire les tests mais nous pouvons les remplacer par nos propres noms.
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {<strong>
|
||||
$this->UnitTestCase('Log class test');</strong>
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Should write this to a file');<strong>
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Ce qui donne...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->File created.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
Par contre pour le nom des méthodes il n'y a rien à faire, désolé.
|
||||
</p>
|
||||
<p>
|
||||
Les messages d'un test comme ceux-ci ressemblent à bien des égards à des commentaires de code. Certains ne jurent que par eux, d'autres au contraire les bannissent purement et simplement en les considérant aussi encombrants qu'inutiles. Pour ma part, je me situe quelque part au milieu.
|
||||
</p>
|
||||
<p>
|
||||
Pour que le test passe, nous pourrions nous contenter de créer le fichier dans le constructeur de <code>Log</code>. Cette technique "en faisant semblant" est très utile pour vérifier que le test fonctionne pendant les passages difficiles. Elle le devient encore plus si vous sortez d'un passage avec des tests ayant échoués et que vous voulez juste vérifier de ne pas avoir oublié un truc bête. Nous n'allons pas aussi lentement donc...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class Log {<strong>
|
||||
var $_file_path;</strong>
|
||||
|
||||
function Log($file_path) {<strong>
|
||||
$this->_file_path = $file_path;</strong>
|
||||
}
|
||||
|
||||
function message($message) {<strong>
|
||||
$file = fopen($this->_file_path, 'a');
|
||||
fwrite($file, $message . "\n");
|
||||
fclose($file);</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Au total, pas moins de 4 échecs ont été nécessaire pour passer à l'étape suivante. Je n'avais pas créé le répertoire temporaire, je ne lui avais pas donné les droits d'écriture, j'avais une coquille et je n'avais pas non plus ajouté ce nouveau répertoire dans CVS. N'importe laquelle de ces erreurs aurait pu m'occuper pendant plusieurs heures si elle était apparue plus tard mais c'est bien pour ces cas là qu'on teste. Avec les corrections adéquates, ça donne...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Ça marche!
|
||||
</p>
|
||||
<p>
|
||||
Peut-être n'aimez-vous pas le style plutôt minimal de l'affichage. Les succès ne sont pas montrés par défaut puisque généralement vous n'avez pas besoin de plus d'information quand vous comprenez effectivement ce qui se passe. Dans le cas contraire, pensez à écrire d'autres tests.
|
||||
</p>
|
||||
<p>
|
||||
D'accord, c'est assez strict. Si vous voulez aussi voir les succès alors vous pouvez <a local="display_subclass_tutorial">créer une sous-classe de <code>HtmlReporter</code></a> et l'utiliser pour les tests. Même moi j'aime bien ce confort parfois.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="doc"><h2>Les tests comme documentation</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Il y a une nuance ici. Nous ne voulons pas créer de fichier avant d'avoir effectivement envoyé de message. Plutôt que d'y réfléchir trop longtemps, nous allons juste ajouter un test pour ça.
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');<strong>
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'No file created before first message');</strong>
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
...et découvrir que ça marche déjà...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>2</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
En fait je savais que ça allait être le cas. J'ajoute ce test de confirmation tout d'abord pour garder l'esprit tranquille, mais aussi pour documenter ce comportement. Ce petit test supplémentaire dans son contexte en dit plus long qu'un scénario utilisateur d'une douzaine de lignes ou qu'un diagramme UML complet. Que la suite de tests devienne une source de documentation est un effet secondaire assez agréable.
|
||||
</p>
|
||||
<p>
|
||||
Devrions-nous supprimer le fichier temporaire à la fin du test ? Par habitude, je le fais une fois que j'en ai terminé avec la méthode de test et qu'elle marche. Je n'ai pas envie de valider du code qui laisse des restes de fichiers de test traîner après un test. Mais je ne le fais pas non plus pendant que j'écris le code. Peut-être devrais-je, mais parfois j'ai besoin de voir ce qui se passe : on retrouve cet aspect confort évoqué plus haut.
|
||||
</p>
|
||||
<p>
|
||||
Dans un véritable projet, nous avons habituellement plus qu'un unique scénario de test : c'est pourquoi nous allons regarder comment <a local="group_test_tutorial">grouper des tests dans des suites de tests</a>.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>Créer un <a href="#nouveau">nouveau scénario de test</a>.</link>
|
||||
<link>Le <a href="#tdd">Développement Piloté par les Tests</a> en PHP.</link>
|
||||
<link>Les <a href="#doc">tests comme documentation</a> est un des nombreux effets secondaires.</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ de JUnit</a> contient plein de conseils judicieux sur les tests.
|
||||
</link>
|
||||
<link>
|
||||
<a href="group_test_tutorial.php">Ensuite</a> vient "comment grouper des scénarios de tests ensemble".
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin du <a href="simple_test.php">framework de test SimpleTest</a> pour ces exemples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressouces php,
|
||||
objets fantaisie,
|
||||
junit,
|
||||
test php,
|
||||
test unitaire,
|
||||
test php automatisé,
|
||||
tutorial de scénarios de test,
|
||||
explication d'un scénario de test unitaire,
|
||||
exemple de test unitaire
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,207 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur les tests de formulaire" here="Les tests des formulaires">
|
||||
<long_title>Documentation SimpleTest : tester des formulaires HTML</long_title>
|
||||
<content>
|
||||
<section name="submit" title="Valider un formulaire simple">
|
||||
<p>
|
||||
Lorsqu'une page est téléchargée par <code>WebTestCase</code> en utilisant <code>get()</code> ou <code>post()</code> 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...
|
||||
<pre><![CDATA[
|
||||
<form>
|
||||
<input type="text" name="a" value="A default" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
]]></pre>
|
||||
Il ressemble à...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<input type="text" name="a" value="A default" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
Nous pouvons naviguer vers ce code, via le site <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>, avec le test suivant...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
<strong>
|
||||
function testDefaultValue() {
|
||||
$this->get('http://www.lastcraft.com/form_testing_documentation.php');
|
||||
$this->assertField('a', 'A default');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
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".
|
||||
</p>
|
||||
<p>
|
||||
Nous pourrions retourner le formulaire tout de suite, mais d'abord nous allons changer la valeur du champ texte. Ce n'est qu'après que nous le transmettrons...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
|
||||
function testDefaultValue() {
|
||||
$this->get('http://www.my-site.com/');
|
||||
$this->assertField('a', 'A default');<strong>
|
||||
$this->setField('a', 'New value');
|
||||
$this->clickSubmit('Go');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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 <em>GET</em> 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 <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> devraient être employés.
|
||||
</p>
|
||||
<p>
|
||||
Si un champ manque dans n'importe quel formulaire ou si une option est indisponible alors <code>WebTestCase::setField()</code> renverra <code>false</code>. Par exemple, supposons que nous souhaitons vérifier qu'une option "Superuser" n'est pas présente dans ce formulaire...
|
||||
<pre><![CDATA[
|
||||
<strong>Select type of user to add:</strong>
|
||||
<select name="type">
|
||||
<option>Subscriber</option>
|
||||
<option>Author</option>
|
||||
<option>Administrator</option>
|
||||
</select>
|
||||
]]></pre>
|
||||
Qui ressemble à...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<strong>Select type of user to add:</strong>
|
||||
<select name="type">
|
||||
<option>Subscriber</option>
|
||||
<option>Author</option>
|
||||
<option>Administrator</option>
|
||||
</select>
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
Le test suivant le confirmera...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...
|
||||
function testNoSuperuserChoiceAvailable() {<strong>
|
||||
$this->get('http://www.lastcraft.com/form_testing_documentation.php');
|
||||
$this->assertFalse($this->setField('type', 'Superuser'));</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
La sélection ne sera pas changée suite à un échec d'initialisation d'une valeur sur un objet.
|
||||
</p>
|
||||
<p>
|
||||
Voici la liste complète des objets supportés à aujourd'hui...
|
||||
<ul>
|
||||
<li>Champs texte, y compris les champs masqués (hidden) ou cryptés (password).</li>
|
||||
<li>Boutons submit, en incluant aussi la balise button, mais pas encore les boutons reset</li>
|
||||
<li>Aires texte (textarea) avec leur gestion des retours à la ligne (wrap).</li>
|
||||
<li>Cases à cocher, y compris les cases à cocher multiples dans un même formulaire.</li>
|
||||
<li>Listes à menu déroulant, y compris celles à sélections multiples.</li>
|
||||
<li>Boutons radio.</li>
|
||||
<li>Images.</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Bien que la plupart des objets HTML standards soient couvert par le parseur de <em>SimpleTest</em>, il est peu probable que JavaScript soit implémenté dans un futur proche.
|
||||
</p>
|
||||
</section>
|
||||
<section name="multiple" title="Champs à valeurs multiples">
|
||||
<p>
|
||||
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...
|
||||
<pre><![CDATA[
|
||||
<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>
|
||||
]]></pre>
|
||||
Qui se traduit par...
|
||||
</p>
|
||||
<p>
|
||||
<form class="demo">
|
||||
<strong>Create privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="c" checked=""/><br/>
|
||||
<strong>Retrieve privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="r" checked=""/><br/>
|
||||
<strong>Update privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="u" checked=""/><br/>
|
||||
<strong>Destroy privileges allowed:</strong>
|
||||
<input type="checkbox" name="crud" value="d" checked=""/><br/>
|
||||
<input type="submit" value="Enable Privileges"/>
|
||||
</form>
|
||||
</p>
|
||||
<p>
|
||||
Si nous souhaitons désactiver tous les privilèges sauf ceux de téléchargement (Retrieve) et transmettre cette information, nous pouvons y arriver par...
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...<strong>
|
||||
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');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="brut"><h2>Envoi brut</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Si vous souhaitez tester un gestionnaire de formulaire mais que vous ne l'avez pas écrit ou que vous n'y avez pas encore accès, vous pouvez créer un envoi de formulaire à la main.
|
||||
<php><![CDATA[
|
||||
class SimpleFormTests extends WebTestCase {
|
||||
...<strong>
|
||||
function testAttemptedHack() {
|
||||
$this->post(
|
||||
'http://www.my-site.com/add_user.php',
|
||||
array('type' => 'superuser'));
|
||||
$this->assertNoUnwantedPattern('/user created/i');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
En ajoutant des données à la méthode <code>WebTestCase::post()</code>, nous essayons de télécharger la page via la transmission d'un formulaire.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Modifier les valeurs d'un formulaire et <a href="#submit">réussir à transmettre un simple formulaire</a>
|
||||
</link>
|
||||
<link>
|
||||
Gérer des <a href="#multiple">objets à valeurs multiples</a> en initialisant des listes.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#brut">Envoi brut</a> quand il n'existe pas de bouton à cliquer.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API du développeur pour SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php pour des clients,
|
||||
php centré sur le client,
|
||||
outils de développement logiciel,
|
||||
frameword de test de recette,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressources php,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
test php,
|
||||
ressources de test unitaire,
|
||||
test web
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,215 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Prendre le contrôle des tests" here="Prendre le contrôle des tests">
|
||||
<long_title>Tutorial de test unitaire en PHP - Isoler les variables pendant le test</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Pour tester un module de code vous avez besoin d'avoir un contrôle très précis sur son environnement. Si quelque chose change dans les coulisses, par exemple dans un fichier de configuration, alors les tests peuvent échouer de façon inattendue. Il ne s'agirait plus d'un test de code sans équivoque et pourrait vous faire perdre des heures précieuses à la recherche d'erreurs dans un code qui fonctionne. Alors qu'il s'agit d'un problème de configuration qui plante le test en question. Au mieux vos scénarios de test deviennent de plus en plus compliqués afin de prendre en compte toutes les variations possibles.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="temps"><h2>Contrôler le temps</h2></a>
|
||||
<p>
|
||||
</p>
|
||||
Il y a souvent beaucoup de variables évidentes qui peuvent affecter un scénario de test unitaire, d'autant plus dans un environnement de développement web dans lequel PHP a ses aises. Parmi celles-ci, on trouve les paramètres de connexion à la base de données et ceux de configuration, les droits de fichier et les ressources réseau, etc. L'échec ou la mauvaise installation de l'un ou l'autre de ces composants cassera la suite de test. Est-ce que nous devons ajouter des tests pour valider l'installation de ces composants ? C'est une bonne idée mais si vous les placez dans les tests du module de code vous aller commencer à encombrer votre code de test avec des détails hors de propos avec la tâche en cours. Ils doivent être placés dans leur propre groupe de tests.
|
||||
</p>
|
||||
<p>
|
||||
Par contre un autre problème reste : nos machines de développement doivent aussi avoir tous les composants système d'installés avant l'exécution de la suite de test. Et vos tests s'exécuteront plus lentement.
|
||||
</p>
|
||||
<p>
|
||||
Devant un tel dilemme, nous créerons souvent des versions enveloppantes des classes qui gèrent ces ressources. Les vilains détails de ces ressources sont ensuite codés une seule fois. J'aime bien appeler ces classes des "classes frontière" étant donné qu'elles existent en bordure de l'application, l'interface entre votre application et le reste du système. Ces classes frontière sont - dans le meilleur des cas - simulées pendant les tests par des versions de simulacre. Elles s'exécutent plus rapidement et sont souvent appelées "bouchon serveur [Ndt : Server Stubs]" ou dans leur forme plus générique "objet fantaisie [Ndt : Mock Objects]". Envelopper et bouchonner chacune de ces ressources permet d'économiser pas mal de temps.
|
||||
</p>
|
||||
<p>
|
||||
Un des facteurs souvent négligés reste le temps. Par exemple, pour tester l'expiration d'une session des codeurs vont souvent temporairement en caler la durée à une valeur très courte, disons 2 secondes, et ensuite effectuer un <code>sleep(3)</code> : ils estiment alors que la session a expirée. Sauf que cette opération ajoute 3 secondes à la suite de test : il s'agit souvent de beaucoup de code en plus pour rendre la classe de session aussi malléable. Plus simple serait d'avoir un moyen d'avancer l'horloge arbitrairement. De contrôler le temps.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="horloge"><h2>Une classe horloge</h2></a>
|
||||
Une nouvelle fois, nous allons effectuer notre conception d'une enveloppe d'horloge via l'écriture de tests. Premièrement nous ajoutons un scénario de test d'horloge dans notre suite de test <em>tests/all_tests.php</em>...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
require_once('log_test.php');<strong>
|
||||
require_once('clock_test.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All tests');
|
||||
$test->addTestCase(new TestOfLogging());<strong>
|
||||
$test->addTestCase(new TestOfClock());</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Ensuite nous créons le scénario de test dans un nouveau fichier <em>tests/clock_test.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('../classes/clock.php');
|
||||
|
||||
class TestOfClock extends UnitTestCase {
|
||||
function TestOfClock() {
|
||||
$this->UnitTestCase('Clock class test');
|
||||
}
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertEqual($clock->now(), time(), 'Now is the right time');
|
||||
}
|
||||
function testClockAdvance() {
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Notre unique test pour le moment, c'est que notre nouvelle class <code>Clock</code> se comporte comme un simple substitut de la fonction <code>time()</code> en PHP. L'autre méthode tient lieu d'emploi. C'est notre <em>chose à faire</em> en quelque sorte. Nous ne lui avons pas donnée de test parce que ça casserait notre rythme. Nous écrirons cette fonctionnalité de décalage dans le temps une fois que nous serons au vert. Pour le moment nous ne sommes évidemment pas dans le vert...
|
||||
<div class="demo">
|
||||
<br />
|
||||
<b>Fatal error</b>: Failed opening required '../classes/clock.php' (include_path='') in
|
||||
<b>/home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php</b> on line <b>2</b>
|
||||
<br />
|
||||
</div>
|
||||
Nous créons un fichier <em>classes/clock.php</em> comme ceci...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
class Clock {
|
||||
|
||||
function Clock() {
|
||||
}
|
||||
|
||||
function now() {
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
De la sorte nous reprenons le cours du code.
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="fail">Fail</span>: Clock class test->testclocktellstime->[NULL: ] should be equal to [integer: 1050257362]<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">3/3 test cases complete.
|
||||
<strong>4</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
Facile à corriger...
|
||||
<php><![CDATA[
|
||||
class Clock {
|
||||
|
||||
function Clock() {
|
||||
}
|
||||
|
||||
function now() {<strong>
|
||||
return time();</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Et nous revoici dans le vert...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>5</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Il y a juste un petit problème. L'horloge pourrait basculer pendant l'assertion et créer un écart d'une seconde. Les probabilités sont assez faibles mais s'il devait y avoir beaucoup de tests de chronométrage nous finirions avec une suite de test qui serait erratique et forcément presque inutile. Nous nous <a href="subclass_tutorial.php">y attaquerons bientôt</a> et pour l'instant nous l'ajoutons dans la liste des "choses à faire".
|
||||
</p>
|
||||
<p>
|
||||
Le test d'avancement ressemble à...
|
||||
<php><![CDATA[
|
||||
class TestOfClock extends UnitTestCase {
|
||||
function TestOfClock() {
|
||||
$this->UnitTestCase('Clock class test');
|
||||
}
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertEqual($clock->now(), time(), 'Now is the right time');
|
||||
}<strong>
|
||||
function testClockAdvance() {
|
||||
$clock = new Clock();
|
||||
$clock->advance(10);
|
||||
$this->assertEqual($clock->now(), time() + 10, 'Advancement');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Le code pour arriver au vert est direct : il suffit d'ajouter un décalage de temps.
|
||||
<php><![CDATA[
|
||||
class Clock {<strong>
|
||||
var $_offset;</strong>
|
||||
|
||||
function Clock() {<strong>
|
||||
$this->_offset = 0;</strong>
|
||||
}
|
||||
|
||||
function now() {
|
||||
return time()<strong> + $this->_offset</strong>;
|
||||
}
|
||||
<strong>
|
||||
function advance($offset) {
|
||||
$this->_offset += $offset;
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="nettoyer"><h2>Nettoyer le test de groupe</h2></a>
|
||||
Notre fichier <em>all_tests.php</em> contient des répétitions dont nous pourrions nous débarrasser. Nous devons ajouter manuellement tous nos scénarios de test depuis chaque fichier inclus. C'est possible de les enlever mais avec les précautions suivantes. La classe <code>GroupTest</code> inclue une méthode bien pratique appelée <code>addTestFile()</code> qui prend un fichier PHP comme paramètre. Ce mécanisme prend note de toutes les classes : elle inclut le fichier et ensuite regarde toutes les classes nouvellement créées. S'il y a des filles de <code>TestCase</code> elles sont ajoutées au nouveau test de groupe.
|
||||
</p>
|
||||
<p>
|
||||
Voici notre suite de test remaniée en appliquant cette méthode...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}<strong>
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All tests');<strong>
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->addTestFile('clock_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Les inconvéniants sont les suivants...
|
||||
<ol>
|
||||
<li>
|
||||
Si le fichier de test a déjà été inclus, aucune nouvelle classe ne sera ajoutée au groupe.
|
||||
</li>
|
||||
<li>
|
||||
Si le fichier de test contient d'autres classes reliées à <code>TestCase</code> alors celles-ci aussi seront ajouté au test de groupe.
|
||||
</li>
|
||||
</ol>
|
||||
Dans nos test nous n'avons que des scénarios dans les fichiers de test et en plus nous avons supprimé leur inclusion du script <em>all_tests.php</em> : nous sommes donc en règle. C'est la situation la plus commune.
|
||||
</p>
|
||||
<p>
|
||||
Nous devrions corriger au plus vite le petit problème de décalage possible sur l'horloge : c'est ce que nous <a href="subclass_tutorial.php">faisons ensuite</a>.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>Le <a href="#temps">temps</a> est souvent une variable négligée dans les tests.</link>
|
||||
<link>Une <a href="#horloge">classe horloge</a> nous permet de modifier le temps.</link>
|
||||
<link><a href="#nettoyer">Nettoyer le test de groupe</a>.</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La section précédente : <a href="group_test_tutorial.php">grouper des tests unitaires</a>.
|
||||
</link>
|
||||
<link>
|
||||
La section suivante : <a href="subclass_tutorial.php">sous classer les scénarios de test</a>.
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin du <a href="simple_test.php">testeur unitaire SimpleTest</a> pour les exemples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
organisation de tests unitaires,
|
||||
conseil de test,
|
||||
astuce de développement,
|
||||
architecture logicielle pour des tests,
|
||||
exemple de code php,
|
||||
objets fantaisie,
|
||||
junit,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,255 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur le groupement des tests" here="Les groupes de tests">
|
||||
<long_title>Documentation SimpleTest : Grouper des tests</long_title>
|
||||
<content>
|
||||
<section name="grouper" title="Grouper des tests">
|
||||
<p>
|
||||
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><![CDATA[
|
||||
<strong><?php
|
||||
require_once('../classes/io.php');
|
||||
|
||||
class FileTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
|
||||
class SocketTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Si vous avez étendu l'un ou l'autre des scénarios de test, vous pouvez aussi les inclure.
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/io.php');
|
||||
<strong>
|
||||
class MyFileTestCase extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
SimpleTestOptions::ignore('MyFileTestCase');</strong>
|
||||
|
||||
class FileTester extends MyFileTestCase {
|
||||
...
|
||||
}
|
||||
|
||||
class SocketTester extends UnitTestCase {
|
||||
...
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
La classe <code>FileTester</code> 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 <code>SimpleTestOptions::ignore()</code> 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 <em>file_test.php</em>.
|
||||
</p>
|
||||
<p>
|
||||
Ensuite nous créons un fichier de groupe de tests, disons <em>group_test.php</em>. 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><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('file_test.php');
|
||||
|
||||
$test = &new GroupTest('All file tests');
|
||||
$test->addTestCase(new FileTestCase());
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
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><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('file_test.php');
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestClass('FileTestCase');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Le problème de cette technique est que pour chaque scénario de test supplémentaire nous aurons à importer (via <code>require_once()</code>) le fichier de code de test et à instancier manuellement chaque scénario de test. Nous pouvons nous épargner beaucoup de dactylographie avec...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestFile('file_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Voici ce qui vient de se passer : la classe <code>GroupTest</code> a réalisé le <code>require_once()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Il y a deux choses qui peuvent planter et qui demandent un minimum d'attention...
|
||||
<ol>
|
||||
<li>
|
||||
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.
|
||||
</li>
|
||||
<li>
|
||||
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 <code>SimpleTestOptions::ignore()</code> pour ces classes ou alors pensez à les ajouter avant la ligne <code>GroupTest::addTestFile()</code>.
|
||||
</li>
|
||||
</ol>
|
||||
</p>
|
||||
</section>
|
||||
<section name="plus-haut" title="Groupements de plus haut niveau">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Pour obtenir un groupe de tests plus souple nous pouvons sous classer <code>GroupTest</code> et ensuite l'instancier au cas par cas...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
<strong>
|
||||
class FileGroupTest extends GroupTest {
|
||||
function FileGroupTest() {
|
||||
$this->GroupTest('All file tests');
|
||||
$this->addTestFile('file_test.php');
|
||||
}
|
||||
}</strong>
|
||||
?>
|
||||
]]></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><![CDATA[
|
||||
<?php
|
||||
require_once('file_group_test.php');
|
||||
<strong>
|
||||
$test = &new FileGroupTest();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
...ou alors nous pouvons les grouper dans un groupe de tests encore plus grand...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('file_group_test.php');
|
||||
<strong>
|
||||
$test = &new BigGroupTest('Big group');
|
||||
$test->addTestCase(new FileGroupTest());
|
||||
$test->addTestCase(...);
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
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><![CDATA[
|
||||
<?php
|
||||
class FileGroupTest extends GroupTest {
|
||||
function FileGroupTest() {
|
||||
$this->GroupTest('All file tests');
|
||||
$test->addTestFile('file_test.php');
|
||||
}
|
||||
}
|
||||
<strong>
|
||||
if (! defined('RUNNER')) {
|
||||
define('RUNNER', true);</strong>
|
||||
$test = &new FileGroupTest();
|
||||
$test->run(new HtmlReporter());
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
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 <code>run()</code> ne sera lancé qu'une seule fois à partir du script de haut niveau qui l'a invoqué.
|
||||
<php><![CDATA[
|
||||
<?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());
|
||||
?>
|
||||
]]></php>
|
||||
Comme les scénarios de test normaux, un <code>GroupTest</code> peut être chargé avec la méthode <code>GroupTest::addTestFile()</code>.
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
define('RUNNER', true);
|
||||
|
||||
$test = &new BigGroupTest('Big group');<strong>
|
||||
$test->addTestFile('file_group_test.php');
|
||||
$test->addTestFile(...);</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="heritage" title="Intégrer des scénarios de test hérités">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Par exemple, supposons que nous ayons ce scénario de test prévu pour <a href="http://sourceforge.net/projects/phpunit">PhpUnit</a> dans le fichier <em>config_test.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong>class ConfigFileTest extends TestCase {
|
||||
function ConfigFileTest() {
|
||||
$this->TestCase('Config file test');
|
||||
}
|
||||
|
||||
function testContents() {
|
||||
$config = new ConfigFile('test.conf');
|
||||
$this->assertRegexp('/me/', $config->getValue('username'));
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
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><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('simpletest/adapters/phpunit_test_case.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestFile('config_test.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Il n'y a que deux adaptateurs, l'autre est pour le paquet testeur unitaire de <a href="http://pear.php.net/manual/en/package.php.phpunit.php">PEAR</a>...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');<strong>
|
||||
require_once('simpletest/adapters/pear_test_case.php');</strong>
|
||||
|
||||
$test = &new GroupTest('All file tests');<strong>
|
||||
$test->addTestFile('some_pear_test_cases.php');</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Plusieurs approches pour <a href="#group">grouper des tests</a> ensemble.
|
||||
</link>
|
||||
<link>
|
||||
Combiner des groupes des tests dans des <a href="#plus-haut">groupes plus grands</a>.
|
||||
</link>
|
||||
<link>
|
||||
Intégrer des <a href="#heritage">scénarios de test hérités</a> d'un autre type de PHPUnit.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
test unitaire en php,
|
||||
intégration de test,
|
||||
documentation,
|
||||
marcus baker,
|
||||
perrick penet,
|
||||
test simple,
|
||||
documentation simpletest,
|
||||
phpunit,
|
||||
pear
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,198 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Grouper des tests" here="Grouper des tests">
|
||||
<long_title>
|
||||
Tutorial de test unitaire PHP - Grouper des tests unitaires et exemples d'écriture de scénarios de tests
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Pour enchaîner nous allons remplir des blancs et créer une suite de tests.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="autre"><h2>Un autre test</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Ajouter un autre test peut être aussi simple qu'ajouter une nouvelle méthode à un scénario de test...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');<strong>
|
||||
@unlink('../temp/test.log');</strong>
|
||||
}<strong>
|
||||
function testAppendingToFile() {
|
||||
@unlink('../temp/test.log');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line 1');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 1/', $messages[0]);
|
||||
$log->message('Test line 2');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 2/', $messages[1]);
|
||||
@unlink('../temp/test.log');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
La méthode du scénario de test <code>assertWantedPattern()</code> utilise les expressions rationnelles Perl pour vérifier qu'une chaîne respecte un certain motif.
|
||||
</p>
|
||||
<p>
|
||||
Tout ce que nous faisons dans ce nouveau test, c'est écrire une ligne dans un fichier, puis la lire, le tout deux fois de suite. Nous souhaitons simplement vérifier que le loggueur ajoute le texte à la fin plutôt qu'écraser les données déjà existantes. Quelque peu pédant, mais après tout il s'agit d'un tutorial !
|
||||
</p>
|
||||
<p>
|
||||
De toute façon ce test passe directement...
|
||||
<div class="demo">
|
||||
<h1>Log class test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>4</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Notre code contient actuellement beaucoup de répétitions, nous devons effacer le fichier de test avant et après chaque test. De même que <a href="http://www.junit.org/">JUnit</a>, SimpleTest utilise les méthodes <code>setUp()</code> et <code>tearDown()</code> qui sont exécutées respectivement avant et après chaque test. La suppression du fichier est commune à tous les tests : nous devrions donc y mettre cette opération.
|
||||
</p>
|
||||
<p>
|
||||
Nos tests sont verts donc nous pouvons faire un peu de remaniement...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}<strong>
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function testCreatingNewFile() {</strong>
|
||||
$log = new Log('../temp/test.log');
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');<strong>
|
||||
}
|
||||
function testAppendingToFile() {</strong>
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line 1');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 1/', $messages[0]);
|
||||
$log->message('Test line 2');
|
||||
$messages = file('../temp/test.log');
|
||||
$this->assertWantedPattern('/Test line 2/', $messages[1]);<strong>
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Le test reste vert. Nous pouvons continuer à ajouter des méthodes sans test au scénario, il suffit que leur nom ne commence pas par la chaîne "test". Seules les méthodes commençant par "test" sont exécutées. Nous pouvons donc continuer le remaniement...
|
||||
<php><![CDATA[
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}<strong>
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}</strong>
|
||||
function testCreatingNewFile() {
|
||||
$log = new Log('../temp/test.log');
|
||||
$this->assertFalse(file_exists('../temp/test.log'), 'Created before message');
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('../temp/test.log'), 'File created');
|
||||
}
|
||||
function testAppendingToFile() {
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line 1');<strong>
|
||||
$this->assertWantedPattern('/Test line 1/', $this->getFileLine('../temp/test.log', 0));</strong>
|
||||
$log->message('Test line 2');<strong>
|
||||
$this->assertWantedPattern('/Test line 2/', $this->getFileLine('../temp/test.log', 1));</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Que vous préfériez cette version ou la précédente ne dépend que de votre goût personnel. Il y a un peu plus de code dans cette dernière mais la logique du test est plus claire.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="groupe"><h2>Un groupe de tests</h2></a>
|
||||
Un scénario de test ne fonctionne pas tout seul pendant très longtemps. Quand on code pour de vrai nous souhaitons exécuter un maximum de tests aussi souvent et aussi rapidement que possible. Ça veut dire les grouper dans des suites de tests qui incluent l'ensemble des tests de l'application.
|
||||
</p>
|
||||
<p>
|
||||
Premièrement nous devons supprimer le code d'exécution des tests se trouvant dans notre scénario de test.
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
...
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
Nous n'avons plus besoin de la constante <code>SIMPLE_TEST</code>. Ensuite nous créons un groupe de tests appelé <em>all_tests.php</em> dans le répertoire <em>tests</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
require_once(SIMPLE_TEST . 'reporter.php');
|
||||
require_once('log_test.php');
|
||||
|
||||
$test = &new GroupTest('All tests');
|
||||
$test->addTestCase(new TestOfLogging());
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
]]></php>
|
||||
Il n'y a presque de pas de différence tant que les choses marchent...
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>4</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Les tests du groupe s'ajoutent au compteur des scénarios de test. Ajouter des nouveaux scénarios de test est très simple. Il suffit d'inclure le fichier d'un scénario et d'ajouter individuellement tous les scénarios autonomes. Vous pouvez aussi emboîter les groupes de test les uns dans les autres (tout en faisant bien attention d'éviter les boucles).
|
||||
</p>
|
||||
<p>
|
||||
Dans la <a href="gain_control_tutorial.php">page suivante</a> nous les ajouterons encore plus rapidement.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#autre">Ajouter un autres test</a> au scénario existant et remanier.
|
||||
</link>
|
||||
<link>
|
||||
La technique brute pour <a href="#groupe">grouper des tests unitaires</a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a href="gain_control_tutorial.php">Ensuite</a> vient le contrôle de comment la classe sous le test interagit avec le reste du système.
|
||||
</link>
|
||||
<link>
|
||||
<a href="first_test_tutorial.php">Avant</a> il y a la création du premier test.
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin de <a href="simple_test.php">SimpleTest</a> pour exécuter ces exemples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
pilotage par les tests,
|
||||
architecture,
|
||||
ressouces php,
|
||||
objets fantaisie,
|
||||
junit,
|
||||
test php,
|
||||
test unitaire,
|
||||
phpunit,
|
||||
test unitaire php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,137 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Du haut vers le bas et piloté par les tests" here="Du haut vers le bas et piloté par les tests">
|
||||
<long_title>
|
||||
tutoriel de test unitaire en PHP - Conception du haut vers le bas, tester d'abord avec des objets fantaisie
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
<a class="target" name="fantaisie"><h2>Commencer par la fantaisie, passer au code ensuite</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
J'ai menti.
|
||||
</p>
|
||||
<p>
|
||||
Je n'ai pas créé de test pour le scripteur, uniquement l'interface <code>FileWriter</code> que j'ai affiché plus tôt. En fait je vais encore m'éloigner d'un article fini et présumer l'existence un scripteur abstrait dans <em>classes/writer.php</em>...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class <strong>Writer</strong> {
|
||||
|
||||
function <strong>Writer()</strong> {
|
||||
}
|
||||
|
||||
function write($message) {
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Les changements correspondant au niveau du test sont...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');
|
||||
require_once('../classes/writer.php');
|
||||
Mock::generate('Clock');<strong>
|
||||
Mock::generate('Writer');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}
|
||||
function testWriting() {
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$writer = &new <strong>MockWriter($this)</strong>;
|
||||
$writer->expectOnce('write', array('[Timestamp] Test line'));
|
||||
$log = &new Log($writer);
|
||||
$log->message('Test line', &$clock);
|
||||
$writer->tally();
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Afin d'utiliser la classe de log, nous aurions besoin de coder un scripteur de fichier - ou un autre type de scripteur - mais pour le moment nous ne faisons que des tests et nous n'en avons pas encore besoin. En d'autres termes, en utilisant des objets fantaisie nous pouvons décaler la création d'un objet de niveau plus bas jusqu'au moment opportun. Non seulement nous pouvons faire la conception du haut vers le bas, mais en plus nous pouvons aussi tester du haut vers le bas.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="bridge"><h2>S'approcher du bridge - pont</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Imaginez pour un moment que nous ayons commencé la classe de log à partir d'une autre direction. Simulez avoir écrit juste assez du <code>Log</code> pour avoir réaliser le besoin d'un <code>Writer</code>. Comme l'aurions-nous inclus ?
|
||||
</p>
|
||||
<p>
|
||||
Bon, l'héritage du scripteur ne nous aurait pas permis de le simuler du point de vue des tests. De celui de la conception nous aurions été restreint à un unique scripteur sans héritage multiple.
|
||||
</p>
|
||||
<p>
|
||||
Créer un scripteur interne, plutôt qu'en le passant au constructeur, en choisissant un nom de classe, est possible, mais nous aurions moins de contrôle sur l'initialisation de l'objet fantaisie. Du point de vue de la conception il aurait été presque impossible de passer des paramètres au scripteur dans tous les formats possibles et envisageables. Vous auriez dû restreindre le scripteur à un hash ou à une chaîne compliquée décrivant tous les détails de la cible. Au mieux compliqué sans raison.
|
||||
</p>
|
||||
<p>
|
||||
Utiliser une méthode fabrique pour créer le scripteur intérieurement serait possible, mais ça voudrait dire le sous classer pour les tests de manière à remplacer la méthode fabrique par une autre méthode renvoyant un leurre. Plus de boulot du point de vue des tests, quoique toujours possible. Du point de vue de la conception, ça voudrait dire créer une nouvelle sous-classe de log pour chaque type de scripteur. Cela s'appelle une hiérarchie de classe parallèle et fait bien entendu à de la duplication. Beurk.
|
||||
</p>
|
||||
<p>
|
||||
A l'autre extrême, passer ou créer le scripteur à chaque message aurait été répétitif et aurait réduit le code de la classe <code>Log</code> à une unique méthode, un signe certain que toute la classe est devenue redondante.
|
||||
</p>
|
||||
<p>
|
||||
Cette tension entre la facilité du test et le refus de la répétition nous a permis de trouver une conception à la fois flexible et propre. Vous vous souvenez de notre bref envie de l'héritage multiple ? Nous l'avons remplacé par du polymorphisme (plein de scripteurs) et séparé la hiérarchie du journal de celle de l'écriture. Nous relions les deux par agrégation à travers le plus simple <code>Log</code>. Cette astuce est en fait un design pattern (modèle de conception) appelé "Pont" ou "Bridge".
|
||||
</p>
|
||||
<p>
|
||||
Donc nous avons été poussé par le code de test (nous n'avons presque rien écrit d'autre) vers un design pattern. Pensez-y une seconde. Les tests améliorent la qualité du code, à coup sûr dans mon cas, mais il y a quelque chose de bien plus profond et plus puissant.
|
||||
</p>
|
||||
<p>
|
||||
Les tests ont amélioré la conception.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="conception"><h2>Simuler la conception</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Créer un objet fantaisie est aussi simple que de créer l'interface à l'écrit. Si vous utilisez de l'UML ou d'autres outils pour générer ces interfaces alors vous avez un chemin encore plus flexible pour générer rapidement vos objets de test. Même sans, vous pouvez passer du dessin sur tableau blanc, à l'écriture de l'objet fantaisie, puis à la génération de l'interface qui nous renvoie de nouveau au tableau blanc, le tout très simplement. Comme le remaniement, la conception, le code et les tests s'unifient.
|
||||
</p>
|
||||
<p>
|
||||
Parce que les objets fantaisie travaillent du haut vers le bas, ils peuvent être amenés dans la conception plus rapidement qu'un remaniement classique qui demande quant à lui du code fonctionnel avant de pourvoir s'installer. Ça veut dire que le code de test interagit plus vite avec la conception : par conséquent la qualité de la conception augmente elle aussi plus vite.
|
||||
</p>
|
||||
<p>
|
||||
Un testeur unitaire est un outil de code. Un testeur unitaire avec objet fantaisie est un outil de conception.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#fantaisie">Simuler maintenant</a>, coder plus tard.
|
||||
</link>
|
||||
<link>
|
||||
Nous dérivons vers le <a href="#bridge">design pattern bridge</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#conception">Conception et test</a> main dans la main.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
Ce tutorial suit <a href="boundary_classes_tutorial.php">les classes frontière</a>.
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin du <a href="simple_test.php">framework de test SimpleTest</a> pour essayer ces exemples.
|
||||
</link>
|
||||
<link>
|
||||
Pour des discussions plus fournis sur les objets fantaisie, voyez le <a href="http://www.xpdeveloper.org/xpdwiki/Wiki.jsp?page=MockObjects">Wiki des Extreme Tuesday</a> ou le <a href="http://c2.com/cgi/wiki?MockObject">Wiki C2</a> (en anglais tous les deux).
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
tutoriel de programmation php,
|
||||
scénarios de test en php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
exemple php,
|
||||
exemple d'objet fantaisie,
|
||||
test style junit,
|
||||
architecture logicielle pour des tests,
|
||||
framework de test en php,
|
||||
test unitaire,
|
||||
objet fantaisie en php
|
||||
test php,
|
||||
suite de test php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,68 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Les articles de :: onpk :: sur php / simpletest" here="php / simpletest">
|
||||
<long_title>
|
||||
Les articles de :: onpk :: sur php / simpletest : traductions en français des articles publiés sur Lastcraft.com
|
||||
</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
Cette section rassemble l'ensemble des articles et documentations pour SimpleTest traduits en français.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="comment" title="Comment en arrive-t-on au développement piloté par les tests ?">
|
||||
<p>
|
||||
J'ai commencé par découvrir l'Extreme Programming via le web. Ensuite j'ai gagné un livre en français sur XP. Et découvrant la confiance supplémentaire gagnée via les tests unitaires et de recette, je suis devenu "test-infected".
|
||||
</p>
|
||||
<p>
|
||||
Après avoir goûté aux joies de SimpleTest, j'ai contacté Marcus Baker -- responsable du projet -- pour lui proposer de traduire en français la page d'introduction, puis les tutoriaux et finalement toute la documentation. Un travail qui n'aurait pas été possible sans l'aide de quelques relecteurs bienveillants : Jérémie C., David B., Emmanuel G., Olivier L. et Cédric G. (dans le désordre).
|
||||
</p>
|
||||
<p>
|
||||
Si vous lisez attentivement ces quelques pages et que vous y trouvez encore des fautes d'orthographe, pensez à me les renvoyer : comme ça le prochain ne pourra pas se dire la même chose.
|
||||
</p>
|
||||
</section>
|
||||
<section name="ailleurs" title="Et en dehors des tests ?">
|
||||
<p>
|
||||
J'ai un blog -- <a href="http://www.onpk.net/">:: onpk ::</a>, une entreprise -- <a href="http://www.noparking.net">No Parking</a> dont le produit phare est <a href="http://www.noparking.net/opentime/">openTIME</a>. Dans la communauté je me ballade du côté de l'<a href="http://www.afup.org/">AFUP</a>, des <a href="http://www.aperophp.net/">apéros PHP</a> et des <a href="http://xp-france.net/cgi-bin/wiki.pl">praticiens XP</a>.
|
||||
</p>
|
||||
</section>
|
||||
<section name="articles" title="Tous les articles">
|
||||
<p>
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#comment">Comment</a> en arrive-t-on au développement piloté par les tests ?
|
||||
</link>
|
||||
<link>
|
||||
Et <a href="#ailleurs">en dehors</a> des tests ?
|
||||
</link>
|
||||
<link>
|
||||
Tous les <a href="#articles">articles</a>
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a> -- l'original en anglais.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
conseil de test,
|
||||
architecture logicielle pour des tests,
|
||||
exemple de code php,
|
||||
junit,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
<description>
|
||||
Des articles (documentations et tutoriels) pour découvrir le développement agile en PHP avec le framework de tests unitaires SimpleTest.
|
||||
</description>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Introduction à SimpleTest" here="Version française">
|
||||
<long_title>
|
||||
Les articles de :: onpk :: sur php / simpletest : traductions en français des articles publiés sur Lastcraft.com
|
||||
</long_title>
|
||||
<content>
|
||||
<p>
|
||||
Le <a local="simple_test">testeur unitaire SimpleTest PHP</a> a enfin atteint la délicate version 1.0 : il est disponible au téléchargement chez votre <a href="http://souceforge.net/projects/simpletest/">SourceForge</a> le plus proche.
|
||||
</p>
|
||||
<p>
|
||||
Il s'agit d'un testeur unitaire PHP et aussi d'un testeur web. Il est construit pour être extensible de plusieurs manières. Les utilisateurs de <a href="http://www.junit.org/">JUnit</a> seront familiers avec la plupart des interfaces. L'affichage des tests est largement modifiable tout comme le scénario de test de base. Par ailleurs les objets fantaisie peuvent être utilisés avec d'autres testeurs unitaires.
|
||||
</p>
|
||||
<p>
|
||||
Les fonctionnalités à-la-<a href="http://jwebunit.sourceforge.net/">JWebUnit</a> sont plus complètes aussi. Il y a le support pour SSL, les fenêtres, les proxies, l'authentification simple et un large choix de contrôles HTML. L'idée est que les tâches fastidieuses en PHP, se connecter à un site par exemple, puissent être testées facilement.
|
||||
</p>
|
||||
</content>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
conseil de test,
|
||||
architecture logicielle pour des tests,
|
||||
exemple de code php,
|
||||
junit,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
<description>
|
||||
Des articles (documentations et tutoriels) pour découvrir le développement agile en PHP avec le framework de tests unitaires SimpleTest.
|
||||
</description>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,458 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur les objets fantaisie" here="Les objets fantaisie">
|
||||
<long_title>Documentation SimpleTest : les objets fantaise</long_title>
|
||||
<content>
|
||||
<section name="quoi" title="Que sont les objets fantaisie ?">
|
||||
<p>
|
||||
Les objets fantaisie - ou "mock objects" en anglais - ont deux rôles pendant un scénario de test : acteur et critique.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Si les objets fantaisie ne se comportaient que comme des acteurs alors on les connaîtrait sous le nom de <a local="server_stubs_documentation">bouchons serveur</a>.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
<section name="creation" title="Créer des objets fantaisie">
|
||||
<p>
|
||||
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 à...
|
||||
<php><![CDATA[
|
||||
<strong>class DatabaseConnection {
|
||||
function DatabaseConnection() {
|
||||
}
|
||||
|
||||
function query() {
|
||||
}
|
||||
|
||||
function selectQuery() {
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
<strong>require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
|
||||
Mock::generate('DatabaseConnection');</strong>
|
||||
]]></php>
|
||||
Ceci génère une classe clone appelée <code>MockDatabaseConnection</code>. Nous pouvons désormais créer des instances de cette nouvelle classe à l'intérieur même de notre scénario de test...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
|
||||
Mock::generate('DatabaseConnection');
|
||||
<strong>
|
||||
class MyTestCase extends UnitTestCase {
|
||||
|
||||
function testSomething() {
|
||||
$connection = &new MockDatabaseConnection($this);
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="bouchon"><h2>Objets fantaisie en action</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
La version fantaisie d'une classe contient toutes les méthodes de l'originale. De la sorte une opération comme <code><![CDATA[$connection->query()]]></code> est encore possible. Tout comme avec les bouchons, nous pouvons remplacer la valeur nulle renvoyée par défaut...
|
||||
<php><![CDATA[
|
||||
<strong>$connection->setReturnValue('query', 37);</strong>
|
||||
]]></php>
|
||||
Désormais à chaque appel de <code><![CDATA[$connection->query()]]></code> 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...
|
||||
<php><![CDATA[
|
||||
<strong>Mock::generate('DatabaseConnection', 'MyMockDatabaseConnection', array('setOptions'));</strong>
|
||||
]]></php>
|
||||
Ici l'objet fantaisie se comportera comme si <code>setOptions()</code> existait dans la classe originale. C'est pratique si une classe a utilisé le mécanisme <code>overload()</code> de PHP pour ajouter des méthodes dynamiques. Vous pouvez créer des fantaisies spéciales pour simuler cette situation.
|
||||
</p>
|
||||
<p>
|
||||
Tous les modèles disponibles avec les bouchons serveur le sont également avec les objets fantaisie...
|
||||
<php><![CDATA[
|
||||
class Iterator {
|
||||
function Iterator() {
|
||||
}
|
||||
|
||||
function next() {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Une nouvelle fois, supposons que cet itérateur ne retourne que du texte jusqu'au moment où il atteint son terme, quand il renvoie <code>false</code>. Nous pouvons le simuler avec...
|
||||
<php><![CDATA[
|
||||
Mock::generate('Iterator');
|
||||
|
||||
class IteratorTest extends UnitTestCase() {
|
||||
|
||||
function testASequence() {<strong>
|
||||
$iterator = &new MockIterator($this);
|
||||
$iterator->setReturnValue('next', false);
|
||||
$iterator->setReturnValueAt(0, 'next', 'First string');
|
||||
$iterator->setReturnValueAt(1, 'next', 'Second string');</strong>
|
||||
...
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Au moment du premier appel à <code>next()</code> 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 <code>false</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Reprenons aussi le conteneur d'information bouchonné avec des pairs clef / valeur...
|
||||
<php><![CDATA[
|
||||
class Configuration {
|
||||
function Configuration() {
|
||||
}
|
||||
|
||||
function getValue($key) {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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 <code>getValue()</code> et que nous voulons des résultats différents pour des clefs différentes. Heureusement les objets fantaisie ont un système de filtrage...
|
||||
<php><![CDATA[
|
||||
<strong>$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'));</strong>
|
||||
]]></php>
|
||||
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 <code>getValue()</code> est invoquée sur l'objet fantaisie...
|
||||
<php><![CDATA[
|
||||
$config->getValue('db_user')
|
||||
]]></php>
|
||||
...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.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class Thing {
|
||||
}
|
||||
|
||||
class Vector {
|
||||
function Vector() {
|
||||
}
|
||||
|
||||
function get($index) {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Dans ce cas vous pouvez placer une référence dans la liste renvoyée par l'objet fantaisie...
|
||||
<php><![CDATA[
|
||||
$thing = new Thing();<strong>
|
||||
$vector = &new MockVector($this);
|
||||
$vector->setReturnReference('get', $thing, array(12));</strong>
|
||||
]]></php>
|
||||
Avec cet arrangement vous savez qu'à chaque appel de <code><![CDATA[$vector->get(12)]]></code> le même <code>$thing</code> sera renvoyé.
|
||||
</p>
|
||||
</section>
|
||||
<section name="attentes" title="Objets fantaisie en critique">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Pour l'exemple, prenons une classe <code>SessionPool</code> à 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 <code>SessionPool</code> ressemble à...
|
||||
<php><![CDATA[
|
||||
<strong>class SessionPool {
|
||||
function SessionPool() {
|
||||
...
|
||||
}
|
||||
|
||||
function &findSession($cookie) {
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
|
||||
class Session {
|
||||
...
|
||||
}</strong>
|
||||
]]>
|
||||
</php>
|
||||
Alors que pour notre code de log, nous avons...
|
||||
<php><![CDATA[<strong>
|
||||
class Log {
|
||||
function Log() {
|
||||
...
|
||||
}
|
||||
|
||||
function message() {
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
class LoggingSessionPool {
|
||||
function LoggingSessionPool(&$session_pool, &$log) {
|
||||
...
|
||||
}
|
||||
|
||||
function &findSession(\$cookie) {
|
||||
...
|
||||
}
|
||||
...
|
||||
}</strong>
|
||||
]]></php>
|
||||
Dans tout ceci, la seule classe à tester est <code>LoggingSessionPool</code>. En particulier, nous voulons vérifier que la méthode <code>findSession()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
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 :
|
||||
<ol>
|
||||
<li>Créer un objet de log.</li>
|
||||
<li>Indiquer le répertoire d'écriture du fichier de log.</li>
|
||||
<li>Modifier les droits sur le répertoire pour pouvoir y écrire le fichier.</li>
|
||||
<li>Créer un objet <code>SessionPool</code>.</li>
|
||||
<li>Lancer une session, ce qui demande probablement pas mal de choses.</li>
|
||||
<li>Invoquer <code>findSession()</code>.</li>
|
||||
<li>Lire le nouvel identifiant de session (en espérant qu'il existe un accesseur !).</li>
|
||||
<li>Lever une assertion de test pour vérifier que cet identifiant correspond bien au cookie.</li>
|
||||
<li>Lire la dernière ligne du fichier de log.</li>
|
||||
<li>Supprimer avec une (ou plusieurs) expression rationnelle les timestamps de log en trop, etc.</li>
|
||||
<li>Vérifier que le message de session est bien dans le texte.</li>
|
||||
</ol>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
A la place, voici la méthode complète pour le test avec un peu de magie via les objets fantaisie...
|
||||
<php><![CDATA[
|
||||
Mock::generate('Session');
|
||||
Mock::generate('SessionPool');
|
||||
Mock::generate('Log');
|
||||
|
||||
class LoggingSessionPoolTest extends UnitTestCase {
|
||||
...
|
||||
function testFindSessionLogging() {<strong>
|
||||
$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();</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
<code>findSession()</code> est un méthode fabrique dont la simulation est décrite <a href="#stub">plus haut</a>. Le point de départ vient avec le premier appel <code>expectOnce()</code>. Cette ligne indique qu'à chaque fois que <code>findSession()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
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 <code>tally()</code> à la fin du test.
|
||||
</p>
|
||||
<p>
|
||||
Nous utilisons le même modèle pour mettre sur pied le loggueur fantaisie. Nous lui indiquons que <code>message()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Nous commençons le lancement nos tests à la création du nouveau <code>LoggingSessionPool</code> et nous l'alimentons avec nos objets fantaisie juste créés. Désormais tout est sous contrôle. Au final nous confirmons que le <code>$session</code> 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 <code>tally()</code>.
|
||||
</p>
|
||||
<p>
|
||||
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 <code>setUp()</code>.
|
||||
</p>
|
||||
<p>
|
||||
Voici la liste complète des attentes que vous pouvez placer sur un objet fantaisie avec <a href="http://www.lastcraft.com/simple_test.php">SimpleTest</a>...
|
||||
<table><thead>
|
||||
<tr><th>Attente</th><th>Nécessite <code>tally()</code></th></tr>
|
||||
</thead><tbody><tr>
|
||||
<td><code>expectArguments($method, $args)</code></td>
|
||||
<td style="text-align: center">Non</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectArgumentsAt($timing, $method, $args)</code></td>
|
||||
<td style="text-align: center">Non</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectCallCount($method, $count)</code></td>
|
||||
<td style="text-align: center">Oui</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectMaximumCallCount($method, $count)</code></td>
|
||||
<td style="text-align: center">Non</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectMinimumCallCount($method, $count)</code></td>
|
||||
<td style="text-align: center">Oui</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectNever($method)</code></td>
|
||||
<td style="text-align: center">Non</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectOnce($method, $args)</code></td>
|
||||
<td style="text-align: center">Oui</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>expectAtLeastOnce($method, $args)</code></td>
|
||||
<td style="text-align: center">Oui</td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
Où les paramètres sont...
|
||||
<dl>
|
||||
<dt class="new_code">$method</dt>
|
||||
<dd>Le nom de la méthode, sous la forme d'une chaîne, à laquelle la condition doit être appliquée.</dd>
|
||||
<dt class="new_code">$args</dt>
|
||||
<dd>
|
||||
Les arguments sous la forme d'une liste. Les jokers peuvent être inclus de la même manière qu'avec <code>setReturn()</code>. Cet argument est optionnel pour <code>expectOnce()</code> et <code>expectAtLeastOnce()</code>.
|
||||
</dd>
|
||||
<dt class="new_code">$timing</dt>
|
||||
<dd>
|
||||
Le seul point dans le temps pour tester la condition. Le premier appel commence à zéro.
|
||||
</dd>
|
||||
<dt class="new_code">$count</dt>
|
||||
<dd>Le nombre d'appels attendu.</dd>
|
||||
</dl>
|
||||
La méthode <code>expectMaximumCallCount()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
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".
|
||||
</p>
|
||||
</section>
|
||||
<section name="approches" title="D'autres approches">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Les objets fantaisie générés avec <a local="simple_test">SimpleTest</a> sont dynamiques. Ils sont créés à l'exécution dans la mémoire, grâce à <code>eval()</code>, 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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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 <em>mocks/connection.php</em> 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><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('../classes/connection.php');
|
||||
<strong>
|
||||
Mock::generate('Connection', 'BasicMockConnection');
|
||||
class MockConnection extends BasicMockConnection {
|
||||
function MockConnection(&$test, $wildcard = '*') {
|
||||
$this->BasicMockConnection($test, $wildcard);
|
||||
$this->setReturn('query', false);
|
||||
}
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
L'appel <code>generate</code> dit au générateur de classe d'en créer une appelée <code>BasicMockConnection</code> plutôt que la plus courante <code>MockConnection</code>. Ensuite nous héritons à partir de celle-ci pour obtenir notre version de <code>MockConnection</code>. En interceptant de cette manière nous pouvons ajouter un comportement, ici transformer la valeur par défaut de <code>query()</code> 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 <code>MockConnection</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Utiliser cette astuce si vous vous trouvez avec beaucoup de comportement en commun sur les objets fantaisie ou si vous avez de fréquents problèmes d'intégration plus tard dans les étapes de test.
|
||||
</p>
|
||||
</section>
|
||||
<section name="autres_testeurs" title="Je pense que SimpleTest pue !">
|
||||
<p>
|
||||
Mais au moment d'écrire ces lignes c'est le seul à gérer les objets fantaisie, donc vous êtes bloqué avec lui ?
|
||||
</p>
|
||||
<p>
|
||||
Non, pas du tout.
|
||||
<a local="simple_test">SimpleTest</a> 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 à...
|
||||
<php><![CDATA[
|
||||
class PHPUnit {
|
||||
function PHPUnit() {
|
||||
}
|
||||
|
||||
function assertion($message, $assertion) {
|
||||
}
|
||||
...
|
||||
}
|
||||
]]></php>
|
||||
La seule chose que la méthode <code>assertion()</code> 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...
|
||||
<php><![CDATA[
|
||||
$unit_test = new PHPUnit();
|
||||
$unit_test>assertion('I hope this file exists', file_exists('my_file'));
|
||||
]]></php>
|
||||
Comment utiliser les objets fantaisie avec ceci ?
|
||||
</p>
|
||||
<p>
|
||||
Il y a une méthode protégée sur la classe de base des objets fantaisie : elle s'appelle <code>_assertTrue()</code>. En surchargeant cette méthode nous pouvons utiliser notre propre format d'assertion. Nous commençons avec une sous-classe, dans <em>my_mock.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?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);
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Maintenant une instance de <code>MyMock</code> 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><![CDATA[
|
||||
<?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);
|
||||
}
|
||||
}<strong>
|
||||
SimpleTestOptions::setMockBaseClass('MyMock');</strong>
|
||||
?>
|
||||
]]></php>
|
||||
A partir de maintenant vous avez juste à inclure <em>my_mock.php</em> à la place de la version par défaut <em>simple_mock.php</em> et vous pouvez introduire des objets fantaisie dans votre suite de tests existants.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#quoi">Que sont les objets fantaisie ?</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#creation">Créer des objets fantaisie</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#bouchon">L'objet fantaisie - acteur</a> ou bouchon.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#attentes">L'objet fantaisie - critique</a> avec des attentes.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#approches">D'autres approches</a> y compris des librairies d'objets fantaisie.
|
||||
</link>
|
||||
<link>
|
||||
Utiliser les objets fantaisie avec <a href="#autres_testeurs">d'autres testeurs unitaires</a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
L'article originel sur <a href="http://www.mockobjects.com/">les objets fantaisie</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page d'accueil de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation en php,
|
||||
outils de développement logiciel,
|
||||
tutoriel php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressources php,
|
||||
mock objects,
|
||||
objets fantaisie,
|
||||
junit,
|
||||
test php,
|
||||
test unitaire,
|
||||
tester en php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,269 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Objets fantaisie" here="Utiliser des objets fantaisie">
|
||||
<long_title>tutorial sur les tests unitaires en PHP - Utiliser les objets fantaisie en PHP</long_title>
|
||||
<content>
|
||||
<p>
|
||||
<a class="target" name="remaniement"><h2>Remanier les tests à nouveau</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Avant d'ajouter de nouvelles fonctionnalités il y a du remaniement à faire. Nous allons effectuer des tests chronométrés et la classe <code>TimeTestCase</code> a définitivement besoin d'un fichier propre. Appelons le <em>tests/time_test_case.php</em>...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
if (! defined('SIMPLE_TEST')) {
|
||||
define('SIMPLE_TEST', 'simpletest/');
|
||||
}
|
||||
require_once(SIMPLE_TEST . 'unit_tester.php');
|
||||
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase($test_name = '') {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, $message = '') {
|
||||
if (! $message) {
|
||||
$message = "Time [$time1] should match time [$time2]";
|
||||
}
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Nous pouvons lors utiliser <code>require()</code> pour incorporer ce fichier dans le script <em>all_tests.php</em>.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="timestamp"><h2>Ajouter un timestamp au Log</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Je ne sais pas trop quel devrait être le format du message de log pour le test alors pour vérifier le timestamp nous pourrions juste faire la plus simple des choses possibles, c'est à dire rechercher une suite de chiffres.
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');<strong>
|
||||
require_once('../classes/clock.php');
|
||||
|
||||
class TestOfLogging extends TimeTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->TimeTestCase('Log class test');
|
||||
}</strong>
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
...
|
||||
}
|
||||
function testAppendingToFile() {
|
||||
...
|
||||
}<strong>
|
||||
function testTimestamps() {
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line');
|
||||
$this->assertTrue(
|
||||
preg_match('/(\d+)/', $this->getFileLine('../temp/test.log', 0), $matches),
|
||||
'Found timestamp');
|
||||
$clock = new clock();
|
||||
$this->assertSameTime((integer)$matches[1], $clock->now(), 'Correct time');
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Ce scénario de test crée un nouvel objet <code>Log</code> et écrit un message. Nous recherchons une suite de chiffres et nous la comparons à l'horloge présente en utilisant notre objet <code>Clock</code>. Bien sûr ça ne marche pas avant d'avoir écrit le code.
|
||||
<div class="demo">
|
||||
<h1>All tests</h1>
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 1/] in [Test line 1]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testappendingtofile->Expecting [/Test line 2/] in [Test line 2]<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->Created before message<br />
|
||||
<span class="pass">Pass</span>: log_test.php->Log class test->testcreatingnewfile->File created<br />
|
||||
<span class="fail">Fail</span>: log_test.php->Log class test->testtimestamps->Found timestamp<br />
|
||||
<br />
|
||||
<b>Notice</b>: Undefined offset: 1 in <b>/home/marcus/projects/lastcraft/tutorial_tests/tests/log_test.php</b> on line <b>44</b><br />
|
||||
<span class="fail">Fail</span>: log_test.php->Log class test->testtimestamps->Correct time<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclockadvance->Advancement<br />
|
||||
<span class="pass">Pass</span>: clock_test.php->Clock class test->testclocktellstime->Now is the right time<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>2</strong> fails.</div>
|
||||
</div>
|
||||
Cette suite de tests montre encore les succès de notre modification précédente.
|
||||
</p>
|
||||
<p>
|
||||
Nous pouvons faire passer les tests en ajoutant simplement un timestamp à l'écriture dans le fichier. Oui, bien sûr, tout ceci est assez trivial et d'habitude je ne le testerais pas aussi fanatiquement, mais ça va illustrer un problème plus général... Le fichier <em>log.php</em> devient...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('../classes/clock.php');</strong>
|
||||
|
||||
class Log {
|
||||
var $_file_path;
|
||||
|
||||
function Log($file_path) {
|
||||
$this->_file_path = $file_path;
|
||||
}
|
||||
|
||||
function message($message) {<strong>
|
||||
$clock = new Clock();</strong>
|
||||
$file = fopen($this->_file_path, 'a');<strong>
|
||||
fwrite($file, "[" . $clock->now() . "] $message\n");</strong>
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Les tests devraient passer.
|
||||
</p>
|
||||
<p>
|
||||
Par contre notre nouveau test est plein de problèmes. Qu'est-ce qui se passe si notre format de temps change ? Les choses vont devenir largement plus compliquées si ça venait à se produire. Cela veut aussi dire que n'importe quel changement du format de notre classe horloge causera aussi un échec dans les tests de log. Bilan : nos tests de log sont tout mélangés avec les test d'horloge et par la même très fragiles. Tester à la fois des facettes de l'horloge et d'autres du log manque de cohésion, ou de focalisation étanche si vous préférez. Nos problèmes sont causés en partie parce que le résultat de l'horloge est imprévisible alors que l'unique chose à tester est la présence du résultat de <code>Clock::now()</code>. Peu importe le contenu de l'appel de cette méthode.
|
||||
</p>
|
||||
<p>
|
||||
Pouvons-nous rendre cet appel prévisible ? Oui si nous pouvons forcer le loggueur à utiliser une version factice de l'horloge lors du test. Cette classe d'horloge factice devrait se comporter exactement comme la classe <code>Clock</code> à part une sortie fixée dans la méthode <code>now()</code>. Et au passage, ça nous affranchirait même de la classe <code>TimeTestCase</code> !
|
||||
</p>
|
||||
<p>
|
||||
Nous pourrions écrire une telle classe assez facilement même s'il s'agit d'un boulot plutôt fastidieux. Nous devons juste créer une autre classe d'horloge avec la même interface sauf que la méthode <code>now()</code> retourne une valeur modifiable via une autre méthode d'initialisation. C'est plutôt pas mal de travail pour un test plutôt mineur.
|
||||
</p>
|
||||
<p>
|
||||
Sauf que ça se fait sans aucun effort.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="fantaisie"><h2>Une horloge fantaisie</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Pour atteindre le nirvana de l'horloge instantané pour test nous n'avons besoin que de trois lignes de code supplémentaires...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/mock_objects.php');
|
||||
]]></php>
|
||||
Cette instruction inclut le code de générateur d'objet fantaisie. Le plus simple reste de le mettre dans le script <em>all_tests.php</em> étant donné qu'il est utilisé assez fréquemment.
|
||||
<php><![CDATA[
|
||||
Mock::generate('Clock');
|
||||
]]></php>
|
||||
C'est la ligne qui fait le travail. Le générateur de code scanne la classe, en extrait toutes ses méthodes, crée le code pour générer une classe avec une interface identique, mais en ajoutant le nom "Mock" et ensuite <code>eval()</code> le nouveau code pour créer la nouvelle classe.
|
||||
<php><![CDATA[
|
||||
$clock = &new MockClock($this);
|
||||
]]></php>
|
||||
Cette ligne peut être ajoutée dans n'importe quelle méthode de test qui nous intéresserait. Elle crée l'horloge fantaisie prête à recevoir nos instructions.
|
||||
</p>
|
||||
<p>
|
||||
Notre scénario de test en est à ses premiers pas vers un nettoyage radical...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/clock.php');<strong>
|
||||
Mock::generate('Clock');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
function TestOfLogging() {
|
||||
$this->UnitTestCase('Log class test');
|
||||
}</strong>
|
||||
function setUp() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.log');
|
||||
}
|
||||
function getFileLine($filename, $index) {
|
||||
$messages = file($filename);
|
||||
return $messages[$index];
|
||||
}
|
||||
function testCreatingNewFile() {
|
||||
...
|
||||
}
|
||||
function testAppendingToFile() {
|
||||
...
|
||||
}
|
||||
function testTimestamps() {<strong>
|
||||
$clock = &new MockClock($this);
|
||||
$clock->setReturnValue('now', 'Timestamp');
|
||||
$log = new Log('../temp/test.log');
|
||||
$log->message('Test line', &$clock);
|
||||
$this->assertWantedPattern(
|
||||
'/Timestamp/',
|
||||
$this->getFileLine('../temp/test.log', 0),
|
||||
'Found timestamp');</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Cette méthode de test crée un objet <code>MockClock</code> puis définit la valeur retourné par la méthode <code>now()</code> par la chaîne "Timestamp". A chaque fois que nous appelons <code>$clock->now()</code>, elle retournera cette même chaîne. Ça devrait être quelque chose de facilement repérable.
|
||||
</p>
|
||||
<p>
|
||||
Ensuite nous créons notre loggueur et envoyons un message. Nous incluons dans l'appel <code>message()</code> l'horloge que nous souhaitons utiliser. Ça veut dire que nous aurons à ajouter un paramètre optionnel à la classe de log pour rendre ce test possible...
|
||||
<php><![CDATA[
|
||||
class Log {
|
||||
var $_file_path;
|
||||
|
||||
function Log($file_path) {
|
||||
$this->_file_path = $file_path;
|
||||
}
|
||||
|
||||
function message($message, <strong>$clock = false</strong>) {<strong>
|
||||
if (!is_object($clock)) {
|
||||
$clock = new Clock();
|
||||
}</strong>
|
||||
$file = fopen($this->_file_path, 'a');
|
||||
fwrite($file, "[" . $clock->now() . "] $message\n");
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Maintenant tous les tests passent et ils ne testent que le code du loggueur. Nous pouvons à nouveau respirer.
|
||||
</p>
|
||||
<p>
|
||||
Est-ce que ce paramètre supplémentaire dans la classe <code>Log</code> vous gêne ? Nous n'avons changé l'interface que pour faciliter les tests après tout. Les interfaces ne sont-elles pas la chose la plus importante ? Avons nous souillé notre classe avec du code de test ?
|
||||
</p>
|
||||
<p>
|
||||
Peut-être, mais réfléchissez à ce qui suit. A la prochaine occasion, regardez une carte avec des circuits imprimés, peut-être la carte mère de l'ordinateur que vous regardez actuellement. Sur la plupart d'entre elles vous trouverez un trou bizarre et vide ou alors un point de soudure sans rien de fixé ou même une épingle ou une prise sans aucune fonction évidente. Peut-être certains sont là en prévision d'une expansion ou d'une variation future, mais la plupart n'y sont que pour les tests.
|
||||
</p>
|
||||
<p>
|
||||
Pensez-y. Les usines qui fabriquent ces cartes imprimées par centaine de milliers gaspillent des matières premières sur des pièces qui n'ajoutent rien à la fonction finale. Si les ingénieurs matériel peuvent faire quelques sacrifices à l'élégance, je suis sûr que nous pouvons aussi le faire. Notre sacrifice ne gaspille pas de matériel après tout.
|
||||
</p>
|
||||
<p>
|
||||
Ça vous gêne encore ? En fait moi aussi, mais pas tellement ici. La priorité numéro 1 reste du code qui marche, pas un prix pour minimalisme. Si ça vous gêne vraiment alors déplacez la création de l'horloge dans une autre méthode mère protégée. Ensuite sous classez l'horloge pour le test et écrasez la méthode mère avec une qui renvoie le leurre. Vos tests sont bancals mais votre interface est intacte.
|
||||
</p>
|
||||
<p>
|
||||
Une nouvelle fois je vous laisse la décision finale.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#remaniement">Remanier les tests</a> dans le but de réutiliser notre nouveau test de temps.
|
||||
</link>
|
||||
<link>Ajouter des <a href="#timestamp">timestamps de Log</a>.</link>
|
||||
<link><a href="#fantaisie">Créer une horloge fantaisie</a> pour rendre les tests cohésifs.</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La section précédente : <a href="first_test_tutorial.php">tutorial de test unitaire</a>.
|
||||
</link>
|
||||
<link>
|
||||
La section suivante : <a href="boundary_classes_tutorial.php">les frontières de l'application</a>.
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin du <a href="simple_test.php">framework de test SimpleTest</a> pour essayer ces exemples.
|
||||
</link>
|
||||
<link>
|
||||
Documents sur les <a href="http://www.mockobjects.com/">objets fantaisie</a>.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutoriel php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressources php,
|
||||
objet fantaisie,
|
||||
junit,
|
||||
phpunit,
|
||||
simpletest,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,295 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Apercu de SimpleTest" here="Aperçu">
|
||||
<long_title>
|
||||
Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP
|
||||
</long_title>
|
||||
<content>
|
||||
<section name="resume" title="Qu'est-ce que SimpleTest ?">
|
||||
<p>
|
||||
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 <code>run()</code> à 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, <code>assertEqual()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Un <a local="unit_test_documentation">scénario de test</a> ressemble à...
|
||||
<php><![CDATA[
|
||||
class <strong>MyTestCase</strong> extends UnitTestCase {
|
||||
<strong>
|
||||
function testLog() {
|
||||
$log = &new Log('my.log');
|
||||
$log->message('Hello');
|
||||
$this->assertTrue(file_exists('my.log'));
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Le type de scénario de test le plus simple est le <code>UnitTestCase</code>. 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.
|
||||
</p>
|
||||
<p>
|
||||
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 <code>WebTestCase</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Un <a local="web_tester_documentation">scénario de test web</a> ressemble à...
|
||||
<php><![CDATA[
|
||||
class <strong>MySiteTest</strong> extends WebTestCase {
|
||||
<strong>
|
||||
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/');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="fonctionnalites" title="Liste des fonctionnalites">
|
||||
<p>
|
||||
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".
|
||||
<table><thead>
|
||||
<tr><th>Fonctionnalité</th><th>Description</th><th>Publication</th></tr>
|
||||
</thead><tbody><tr>
|
||||
<td>Scénariot de test unitaire</td>
|
||||
<td>Les classes de test et assertions de base</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Affichage HTML</td>
|
||||
<td>L'affichage le plus simple possible</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Autochargement des scénarios de test</td>
|
||||
<td>Lire un fichier avec des scénarios de test et les charger dans un groupe de tests automatiquement</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Générateur de code d'objets fantaisie</td>
|
||||
<td>Des objets capable de simuler d'autres objets, supprimant les dépendances dans les tests</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Bouchons serveur</td>
|
||||
<td>Des objets fantaisie sans résultat attendu à utiliser à l'extérieur des scénarios de test, pour le prototypage par exemple.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Intégration d'autres testeurs unitaires</td>
|
||||
<td>
|
||||
La capacité de lire et simuler d'autres scénarios de test en provenance de PHPUnit et de PEAR::Phpunit.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Scénario de test web</td>
|
||||
<td>Appariement basique de motifs dans une page téléchargée.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Analyse de page HTML</td>
|
||||
<td>Permet de suivre les liens et de trouver la balise de titre</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Simulacre partiel</td>
|
||||
<td>Simuler des parties d'une classe pour tester moins qu'une classe ou dans des cas complexes.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Gestion des cookies Web</td>
|
||||
<td>Gestion correcte des cookies au téléchargement d'une page.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Suivi des redirections</td>
|
||||
<td>Le téléchargement d'une page suit automatiquement une redirection 300.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Analyse d'un formulaire</td>
|
||||
<td>La capacité de valider un formulaire simple et d'en lire les valeurs par défaut.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Interface en ligne de commande</td>
|
||||
<td>Affiche le résultat des tests sans navigateur web.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Mise à nu des attentes d'une classe</td>
|
||||
<td>Peut créer des tests précis avec des simulacres ainsi que des scénarios de test.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Sortie et analyse XML</td>
|
||||
<td>Permet de tester sur plusieurs hôtes et d'intégrer des extensions d'acceptation de test.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Scénario de test en ligne de commande</td>
|
||||
<td>Permet de tester des outils ou scripts en ligne de commande et de manier des fichiers.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Compatibilité avec PHP Documentor</td>
|
||||
<td>Génération automatique et complète de la documentation au niveau des classes.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Interface navigateur</td>
|
||||
<td>Mise à nu des niveaux bas de l'interface du navigateur web pour des scénarios de test plus précis.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Authentification HTTP</td>
|
||||
<td>Téléchargement des pages web protégées avec une authentification basique seulement.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Boutons de navigation d'un navigateur</td>
|
||||
<td>Arrière, avant et recommencer</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Support de SSL</td>
|
||||
<td>Peut se connecter à des pages de type https.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Support de proxy</td>
|
||||
<td>Peut se connecter via des proxys communs</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Support des cadres</td>
|
||||
<td>Gère les cadres dans les scénarios de test web.</td>
|
||||
<td style="color: green;">Fini</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Test de l'upload de fichier</td>
|
||||
<td>Peut simuler la balise input de type file</td>
|
||||
<td style="color: red;">1.0.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Amélioration sur la machinerie des rapports</td>
|
||||
<td>Retouche sur la transmission des messages pour une meilleur coopération avec les IDEs</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Amélioration de l'affichage des tests</td>
|
||||
<td>Une meilleure interface graphique web, avec un arbre des scénarios de test.</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Localisation</td>
|
||||
<td>Abstraction des messages et génration du code à partir de fichiers XML.</td>
|
||||
<td style="color: red;">1.1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Simulation d'interface</td>
|
||||
<td>Peut générer des objets fantaisie tant vers des interfaces que vers des classes.</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Test sur es exceptions</td>
|
||||
<td>Dans le même esprit que sur les tests des erreurs PHP.</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Rercherche d'éléments avec XPath</td>
|
||||
<td>Peut utiliser Tidy HTML pour un appariement plus rapide et plus souple.</td>
|
||||
<td style="color: red;">2.0</td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
<section name="ressources" title="Ressources sur le web pour les tests">
|
||||
<p>
|
||||
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'<a href="http://www.extremeprogramming.org/">Extreme Programming</a>. Il s'agit là d'une des <a href="http://www.agilealliance.com/articles/index">méthodes agiles</a> qui combinent plusieurs pratiques pour "lisser la courbe de coût" du développement logiciel. La plus extrème reste le <a href="http://www.testdriven.com/modules/news/">développement piloté par les tests</a>, où vous devez adhérer à la règle du <cite>pas de code avant d'avoir un test</cite>. 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 <a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a>. Je ne l'ai pas testé mais je peux voir où vous aurez besoin d'outils de test (cf. illustration 9).
|
||||
</p>
|
||||
<p>
|
||||
La plupart des testeurs unitaires sont dans une certaine mesure un clone de <a href="http://www.junit.org/">JUnit</a>, au moins dans l'interface. Il y a énormément d'information sur le site de JUnit, à commencer par la <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a> 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 <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">infecté par les tests</a> trouvée par Eric Gamma. Si vous êtes encore en train de tergiverser sur un testeur unitaire, sachez que les choix principaux sont <a href="http://phpunit.sourceforge.net/">PHPUnit</a> et <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>. De nombreuses fonctionnalité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 <a href="http://www.junit.org/">JUnit</a>.
|
||||
</p>
|
||||
<p>
|
||||
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 <a href="http://wact.sourceforge.net/">WACT</a> et <a href="http://sourceforge.net/projects/htmlsax">PEAR::XML_HTMLSax</a>.
|
||||
</p>
|
||||
<p>
|
||||
Au jour d'aujourd'hui il manque tristement beaucoup de matière sur les objets fantaisie : dommage, surtout que tester unitairement sans eux représente pas mal de travail en plus. L'<a href="http://www.sidewize.com/company/mockobjects.pdf">article original sur les objets fantaisie</a> est trè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 <a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a> ou <a href="http://www.mockobjects.com/MocksObjectsPaper.html">www.mockobjects.com</a>ou <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>. Injecter des objets fantaisie dans une classe est un des champs principaux du débat : cet <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">article chez IBM</a> en est un bon point de départ.
|
||||
</p>
|
||||
<p>
|
||||
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 <a href="http://httpunit.sourceforge.net/">HTTPUnit</a>, <a href="http://htmlunit.sourceforge.net/">HTMLUnit</a> ou <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> et d'espé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.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#resume">Résumé rapide</a> de l'outil SimpleTest pour PHP.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#fonctionnalites">La liste des fonctionnalites</a>, à la fois présentes et à venir.
|
||||
</link>
|
||||
<link>
|
||||
Il y a beaucoup de <a href="#ressources">ressources sur les tests unitaires</a> sur le web.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a local="unit_test_documentation">Documentation pour SimpleTest</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://www.lastcraft.com/first_test_tutorial.php">Comment écrire des scénarios de test en PHP</a> est un tutoriel plutôt avancé.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API de SimpleTest</a> par phpdoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
outils de développement logiciel,
|
||||
programmation php,
|
||||
outils pour l'extreme programming,
|
||||
liens pour des outils de test,
|
||||
ressources pour test en php,
|
||||
objets fantaise,
|
||||
junit,
|
||||
jwebunit,
|
||||
htmlunit,
|
||||
itc,
|
||||
liens pour tests en php,
|
||||
conseil et documentation pour test unitaire,
|
||||
extreme programming en php
|
||||
</keywords>
|
||||
</meta>
|
||||
<refsynopsisdiv>
|
||||
<authorgroup>
|
||||
<author>
|
||||
Marcus Baker
|
||||
<authorblurb>
|
||||
<para>Développeur principal</para><para>{@link mailto:marcus@lastcraft.com marcus@lastcraft.com}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
<author>
|
||||
Harry Fuecks
|
||||
<authorblurb>
|
||||
<para>Packageur</para><para>{@link mailto:harryf@users.sourceforge.net harryf@users.sourceforge.net}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
<author>
|
||||
Jason Sweat
|
||||
<authorblurb>
|
||||
<para>Documentation</para><para>{@link mailto:jsweat_php@yahoo.com jsweat_php@yahoo.com}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
<author>
|
||||
Perrick Penet
|
||||
<authorblurb>
|
||||
<para>Traduction</para><para>{@link mailto:perrick@onpk.net perrick@onpk.net}</para>
|
||||
</authorblurb>
|
||||
</author>
|
||||
</authorgroup>
|
||||
</refsynopsisdiv>
|
||||
</page>
|
||||
|
@ -0,0 +1,306 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur les objets fantaisie partiels" here="Les objets fantaisie partiels">
|
||||
<long_title>Documentation SimpleTest : les objets fantaisie partiels</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
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à.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="injection" title="Le problème de l'injection dans un objet fantaisie">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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><![CDATA[
|
||||
<strong><?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {
|
||||
$socket = &new Socket($ip, $port);
|
||||
$socket->read( ... );
|
||||
...
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Nous voudrions vraiment avoir une version fantaisie de l'objet socket, que pouvons nous faire ?
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Voici ce que ça devrait être...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
<strong>function &connect(&$socket, $username, $password) {
|
||||
$socket->read( ... );
|
||||
...
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Sous-entendu, votre code de test est typique d'un cas de test avec un objet fantaisie.
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new Telnet();
|
||||
$telnet->connect($socket, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
La solution suivante est de passer l'objet créé sous la forme d'un paramètre optionnel...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...<strong>
|
||||
function &connect($ip, $port, $username, $password, $socket = false) {
|
||||
if (!$socket) {
|
||||
$socket = &new Socket($ip, $port);
|
||||
}
|
||||
$socket->read( ... );</strong>
|
||||
...
|
||||
return $socket;
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret', &$socket);
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Une autre solution encore est de laisser un objet fabrique s'occuper de la création...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {<strong>
|
||||
function Telnet(&$network) {
|
||||
$this->_network = &$network;
|
||||
}</strong>
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {<strong>
|
||||
$socket = &$this->_network->createSocket($ip, $port);
|
||||
$socket->read( ... );</strong>
|
||||
...
|
||||
return $socket;
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$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');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Peut-on trouver un juste milieu ?
|
||||
</p>
|
||||
</section>
|
||||
<section name="creation" title="Méthode fabrique protégée">
|
||||
<p>
|
||||
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><![CDATA[
|
||||
<?php
|
||||
require_once('socket.php');
|
||||
|
||||
class Telnet {
|
||||
...
|
||||
function &connect($ip, $port, $username, $password) {<strong>
|
||||
$socket = &$this->_createSocket($ip, $port);</strong>
|
||||
$socket->read( ... );
|
||||
...
|
||||
}<strong>
|
||||
|
||||
function &_createSocket($ip, $port) {
|
||||
return new Socket($ip, $port);
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Il s'agit là de la seule modification dans le code de l'application.
|
||||
</p>
|
||||
<p>
|
||||
Pour le scénario de test, nous devons créer une sous-classe de manière à intercepter la création de la socket...
|
||||
<php><![CDATA[
|
||||
<strong>class TelnetTestVersion extends Telnet {
|
||||
var $_mock;
|
||||
|
||||
function TelnetTestVersion(&$mock) {
|
||||
$this->_mock = &$mock;
|
||||
$this->Telnet();
|
||||
}
|
||||
|
||||
function &_createSocket() {
|
||||
return $this->_mock;
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
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 <code>connect()</code>. Autrement il pourrait donner un valeur nulle à partir de <code>_createSocket()</code>.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($socket);
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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 ?
|
||||
</p>
|
||||
</section>
|
||||
<section name="partiel" title="Un objet fantaisie partiel">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Voici donc une version avec objet fantaisie partiel du test...
|
||||
<php><![CDATA[
|
||||
<strong>Mock::generatePartial(
|
||||
'Telnet',
|
||||
'TelnetTestVersion',
|
||||
array('_createSocket'));</strong>
|
||||
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {<strong>
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($this);
|
||||
$telnet->setReturnReference('_createSocket', $socket);
|
||||
$telnet->Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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 à <code>generatePartial()</code> nécessite trois paramètres : la classe à sous classer, le nom de la nouvelle classe et une liste des méthodes à simuler.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TelnetTest extends UnitTestCase {
|
||||
...
|
||||
function testConnection() {
|
||||
$socket = &new MockSocket($this);
|
||||
...
|
||||
$telnet = &new TelnetTestVersion($this);
|
||||
$telnet->setReturnReference('_createSocket', $socket);<strong>
|
||||
$telnet->expectOnce('_createSocket', array('127.0.0.1', 21));</strong>
|
||||
$telnet->Telnet();
|
||||
$telnet->connect('127.0.0.1', 21, 'Me', 'Secret');
|
||||
...<strong>
|
||||
$telnet->tally();</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="moins" title="Tester moins qu'une classe">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Pour choisir le mécanisme à utiliser, on en revient toujours aux standards de code de votre projet.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#injection">Le problème de l'injection d'un objet fantaisie</a>.
|
||||
</link>
|
||||
<link>
|
||||
Déplacer la création vers une méthode <a href="#creation">fabrique protégée</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#partiel">L'objet fantaisie partiel</a> génère une sous-classe.
|
||||
</link>
|
||||
<link>
|
||||
Les objets fantaisie partiels <a href="#moins">testent moins qu'une classe</a>.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API complète pour SimpleTest</a> à partir de PHPDoc.
|
||||
</link>
|
||||
<link>
|
||||
La méthode fabrique protégée est décrite dans <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">cet article d'IBM</a>. Il s'agit de l'unique papier formel que j'ai vu sur ce problème.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel en php,
|
||||
dévelopement d'un scénario de test en php,
|
||||
programmation php avec base de données,
|
||||
outils de développement logiciel,
|
||||
tutoriel avancé en php,
|
||||
scripts à la manière de phpunit,
|
||||
architecture,
|
||||
ressources php,
|
||||
objets fantaisie,
|
||||
junit,
|
||||
framework de test en php,
|
||||
test unitaire,
|
||||
test en php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,341 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur le rapporteur de test" here="Le rapporteur de test">
|
||||
<long_title>Documentation SimpleTest : le rapporteur de test</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="html" title="Les résultats rapportés au format HTML">
|
||||
<p>
|
||||
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...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<span class="fail">Fail</span>: createnewfile->True assertion failed.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
Alors qu'ici tous les tests passent...
|
||||
<div class="demo">
|
||||
<h1>File test</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div>
|
||||
</div>
|
||||
La bonne nouvelle, c'est qu'il existe pas mal de points dans la hiérarchie de l'affichage pour créer des sous-classes.
|
||||
</p>
|
||||
<p>
|
||||
Pour l'affichage basé sur des pages web, il y a la classe <code>HtmlReporter</code> avec la signature suivante...
|
||||
<php><![CDATA[
|
||||
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() { ... }
|
||||
}
|
||||
]]></php>
|
||||
Voici ce que certaines de ces méthodes veulent dire. Premièrement les méthodes d'affichage que vous voudrez probablement surcharger...
|
||||
<ul class="api">
|
||||
<li>
|
||||
<code>HtmlReporter(string $encoding)</code><br />
|
||||
est le constructeur. Notez que le test unitaire initie le lien à l'affichage plutôt que l'opposé. L'affichage est principalement un receveur passif des évènements de tests. Cela permet d'adapter facilement l'affichage pour d'autres systèmes en dehors des tests unitaires, tel le suivi de la charge de serveurs. L'"encoding" est le type d'encodage que vous souhaitez utiliser pour l'affichage du test. Pour pouvoir effectuer un rendu correct de la sortie de débogage quand on utilise le testeur web, il doit correspondre à l'encodage du site testé. Les chaînes de caractères disponibles sont indiquées dans la fonction PHP <a href="http://www.php.net/manual/fr/function.htmlentities.php">html_entities()</a>.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintHeader(string $test_name)</code><br />
|
||||
est appelé une fois, au début du test quand l'évènement de démarrage survient. Le premier évènement de démarrage est souvent délivré par le groupe de tests du niveau le plus haut et donc c'est de là que le <code>$test_name</code> arrive. Il peint les titres de la page, CSS, la balise "body", etc. Il ne renvoie rien du tout (<code>void</code>).
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintFooter(string $test_name)</code><br />
|
||||
est appelé à la toute fin du test pour fermer les balises ouvertes par l'entête de la page. Par défaut il affiche aussi la barre rouge ou verte et le décompte final des résultats. En fait la fin des tests arrive quand l'évènement de fin de test arrive avec le même nom que celui qui l'a initié au même niveau. Le nid des tests en quelque sorte. Fermer le dernier test finit l'affichage.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintMethodStart(string $test_name)</code><br />
|
||||
est appelé au début de chaque méthode de test. Normalement le nom vient de celui de la méthode. Les autres évènements de départ de test se comportent de la même manière sauf que celui du groupe de tests indique au rapporteur le nombre de scénarios de test qu'il contient. De la sorte le rapporteur peut afficher une barre de progrès au fur et à mesure que l'exécuteur passe en revue les scénarios de test.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintMethodEnd(string $test_name)</code><br />
|
||||
clôt le test lancé avec le même nom.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintFail(string $message)</code><br />
|
||||
peint un échec. Par défaut il ne fait qu'afficher le mot "fail", une trace d'arborescence affichant la position du test en cours et le message transmis par l'assertion.
|
||||
</li>
|
||||
<li>
|
||||
<code>void paintPass(string $message)</code><br />
|
||||
ne fait rien, par défaut.
|
||||
</li>
|
||||
<li>
|
||||
<code>string _getCss()</code><br />
|
||||
renvoie les styles CSS sous la forme d'une chaîne à l'attention de la méthode d'entêtes d'une page. Des styles additionnels peuvent être ajoutés ici si vous ne surchargez pas les entêtes de la page. Vous ne voudrez pas utiliser cette méthode dans des entêtes d'une page surchargée si vous souhaitez inclure le feuille de style CSS d'origine.
|
||||
</li>
|
||||
</ul>
|
||||
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...
|
||||
<ul class="api">
|
||||
<li>
|
||||
<code>array getTestList()</code><br />
|
||||
est la première méthode très commode pour les sous-classes. Elle liste l'arborescence courante des tests sous la forme d'une liste de noms de tests. Le premier test -- celui le plus proche du coeur -- sera le premier dans la liste et la méthode de test en cours sera la dernière.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getPassCount()</code><br />
|
||||
renvoie le nombre de succès atteint. Il est nécessaire pour l'affichage à la fin.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getFailCount()</code><br />
|
||||
renvoie de la même manière le nombre d'échecs.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getExceptionCount()</code><br />
|
||||
renvoie quant à lui le nombre d'erreurs.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getTestCaseCount()</code><br />
|
||||
est le nombre total de scénarios lors de l'exécution des tests. Il comprend aussi les tests groupés.
|
||||
</li>
|
||||
<li>
|
||||
<code>integer getTestCaseProgress()</code><br />
|
||||
est le nombre de scénarios réalisés jusqu'à présent.
|
||||
</li>
|
||||
</ul>
|
||||
Une modification simple : demander à l'HtmlReporter d'afficher aussi bien les succès que les échecs et les erreurs...
|
||||
<php><![CDATA[
|
||||
<strong>class ShowPasses extends HtmlReporter {
|
||||
|
||||
function paintPass($message) {
|
||||
parent::paintPass($message);
|
||||
print "&<span class=\"pass\">Pass</span>: ";
|
||||
$breadcrumb = $this->getTestList();
|
||||
array_shift($breadcrumb);
|
||||
print implode("->", $breadcrumb);
|
||||
print "->$message<br />\n";
|
||||
}
|
||||
|
||||
function _getCss() {
|
||||
return parent::_getCss() . ' .pass { color: green; }';
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
Une méthode qui a beaucoup fait jaser reste la méthode <code>makeDry()</code>. 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é.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
<section name="autre" title="Etendre le rapporteur">
|
||||
<p>
|
||||
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 <code>HtmlReporter</code> nous pouvons nous rendre une étape plus haut dans la hiérarchie de classe vers <code>SimpleReporter</code> dans le fichier source <em>simple_test.php</em>.
|
||||
</p>
|
||||
<p>
|
||||
Un affichage sans rien, un canevas vierge pour votre propre création, serait...
|
||||
<php><![CDATA[
|
||||
<strong>require_once('simpletest/simple_test.php');</strong>
|
||||
|
||||
class MyDisplay extends SimpleReporter {<strong>
|
||||
</strong>
|
||||
function paintHeader($test_name) {
|
||||
}
|
||||
|
||||
function paintFooter($test_name) {
|
||||
}
|
||||
|
||||
function paintStart($test_name, $size) {<strong>
|
||||
parent::paintStart($test_name, $size);</strong>
|
||||
}
|
||||
|
||||
function paintEnd($test_name, $size) {<strong>
|
||||
parent::paintEnd($test_name, $size);</strong>
|
||||
}
|
||||
|
||||
function paintPass($message) {<strong>
|
||||
parent::paintPass($message);</strong>
|
||||
}
|
||||
|
||||
function paintFail($message) {<strong>
|
||||
parent::paintFail($message);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Aucune sortie ne viendrait de cette classe jusqu'à un ajout de votre part.
|
||||
</p>
|
||||
</section>
|
||||
<section name="cli" title="Le rapporteur en ligne de commande">
|
||||
<p>
|
||||
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><![CDATA[
|
||||
<?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(<strong>new TextReporter()</strong>);
|
||||
?>
|
||||
]]></php>
|
||||
Et ensuite d'invoquer la suite de test à partir d'une ligne de commande...
|
||||
<pre class="shell">
|
||||
php file_test.php
|
||||
</pre>
|
||||
Bien sûr vous aurez besoin d'installer PHP en ligne de commande. Une suite de test qui passerait toutes ses assertions ressemble à...
|
||||
<pre class="shell">
|
||||
File test
|
||||
OK
|
||||
Test cases run: 1/1, Failures: 0, Exceptions: 0
|
||||
</pre>
|
||||
Un échec déclenche un affichage comme...
|
||||
<pre class="shell">
|
||||
File test
|
||||
1) True assertion failed.
|
||||
in createnewfile
|
||||
FAILURES!!!
|
||||
Test cases run: 1/1, Failures: 1, Exceptions: 0
|
||||
</pre>
|
||||
</p>
|
||||
<p>
|
||||
Une des principales raisons pour utiliser une suite de test en ligne de commande tient dans l'utilisation possible du testeur avec un processus automatisé. 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 <code>false</code> est renvoyée par la méthode <code>SimpleTest::run()</code>. Nous pouvons utiliser ce résultat pour terminer le script avec la bonne valeur renvoyée...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
<strong>exit ($test->run(new TextReporter()) ? 0 : 1);</strong>
|
||||
?>
|
||||
]]></php>
|
||||
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><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('File test');
|
||||
$test->addTestFile('tests/file_test.php');
|
||||
<strong>if (TextReporter::inCli()) {</strong>
|
||||
exit ($test->run(new TextReporter()) ? 0 : 1);
|
||||
<strong>}</strong>
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
Il s'agit là de la forme utilisée par SimpleTest lui-même.
|
||||
</p>
|
||||
</section>
|
||||
<section name="xml" title="Test distant">
|
||||
<p>
|
||||
SimpleTest est livré avec une classe <code>XmlReporter</code> utilisée pour de la communication interne. Lors de son exécution, le résultat ressemble à...
|
||||
<pre class="shell"><![CDATA[
|
||||
<?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>
|
||||
]]></pre>
|
||||
Vous pouvez utiliser ce format avec le parseur fourni dans SimpleTest lui-même. Il s'agit de <code>SimpleTestXmlParser</code> et se trouve <em>xml.php</em> à l'intérieur du paquet SimpleTest...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/xml.php');
|
||||
|
||||
...
|
||||
$parser = &new SimpleTestXmlParser(new HtmlReporter());
|
||||
$parser->parse($test_output);
|
||||
?>
|
||||
]]></php>
|
||||
<code>$test_output</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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><![CDATA[
|
||||
<?php
|
||||
<strong>require_once('../remote.php');</strong>
|
||||
require_once('../reporter.php');
|
||||
|
||||
$test_url = ...;
|
||||
$dry_url = ...;
|
||||
|
||||
$test = &new GroupTest('Remote tests');
|
||||
$test->addTestCase(<strong>new RemoteTestCase($test_url, $dry_url)</strong>);
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
<code>RemoteTestCase</code> 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. <code>RemoteTestCase</code> peut être ajouté à une suite de test comme n'importe quel autre groupe de tests.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Afficher <a href="#html">les résultats en HTML</a>
|
||||
</link>
|
||||
<link>
|
||||
Afficher et <a href="#autres">rapporter les résultats</a> dans d'autres formats
|
||||
</link>
|
||||
<link>
|
||||
Utilisé <a href="#cli">SimpleTest depuis la ligne de commande</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#xml">Utiliser XML</a> pour des tests distants
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
L'<a href="http://simpletest.sourceforge.net/">API pour développeur de SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
test unitaire en php,
|
||||
documentation,
|
||||
marcus baker,
|
||||
perrick penet
|
||||
test simple,
|
||||
simpletest,
|
||||
test distant,
|
||||
tests xml,
|
||||
test automatisé
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,251 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur les bouchons serveur" here="Les bouchons serveur">
|
||||
<long_title>Documentation SimpleTest : les bouchons serveur</long_title>
|
||||
<content>
|
||||
<section name="quoi" title="Que sont les bouchons serveur ?">
|
||||
<p>
|
||||
Au départ il s'agit d'un modèle de conception initié par Robert Binder (Testing object-oriented systems: models, patterns, and tools, Addison-Wesley) in 1999. Un bouchon serveur est une simulation d'un objet ou d'un composant. Il doit remplacer exactement un composant dans un système pour des raisons de testabilité ou de prototypage, tout en restant léger. Il permet aux tests de tourner plus rapidement ou alors, si la classe simulée n'a pas été écrite, juste de fonctionner.
|
||||
</p>
|
||||
</section>
|
||||
<section name="creation" title="Créer des bouchons serveur">
|
||||
<p>
|
||||
Nous avons juste besoin d'une classe préexistante, par exemple une connexion vers une base de données qui ressemblerait à...
|
||||
<php><![CDATA[
|
||||
<strong>class DatabaseConnection {
|
||||
function DatabaseConnection() {
|
||||
}
|
||||
|
||||
function query() {
|
||||
}
|
||||
|
||||
function selectQuery() {
|
||||
}
|
||||
}</strong>
|
||||
]]></php>
|
||||
La classe n'a même pas encore besoin d'avoir été implémentée. Pour créer la version bouchonnée de cette classe, nous incluons la librairie de bouchon serveur et exécutons le générateur...
|
||||
<php><![CDATA[
|
||||
<strong>require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
Stub::generate('DatabaseConnection');</strong>
|
||||
]]></php>
|
||||
Est généré un clone de la classe appelé <code>StubDatabaseConnection</code>. Nous pouvons alors créer des instances de cette nouvelle classe à l'intérieur de notre prototype de script...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/mock_objects.php');
|
||||
require_once('database_connection.php');
|
||||
Stub::generate('DatabaseConnection');
|
||||
<strong>
|
||||
$connection = new StubDatabaseConnection();
|
||||
</strong>
|
||||
]]></php>
|
||||
La version bouchonnée de la classe contient toutes les méthodes de l'original de telle sorte qu'une opération comme <code><![CDATA[$connection->query()]]></code> soit encore légale. La valeur retournée sera <code>null</code>, Mais nous pouvons y remédier avec...
|
||||
<php><![CDATA[
|
||||
<strong>$connection->setReturnValue('query', 37)</strong>
|
||||
]]></php>
|
||||
Désormais à chaque appel de <code><![CDATA[$connection->query()]]></code> nous obtenons un résultat de 37. Nous pouvons choisir n'importe quelle valeur pour le résultat, par exemple un hash de résultats provenant d'une base de données imaginaire ou alors une liste d'objets persistants. Peu importe les paramètres, nous obtenons systématiquement les même valeurs chaque fois qu'ils ont été initialisés de la sorte : ça ne ressemble peut-être pas à une réponse convaincante venant d'une connexion vers une base de données. Mais pour la demi-douzaine de lignes d'une méthode de test c'est souvent largement suffisant.
|
||||
</p>
|
||||
</section>
|
||||
<section name="modèles" title="Modèles de simulation">
|
||||
<p>
|
||||
Sauf que les choses ne sont que rarement aussi simples. Parmi les problèmes les plus courants on trouve les itérateurs : le renvoi d'une valeur constante peut causer une boucle infini dans l'objet testé. Pour ceux-ci nous avons besoin de mettre sur pied une suite de valeurs. Prenons par exemple un itérateur simple qui ressemble à...
|
||||
<php><![CDATA[
|
||||
class Iterator {
|
||||
function Iterator() {
|
||||
}
|
||||
|
||||
function next() {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
C'est probablement le plus simple des itérateurs possibles. Supposons que cet itérateur ne retourne que du texte, jusqu'à la fin - quand il retourne <code>false</code>. Une simulation est possible avec...
|
||||
<php><![CDATA[
|
||||
<strong>Stub::generate('Iterator');
|
||||
|
||||
$iterator = new StubIterator();
|
||||
$iterator->setReturnValue('next', false);
|
||||
$iterator->setReturnValueAt(0, 'next', 'First string');
|
||||
$iterator->setReturnValueAt(1, 'next', 'Second string');</strong>
|
||||
]]></php>
|
||||
A l'appel de <code>next()</code> sur l'itérateur bouchonné il va d'abord renvoyer "First string", puis au second appel c'est "Second string" qui sera renvoyé. Finalement pour tous les autres appels, il s'agira d'un <code>false</code>. Les valeurs renvoyées successivement ont priorité sur la valeur constante renvoyé. Cette dernière est un genre de valeur par défaut.
|
||||
</p>
|
||||
<p>
|
||||
Une autre situation délicate est une opération <code>get()</code> surchargée. Un exemple ? Un porteur d'information avec des pairs de clef / valeur. Prenons une classe de configuration...
|
||||
<php><![CDATA[
|
||||
class Configuration {
|
||||
function Configuration() {
|
||||
}
|
||||
|
||||
function getValue($key) {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Il s'agit d'une situation propice à l'utilisation d'objets bouchon, surtout que la configuration en production dépend invariablement de la machine : l'utiliser directement ne va pas nous aider à maintenir notre confiance dans nos tests. Sauf que le problème tient de ce que toutes les données proviennent de la méthode <code>getValue()</code> et que nous voulons des résultats différents suivant la clef. Par chance les bouchons ont un système de filtre...
|
||||
<php><![CDATA[
|
||||
<strong>Stub::generate('Configuration');
|
||||
|
||||
$config = &new StubConfiguration();
|
||||
$config->setReturnValue('getValue', 'primary', array('db_host'));
|
||||
$config->setReturnValue('getValue', 'admin', array('db_user'));
|
||||
$config->setReturnValue('getValue', 'secret', array('db_password'));</strong>
|
||||
]]></php>
|
||||
Ce paramètre supplémentaire est une liste d'arguments que l'on peut utiliser. Dans ce cas nous essayons d'utiliser un unique argument, à savoir la clef recherchée. Maintenant quand on invoque le bouchon serveur via la méthode <code>getValue()</code> avec...
|
||||
<php><![CDATA[
|
||||
$config->getValue('db_user');
|
||||
]]></php>
|
||||
...il renvoie "admin". Il le trouve en essayant d'assortir successivement les arguments d'entrée avec sa liste de ceux de sortie jusqu'au moment où une correspondance exacte est trouvée.
|
||||
</p>
|
||||
<p>
|
||||
Vous pouvez définir un argument par défaut avec...
|
||||
<php><![CDATA[<strong>
|
||||
$config->setReturnValue('getValue', false, array('*'));</strong>
|
||||
]]></php>
|
||||
Attention ce n'est pas équivalent à initialiser la valeur retournée sans aucun argument.
|
||||
<php><![CDATA[<strong>
|
||||
$config->setReturnValue('getValue', false);</strong>
|
||||
]]></php>
|
||||
Dans le premier cas il acceptera n'importe quel argument, mais exactement un -- pas plus -- est nécessaire. Dans le second cas n'importe quel nombre d'arguments fera l'affaire : il agit comme un <cite>catchall</cite> après tous les correspondances. Prenez garde à l'ordre : si nous ajoutons un autre paramètre après le joker ('*') il sera ignoré puisque le joker aura été trouvé auparavant. Avec des listes de paramètres complexes l'ordre peut devenir crucial, au risque de perdre des correspondances souhaitées, masquées par un joker antérieur. Pensez à mettre d'abord les cas les plus spécifiques si vous n'êtes pas sûr.
|
||||
</p>
|
||||
<p>
|
||||
Il y a des fois où l'on souhaite qu'un objet spécifique soit servi par le bouchon plutôt qu'une simple copie. La sémantique de la copie en PHP nous force à utiliser une autre méthode pour cela. Vous êtes peut-être en train de simuler un conteneur par exemple...
|
||||
<php><![CDATA[
|
||||
class Thing {
|
||||
}
|
||||
|
||||
class Vector {
|
||||
function Vector() {
|
||||
}
|
||||
|
||||
function get($index) {
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Dans ce cas vous pouvez mettre une référence dans la liste renvoyée par le bouchon...
|
||||
<php><![CDATA[
|
||||
Stub::generate('Vector');
|
||||
|
||||
$thing = new Thing();<strong>
|
||||
$vector = &new StubVector();
|
||||
$vector->setReturnReference('get', $thing, array(12));</strong>
|
||||
]]></php>
|
||||
Avec ce petit arrangement vous vous assurez qu'à chaque fois que <code><![CDATA[$vector->get(12)]]></code> est appelé il renverra le même <code>$thing</code>.
|
||||
</p>
|
||||
<p>
|
||||
Ces trois facteurs, ordre, paramètres et copie (ou référence), peuvent être combinés orthogonalement. Par exemple...
|
||||
<php><![CDATA[
|
||||
$complex = &new StubComplexThing();
|
||||
$stuff = new Stuff();<strong>
|
||||
$complex->setReturnReferenceAt(3, 'get', $stuff, array('*', 1));</strong>
|
||||
]]></php>
|
||||
Le <code>$stuff</code> ne sera renvoyé qu'au troisième appel et seulement si deux paramètres étaient indiqués, avec la contrainte que le second de ceux-ci soit l'entier 1. N'est-ce pas suffisant pour des situations de prototypage simple ?
|
||||
</p>
|
||||
<p>
|
||||
Un dernier cas critique reste celle d'un objet en créant un autre, connu sous le nom du modèle factory - fabrique. Supposons qu'après une requête réussie à notre base de données imaginaire, un ensemble de résultats est retourné sous la forme d'un itérateur, chaque appel à <code>next()</code> donnant une ligne et à la fin un <code>false</code>.
|
||||
Au premier abord, ça donne l'impression d'être cauchemardesque à simuler. Alors qu'en fait tout peut être bouchonné en utilisant les mécanismes ci-dessus.
|
||||
</p>
|
||||
<p>
|
||||
Voici comment...
|
||||
<php><![CDATA[
|
||||
Stub::generate('DatabaseConnection');
|
||||
Stub::generate('ResultIterator');
|
||||
|
||||
class DatabaseTest extends UnitTestCase {
|
||||
|
||||
function testUserFinder() {<strong>
|
||||
$result = &new StubResultIterator();
|
||||
$result->setReturnValue('next', false);
|
||||
$result->setReturnValueAt(0, 'next', array(1, 'tom'));
|
||||
$result->setReturnValueAt(1, 'next', array(3, 'dick'));
|
||||
$result->setReturnValueAt(2, 'next', array(6, 'harry'));
|
||||
|
||||
$connection = &new StubDatabaseConnection();
|
||||
$connection->setReturnValue('query', false);
|
||||
$connection->setReturnReference(
|
||||
'query',
|
||||
$result,
|
||||
array('select id, name from users'));</strong>
|
||||
|
||||
$finder = &new UserFinder($connection);
|
||||
$this->assertIdentical(
|
||||
$finder->findNames(),
|
||||
array('tom', 'dick', 'harry'));
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Désormais ce n'est que si notre <code>$connection</code> est appelé avec la bonne <code>query()</code> que le <code>$result</code> sera renvoyé après le troisième appel à <code>next()</code>. Cela devrait être suffisant pour que notre classe <code>UserFinder</code>, la classe effectivement testée à ce niveau, puisse s'exécuter comme il faut. Un test très précis et pas une seule base de données à l'horizon.
|
||||
</p>
|
||||
</section>
|
||||
<section name="options" title="Options de création pour les bouchons">
|
||||
<p>
|
||||
Il y a d'autres options additionnelles à la création d'un bouchon. Au moment de la génération nous pouvons changer le nom de la classe...
|
||||
<php><![CDATA[
|
||||
<strong>Stub::generate('Iterator', 'MyStubIterator');
|
||||
$iterator = &new MyStubIterator();
|
||||
</strong>
|
||||
]]></php>
|
||||
Pris tout seul ce n'est pas très utile étant donné qu'il n'y aurait pas de différence entre cette classe et celle par défaut -- à part le nom bien entendu. Par contre nous pouvons aussi lui ajouter d'autres méthodes qui ne se trouveraient pas dans l'interface originale...
|
||||
<php><![CDATA[
|
||||
class Iterator {
|
||||
}
|
||||
<strong>Stub::generate('Iterator', 'PrototypeIterator', array('next', 'isError'));
|
||||
$iterator = &new PrototypeIterator();
|
||||
$iterator->setReturnValue('next', 0);
|
||||
</strong>
|
||||
]]></php>
|
||||
Les méthodes <code>next()</code> et <code>isError()</code> peuvent maintenant renvoyer des ensembles de valeurs exactement comme si elles existaient dans la classe originale.
|
||||
</p>
|
||||
<p>
|
||||
Un moyen encore plus ésotérique de modifier les bouchons est de changer le joker utilisé par défaut pour la correspondance des paramètres.
|
||||
<php><![CDATA[
|
||||
<strong>Stub::generate('Connection');
|
||||
$iterator = &new StubConnection('wild');
|
||||
$iterator->setReturnValue('query', array('id' => 33), array('wild'));
|
||||
</strong>
|
||||
]]></php>
|
||||
L'unique raison valable pour effectuer cette opération, c'est quand vous souhaitez tester la chaîne "*" sans pour autant l'interpréter comme un "n'importe lequel".
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#quoi">Que sont les bouchons ?</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#creation">Créer des bouchons serveur</a> avec SimpleTest.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#modeles">Modèles de simulation</a> pour simuler des interactions d'objet plus complexes.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#options">Options à la génération</a> pour différents contextes.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API complète pour SimpleTest</a> générée par PHPDoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutoriel php,
|
||||
outil gratuit de test pour php,
|
||||
architecture,
|
||||
ressuorces php,
|
||||
objets fantaisie,
|
||||
prototypage avec langage de scripts,
|
||||
bouchons serveur,
|
||||
test unitaire,
|
||||
prototypage en php,
|
||||
méthodes de test,
|
||||
méthodologie de test
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,339 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Prise en main rapide de SimpleTest" here="Prise en main rapide de SimpleTest">
|
||||
<long_title>
|
||||
Prise en main rapide de SimpleTest pour PHP - Tests unitaire et objets fantaisie pour PHP
|
||||
</long_title>
|
||||
<content>
|
||||
<introduction>
|
||||
<p>
|
||||
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 <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>. Pour une documentation plus complète, particulièrement si vous découvrez les tests unitaires, consultez la <a href="http://www.lastcraft.com/unit_test_documentation.php">documentation en cours</a>, et pour des exemples de scénarios de test, consultez le <a href="http://www.lastcraft.com/first_test_tutorial.php">tutorial sur les tests unitaires</a>.
|
||||
</p>
|
||||
</introduction>
|
||||
<section name="unit" title="Utiliser le testeur rapidement">
|
||||
<p>
|
||||
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 <a href="http://www.junit.org/">JUnit</a> et des <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>, mais elle inclut aussi les <a href="http://www.mockobjects.com/">objets fantaisie ou "mock objects"</a>. Sans compter quelques fonctionnalités de <a href="http://sourceforge.net/projects/jwebunit/">JWebUnit</a> : parmi celles-ci la navigation sur des pages web, les tests sur les cookies et l'envoi de formulaire.
|
||||
</p>
|
||||
<p>
|
||||
La démonstration la plus rapide : l'exemple
|
||||
</p>
|
||||
<p>
|
||||
Supposons que nous sommes en train de tester une simple classe de log dans un fichier : elle s'appelle <code>Log</code> dans <em>classes/Log.php</em>. Commençons par créer un script de test, appelé <em>tests/log_test.php</em>. Son contenu est le suivant...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
?></strong>
|
||||
]]></php>
|
||||
Ici le répertoire <em>simpletest</em> est soit dans le dossier courant, soit dans les dossiers pour fichiers inclus. Vous auriez à éditer ces arborescences suivant l'endroit où vous avez installé SimpleTest. Ensuite créons un scénario de test...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
<strong>
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
A présent il y a 5 lignes de code d'échafaudage et toujours pas de test. Cependant à partir de cet instant le retour sur investissement arrive très rapidement. Supposons que la classe <code>Log</code> prenne le nom du fichier à écrire dans le constructeur et que nous ayons un répertoire temporaire dans lequel placer ce fichier...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
<strong>
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));
|
||||
}</strong>
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
Au lancement du scénario de test, toutes les méthodes qui commencent avec la chaîne <code>test</code> sont identifiées puis exécutées. D'ordinaire nous avons bien plusieurs méthodes de tests. Les assertions dans les méthodes de test envoient des messages vers le framework de test qui affiche immédiatement le résultat. Cette réponse immédiate est importante, non seulement lors d'un crash causé par le code, mais aussi de manière à rapprocher l'affichage de l'erreur au plus près du scénario de test concerné.
|
||||
</p>
|
||||
<p>
|
||||
Pour voir ces résultats lançons effectivement les tests. S'il s'agit de l'unique scénario de test à lancer, on peut y arriver avec...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
require_once('../classes/log.php');
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));
|
||||
}
|
||||
}
|
||||
<strong>
|
||||
$test = &new TestOfLogging();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
En cas échec, l'affichage ressemble à...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<span class="fail">Fail</span>: testcreatingnewfile->True assertion failed.<br />
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete.
|
||||
<strong>1</strong> passes and <strong>1</strong> fails.</div>
|
||||
</div>
|
||||
...et si ça passe, on obtient...
|
||||
<div class="demo">
|
||||
<h1>testoflogging</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete.
|
||||
<strong>2</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
Et si vous obtenez ça...
|
||||
<div class="demo">
|
||||
<b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b>
|
||||
</div>
|
||||
c'est qu'il vous manque le fichier <em>classes/Log.php</em> qui pourrait ressembler à :
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
class Log {
|
||||
|
||||
function Log($file_path) {
|
||||
}
|
||||
}
|
||||
?>;
|
||||
]]></php>
|
||||
</p>
|
||||
</section>
|
||||
<section name="group" title="Construire des groupes de tests">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Notre première étape est de supprimer les includes et de défaire notre hack précédent...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('../classes/log.php');</strong>
|
||||
|
||||
class TestOfLogging extends UnitTestCase {
|
||||
|
||||
function testCreatingNewFile() {
|
||||
@unlink('/temp/test.log');
|
||||
$log = new Log('/temp/test.log');
|
||||
$this->assertFalse(file_exists('/temp/test.log'));
|
||||
$log->message('Should write this to a file');
|
||||
$this->assertTrue(file_exists('/temp/test.log'));<strong>
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
Ensuite nous créons un nouveau fichier appelé <em>tests/all_tests.php</em>. On y insère le code suivant...
|
||||
<php><![CDATA[
|
||||
<strong><?php
|
||||
require_once('simpletest/unit_tester.php');
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('All tests');
|
||||
$test->addTestFile('log_test.php');
|
||||
$test->run(new HtmlReporter());
|
||||
?></strong>
|
||||
]]></php>
|
||||
Cette méthode <code>GroupTest::addTestFile()</code> va inclure le fichier de scénarios de test et lire parmi toutes les nouvelles classes créées celles qui sont issues de <code>TestCase</code>. Dans un premier temps, seuls les noms sont stockés, de la sorte le lanceur de test peut instancier la classe au fur et à mesure qu'il exécute votre suite de tests.
|
||||
</p>
|
||||
<p>
|
||||
Pour que ça puisse marcher proprement le fichier de suite de tests ne devrait pas inclure aveuglement d'autres extensions de scénarios de test qui n'exécuteraient pas effectivement de test. Le résultat pourrait être que des tests supplémentaires soient alors comptabilisés pendant l'exécution des tests. Ce n'est pas un problème grave mais pour éviter ce désagrément, il suffit d'ajouter la commande <code>SimpleTestOptions::ignore()</code> quelque part dans le fichier de scénario de test. Par ailleurs le scénario de test ne devrait pas avoir été inclus ailleurs ou alors aucun scénario ne sera ajouté aux groupes de test. Il s'agirait là d'une erreur autrement sérieuse : si toutes les classes de scénario de test sont chargées par PHP, alors la méthode <code>GroupTest::addTestFile()</code> ne pourra pas les détecter.
|
||||
</p>
|
||||
<p>
|
||||
Pour afficher les résultats, il est seulement nécessaire d'invoquer <em>tests/all_tests.php</em> à partir du serveur web.
|
||||
</p>
|
||||
</section>
|
||||
<section name="mock" title="Utiliser les objets fantaisie">
|
||||
<p>
|
||||
Avançons un peu plus dans le futur.
|
||||
</p>
|
||||
<p>
|
||||
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 <code>SessionPool</code>. Nous voulons tester une méthode qui ressemblera probablement à quelque chose comme...
|
||||
<php><![CDATA[<strong>
|
||||
class SessionPool {
|
||||
...
|
||||
function logIn($username) {
|
||||
...
|
||||
$this->_log->message('User $username logged in.');
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
</strong>
|
||||
]]></php>
|
||||
Avec le concept de "réutilisation de code" comme fil conducteur, nous utilisons notre class <code>Log</code>. Un scénario de test classique ressemblera peut-être à...
|
||||
<php><![CDATA[<strong>
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/session_pool.php');
|
||||
|
||||
class TestOfSessionLogging extends UnitTestCase {
|
||||
|
||||
function setUp() {
|
||||
@unlink('/temp/test.log');
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
@unlink('/temp/test.log');
|
||||
}
|
||||
|
||||
function testLogInIsLogged() {
|
||||
$log = new Log('/temp/test.log');
|
||||
$session_pool = &new SessionPool($log);
|
||||
$session_pool->logIn('fred');
|
||||
$messages = file('/temp/test.log');
|
||||
$this->assertEqual($messages[0], "User fred logged in.\n");
|
||||
}
|
||||
}
|
||||
?></strong>
|
||||
]]></php>
|
||||
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 <code>Log</code> et ce test. Que se passerait-il si nous n'utilisions plus de fichiers, mais la bibliothèque <em>syslog</em> à la place ? Avez-vous remarqué le retour chariot supplémentaire à la fin du message ? A-t-il été ajouté par le loggueur ? Et si il ajoutait aussi un timestamp ou d'autres données ?
|
||||
</p>
|
||||
<p>
|
||||
L'unique partie à tester réellement est l'envoi d'un message précis au loggueur. Nous réduisons le couplage en créant une fausse classe de logging : elle ne fait qu'enregistrer le message pour le test, mais ne produit aucun résultat. Sauf qu'elle doit ressembler exactement à l'original.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
<p>
|
||||
</p>
|
||||
Trop beau pour être vrai ? Par chance on peut créer un tel objet très facilement...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/log.php');
|
||||
require_once('../classes/session_pool.php');<strong>
|
||||
Mock::generate('Log');</strong>
|
||||
|
||||
class TestOfSessionLogging extends UnitTestCase {
|
||||
|
||||
function testLogInIsLogged() {<strong>
|
||||
$log = &new MockLog($this);
|
||||
$log->expectOnce('message', array('User fred logged in.'));</strong>
|
||||
$session_pool = &new SessionPool($log);
|
||||
$session_pool->logIn('fred');<strong>
|
||||
$log->tally();</strong>
|
||||
}
|
||||
}
|
||||
?>
|
||||
]]></php>
|
||||
L'appel <code>tally()</code> 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 à <code>message()</code> est invoqué sur l'objet <code>MockLog</code>. L'appel <code>mock</code> va déclencher une comparaison des paramètres et ensuite envoyer le message "pass" ou "fail" au test pour l'affichage. Des jokers peuvent être inclus ici aussi afin d'empêcher que les tests ne deviennent trop spécifiques.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Pour que ce test fonctionne la librairie avec les objets fantaisie doit être incluse dans la suite de tests, par exemple dans <em>all_tests.php</em>.
|
||||
</p>
|
||||
</section>
|
||||
<section name="web" title="Tester une page web">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Effectuer un test web via SimpleTest reste assez primitif : il n'y a pas de javascript par exemple. Pour vous donner une idé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><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('simpletest/web_tester.php');</strong>
|
||||
require_once('simpletest/reporter.php');
|
||||
<strong>
|
||||
class TestOfAbout extends WebTestCase {
|
||||
|
||||
function setUp() {
|
||||
$this->get('http://test-server/index.php');
|
||||
$this->clickLink('About');
|
||||
}
|
||||
|
||||
function testSearchEngineOptimisations() {
|
||||
$this->assertTitle('A long title about us for search engines');
|
||||
$this->assertWantedPattern('/a popular keyphrase/i');
|
||||
}
|
||||
}</strong>
|
||||
$test = &new TestOfAbout();
|
||||
$test->run(new HtmlReporter());
|
||||
?>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
<a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"/></a>
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#unit">Utiliser le testeur rapidement</a>
|
||||
avec un exemple.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#group">Groupes de tests</a>
|
||||
pour tester en un seul clic.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#mock">Utiliser les objets fantaisie</a>
|
||||
pour faciliter les tests et gagner en contrôle.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#web">Tester des pages web</a>
|
||||
au niveau de l'HTML.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
<a href="https://sourceforge.net/project/showfiles.php?group_id=76550&release_id=153280">Télécharger PHP Simple Test</a>
|
||||
depuis <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
L'<a href="http://simpletest.sourceforge.net/">API de SimpleTest pour développeur</a>
|
||||
donne tous les détails sur les classes et assertions existantes.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressources php,
|
||||
objets fantaise,
|
||||
junit,
|
||||
php testing,
|
||||
php unit,
|
||||
méthodologie,
|
||||
développement piloté par les tests,
|
||||
sourceforge,
|
||||
open source,
|
||||
unit test,
|
||||
web tester,
|
||||
web testing,
|
||||
outils tests html,
|
||||
tester des web pages,
|
||||
php objets fantaise,
|
||||
naviguer automatiquement sur des sites web,
|
||||
test automatisé,
|
||||
scripting web,
|
||||
wget,
|
||||
test curl,
|
||||
jmock pour php,
|
||||
jwebunit,
|
||||
phpunit,
|
||||
php unit testing,
|
||||
php web testing,
|
||||
jason sweat,
|
||||
marcus baker,
|
||||
perrick penet,
|
||||
topstyle plug in,
|
||||
phpedit plug in
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,195 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Sous classer un scénario de test unitaire" here="Sous classer un scénario de test unitaire">
|
||||
<long_title>Tutorial de test unitaire en PHP - Sous classer un scénario de test</long_title>
|
||||
<content>
|
||||
<p>
|
||||
<a class="target" name="temps"><h2>Une assertion insensible au chronomètre</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Nous avions laissé notre test d'horloge avec un trou. Si la fonction <code>time()</code> de PHP avançait pendant cette comparaison...
|
||||
<php><![CDATA[
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertEqual($clock->now(), time(), 'Now is the right time');
|
||||
}
|
||||
]]></php>
|
||||
...notre test aurait un écart d'une seconde et entraînerait un faux échec. Un comportement erratique de notre suite de test n'est vraiment pas ce que nous souhaitons : nous pourrions la lancer une centaine de fois par jour.
|
||||
</p>
|
||||
<p>
|
||||
Nous pourrions ré-écrire notre test...
|
||||
<php><![CDATA[
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();<strong>
|
||||
$time1 = $clock->now();
|
||||
$time2 = time();
|
||||
$this->assertTrue(($time1 == $time2) || ($time1 + 1 == $time2), 'Now is the right time');</strong>
|
||||
}
|
||||
]]></php>
|
||||
Sauf que la conception n'est pas plus claire et que nous devrons le répéter pour chaque test de chronométrage. Les répétitions sont un ennemi public n°1 et donc un très bon stimulant pour le remaniement de notre code de test.
|
||||
<php><![CDATA[
|
||||
class TestOfClock extends UnitTestCase {
|
||||
function TestOfClock() {
|
||||
$this->UnitTestCase('Clock class test');
|
||||
}<strong>
|
||||
function assertSameTime($time1, $time2, $message) {
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}</strong>
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();<strong>
|
||||
$this->assertSameTime($clock->now(), time(), 'Now is the right time');</strong>
|
||||
}
|
||||
function testClockAdvance() {
|
||||
$clock = new Clock();
|
||||
$clock->advance(10);<strong>
|
||||
$this->assertSameTime($clock->now(), time() + 10, 'Advancement');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Bien entendu à chaque modification je relance les tests pour bien vérifier que nous sommes dans les clous. Remaniement au vert. C'est beaucoup plus sûr.
|
||||
</p>
|
||||
<p>
|
||||
<a class="target" name="sous-classe"><h2>Réutiliser notre assertion</h2></a>
|
||||
</p>
|
||||
<p>
|
||||
Peut-être voulons nous ajouter d'autres tests sensibles au temps. Peut-être lisons nous des timestamps - en provenance d'une entrée dans une base de données ou d'ailleurs - qui tiendraient compte d'une simple seconde pour basculer. Pour que ces nouvelles classes de test profitent de notre nouvelle assertion nous avons besoin de la placer dans une "super classe".
|
||||
</p>
|
||||
<p>
|
||||
Voici notre fichier <em>clock_test.php</em> au complet après la promotion de notre méthode <code>assertSameTime()</code> dans sa propre "super classe"...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('../classes/clock.php');
|
||||
<strong>
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase($test_name) {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, $message) {
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
|
||||
class TestOfClock extends TimeTestCase {
|
||||
function TestOfClock() {
|
||||
$this->TimeTestCase('Clock class test');
|
||||
}</strong>
|
||||
function testClockTellsTime() {
|
||||
$clock = new Clock();
|
||||
$this->assertSameTime($clock->now(), time(), 'Now is the right time');
|
||||
}
|
||||
function testClockAdvance() {
|
||||
$clock = new Clock();
|
||||
$clock->advance(10);
|
||||
$this->assertSameTime($clock->now(), time() + 10, 'Advancement');
|
||||
}<strong>
|
||||
}</strong>
|
||||
?>
|
||||
]]></php>
|
||||
Désormais nous bénéficions de notre nouvelle assertion à chaque fois que nous héritons de notre propre classe <code>TimeTestCase</code> plutôt que de la classe par défaut <code>UnitTestCase</code>. Nous retrouvons la conception de l'outil JUnit et SimpleTest est un portage en PHP de cette interface. Il s'agit d'un framework de test à partir duquel votre propre système de test peut s'agrandir.
|
||||
</p>
|
||||
<p>
|
||||
Si nous lançons les tests maintenant une légère broutille survient...
|
||||
<div class="demo">
|
||||
<b>Warning</b>: Missing argument 1 for timetestcase()
|
||||
in <b>/home/marcus/projects/lastcraft/tutorial_tests/tests/clock_test.php</b> on line <b>5</b><br />
|
||||
<h1>All tests</h1>
|
||||
<div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">3/3 test cases complete.
|
||||
<strong>6</strong> passes and <strong>0</strong> fails.</div>
|
||||
</div>
|
||||
La raison est assez délicate.
|
||||
</p>
|
||||
<p>
|
||||
Notre sous-classe exige un paramètre dans le constructeur qui n'a pas été fourni et pourtant il semblerait que nous l'ayons bel et bien fourni. Quand nous avons hérité de notre nouvelle casse nous lui avons passé notre propre constructeur. C'est juste là...
|
||||
<php><![CDATA[
|
||||
function TestOfClock() {
|
||||
$this->TimeTestCase('Clock class test');
|
||||
}
|
||||
]]></php>
|
||||
En fait nous avons raison, là n'est pas le problème.
|
||||
</p>
|
||||
<p>
|
||||
Vous vous souvenez de quand nous avons construit le test de groupe <em>all_tests.php</em> en utilisant la méthode <code>addTestFile()</code>. Cette méthode recherche les classes de scénario de test, les instancie si elles sont nouvelles puis exécute tous nos tests. Ce qui s'est passé ? Elle a aussi trouvé notre extension de scénario de test. C'est sans conséquence puisque qu'il n'y a pas de méthode de test à l'intérieur - comprendre pas de méthode commençant par "test". Aucun test supplémentaire n'est exécuté.
|
||||
</p>
|
||||
<p>
|
||||
Le problème vient du fait qu'il instancie la classe et le fait sans le paramètre <code>$test_name</code> qui déclenche l'avertissement. Ce paramètre n'est généralement nécessaire ni pour un scénario de test, ni pour son assertion. Pour que notre scénario de test étendu corresponde à l'interface de <code>UnitTestCase</code>, nous avons besoin de le rendre optionnel...
|
||||
<php><![CDATA[
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase(<strong>$test_name = false</strong>) {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, <strong>$message = false</strong>) {<strong>
|
||||
if (! $message) {
|
||||
$message = "Time [$time1] should match time [$time2]";
|
||||
}</strong>
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Bien sûr, que cette classe soit instanciée sans raison par la suite de test devrait continuer à vous ennuyer. Voici une modification pour l'empêcher de s'exécuter...
|
||||
<php><![CDATA[
|
||||
<strong>SimpleTestOptions::ignore('TimeTestCase');</strong>
|
||||
class TimeTestCase extends UnitTestCase {
|
||||
function TimeTestCase($test_name = false) {
|
||||
$this->UnitTestCase($test_name);
|
||||
}
|
||||
function assertSameTime($time1, $time2, $message = '') {
|
||||
if (!$message) {
|
||||
$message = "Time [$time1] should match time [$time2]";
|
||||
}
|
||||
$this->assertTrue(
|
||||
($time1 == $time2) || ($time1 + 1 == $time2),
|
||||
$message);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Cette ligne ne fait que demander à SimpleTest d'ignorer cette classe lors de la construction des suites de test. Elle peut être ajoutée n'importe où dans le fichier de scénario de test.
|
||||
</p>
|
||||
<p>
|
||||
Les six succès ont l'air bien mais ne disent pas à un observateur peu attentif ce qui a été testé. Pour cela il faut regarder dans le code. Si cela vous paraît trop de boulot et que vous préfèreriez lire ces informations directement alors vous devriez aller lire comment <a local="display_subclass_tutorial">afficher les succès</a>.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Une <a href="#temps">assertion insensible au chronomètre</a> qui permet de gagner une seconde.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#sous-classe">Sous classer un scénario de test</a> afin de réutiliser la méthode de test.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
Section précédente : <a local="gain_control_tutorial">contrôler les variables de test</a>.
|
||||
</link>
|
||||
<link>
|
||||
Section suivante : <a local="display_subclass_tutorial">changer l'affichage des tests</a>.
|
||||
</link>
|
||||
<link>
|
||||
Vous aurez besoin du <a href="simple_test.php">testeur unitaire SimpleTest</a> pour les exemples.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php,
|
||||
outils de développement logiciel,
|
||||
tutorial php,
|
||||
scripts php gratuits,
|
||||
organisation de tests unitaires,
|
||||
création de sous-classe,
|
||||
conseil de test,
|
||||
astuce de développement,
|
||||
exemple de code php,
|
||||
objets fantaisie,
|
||||
junit,
|
||||
test php,
|
||||
outil de test unitaire,
|
||||
suite de test php
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,43 @@
|
||||
<?xml version="1.0"?>
|
||||
<page title="Mailing-list de support" here="Mailing-list de support">
|
||||
<long_title>Mailing-list de support</long_title>
|
||||
<content>
|
||||
<p>
|
||||
La mailing-list <strong>simpletest-support</strong> est probablement l'endroit
|
||||
le plus actif autour de SimpleTest : aide, conseil, bugs et détours, c'est là
|
||||
que tout se passe la plupart du temps. Attention tout de même : les échanges
|
||||
ont lieu en anglais.
|
||||
</p>
|
||||
<p>
|
||||
C'est vraiment
|
||||
<a href="https://lists.sourceforge.net/lists/listinfo/simpletest-support">
|
||||
simple de s'y abonner</a> et en plus, on peut aussi
|
||||
<a href="http://sourceforge.net/mailarchive/forum.php?forum=simpletest-support">
|
||||
l'utiliser pour ses recherches</a>.
|
||||
</p>
|
||||
<p>
|
||||
Au dernier pointage, il y avait 114 abonnés et 1908 messages envoyés.
|
||||
Cela fait de 1 à 4 messages par jour en moyenne.
|
||||
</p>
|
||||
</content>
|
||||
<internal>
|
||||
</internal>
|
||||
|
||||
<external>
|
||||
</external>
|
||||
|
||||
<meta>
|
||||
<keywords>
|
||||
SimpleTest,
|
||||
download,
|
||||
source code,
|
||||
stable release,
|
||||
eclipse release,
|
||||
eclipse plugin,
|
||||
debian package,
|
||||
drupal module,
|
||||
pear channel,
|
||||
pearified package
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
@ -0,0 +1,225 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur les tests unitaires en PHP" here="Documentation : les tests unitaires en PHP">
|
||||
<long_title>Documentation SimpleTest pour les tests de régression en PHP</long_title>
|
||||
<content>
|
||||
<section name="unitaire" title="Scénarios de tests unitaires">
|
||||
<p>
|
||||
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 à...
|
||||
<php><![CDATA[
|
||||
<strong>class FileTestCase extends UnitTestCase {
|
||||
}</strong>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
require_once('../classes/writer.php');
|
||||
|
||||
class FileTestCase extends UnitTestCase {
|
||||
function FileTestCase() {
|
||||
$this->UnitTestCase('File test');
|
||||
}<strong>
|
||||
|
||||
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');
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Le constructeur est optionnel et souvent omis. Sans nom, le nom de la classe est utilisé comme nom pour le scénario de test.
|
||||
</p>
|
||||
<p>
|
||||
Notre unique méthode de test pour le moment est <code>testCreation()</code> où nous vérifions qu'un fichier a bien été créé par notre objet <code>Writer</code>. Nous pourrions avoir mis le code <code>unlink()</code> dans cette méthode, mais en la plaçant dans <code>setUp()</code> et <code>tearDown()</code> nous pouvons l'utiliser pour nos autres méthodes de test que nous ajouterons.
|
||||
</p>
|
||||
<p>
|
||||
La méthode <code>setUp()</code> est lancé juste avant chaque méthode de test. <code>tearDown()</code> est lancé après chaque méthode de test.
|
||||
</p>
|
||||
<p>
|
||||
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 <code>setUp()</code>, mais fournit aux codeurs de bibliothèque d'autres crochets.
|
||||
</p>
|
||||
<p>
|
||||
Pour rapporter les résultats de test, le passage par une classe d'affichage - notifiée par les différentes méthodes de type <code>assert...()</code> - est utilisée. En voici la liste complète pour la classe <code>UnitTestCase</code>, celle par défaut dans SimpleTest...
|
||||
<table><tbody>
|
||||
<tr><td><code>assertTrue($x)</code></td><td>Echoue si $x est faux</td></tr>
|
||||
<tr><td><code>assertFalse($x)</code></td><td>Echoue si $x est vrai</td></tr>
|
||||
<tr><td><code>assertNull($x)</code></td><td>Echoue si $x est initialisé</td></tr>
|
||||
<tr><td><code>assertNotNull($x)</code></td><td>Echoue si $x n'est pas initialisé</td></tr>
|
||||
<tr><td><code>assertIsA($x, $t)</code></td><td>Echoue si $x n'est pas de la classe ou du type $t</td></tr>
|
||||
<tr><td><code>assertEqual($x, $y)</code></td><td>Echoue si $x == $y est faux</td></tr>
|
||||
<tr><td><code>assertNotEqual($x, $y)</code></td><td>Echoue si $x == $y est vrai</td></tr>
|
||||
<tr><td><code>assertIdentical($x, $y)</code></td><td>Echoue si $x === $y est faux</td></tr>
|
||||
<tr><td><code>assertNotIdentical($x, $y)</code></td><td>Echoue si $x === $y est vrai</td></tr>
|
||||
<tr><td><code>assertReference($x, $y)</code></td><td>Echoue sauf si $x et $y sont la même variable</td></tr>
|
||||
<tr><td><code>assertCopy($x, $y)</code></td><td>Echoue si $x et $y sont la même variable</td></tr>
|
||||
<tr><td><code>assertWantedPattern($p, $x)</code></td><td>Echoue sauf si l'expression rationnelle $p capture $x</td></tr>
|
||||
<tr><td><code>assertNoUnwantedPattern($p, $x)</code></td><td>Echoue si l'expression rationnelle $p capture $x</td></tr>
|
||||
<tr><td><code>assertNoErrors()</code></td><td>Echoue si une erreur PHP arrive</td></tr>
|
||||
<tr><td><code>assertError($x)</code></td><td>Echoue si aucune erreur ou message incorrect de PHP n'arrive</td></tr>
|
||||
</tbody></table>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
D'autres exemples...
|
||||
<php><![CDATA[
|
||||
<strong>$variable = null;
|
||||
$this->assertNull($variable, 'Should be cleared');</strong>
|
||||
]]></php>
|
||||
...passera et normalement n'affichera aucun message. Si vous avez <a href="http://www.lastcraft.com/display_subclass_tutorial.php">configuré le testeur pour afficher aussi les succès</a> alors le message sera affiché comme tel.
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertIdentical(0, false, 'Zero is not false [%s]');</strong>
|
||||
]]></php>
|
||||
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.
|
||||
<php><![CDATA[
|
||||
<strong>$a = 1;
|
||||
$b = $a;
|
||||
$this->assertReference($a, $b);</strong>
|
||||
]]></php>
|
||||
Échouera étant donné que la variable <code>$b</code> est une copie de <code>$a</code>.
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertWantedPattern('/hello/i', 'Hello world');</strong>
|
||||
]]></php>
|
||||
Là, ça passe puisque la recherche est insensible à la casse et que donc <code>hello</code> est bien repérable dans <code>Hello world</code>.
|
||||
<php><![CDATA[
|
||||
<strong>trigger_error('Disaster');
|
||||
trigger_error('Catastrophe');
|
||||
$this->assertError();
|
||||
$this->assertError('Catastrophe');
|
||||
$this->assertNoErrors();</strong>
|
||||
]]></php>
|
||||
Ici, il y a besoin d'une petite explication : toutes passent !
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Les scénarios de test peuvent utiliser des méthodes bien pratiques pour déboguer le code ou pour étendre la suite...
|
||||
<table><tbody>
|
||||
<tr><td><code>setUp()</code></td><td>Est lancée avant chaque méthode de test</td></tr>
|
||||
<tr><td><code>tearDown()</code></td><td>Est lancée après chaque méthode de test</td></tr>
|
||||
<tr><td><code>pass()</code></td><td>Envoie un succès</td></tr>
|
||||
<tr><td><code>fail()</code></td><td>Envoie un échec</td></tr>
|
||||
<tr><td><code>error()</code></td><td>Envoi un évènement exception</td></tr>
|
||||
<tr><td><code>sendMessage()</code></td><td>Envoie un message d'état aux systèmes d'affichage qui le supporte</td></tr>
|
||||
<tr><td><code>signal($type, $payload)</code></td><td>Envoie un message défini par l'utilisateur au rapporteur du test</td></tr>
|
||||
<tr><td><code>dump($var)</code></td><td>Effectue un <code>print_r()</code> formaté pour du déboguage rapide et grossier</td></tr>
|
||||
<tr><td><code>swallowErrors()</code></td><td>Vide les erreurs de la queue</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
</section>
|
||||
<section name="extension_unitaire" title="Etendre les scénarios de test">
|
||||
<p>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
require_once('simpletest/unit_tester.php');
|
||||
<strong>
|
||||
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'));
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
Ici la bibliothèque SimpleTest est localisée dans un répertoire local appelé <em>simpletest</em>. Pensez à le modifier pour votre propre environnement.
|
||||
</p>
|
||||
<p>
|
||||
Ce nouveau scénario peut être hérité exactement comme un scénario de test classique...
|
||||
<php><![CDATA[
|
||||
class FileTestCase extends <strong>FileTester</strong> {
|
||||
|
||||
function setUp() {
|
||||
@unlink('../temp/test.txt');
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
@unlink('../temp/test.txt');
|
||||
}
|
||||
|
||||
function testCreation() {
|
||||
$writer = &new FileWriter('../temp/test.txt');
|
||||
$writer->write('Hello');<strong>
|
||||
$this->assertFileExists('../temp/test.txt');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
Si vous souhaitez un scénario de test sans toutes les assertions de <code>UnitTestCase</code> mais uniquement avec les vôtres propres, vous aurez besoin d'étendre la classe <code>SimpleTestCase</code> à la place. Elle se trouve dans <em>simple_test.php</em> en lieu et place de <em>unit_tester.php</em>. A consulter <a local="group_test_documentation">plus tard</a> si vous souhaitez incorporer les scénarios d'autres testeurs unitaires dans votre suite de test.
|
||||
</p>
|
||||
</section>
|
||||
<section name="lancement_unitaire" title="Lancer un unique scénario de test">
|
||||
<p>
|
||||
Ce n'est pas souvent qu'il faille lancer des scénarios avec un unique test. Sauf lorsqu'il s'agit de s'arracher les cheveux sur un module à problème sans pour autant désorganiser la suite de test principale. Voici l'échafaudage nécessaire pour lancer un scénario de test solitaire...
|
||||
<php><![CDATA[
|
||||
<?php
|
||||
require_once('simpletest/unit_tester.php');<strong>
|
||||
require_once('simpletest/reporter.php');</strong>
|
||||
require_once('../classes/writer.php');
|
||||
|
||||
class FileTestCase extends UnitTestCase {
|
||||
function FileTestCase() {
|
||||
$this->UnitTestCase('File test');
|
||||
}
|
||||
}<strong>
|
||||
|
||||
$test = &new FileTestCase();
|
||||
$test->run(new HtmlReporter());</strong>
|
||||
?>
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
<a href="#unitaire">Scénarios de test unitaire</a> et opérations basiques.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#extension_unitaire">Étendre des scénarios de test</a> pour les personnaliser à votre propre projet.
|
||||
</link>
|
||||
<link>
|
||||
<a href="#lancement_unitaire">Lancer un scénario seul</a> comme un script unique.
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page de SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API complète de SimpleTest</a> à partir de PHPDoc.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
test unitaire php,
|
||||
test d'intégration,
|
||||
documentation,
|
||||
marcus baker,
|
||||
perrick penet
|
||||
simple test,
|
||||
documentation simpletest,
|
||||
phpunit,
|
||||
junit,
|
||||
xunit
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,266 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1" ?>
|
||||
<page title="Documentation sur le testeur web" here="Le testeur web">
|
||||
<long_title>Documentation SimpleTest : tester des scripts web</long_title>
|
||||
<content>
|
||||
<section name="telecharger" title="Télécharger une page">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
SimpleTest comprend une forme spéciale de scénario de test pour tester les actions d'une page web. <code>WebTestCase</code> 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 à <code>UnitTestCase</code>...
|
||||
<php><![CDATA[
|
||||
<strong>class TestOfLastcraft extends WebTestCase {
|
||||
}</strong>
|
||||
]]></php>
|
||||
Ici nous sommes sur le point de tester le site de <a href="http://www/lastcraft.com/">Last Craft</a>. Si ce scénario de test est situé dans un fichier appelé <em>lastcraft_test.php</em> alors il peut être chargé dans un script de lancement tout comme des tests unitaires...
|
||||
<php><![CDATA[
|
||||
<?php<strong>
|
||||
require_once('simpletest/web_tester.php');</strong>
|
||||
require_once('simpletest/reporter.php');
|
||||
|
||||
$test = &new GroupTest('Web site tests');<strong>
|
||||
$test->addTestFile('lastcraft_test.php');</strong>
|
||||
exit ($test->run(new TextReporter()) ? 0 : 1);
|
||||
?>
|
||||
]]></php>
|
||||
J'utilise ici le rapporteur en mode texte pour mieux distinguer le contenu au format HTML du résultat du test proprement dit.
|
||||
</p>
|
||||
<p>
|
||||
Rien n'est encore testé. Nous pouvons télécharger la page d'accueil en utilisant la méthode <code>get()</code>...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
<strong>
|
||||
function testHomepage() {
|
||||
$this->assertTrue($this->get('http://www.lastcraft.com/'));
|
||||
}</strong>
|
||||
}
|
||||
]]></php>
|
||||
La méthode <code>get()</code> 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 <code>get()</code> renverrait encore un succès.
|
||||
</p>
|
||||
<p>
|
||||
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...
|
||||
<pre class="shell">
|
||||
Web site tests
|
||||
OK
|
||||
Test cases run: 1/1, Failures: 0, Exceptions: 0
|
||||
</pre>
|
||||
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.
|
||||
</p>
|
||||
</section>
|
||||
<section name="contenu" title="Tester le contenu d'une page">
|
||||
<p>
|
||||
Pour obtenir la confirmation que la page téléchargée est bien celle que nous attendions, nous devons vérifier son contenu.
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {<strong>
|
||||
$this->get('http://www.lastcraft.com/');
|
||||
$this->assertWantedPattern('/why the last craft/i');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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.
|
||||
</p>
|
||||
<p>
|
||||
Voici une liste possible d'assertions sur le contenu...
|
||||
<table><tbody>
|
||||
<tr><td><code>assertWantedPattern($pattern)</code></td><td>Vérifier une correspondance sur le contenu via une expression rationnelle Perl</td></tr>
|
||||
<tr><td><code>assertNoUnwantedPattern($pattern)</code></td><td>Une expression rationnelle Perl pour vérifier une absence</td></tr>
|
||||
<tr><td><code>assertTitle($title)</code></td><td>Passe si le titre de la page correspond exactement</td></tr>
|
||||
<tr><td><code>assertLink($label)</code></td><td>Passe si un lien avec ce texte est présent</td></tr>
|
||||
<tr><td><code>assertNoLink($label)</code></td><td>Passe si aucun lien avec ce texte est présent</td></tr>
|
||||
<tr><td><code>assertLinkById($id)</code></td><td>Passe si un lien avec cet attribut d'identification est présent</td></tr>
|
||||
<tr><td><code>assertField($name, $value)</code></td><td>Passe si une balise input avec ce nom contient cette valeur</td></tr>
|
||||
<tr><td><code>assertFieldById($id, $value)</code></td><td>Passe si une balise input avec cet identifiant contient cette valeur</td></tr>
|
||||
<tr><td><code>assertResponse($codes)</code></td><td>Passe si la réponse HTTP trouve une correspondance dans la liste</td></tr>
|
||||
<tr><td><code>assertMime($types)</code></td><td>Passe si le type MIME se retrouve dans cette liste</td></tr>
|
||||
<tr><td><code>assertAuthentication($protocol)</code></td><td>Passe si l'authentification provoquée est de ce type de protocole</td></tr>
|
||||
<tr><td><code>assertNoAuthentication()</code></td><td>Passe s'il n'y pas d'authentification provoquée en cours</td></tr>
|
||||
<tr><td><code>assertRealm($name)</code></td><td>Passe si le domaine provoqué correspond</td></tr>
|
||||
<tr><td><code>assertHeader($header, $content)</code></td><td>Passe si une entête téléchargée correspond à cette valeur</td></tr>
|
||||
<tr><td><code>assertNoUnwantedHeader($header)</code></td><td>Passe si une entête n'a pas été téléchargé</td></tr>
|
||||
<tr><td><code>assertHeaderPattern($header, $pattern)</code></td><td>Passe si une entête téléchargée correspond à cette expression rationnelle Perl</td></tr>
|
||||
<tr><td><code>assertCookie($name, $value)</code></td><td>Passe s'il existe un cookie correspondant</td></tr>
|
||||
<tr><td><code>assertNoCookie($name)</code></td><td>Passe s'il n'y a pas de cookie avec un tel nom</td></tr>
|
||||
</tbody></table>
|
||||
Comme d'habitude avec les assertions de SimpleTest, elles renvoient toutes "false" en cas d'é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".
|
||||
</p>
|
||||
<p>
|
||||
A présent nous pourrions effectué le test sur le titre uniquement...
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertTitle('The Last Craft?');</strong>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
<strong>$this->assertMime(array('text/plain', 'text/html'));</strong>
|
||||
]]></php>
|
||||
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...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {
|
||||
$this->get('http://simpletest.sourceforge.net/');<strong>
|
||||
$this->assertResponse(200);</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
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 <em>http://simpletest.sourceforge.net/</em>, à la place le serveur renverra une redirection vers <em>http://www.lastcraft.com/simple_test.php</em>. <code>WebTestCase</code> 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...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {<strong>
|
||||
$this->setMaximumRedirects(0);</strong>
|
||||
$this->get('http://simpletest.sourceforge.net/');
|
||||
$this->assertResponse(200);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Alors l'assertion échoue comme prévue...
|
||||
<pre class="shell">
|
||||
Web site tests
|
||||
1) Expecting response in [200] got [302]
|
||||
in testhomepage
|
||||
in testoflastcraft
|
||||
in lastcraft_test.php
|
||||
FAILURES!!!
|
||||
Test cases run: 1/1, Failures: 1, Exceptions: 0
|
||||
</pre>
|
||||
Nous pouvons modifier le test pour accepter les redirections...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
|
||||
function testHomepage() {
|
||||
$this->setMaximumRedirects(0);
|
||||
$this->get('http://simpletest.sourceforge.net/');
|
||||
$this->assertResponse(<strong>array(301, 302, 303, 307)</strong>);
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Maitenant ça passe.
|
||||
</p>
|
||||
</section>
|
||||
<section name="navigation" title="Navigeur dans un site web">
|
||||
<p>
|
||||
Les utilisateurs ne naviguent pas souvent en tapant les URLs, mais surtout en cliquant sur des liens et des boutons. Ici nous confirmons que les informations sur le contact peuvent être atteintes depuis la page d'accueil...
|
||||
<php><![CDATA[
|
||||
class TestOfLastcraft extends WebTestCase {
|
||||
...
|
||||
function testContact() {
|
||||
$this->get('http://www.lastcraft.com/');<strong>
|
||||
$this->clickLink('About');
|
||||
$this->assertTitle('About Last Craft');</strong>
|
||||
}
|
||||
}
|
||||
]]></php>
|
||||
Le paramètre est le texte du lien.
|
||||
</p>
|
||||
<p>
|
||||
Il l'objectif est un bouton plutôt qu'une balise ancre, alors <code>clickSubmit()</code> doit être utilisé avec le titre du bouton...
|
||||
<php><![CDATA[
|
||||
<strong>$this->clickSubmit('Go!');</strong>
|
||||
]]></php>
|
||||
</p>
|
||||
<p>
|
||||
La liste des méthodes de navigation est...
|
||||
<table><tbody>
|
||||
<tr><td><code>get($url, $parameters)</code></td><td>Envoie une requête GET avec ces paramètres</td></tr>
|
||||
<tr><td><code>post($url, $parameters)</code></td><td>Envoie une requête POST avec ces paramètres</td></tr>
|
||||
<tr><td><code>head($url, $parameters)</code></td><td>Envoie une requête HEAD sans remplacer le contenu de la page</td></tr>
|
||||
<tr><td><code>retry()</code></td><td>Relance la dernière requête</td></tr>
|
||||
<tr><td><code>back()</code></td><td>Identique au bouton "Précédent" du navigateur</td></tr>
|
||||
<tr><td><code>forward()</code></td><td>Identique au bouton "Suivant" du navigateur</td></tr>
|
||||
<tr><td><code>authenticate($name, $password)</code></td><td>Re-essaye avec une tentative d'authentification</td></tr>
|
||||
<tr><td><code>getFrameFocus()</code></td><td>Le nom de la fenêtre en cours d'utilisation</td></tr>
|
||||
<tr><td><code>setFrameFocusByIndex($choice)</code></td><td>Change le focus d'une fenêtre en commençant par 1</td></tr>
|
||||
<tr><td><code>setFrameFocus($name)</code></td><td>Change le focus d'une fenêtre en utilisant son nom</td></tr>
|
||||
<tr><td><code>clearFrameFocus()</code></td><td>Revient à un traitement de toutes les fenêtres comme une seule</td></tr>
|
||||
<tr><td><code>clickSubmit($label)</code></td><td>Clique sur le premier bouton avec cette étiquette</td></tr>
|
||||
<tr><td><code>clickSubmitByName($name)</code></td><td>Clique sur le bouton avec cet attribut de nom</td></tr>
|
||||
<tr><td><code>clickSubmitById($id)</code></td><td>Clique sur le bouton avec cet attribut d'identification</td></tr>
|
||||
<tr><td><code>clickImage($label, $x, $y)</code></td><td>Clique sur une balise input de type image avec ce titre ou ce texte dans l'attribut alt</td></tr>
|
||||
<tr><td><code>clickImageByName($name, $x, $y)</code></td><td>Clique sur une balise input de type image avec ce nom</td></tr>
|
||||
<tr><td><code>clickImageById($id, $x, $y)</code></td><td>Clique sur une balise input de type image avec cet attribut d'identification</td></tr>
|
||||
<tr><td><code>submitFormById($id)</code></td><td>Soumet un formulaire sans valeur de soumission</td></tr>
|
||||
<tr><td><code>clickLink($label, $index)</code></td><td>Clique sur une ancre avec ce texte d'étiquette visible</td></tr>
|
||||
<tr><td><code>clickLinkById($id)</code></td><td>Clique sur une ancre avec cet attribut d'identification</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
<p>
|
||||
Les paramètres dans les méthodes <code>get()</code>, <code>post()</code> et <code>head()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
Les commandes <code>retry()</code>, <code>back()</code> et <code>forward()</code> 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.
|
||||
</p>
|
||||
<p>
|
||||
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é.
|
||||
</p>
|
||||
<p>
|
||||
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 <a local="form_testing_documentation">des outils pour tester des formulaires web</a>.
|
||||
</p>
|
||||
</section>
|
||||
<section name="requete" title="Modifier la requête">
|
||||
<p>
|
||||
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...
|
||||
<table><tbody>
|
||||
<tr><td><code>getTransportError()</code></td><td>La dernière erreur de socket</td></tr>
|
||||
<tr><td><code>getUrl()</code></td><td>La localisation courante</td></tr>
|
||||
<tr><td><code>showRequest()</code></td><td>Déverse la requête sortante</td></tr>
|
||||
<tr><td><code>showHeaders()</code></td><td>Déverse les entêtes d'entrée</td></tr>
|
||||
<tr><td><code>showSource()</code></td><td>Déverse le contenu brut de la page HTML</td></tr>
|
||||
<tr><td><code>ignoreFrames()</code></td><td>Ne recharge pas les framesets</td></tr>
|
||||
<tr><td><code>setCookie($name, $value)</code></td><td>Initie un cookie à partir de maintenant</td></tr>
|
||||
<tr><td><code>addHeader($header)</code></td><td>Ajoute toujours cette entête à la requête</td></tr>
|
||||
<tr><td><code>setMaximumRedirects($max)</code></td><td>S'arrête après autant de redirections</td></tr>
|
||||
<tr><td><code>setConnectionTimeout($timeout)</code></td><td>Termine la connexion après autant de temps entre les bytes</td></tr>
|
||||
<tr><td><code>useProxy($proxy, $name, $password)</code></td><td>Effectue les requêtes à travers ce proxy d'URL</td></tr>
|
||||
</tbody></table>
|
||||
</p>
|
||||
</section>
|
||||
</content>
|
||||
<internal>
|
||||
<link>
|
||||
Réussir à <a href="#telecharger">télécharger une page web</a>
|
||||
</link>
|
||||
<link>
|
||||
Tester le <a href="#contenu">contenu de la page</a>
|
||||
</link>
|
||||
<link>
|
||||
<a href="#navigation">Naviguer sur un site web</a> pendant le test
|
||||
</link>
|
||||
<link>
|
||||
Méthodes pour <a href="#requete">modifier une requête</a> et pour déboguer
|
||||
</link>
|
||||
</internal>
|
||||
<external>
|
||||
<link>
|
||||
La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>.
|
||||
</link>
|
||||
<link>
|
||||
La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.
|
||||
</link>
|
||||
<link>
|
||||
<a href="http://simpletest.sourceforge.net/">L'API du développeur pour SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles.
|
||||
</link>
|
||||
</external>
|
||||
<meta>
|
||||
<keywords>
|
||||
développement logiciel,
|
||||
programmation php pour des clients,
|
||||
php orienté client,
|
||||
outils de développement logiciel,
|
||||
framework de test de recette,
|
||||
scripts php gratuits,
|
||||
architecture,
|
||||
ressources php,
|
||||
HTMLUnit,
|
||||
JWebUnit,
|
||||
test php,
|
||||
ressource de test unitaire,
|
||||
test web
|
||||
</keywords>
|
||||
</meta>
|
||||
</page>
|
||||
|
@ -0,0 +1,360 @@
|
||||
<?php
|
||||
/**
|
||||
* base include file for SimpleTest
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
* @version $Id: dumper.php,v 1.29 2006/05/13 14:37:16 lastcraft Exp $
|
||||
*/
|
||||
/**
|
||||
* does type matter
|
||||
*/
|
||||
if (! defined('TYPE_MATTERS')) {
|
||||
define('TYPE_MATTERS', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays variables as text and does diffs.
|
||||
* @package SimpleTest
|
||||
* @subpackage UnitTester
|
||||
*/
|
||||
class SimpleDumper {
|
||||
|
||||
/**
|
||||
* Renders a variable in a shorter form than print_r().
|
||||
* @param mixed $value Variable to render as a string.
|
||||
* @return string Human readable string form.
|
||||
* @access public
|
||||
*/
|
||||
function describeValue($value) {
|
||||
$type = $this->getType($value);
|
||||
switch($type) {
|
||||
case "Null":
|
||||
return "NULL";
|
||||
case "Boolean":
|
||||
return "Boolean: " . ($value ? "true" : "false");
|
||||
case "Array":
|
||||
return "Array: " . count($value) . " items";
|
||||
case "Object":
|
||||
return "Object: of " . get_class($value);
|
||||
case "String":
|
||||
return "String: " . $this->clipString($value, 200);
|
||||
default:
|
||||
return "$type: $value";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string representation of a type.
|
||||
* @param mixed $value Variable to check against.
|
||||
* @return string Type.
|
||||
* @access public
|
||||
*/
|
||||
function getType($value) {
|
||||
if (! isset($value)) {
|
||||
return "Null";
|
||||
} elseif (is_bool($value)) {
|
||||
return "Boolean";
|
||||
} elseif (is_string($value)) {
|
||||
return "String";
|
||||
} elseif (is_integer($value)) {
|
||||
return "Integer";
|
||||
} elseif (is_float($value)) {
|
||||
return "Float";
|
||||
} elseif (is_array($value)) {
|
||||
return "Array";
|
||||
} elseif (is_resource($value)) {
|
||||
return "Resource";
|
||||
} elseif (is_object($value)) {
|
||||
return "Object";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between two variables. Uses a
|
||||
* dynamic call.
|
||||
* @param mixed $first First variable.
|
||||
* @param mixed $second Value to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Description of difference.
|
||||
* @access public
|
||||
*/
|
||||
function describeDifference($first, $second, $identical = false) {
|
||||
if ($identical) {
|
||||
if (! $this->_isTypeMatch($first, $second)) {
|
||||
return "with type mismatch as [" . $this->describeValue($first) .
|
||||
"] does not match [" . $this->describeValue($second) . "]";
|
||||
}
|
||||
}
|
||||
$type = $this->getType($first);
|
||||
if ($type == "Unknown") {
|
||||
return "with unknown type";
|
||||
}
|
||||
$method = '_describe' . $type . 'Difference';
|
||||
return $this->$method($first, $second, $identical);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests to see if types match.
|
||||
* @param mixed $first First variable.
|
||||
* @param mixed $second Value to compare with.
|
||||
* @return boolean True if matches.
|
||||
* @access private
|
||||
*/
|
||||
function _isTypeMatch($first, $second) {
|
||||
return ($this->getType($first) == $this->getType($second));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clips a string to a maximum length.
|
||||
* @param string $value String to truncate.
|
||||
* @param integer $size Minimum string size to show.
|
||||
* @param integer $position Centre of string section.
|
||||
* @return string Shortened version.
|
||||
* @access public
|
||||
*/
|
||||
function clipString($value, $size, $position = 0) {
|
||||
$length = strlen($value);
|
||||
if ($length <= $size) {
|
||||
return $value;
|
||||
}
|
||||
$position = min($position, $length);
|
||||
$start = ($size/2 > $position ? 0 : $position - $size/2);
|
||||
if ($start + $size > $length) {
|
||||
$start = $length - $size;
|
||||
}
|
||||
$value = substr($value, $start, $size);
|
||||
return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between two variables. The minimal
|
||||
* version.
|
||||
* @param null $first First value.
|
||||
* @param mixed $second Value to compare with.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeGenericDifference($first, $second) {
|
||||
return "as [" . $this->describeValue($first) .
|
||||
"] does not match [" .
|
||||
$this->describeValue($second) . "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between a null and another variable.
|
||||
* @param null $first First null.
|
||||
* @param mixed $second Null to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeNullDifference($first, $second, $identical) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between a boolean and another variable.
|
||||
* @param boolean $first First boolean.
|
||||
* @param mixed $second Boolean to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeBooleanDifference($first, $second, $identical) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between a string and another variable.
|
||||
* @param string $first First string.
|
||||
* @param mixed $second String to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeStringDifference($first, $second, $identical) {
|
||||
if (is_object($second) || is_array($second)) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
$position = $this->_stringDiffersAt($first, $second);
|
||||
$message = "at character $position";
|
||||
$message .= " with [" .
|
||||
$this->clipString($first, 200, $position) . "] and [" .
|
||||
$this->clipString($second, 200, $position) . "]";
|
||||
return $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between an integer and another variable.
|
||||
* @param integer $first First number.
|
||||
* @param mixed $second Number to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeIntegerDifference($first, $second, $identical) {
|
||||
if (is_object($second) || is_array($second)) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
return "because [" . $this->describeValue($first) .
|
||||
"] differs from [" .
|
||||
$this->describeValue($second) . "] by " .
|
||||
abs($first - $second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between two floating point numbers.
|
||||
* @param float $first First float.
|
||||
* @param mixed $second Float to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeFloatDifference($first, $second, $identical) {
|
||||
if (is_object($second) || is_array($second)) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
return "because [" . $this->describeValue($first) .
|
||||
"] differs from [" .
|
||||
$this->describeValue($second) . "] by " .
|
||||
abs($first - $second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between two arrays.
|
||||
* @param array $first First array.
|
||||
* @param mixed $second Array to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeArrayDifference($first, $second, $identical) {
|
||||
if (! is_array($second)) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
if (! $this->_isMatchingKeys($first, $second, $identical)) {
|
||||
return "as key list [" .
|
||||
implode(", ", array_keys($first)) . "] does not match key list [" .
|
||||
implode(", ", array_keys($second)) . "]";
|
||||
}
|
||||
foreach (array_keys($first) as $key) {
|
||||
if ($identical && ($first[$key] === $second[$key])) {
|
||||
continue;
|
||||
}
|
||||
if (! $identical && ($first[$key] == $second[$key])) {
|
||||
continue;
|
||||
}
|
||||
return "with member [$key] " . $this->describeDifference(
|
||||
$first[$key],
|
||||
$second[$key],
|
||||
$identical);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two arrays to see if their key lists match.
|
||||
* For an identical match, the ordering and types of the keys
|
||||
* is significant.
|
||||
* @param array $first First array.
|
||||
* @param array $second Array to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return boolean True if matching.
|
||||
* @access private
|
||||
*/
|
||||
function _isMatchingKeys($first, $second, $identical) {
|
||||
$first_keys = array_keys($first);
|
||||
$second_keys = array_keys($second);
|
||||
if ($identical) {
|
||||
return ($first_keys === $second_keys);
|
||||
}
|
||||
sort($first_keys);
|
||||
sort($second_keys);
|
||||
return ($first_keys == $second_keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between a resource and another variable.
|
||||
* @param resource $first First resource.
|
||||
* @param mixed $second Resource to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeResourceDifference($first, $second, $identical) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a human readable description of the
|
||||
* difference between two objects.
|
||||
* @param object $first First object.
|
||||
* @param mixed $second Object to compare with.
|
||||
* @param boolean $identical If true then type anomolies count.
|
||||
* @return string Human readable description.
|
||||
* @access private
|
||||
*/
|
||||
function _describeObjectDifference($first, $second, $identical) {
|
||||
if (! is_object($second)) {
|
||||
return $this->_describeGenericDifference($first, $second);
|
||||
}
|
||||
return $this->_describeArrayDifference(
|
||||
get_object_vars($first),
|
||||
get_object_vars($second),
|
||||
$identical);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the first character position that differs
|
||||
* in two strings by binary chop.
|
||||
* @param string $first First string.
|
||||
* @param string $second String to compare with.
|
||||
* @return integer Position of first differing
|
||||
* character.
|
||||
* @access private
|
||||
*/
|
||||
function _stringDiffersAt($first, $second) {
|
||||
if (! $first || ! $second) {
|
||||
return 0;
|
||||
}
|
||||
if (strlen($first) < strlen($second)) {
|
||||
list($first, $second) = array($second, $first);
|
||||
}
|
||||
$position = 0;
|
||||
$step = strlen($first);
|
||||
while ($step > 1) {
|
||||
$step = (integer)(($step + 1) / 2);
|
||||
if (strncmp($first, $second, $position + $step) == 0) {
|
||||
$position += $step;
|
||||
}
|
||||
}
|
||||
return $position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a formatted dump of a variable to a string.
|
||||
* @param mixed $variable Variable to display.
|
||||
* @return string Output from print_r().
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
function dump($variable) {
|
||||
ob_start();
|
||||
print_r($variable);
|
||||
$formatted = ob_get_contents();
|
||||
ob_end_clean();
|
||||
return $formatted;
|
||||
}
|
||||
}
|
||||
?>
|