--- simpletest.test.orig	2009-04-17 17:01:32.000000000 +1200
+++ simpletest.test	2009-04-17 17:00:59.000000000 +1200
@@ -267,6 +267,62 @@
    * @return The test is being run from inside a CURL request.
    */
   function inCURL() {
     return preg_match("/^simpletest\d+/", $_SERVER['HTTP_USER_AGENT']);
   }
+  
+  /**
+   * Tests SimpleTest's environment cleanup functionality by creating a dirty
+   * environment then checking that simpletest_clean_environment() will work as advertised.
+   *
+   */
+  function testEnvironmentCleanup() {
+    global $db_prefix;
+
+    $old_prefix = $db_prefix;
+
+    // Create a prefixed table (note SimpleTest has probably already created a bunch of
+    // simpletest-prefixed tables, so we need to temporarily switch prefixes to test this)
+    $db_prefix = 'simpletest' . mt_rand(1000, 1000000);
+    $table = 'testcleanup';
+    $schema = drupal_get_schema(NULL, true);
+    $ret = array();
+    $prefixed_table_names = array();
+    foreach ($schema as $name => $table) {
+      db_create_table($ret, $name, $table);
+      $prefixed_table_names[] = $db_prefix.$name;
+    }
+
+    // Check they were created
+    $success = true;
+    foreach ($schema as $name => $table) {
+      $success &= db_table_exists($name);
+    }
+    $this->assertTrue($success, t('Checking cleanup test tables exists'));
+
+    // Get any currently set messages
+    $old_messages = $_SESSION['messages'];
+    drupal_get_messages(null, true);
+
+    // Run the cleanup
+    $db_prefix_backup = $db_prefix;
+    $db_prefix = ''; // technically should be the site's default prefix, but it's too risky to reinclude settings.php
+    if (function_exists('simpletest_get_like_tables')) { // Drupal 6
+      $would_be_removed_tables = simpletest_get_like_tables('simpletest', false);
+    }
+    else if (function_exists('db_find_tables')) { // Drupal 7
+      $would_be_removed_tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
+    }
+    $missed_tables = array_diff($prefixed_table_names, $would_be_removed_tables);
+    $this->assertTrue(empty($missed_tables), t('Checking for any missed tables that should have been cleaned up'));
+    $db_prefix = $db_prefix_backup;
+
+    // Remove our testing tables
+    foreach ($schema as $name => $table) {
+      db_drop_table($ret, $name);
+    }
+
+    // restore the original SimpleTest db prefix
+    $db_prefix = $old_prefix;
+    drupal_get_schema(null, true);
+  }
 }
