7.x common.test DrupalHTTPRequestTestCase::testDrupalHTTPRequest()


modules/simpletest/tests/common.test, line 1115
Tests for common.inc functionality.


Test drupal_http_request().


function testDrupalHTTPRequest() {
  global $is_https;

  // Parse URL schema.
  $missing_scheme = drupal_http_request('example.com/path');
    ->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
    ->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
  $unable_to_parse = drupal_http_request('http:///path');
    ->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
    ->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');

  // Fetch page.
  $result = drupal_http_request(url('node', array(
    'absolute' => TRUE,
    ->assertEqual($result->code, 200, 'Fetched page successfully.');
    ->assertTitle(t('Welcome to @site-name | @site-name', array(
    '@site-name' => variable_get('site_name', 'Drupal'),
  )), 'Site title matches.');

  // Test that code and status message is returned.
  $result = drupal_http_request(url('pagedoesnotexist', array(
    'absolute' => TRUE,
    ->assertTrue(!empty($result->protocol), 'Result protocol is returned.');
    ->assertEqual($result->code, '404', 'Result code is 404');
    ->assertEqual($result->status_message, 'Not Found', 'Result status message is "Not Found"');

  // Skip the timeout tests when the testing environment is HTTPS because
  // stream_set_timeout() does not work for SSL connections.
  // @link http://bugs.php.net/bug.php?id=47929
  if (!$is_https) {

    // Test that timeout is respected. The test machine is expected to be able
    // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
    // return within a total of 5 seconds. If the test machine is extremely
    // slow, the test will fail. fsockopen() has been seen to time out in
    // slightly less than the specified timeout, so allow a little slack on
    // the minimum expected time (i.e. 1.8 instead of 2).
    $result = drupal_http_request(url('system-test/sleep/10', array(
      'absolute' => TRUE,
    )), array(
      'timeout' => 2,
    $time = timer_read(__METHOD__) / 1000;
      ->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array(
      '%time' => $time,
      ->assertTrue($result->error, 'An error message was returned.');
      ->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');