SuperSimple Page Monitoring with SimpleTest

Posted on December 2nd, 2006 in PHP by Russ

We’re trying to implement Test Driven Development here. It’s actually a more formalized version of what we normally do:

  1. find a problem
  2. code until the problem goes away
  3. clean up the code

What TDD does is:

  1. define a test
  2. be able to pass the test with a minimum of code
  3. clean up the code

There are plenty of examples on the web of what we’re learning, but I wanted to shine a light on a slightly different facet of these testing frameworks. One client we work with has several hundred domains all using the same database to manage content. This is not unusual; look at wordpress.com for an example. Once in a while his database would fail and “hundreds of websites would be down.” And he really had no way to know that it was down; he needed something to do it for him.

On one hand, it’s pretty easy to use php and open up a socket and make sure there’s a connection to the server. But when the webserver is running and the database is not, many tests will let this one pass. To come up with the solution, a PHP developer has to open up a connection, read the data and check for specific text to either be there or not be there. Not really a “hard problem” when you can use fread() on an url and then preg_match() for the content. But there’s an easier solution.

Download and install SimpleTest. “Install” is misleading; just untar the package, it’s all laid out. If you untar it in your working directory, you’ll wind up with a “simpletest” directory. Then write a quick little page like this:


require_once 'simpletest/web_tester.php';
require_once 'simpletest/reporter.php';

class AwwUp extends WebTestCase {

function testHomepage() {
$this->assertTrue($this->get('http://www.arghwebworks.com/'));
$this->assertResponse( array( 200,301,302,303,307) );
$this->clickLink('Webmastering');
$this->assertTitle('ArghWebWorks ยป Webmastering');
}
}

$test = new AwwUp;

$test->run(new HtmlReporter());

When you browse to this page in your browser, this page will connect to the server (this->get()), make sure that the HTTP response code is ‘ok’ (this->assertResponse()), click on a link (this->clickLink), and check the title of the resulting page for what you coded in (this->assertTitle()). If any of these tests fail the “bar” at the bottom of the page will be red:testfail.gif. If your server is working right, and your tests succeed, you’ll have a green bar: testpass.gif.

There are many other options you can check for success or failure; you should check the API to find which would work best for you.

The client in question would need some more dynamic scripting, using variables in the assertTitle and the get methods, but those are fairly standard programming exercises.