How to check if code is running inside simpletest? Here's the best I've come up with so far:

/**
 * Returns TRUE if our code is running via a simpletest.
 *
 * We don't check for the database prefix so that this can be used by Unit
 * Tests also.
 *
 * We could set a variable in the test setUp method and check that variable,
 * but then some dummy could misuse that variable in code intended for
 * production.
 */
function check_is_simpletest() {
    return class_exists('DrupalTestCase', FALSE) || strpos($_SERVER['HTTP_USER_AGENT'], 'simpletest') === 0;
}


Is this crazy? I'd expect it to break in the Testing UI pages of the site, but I'm only concerned with testing custom code which will not affect those pages, and I usually test via drush.
In Drupal 7, drupal_http_request() use the following code to add an extra header, when tests are running.

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  $test_info = &amp;$GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  }


In your module, similar code should work.

  $test_info = $GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    // Drupal is running tests.
  }


In Drupal 6, the following code is present in drupal_http_request().

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  if (is_string($db_prefix) &amp;&amp; preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
    $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  }


The following code should work for a Drupal 6 module.

  global $db_prefix;

  if (is_string($db_prefix) &amp;&amp; preg_match("/^simpletest\d+$/", $db_prefix)) {
    // Drupal is running tests.
  }