common.test 56.7 KB
Newer Older
1
<?php
2
// $Id$
3

4
/**
5
 * Tests for URL generation functions.
6
 */
7
class CommonURLUnitTest extends DrupalUnitTestCase {
8
  public static function getInfo() {
9
    return array(
10
      'name' => 'URL generation tests',
11
      'description' => 'Confirm that url(), drupal_get_query_parameters(), drupal_http_build_query(), and l() work correctly with various input.',
12
      'group' => 'System',
13 14 15 16 17 18 19 20 21 22 23
    );
  }

  /**
   * Confirm that invalid text given as $path is filtered.
   */
  function testLXSS() {
    $text = $this->randomName();
    $path = "<SCRIPT>alert('XSS')</SCRIPT>";
    $link = l($text, $path);
    $sanitized_path = check_url(url($path));
24
    $this->assertTrue(strpos($link, $sanitized_path) !== FALSE, t('XSS attack @path was filtered', array('@path' => $path)));
25
  }
26 27

  /**
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   * Test drupal_get_query_parameters().
   */
  function testDrupalGetQueryParameters() {
    $original = array(
      'a' => 1,
      'b' => array(
        'd' => 4,
        'e' => array(
          'f' => 5,
        ),
      ),
      'c' => 3,
      'q' => 'foo/bar',
    );

    // Default arguments.
    $result = $_GET;
    unset($result['q']);
    $this->assertEqual(drupal_get_query_parameters(), $result, t("\$_GET['q'] was removed."));

    // Default exclusion.
    $result = $original;
    unset($result['q']);
    $this->assertEqual(drupal_get_query_parameters($original), $result, t("'q' was removed."));

    // First-level exclusion.
    $result = $original;
    unset($result['b']);
    $this->assertEqual(drupal_get_query_parameters($original, array('b')), $result, t("'b' was removed."));

    // Second-level exclusion.
    $result = $original;
    unset($result['b']['d']);
    $this->assertEqual(drupal_get_query_parameters($original, array('b[d]')), $result, t("'b[d]' was removed."));

    // Third-level exclusion.
    $result = $original;
    unset($result['b']['e']['f']);
    $this->assertEqual(drupal_get_query_parameters($original, array('b[e][f]')), $result, t("'b[e][f]' was removed."));

    // Multiple exclusions.
    $result = $original;
    unset($result['a'], $result['b']['e'], $result['c']);
    $this->assertEqual(drupal_get_query_parameters($original, array('a', 'b[e]', 'c')), $result, t("'a', 'b[e]', 'c' were removed."));
  }

  /**
   * Test drupal_http_build_query().
   */
  function testDrupalHttpBuildQuery() {
    $this->assertEqual(drupal_http_build_query(array('a' => ' &#//+%20@۞')), 'a=%20%26%23//%2B%2520%40%DB%9E', t('Value was properly encoded.'));
    $this->assertEqual(drupal_http_build_query(array(' &#//+%20@۞' => 'a')), '%20%26%23%2F%2F%2B%2520%40%DB%9E=a', t('Key was properly encoded.'));
    $this->assertEqual(drupal_http_build_query(array('a' => '1', 'b' => '2', 'c' => '3')), 'a=1&b=2&c=3', t('Multiple values were properly concatenated.'));
    $this->assertEqual(drupal_http_build_query(array('a' => array('b' => '2', 'c' => '3'), 'd' => 'foo')), 'a[b]=2&a[c]=3&d=foo', t('Nested array was properly encoded.'));
  }

  /**
   * Test drupal_parse_url().
   */
  function testDrupalParseUrl() {
    // Relative URL.
    $url = 'foo/bar?foo=bar&bar=baz&baz#foo';
    $result = array(
      'path' => 'foo/bar',
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
      'fragment' => 'foo',
    );
    $this->assertEqual(drupal_parse_url($url), $result, t('Relative URL parsed correctly.'));

97 98 99 100 101 102 103 104 105
    // Relative URL that is known to confuse parse_url().
    $url = 'foo/bar:1';
    $result = array(
      'path' => 'foo/bar:1',
      'query' => array(),
      'fragment' => '',
    );
    $this->assertEqual(drupal_parse_url($url), $result, t('Relative URL parsed correctly.'));

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    // Absolute URL.
    $url = '/foo/bar?foo=bar&bar=baz&baz#foo';
    $result = array(
      'path' => '/foo/bar',
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
      'fragment' => 'foo',
    );
    $this->assertEqual(drupal_parse_url($url), $result, t('Absolute URL parsed correctly.'));

    // External URL.
    $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
    $result = array(
      'path' => 'http://drupal.org/foo/bar',
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
      'fragment' => 'foo',
    );
    $this->assertEqual(drupal_parse_url($url), $result, t('External URL parsed correctly.'));
  }

125
  /**
126 127
   * Test url() with/without query, with/without fragment, absolute on/off and
   * assert all that works when clean URLs are on and off.
128 129 130
   */
  function testUrl() {
    global $base_url;
131

132 133 134 135
    foreach (array(FALSE, TRUE) as $absolute) {
      // Get the expected start of the path string.
      $base = $absolute ? $base_url . '/' : base_path();
      $absolute_string = $absolute ? 'absolute' : NULL;
136 137

      // Disable Clean URLs.
138
      $GLOBALS['conf']['clean_url'] = 0;
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

      $url = $base . '?q=node/123';
      $result = url('node/123', array('absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . '?q=node/123#foo';
      $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . '?q=node/123&foo';
      $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . '?q=node/123&foo=bar&bar=baz';
      $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . '?q=node/123&foo#bar';
      $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base;
      $result = url('<front>', array('absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      // Enable Clean URLs.
165
      $GLOBALS['conf']['clean_url'] = 1;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

      $url = $base . 'node/123';
      $result = url('node/123', array('absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . 'node/123#foo';
      $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . 'node/123?foo';
      $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . 'node/123?foo=bar&bar=baz';
      $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base . 'node/123?foo#bar';
      $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");

      $url = $base;
      $result = url('<front>', array('absolute' => $absolute));
      $this->assertEqual($url, $result, "$url == $result");
190 191
    }
  }
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

  /**
   * Test external URL handling.
   */
  function testExternalUrls() {
    $test_url = 'http://drupal.org/';

    // Verify external URL can contain a fragment.
    $url = $test_url . '#drupal';
    $result = url($url);
    $this->assertEqual($url, $result, t('External URL with fragment works without a fragment in $options.'));

    // Verify fragment can be overidden in an external URL.
    $url = $test_url . '#drupal';
    $fragment = $this->randomName(10);
    $result = url($url, array('fragment' => $fragment));
    $this->assertEqual($test_url . '#' . $fragment, $result, t('External URL fragment is overidden with a custom fragment in $options.'));

    // Verify external URL can contain a query string.
    $url = $test_url . '?drupal=awesome';
    $result = url($url);
    $this->assertEqual($url, $result, t('External URL with query string works without a query string in $options.'));

    // Verify external URL can be extended with a query string.
    $url = $test_url;
    $query = array($this->randomName(5) => $this->randomName(5));
    $result = url($url, array('query' => $query));
    $this->assertEqual($url . '?' . http_build_query($query, '', '&'), $result, t('External URL can be extended with a query string in $options.'));

    // Verify query string can be extended in an external URL.
    $url = $test_url . '?drupal=awesome';
    $query = array($this->randomName(5) => $this->randomName(5));
    $result = url($url, array('query' => $query));
    $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result, t('External URL query string can be extended with a custom query string in $options.'));
  }
227 228
}

229
class CommonSizeTestCase extends DrupalUnitTestCase {
230 231
  protected $exact_test_cases;
  protected $rounded_test_cases;
232

233
  public static function getInfo() {
234
    return array(
235 236 237
      'name' => 'Size parsing test',
      'description' => 'Parse a predefined amount of bytes and compare the output with the expected value.',
      'group' => 'System'
238 239 240 241
    );
  }

  function setUp() {
242
    $kb = DRUPAL_KILOBYTE;
243
    $this->exact_test_cases = array(
244 245 246 247 248 249 250 251 252
      '1 byte' => 1,
      '1 KB'   => $kb,
      '1 MB'   => $kb * $kb,
      '1 GB'   => $kb * $kb * $kb,
      '1 TB'   => $kb * $kb * $kb * $kb,
      '1 PB'   => $kb * $kb * $kb * $kb * $kb,
      '1 EB'   => $kb * $kb * $kb * $kb * $kb * $kb,
      '1 ZB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
      '1 YB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
253 254
    );
    $this->rounded_test_cases = array(
255 256 257 258 259
      '2 bytes' => 2,
      '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
      round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651, // megabytes
      round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
      round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
260 261 262 263 264
    );
    parent::setUp();
  }

  /**
265
   * Check that format_size() returns the expected string.
266 267 268
   */
  function testCommonFormatSize() {
    foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
269 270 271 272 273
      foreach ($test_cases as $expected => $input) {
        $this->assertEqual(
          ($result = format_size($input, NULL)),
          $expected,
          $expected . ' == ' . $result . ' (' . $input . ' bytes)'
274 275 276 277
        );
      }
    }
  }
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

  /**
   * Check that parse_size() returns the proper byte sizes.
   */
  function testCommonParseSize() {
    foreach ($this->exact_test_cases as $string => $size) {
      $this->assertEqual(
        $parsed_size = parse_size($string),
        $size,
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
      );
    }

    // Some custom parsing tests
    $string = '23476892 bytes';
    $this->assertEqual(
      ($parsed_size = parse_size($string)),
      $size = 23476892,
      $string . ' == ' . $parsed_size . ' bytes'
    );
    $string = '76MRandomStringThatShouldBeIgnoredByParseSize.'; // 76 MB
    $this->assertEqual(
      $parsed_size = parse_size($string),
      $size = 79691776,
      $string . ' == ' . $parsed_size . ' bytes'
    );
    $string = '76.24 Giggabyte'; // Misspeld text -> 76.24 GB
    $this->assertEqual(
      $parsed_size = parse_size($string),
      $size = 81862076662,
      $string . ' == ' . $parsed_size . ' bytes'
    );
  }

  /**
   * Cross-test parse_size() and format_size().
   */
  function testCommonParseSizeFormatSize() {
    foreach ($this->exact_test_cases as $size) {
      $this->assertEqual(
        $size,
        ($parsed_size = parse_size($string = format_size($size, NULL))),
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
      );
    }
  }
324
}
325 326 327 328 329 330 331 332 333 334 335 336

/**
 * Test drupal_explode_tags() and drupal_implode_tags().
 */
class DrupalTagsHandlingTestCase extends DrupalWebTestCase {
  var $validTags = array(
    'Drupal' => 'Drupal',
    'Drupal with some spaces' => 'Drupal with some spaces',
    '"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
    '"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
  );

337
  public static function getInfo() {
338
    return array(
339 340 341
      'name' => 'Drupal tags handling',
      'description' => "Performs tests on Drupal's handling of tags, both explosion and implosion tactics used.",
      'group' => 'System'
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    );
  }

  /**
   * Explode a series of tags.
   */
  function testDrupalExplodeTags() {
    $string = implode(', ', array_keys($this->validTags));
    $tags = drupal_explode_tags($string);
    $this->assertTags($tags);
  }

  /**
   * Implode a series of tags.
   */
  function testDrupalImplodeTags() {
    $tags = array_values($this->validTags);
    // Let's explode and implode to our heart's content.
    for ($i = 0; $i < 10; $i++) {
      $string = drupal_implode_tags($tags);
      $tags = drupal_explode_tags($string);
    }
    $this->assertTags($tags);
  }

  /**
   * Helper function: asserts that the ending array of tags is what we wanted.
   */
  function assertTags($tags) {
    $original = $this->validTags;
    foreach ($tags as $tag) {
      $key = array_search($tag, $original);
374
      $this->assertTrue($key, t('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
375 376 377
      unset($original[$key]);
    }
    foreach ($original as $leftover) {
378
      $this->fail(t('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
379 380
    }
  }
381 382
}

383 384 385 386
/**
 * Test the Drupal CSS system.
 */
class CascadingStylesheetsTestCase extends DrupalWebTestCase {
387
  public static function getInfo() {
388
    return array(
389 390 391
      'name' => 'Cascading stylesheets',
      'description' => 'Tests adding various cascading stylesheets to the page.',
      'group' => 'System',
392 393 394 395
    );
  }

  function setUp() {
396
    parent::setUp('php', 'locale');
397
    // Reset drupal_add_css() before each test.
398
    drupal_static_reset('drupal_add_css');
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
  }

  /**
   * Check default stylesheets as empty.
   */
  function testDefault() {
    $this->assertEqual(array(), drupal_add_css(), t('Default CSS is empty.'));
  }

  /**
   * Tests adding a file stylesheet.
   */
  function testAddFile() {
    $path = drupal_get_path('module', 'simpletest') . '/simpletest.css';
    $css = drupal_add_css($path);
414
    $this->assertEqual($css[$path]['data'], $path, t('Adding a CSS file caches it properly.'));
415 416
  }

417 418 419 420 421 422 423 424 425
  /**
   * Tests adding an external stylesheet.
   */
  function testAddExternal() {
    $path = 'http://example.com/style.css';
    $css = drupal_add_css($path, 'external');
    $this->assertEqual($css[$path]['type'], 'external', t('Adding an external CSS file caches it properly.'));
  }

426 427 428 429
  /**
   * Makes sure that reseting the CSS empties the cache.
   */
  function testReset() {
430
    drupal_static_reset('drupal_add_css');
431 432 433
    $this->assertEqual(array(), drupal_add_css(), t('Resetting the CSS empties the cache.'));
  }

434 435 436 437 438 439
  /**
   * Tests rendering the stylesheets.
   */
  function testRenderFile() {
    $css = drupal_get_path('module', 'simpletest') . '/simpletest.css';
    drupal_add_css($css);
440 441 442 443 444 445 446 447 448 449 450 451
    $styles = drupal_get_css();
    $this->assertTrue(strpos($styles, $css) > 0, t('Rendered CSS includes the added stylesheet.'));
  }

  /**
   * Tests rendering an external stylesheet.
   */
  function testRenderExternal() {
    $css = 'http://example.com/style.css';
    drupal_add_css($css, 'external');
    $styles = drupal_get_css();
    $this->assertTrue(strpos($styles, 'href="' . $css) > 0, t('Rendering an external CSS file.'));
452
  }
453 454 455 456 457 458 459 460

  /**
   * Tests rendering inline stylesheets with preprocessing on.
   */
  function testRenderInlinePreprocess() {
    $css = 'body { padding: 0px; }';
    $css_preprocessed = '<style type="text/css">' . drupal_load_stylesheet_content($css, TRUE) . '</style>';
    drupal_add_css($css, 'inline');
461 462
    $styles = drupal_get_css();
    $this->assertEqual($styles, "\n" . $css_preprocessed, t('Rendering preprocessed inline CSS adds it to the page.'));
463 464 465 466 467 468 469 470
  }

  /**
   * Tests rendering inline stylesheets with preprocessing off.
   */
  function testRenderInlineNoPreprocess() {
    $css = 'body { padding: 0px; }';
    drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
471 472
    $styles = drupal_get_css();
    $this->assertTrue(strpos($styles, $css) > 0, t('Rendering non-preprocessed inline CSS adds it to the page.'));
473 474 475 476 477 478
  }

  /**
   * Tests rendering inline stylesheets through a full page request.
   */
  function testRenderInlineFullPage() {
479 480
    $css = 'body { font-size: 254px; }';
    $expected = 'font-size:254px;';
481 482 483 484

    // Create a node, using the PHP filter that tests drupal_add_css().
    $settings = array(
      'type' => 'page',
485 486 487 488 489 490 491 492 493 494 495
      'body' => array(
        FIELD_LANGUAGE_NONE => array(
          array(
            'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
            // The "PHP code" format is always the most recent one added, since
            // the PHP module was enabled in the setUp() method of the current
            // test.
            'format' => db_query("SELECT MAX(format) FROM {filter_format}")->fetchField(),
          ),
        ),
      ),
496 497 498 499 500 501
      'promote' => 1,
    );
    $node = $this->drupalCreateNode($settings);

    // Fetch the page.
    $this->drupalGet('node/' . $node->nid);
502
    $this->assertRaw($expected, t('Inline stylesheets appear in the full page rendering.'));
503
  }
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

  /**
   * Test CSS ordering.
   */
  function testRenderOrder() {
    // A module CSS file.
    drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
    // A few system CSS files, ordered in a strange way.
    $system_path = drupal_get_path('module', 'system');
    drupal_add_css($system_path . '/defaults.css', array('weight' => CSS_SYSTEM));
    drupal_add_css($system_path . '/system.css', array('weight' => CSS_SYSTEM - 10));
    drupal_add_css($system_path . '/system-menus.css', array('weight' => CSS_SYSTEM));

    $expected = array(
      $system_path . '/system.css',
      $system_path . '/defaults.css',
      $system_path . '/system-menus.css',
      drupal_get_path('module', 'simpletest') . '/simpletest.css',
    );

524

525
    $styles = drupal_get_css();
526
    if (preg_match_all('/href="' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
      $result = $matches[1];
    }
    else {
      $result = array();
    }

    $this->assertIdentical($result, $expected, t('The CSS files are in the expected order.'));
  }

  /**
   * Test CSS override.
   */
  function testRenderOverride() {
    drupal_add_css(drupal_get_path('module', 'system') . '/system.css');
    drupal_add_css(drupal_get_path('module', 'simpletest') . '/tests/system.css');

    // The dummy stylesheet should be the only one included.
544 545 546
    $styles = drupal_get_css();
    $this->assert(strpos($styles, drupal_get_path('module', 'simpletest') . '/tests/system.css') !== FALSE, t('The overriding CSS file is output.'));
    $this->assert(strpos($styles, drupal_get_path('module', 'system') . '/system.css') === FALSE, t('The overriden CSS file is not output.'));
547 548 549 550 551

    drupal_add_css(drupal_get_path('module', 'simpletest') . '/tests/system.css');
    drupal_add_css(drupal_get_path('module', 'system') . '/system.css');

    // The standard stylesheet should be the only one included.
552 553 554
    $styles = drupal_get_css();
    $this->assert(strpos($styles, drupal_get_path('module', 'system') . '/system.css') !== FALSE, t('The overriding CSS file is output.'));
    $this->assert(strpos($styles, drupal_get_path('module', 'simpletest') . '/tests/system.css') === FALSE, t('The overriden CSS file is not output.'));
555 556 557 558 559 560 561 562 563 564 565 566
  }

  /**
   * Tests Locale module's CSS Alter to include RTL overrides.
   */
  function testAlter() {
    // Switch the language to a right to left language and add system.css.
    global $language;
    $language->direction = LANGUAGE_RTL;
    drupal_add_css(drupal_get_path('module', 'system') . '/system.css');

    // Check to see if system-rtl.css was also added.
567 568
    $styles = drupal_get_css();
    $this->assert(strpos($styles, drupal_get_path('module', 'system') . '/system-rtl.css') !== FALSE, t('CSS is alterable as right to left overrides are added.'));
569 570 571 572

    // Change the language back to left to right.
    $language->direction = LANGUAGE_LTR;
  }
573 574
}

575 576 577 578
/**
 * Test drupal_http_request().
 */
class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
579
  public static function getInfo() {
580
    return array(
581 582 583
      'name' => 'Drupal HTTP request',
      'description' => "Performs tests on Drupal's HTTP request mechanism.",
      'group' => 'System'
584 585 586
    );
  }

587 588 589 590
  function setUp() {
    parent::setUp('system_test');
  }

591
  function testDrupalHTTPRequest() {
592
    // Parse URL schema.
593
    $missing_scheme = drupal_http_request('example.com/path');
594 595
    $this->assertEqual($missing_scheme->code, -1002, t('Returned with "-1002" error code.'));
    $this->assertEqual($missing_scheme->error, 'missing schema', t('Returned with "missing schema" error message.'));
596 597

    $unable_to_parse = drupal_http_request('http:///path');
598 599
    $this->assertEqual($unable_to_parse->code, -1001, t('Returned with "-1001" error code.'));
    $this->assertEqual($unable_to_parse->error, 'unable to parse URL', t('Returned with "unable to parse URL" error message.'));
600 601 602 603 604

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

    // Test that code and status message is returned.
    $result = drupal_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
609
    $this->assertTrue(!empty($result->protocol),  t('Result protocol is returned.'));
610 611
    $this->assertEqual($result->code, '404', t('Result code is 404'));
    $this->assertEqual($result->status_message, 'Not Found', t('Result status message is "Not Found"'));
612 613 614 615 616 617 618 619 620 621 622 623 624

    // 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).
    timer_start(__METHOD__);
    $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
    $time = timer_read(__METHOD__) / 1000;
    $this->assertTrue(1.8 < $time && $time < 5, t('Request timed out (%time seconds).', array('%time' => $time)));
    $this->assertTrue($result->error, t('An error message was returned.'));
    $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, t('Proper error code was returned.'));
625
  }
626 627 628 629 630 631

  function testDrupalHTTPRequestBasicAuth() {
    $username = $this->randomName();
    $password = $this->randomName();
    $url = url('system-test/auth', array('absolute' => TRUE));

632
    $auth = str_replace('http://', 'http://' . $username . ':' . $password . '@', $url);
633 634
    $result = drupal_http_request($auth);

635 636 637
    $this->drupalSetContent($result->data);
    $this->assertRaw($username, t('$_SERVER["PHP_AUTH_USER"] is passed correctly.'));
    $this->assertRaw($password, t('$_SERVER["PHP_AUTH_PW"] is passed correctly.'));
638 639 640
  }

  function testDrupalHTTPRequestRedirect() {
641
    $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
642
    $this->assertEqual($redirect_301->redirect_code, 301, t('drupal_http_request follows the 301 redirect.'));
643

644 645
    $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 0));
    $this->assertFalse(isset($redirect_301->redirect_code), t('drupal_http_request does not follow 301 redirect if max_redirects = 0.'));
646

647
    $redirect_invalid = drupal_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
648 649
    $this->assertEqual($redirect_invalid->code, -1002, t('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
    $this->assertEqual($redirect_invalid->error, 'missing schema', t('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
650

651
    $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
652 653
    $this->assertEqual($redirect_invalid->code, -1001, t('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
    $this->assertEqual($redirect_invalid->error, 'unable to parse URL', t('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
654

655
    $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
656 657
    $this->assertEqual($redirect_invalid->code, -1003, t('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
    $this->assertEqual($redirect_invalid->error, 'invalid schema ftp', t('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
658

659
    $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 1));
660
    $this->assertEqual($redirect_302->redirect_code, 302, t('drupal_http_request follows the 302 redirect.'));
661

662
    $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 0));
663 664
    $this->assertFalse(isset($redirect_302->redirect_code), t('drupal_http_request does not follow 302 redirect if $retry = 0.'));

665
    $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 1));
666
    $this->assertEqual($redirect_307->redirect_code, 307, t('drupal_http_request follows the 307 redirect.'));
667

668 669
    $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
    $this->assertFalse(isset($redirect_307->redirect_code), t('drupal_http_request does not follow 307 redirect if max_redirects = 0.'));
670 671 672 673
  }

  function testDrupalGetDestination() {
    $query = $this->randomName(10);
674 675 676 677 678 679 680 681 682

    // Verify that a 'destination' query string is used as destination.
    $this->drupalGet('system-test/destination', array('query' => array('destination' => $query)));
    $this->assertText('The destination: ' . $query, t('The given query string destination is determined as destination.'));

    // Verify that the current path is used as destination.
    $this->drupalGet('system-test/destination', array('query' => array($query => NULL)));
    $url = 'system-test/destination?' . $query;
    $this->assertText('The destination: ' . $url, t('The current path is determined as destination.'));
683
  }
684
}
685 686

/**
687
 * Testing drupal_add_region_content and drupal_get_region_content.
688 689
 */
class DrupalSetContentTestCase extends DrupalWebTestCase {
690
  public static function getInfo() {
691
    return array(
692 693 694
      'name' => 'Drupal set/get regions',
      'description' => 'Performs tests on setting and retrieiving content from theme regions.',
      'group' => 'System'
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    );
  }


  /**
   * Test setting and retrieving content for theme regions.
   */
  function testRegions() {
    global $theme_key;

    $block_regions = array_keys(system_region_list($theme_key));
    $delimiter = $this->randomName(32);
    $values = array();
    // Set some random content for each region available.
    foreach ($block_regions as $region) {
      $first_chunk = $this->randomName(32);
711
      drupal_add_region_content($region, $first_chunk);
712
      $second_chunk = $this->randomName(32);
713 714
      drupal_add_region_content($region, $second_chunk);
      // Store the expected result for a drupal_get_region_content call for this region.
715 716 717
      $values[$region] = $first_chunk . $delimiter . $second_chunk;
    }

718 719
    // Ensure drupal_get_region_content returns expected results when fetching all regions.
    $content = drupal_get_region_content(NULL, $delimiter);
720 721 722 723
    foreach ($content as $region => $region_content) {
      $this->assertEqual($region_content, $values[$region], t('@region region text verified when fetching all regions', array('@region' => $region)));
    }

724
    // Ensure drupal_get_region_content returns expected results when fetching a single region.
725
    foreach ($block_regions as $region) {
726
      $region_content = drupal_get_region_content($region, $delimiter);
727 728 729 730
      $this->assertEqual($region_content, $values[$region], t('@region region text verified when fetching single region.', array('@region' => $region)));
    }
  }
}
731

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
/**
 * Testing drupal_goto and hook_drupal_goto_alter().
 */
class DrupalGotoTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Drupal goto',
      'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
      'group' => 'System'
    );
  }

  function setUp() {
    parent::setUp('common_test');
  }

  /**
   * Test setting and retrieving content for theme regions.
   */
  function testDrupalGoto() {
    $this->drupalGet('common-test/drupal_goto/redirect');

    $this->assertNoText(t("Drupal goto failed to stop program"), t("Drupal goto stopped program."));
    $this->assertText('drupal_goto', t("Drupal goto redirect failed."));
  }

  /**
   * Test setting and retrieving content for theme regions.
   */
  function testDrupalGotoAlter() {
    $this->drupalGet('common-test/drupal_goto/redirect_fail');

    $this->assertNoText(t("Drupal goto failed to stop program"), t("Drupal goto stopped program."));
    $this->assertNoText('drupal_goto_fail', t("Drupal goto redirect failed."));
  }
}

769 770 771 772
/**
 * Tests for the JavaScript system.
 */
class JavaScriptTestCase extends DrupalWebTestCase {
773 774 775
  /**
   * Store configured value for JavaScript preprocessing.
   */
776
  protected $preprocess_js = NULL;
777

778
  public static function getInfo() {
779
    return array(
780 781 782
      'name' => 'JavaScript',
      'description' => 'Tests the JavaScript system.',
      'group' => 'System'
783 784
    );
  }
785

786
  function setUp() {
787
    // Enable Locale and SimpleTest in the test environment.
788
    parent::setUp('locale', 'simpletest', 'common_test');
789 790 791 792 793

    // Disable preprocessing
    $this->preprocess_js = variable_get('preprocess_js', 0);
    variable_set('preprocess_js', 0);

794
    // Reset drupal_add_js() and drupal_add_library() statics before each test.
795
    drupal_static_reset('drupal_add_js');
796
    drupal_static_reset('drupal_add_library');
797
  }
798 799 800 801 802 803 804

  function tearDown() {
    // Restore configured value for JavaScript preprocessing.
    variable_set('preprocess_js', $this->preprocess_js);
    parent::tearDown();
  }

805 806 807 808 809 810
  /**
   * Test default JavaScript is empty.
   */
  function testDefault() {
    $this->assertEqual(array(), drupal_add_js(), t('Default JavaScript is empty.'));
  }
811

812 813 814 815
  /**
   * Test adding a JavaScript file.
   */
  function testAddFile() {
816 817 818 819 820
    $javascript = drupal_add_js('misc/collapse.js');
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), t('jQuery is added when a file is added.'));
    $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), t('Drupal.js is added when file is added.'));
    $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), t('JavaScript files are correctly added.'));
    $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], t('Base path JavaScript setting is correctly set.'));
821
  }
822

823 824 825 826
  /**
   * Test adding settings.
   */
  function testAddSetting() {
827 828 829
    $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
    $this->assertEqual(280342800, $javascript['settings']['data'][1]['dries'], t('JavaScript setting is set correctly.'));
    $this->assertEqual('rocks', $javascript['settings']['data'][1]['drupal'], t('The other JavaScript setting is set correctly.'));
830
  }
831

832 833 834 835 836 837 838 839 840
  /**
   * Tests adding an external JavaScript File.
   */
  function testAddExternal() {
    $path = 'http://example.com/script.js';
    $javascript = drupal_add_js($path, 'external');
    $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), t('Added an external JavaScript file.'));
  }

841 842 843 844 845 846 847 848 849 850
  /**
   * Test drupal_get_js() for JavaScript settings.
   */
  function testHeaderSetting() {
    drupal_add_js(array('testSetting' => 'testValue'), 'setting');
    $javascript = drupal_get_js('header');
    $this->assertTrue(strpos($javascript, 'basePath') > 0, t('Rendered JavaScript header returns basePath setting.'));
    $this->assertTrue(strpos($javascript, 'testSetting') > 0, t('Rendered JavaScript header returns custom setting.'));
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, t('Rendered JavaScript header includes jQuery.'));
  }
851

852 853 854 855 856
  /**
   * Test to see if resetting the JavaScript empties the cache.
   */
  function testReset() {
    drupal_add_js('misc/collapse.js');
857
    drupal_static_reset('drupal_add_js');
858 859
    $this->assertEqual(array(), drupal_add_js(), t('Resetting the JavaScript correctly empties the cache.'));
  }
860

861 862 863 864
  /**
   * Test adding inline scripts.
   */
  function testAddInline() {
865
    $inline = 'jQuery(function () { });';
866 867 868 869
    $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), t('jQuery is added when inline scripts are added.'));
    $data = end($javascript);
    $this->assertEqual($inline, $data['data'], t('Inline JavaScript is correctly added to the footer.'));
870
  }
871

872 873 874 875 876 877 878 879 880 881 882
  /**
   * Test rendering an external JavaScript file.
   */
  function testRenderExternal() {
    $external = 'http://example.com/example.js';
    drupal_add_js($external, 'external');
    $javascript = drupal_get_js();
    // Local files have a base_path() prefix, external files should not.
    $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, t('Rendering an external JavaScript file.'));
  }

883 884 885 886
  /**
   * Test drupal_get_js() with a footer scope.
   */
  function testFooterHTML() {
887
    $inline = 'jQuery(function () { });';
888 889 890 891
    drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
    $javascript = drupal_get_js('footer');
    $this->assertTrue(strpos($javascript, $inline) > 0, t('Rendered JavaScript footer returns the inline code.'));
  }
892

893 894 895 896
  /**
   * Test drupal_add_js() sets preproccess to false when cache is set to false.
   */
  function testNoCache() {
897 898 899 900 901 902 903 904 905 906 907 908
    $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
    $this->assertFalse($javascript['misc/collapse.js']['preprocess'], t('Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.'));
  }

  /**
   * Test adding a JavaScript file with a different weight.
   */
  function testDifferentWeight() {
    $javascript = drupal_add_js('misc/collapse.js', array('weight' => JS_THEME));
    $this->assertEqual($javascript['misc/collapse.js']['weight'], JS_THEME, t('Adding a JavaScript file with a different weight caches the given weight.'));
  }

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
  /**
   * Test JavaScript ordering.
   */
  function testRenderOrder() {
    // Add a bunch of JavaScript in strange ordering.
    drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
    drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
    drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
    drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
    drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
    drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
    drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
    drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
    drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));

    // Construct the expected result from the regex.
    $expected = array(
      "-8 #1",
      "-8 #2",
      "-8 #3",
      "-8 #4",
      "0 #1",
      "0 #2",
      "0 #3",
      "5 #1",
      "5 #2",
    );

    // Retrieve the rendered JavaScript and test against the regex.
    $js = drupal_get_js('footer');
    $matches = array();
    if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
      $result = $matches[1];
    }
    else {
      $result = array();
    }
    $this->assertIdentical($result, $expected, t('JavaScript is added in the expected weight order.'));
  }

949 950 951 952
  /**
   * Test rendering the JavaScript with a file's weight above jQuery's.
   */
  function testRenderDifferentWeight() {
953
    drupal_add_js('misc/collapse.js', array('weight' => JS_LIBRARY - 21));
954 955
    $javascript = drupal_get_js();
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), t('Rendering a JavaScript file above jQuery.'));
956
  }
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973

  /**
   * Test altering a JavaScript's weight via hook_js_alter().
   *
   * @see simpletest_js_alter()
   */
  function testAlter() {
    // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
    drupal_add_js('misc/tableselect.js');
    drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => JS_THEME));

    // Render the JavaScript, testing if simpletest.js was altered to be before
    // tableselect.js. See simpletest_js_alter() to see where this alteration
    // takes place.
    $javascript = drupal_get_js();
    $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), t('Altering JavaScript weight through the alter hook.'));
  }
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

  /**
   * Adds a library to the page and tests for both its JavaScript and its CSS.
   */
  function testLibraryRender() {
    $result = drupal_add_library('system', 'farbtastic');
    $this->assertTrue($result !== FALSE, t('Library was added without errors.'));
    $scripts = drupal_get_js();
    $styles = drupal_get_css();
    $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), t('JavaScript of library was added to the page.'));
    $this->assertTrue(strpos($styles, 'misc/farbtastic/farbtastic.css'), t('Stylesheet of library was added to the page.'));
  }

  /**
   * Adds a JavaScript library to the page and alters it.
   *
   * @see common_test_library_alter()
   */
  function testLibraryAlter() {
    // Verify that common_test altered the title of Farbtastic.
    $library = drupal_get_library('system', 'farbtastic');
    $this->assertEqual($library['title'], 'Farbtastic: Altered Library', t('Registered libraries were altered.'));

    // common_test_library_alter() also added a dependency on jQuery Form.
    drupal_add_library('system', 'farbtastic');
    $scripts = drupal_get_js();
    $this->assertTrue(strpos($scripts, 'misc/jquery.form.js'), t('Altered library dependencies are added to the page.'));
  }

  /**
   * Tests that multiple modules can implement the same library.
   *
   * @see common_test_library()
   */
  function testLibraryNameConflicts() {
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
    $this->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', t('Alternative libraries can be added to the page.'));
  }

  /**
   * Tests non-existing libraries.
   */
  function testLibraryUnknown() {
    $result = drupal_get_library('unknown', 'unknown');
    $this->assertFalse($result, t('Unknown library returned FALSE.'));
    drupal_static_reset('drupal_get_library');

    $result = drupal_add_library('unknown', 'unknown');
    $this->assertFalse($result, t('Unknown library returned FALSE.'));
    $scripts = drupal_get_js();
    $this->assertTrue(strpos($scripts, 'unknown') === FALSE, t('Unknown library was not added to the page.'));
  }
1026 1027

  /**
1028
   * Tests the addition of libraries through the #attached['library'] property.
1029 1030
   */
  function testAttachedLibrary() {
1031
    $element['#attached']['library'][] = array('system', 'farbtastic');
1032 1033 1034 1035
    drupal_render($element);
    $scripts = drupal_get_js();
    $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), t('The attached_library property adds the additional libraries.'));
  }
1036 1037
}

1038 1039 1040 1041
/**
 * Tests for drupal_render().
 */
class DrupalRenderUnitTestCase extends DrupalWebTestCase {
1042
  public static function getInfo() {
1043
    return array(
1044 1045 1046
      'name' => 'Drupal render',
      'description' => 'Performs unit tests on drupal_render().',
      'group' => 'System',
1047 1048 1049
    );
  }

1050 1051 1052 1053
  function setUp() {
    parent::setUp('common_test');
  }

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  /**
   * Test sorting by weight.
   */
  function testDrupalRenderSorting() {
    $first = $this->randomName();
    $second = $this->randomName();
    // Build an array with '#weight' set for each element.
    $elements = array(
      'second' => array(
        '#weight' => 10,
        '#markup' => $second,
      ),
      'first' => array(
        '#weight' => 0,
        '#markup' => $first,
      ),
    );
    $output = drupal_render($elements);
1072

1073
    // The lowest weight element should appear last in $output.
1074 1075 1076 1077 1078
    $this->assertTrue(strpos($output, $second) > strpos($output, $first), t('Elements were sorted correctly by weight.'));

    // Confirm that the $elements array has '#sorted' set to TRUE.
    $this->assertTrue($elements['#sorted'], t("'#sorted' => TRUE was added to the array"));

1079 1080 1081 1082 1083 1084 1085 1086 1087
    // Pass $elements through element_children() and ensure it remains
    // sorted in the correct order. drupal_render() will return an empty string
    // if used on the same array in the same request.
    $children = element_children($elements);
    $this->assertTrue(array_shift($children) == 'first', t('Child found in the correct order.'));
    $this->assertTrue(array_shift($children) == 'second', t('Child found in the correct order.'));


    // The same array structure again, but with #sorted set to TRUE.
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    $elements = array(
      'second' => array(
        '#weight' => 10,
        '#markup' => $second,
      ),
      'first' => array(
        '#weight' => 0,
        '#markup' => $first,
      ),
      '#sorted' => TRUE,
    );
    $output = drupal_render($elements);

    // The elements should appear in output in the same order as the array.
    $this->assertTrue(strpos($output, $second) < strpos($output, $first), t('Elements were not sorted.'));
1103
  }
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

  /**
   * Test passing arguments to the theme function.
   */
  function testDrupalRenderThemeArguments() {
    $element = array(
      '#theme' => 'common_test_foo',
    );
    // Test that defaults work.
    $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
1114
    $element = array(
1115 1116 1117 1118 1119 1120 1121
      '#theme' => 'common_test_foo',
      '#foo' => $this->randomName(),
      '#bar' => $this->randomName(),
    );
    // Test that passing arguments to the theme function works.
    $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
  }
1122 1123
}

1124 1125 1126
/**
 * Test for valid_url().
 */
1127
class ValidUrlTestCase extends DrupalUnitTestCase {
1128
  public static function getInfo() {
1129
    return array(
1130 1131 1132
      'name' => 'Valid Url',
      'description' => "Performs tests on Drupal's valid url function.",
      'group' => 'System'
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    );
  }

  /**
   * Test valid absolute urls.
   */
  function testValidAbsolute() {
    $url_schemes = array('http', 'https', 'ftp');
    $valid_absolute_urls = array(
      'example.com',
      'www.example.com',
      'ex-ample.com',
      '3xampl3.com',
      'example.com/paren(the)sis',
      'example.com/index.html#pagetop',
      'example.com:8080',
      'subdomain.example.com',
      'example.com/index.php?q=node',
      'example.com/index.php?q=node&param=false',
      'user@www.example.com',
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
      '127.0.0.1',
      'example.org?',
      'john%20doe:secret:foo@example.org/',
      'example.org/~,$\'*;',
      'caf%C3%A9.example.org',
1159
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    );

    foreach ($url_schemes as $scheme) {
      foreach ($valid_absolute_urls as $url) {
        $test_url = $scheme . '://' . $url;
        $valid_url = valid_url($test_url, TRUE);
        $this->assertTrue($valid_url, t('@url is a valid url.', array('@url' => $test_url)));
      }
    }
  }

  /**
   * Test invalid absolute urls.
   */
  function testInvalidAbsolute() {
    $url_schemes = array('http', 'https', 'ftp');
    $invalid_ablosule_urls = array(
      '',
      'ex!ample.com',
1179
      'ex%ample.com',
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    );

    foreach ($url_schemes as $scheme) {
      foreach ($invalid_ablosule_urls as $url) {
        $test_url = $scheme . '://' . $url;
        $valid_url = valid_url($test_url, TRUE);
        $this->assertFalse($valid_url, t('@url is NOT a valid url.', array('@url' => $test_url)));
      }
    }
  }

  /**
   * Test valid relative urls.
   */
  function testValidRelative() {
    $valid_relative_urls = array(
      'paren(the)sis',
      'index.html#pagetop',
      'index.php?q=node',
      'index.php?q=node&param=false',
      'login.php?do=login&style=%23#pagetop',
    );

    foreach (array('', '/') as $front) {
      foreach ($valid_relative_urls as $url) {
        $test_url = $front . $url;
        $valid_url = valid_url($test_url);
1207
        $this->assertTrue($valid_url, t('@url is a valid url.', array('@url' => $test_url)));
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
      }
    }
  }

  /**
   * Test invalid relative urls.
   */
  function testInvalidRelative() {
    $invalid_relative_urls = array(
      'ex^mple',
1218 1219
      'example<>',
      'ex%ample',
1220 1221 1222 1223 1224 1225
    );

    foreach (array('', '/') as $front) {
      foreach ($invalid_relative_urls as $url) {
        $test_url = $front . $url;
        $valid_url = valid_url($test_url);
1226
        $this->assertFALSE($valid_url, t('@url is NOT a valid url.', array('@url' => $test_url)));
1227 1228 1229 1230 1231
      }
    }
  }
}

1232 1233 1234 1235
/**
 * Tests for CRUD API functions.
 */
class DrupalDataApiTest extends DrupalWebTestCase {
1236
  public static function getInfo() {
1237
    return array(
1238 1239 1240
      'name' => 'Data API functions',
      'description' => 'Tests the performance of CRUD APIs.',
      'group' => 'System',
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    );
  }

  function setUp() {
    parent::setUp('taxonomy');
  }

  /**
   * Test the drupal_write_record() API function.
   */
  function testDrupalWriteRecord() {
    // Insert an object record for a table with a single-field primary key.
1253
    $vocabulary = new stdClass();
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    $vocabulary->name = 'test';
    $insert_result = drupal_write_record('taxonomy_vocabulary', $vocabulary);
    $this->assertTrue($insert_result == SAVED_NEW, t('Correct value returned when a record is inserted with drupal_write_record() for a table with a single-field primary key.'));
    $this->assertTrue(isset($vocabulary->vid), t('Primary key is set on record created with drupal_write_record().'));

    // Update the initial record after changing a property.
    $vocabulary->name = 'testing';
    $update_result = drupal_write_record('taxonomy_vocabulary', $vocabulary, array('vid'));
    $this->assertTrue($update_result == SAVED_UPDATED, t('Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.'));

    // Insert an object record for a table with a multi-field primary key.
1265
    $vocabulary_node_type = new stdClass();
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    $vocabulary_node_type->vid = $vocabulary->vid;
    $vocabulary_node_type->type = 'page';
    $insert_result = drupal_write_record('taxonomy_vocabulary_node_type', $vocabulary_node_type);
    $this->assertTrue($insert_result == SAVED_NEW, t('Correct value returned when a record is inserted with drupal_write_record() for a table with a multi-field primary key.'));

    // Update the record.
    $update_result = drupal_write_record('taxonomy_vocabulary_node_type', $vocabulary_node_type, array('vid', 'type'));
    $this->assertTrue($update_result == SAVED_UPDATED, t('Correct value returned when a record is updated with drupal_write_record() for a table with a multi-field primary key.'));
  }

}

1278
/**
1279
 * Tests Simpletest error and exception collector.
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
 */
class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {

  /**
   * Errors triggered during the test.
   *
   * Errors are intercepted by the overriden implementation
   * of DrupalWebTestCase::error below.
   *
   * @var Array
   */
  protected $collectedErrors = array();

1293
  public static function getInfo() {
1294
    return array(
1295 1296
      'name' => 'SimpleTest error collector',
      'description' => 'Performs tests on the Simpletest error and exception collector.',
1297
      'group' => 'SimpleTest',
1298 1299 1300 1301
    );
  }

  function setUp() {
1302
    parent::setUp('system_test', 'error_test');
1303 1304 1305 1306 1307 1308 1309
  }

  /**
   * Test that simpletest collects errors from the tested site.
   */
  function testErrorCollect() {
    $this->collectedErrors = array();
1310
    $this->drupalGet('error-test/generate-warnings-with-report');