How to check if code is running inside simpletest?
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.
  }