Drupal PHP Cross Reference Content Management Systems

Source: /modules/simpletest/tests/common.test - 2616 lines - 109160 bytes - Summary - Text - Print

   1  <?php
   2  
   3  /**
   4   * @file
   5   * Tests for common.inc functionality.
   6   */
   7  
   8  /**
   9   * Tests for URL generation functions.
  10   */
  11  class DrupalAlterTestCase extends DrupalWebTestCase {
  12    public static function getInfo() {
  13      return array(
  14        'name' => 'drupal_alter() tests',
  15        'description' => 'Confirm that alteration of arguments passed to drupal_alter() works correctly.',
  16        'group' => 'System',
  17      );
  18    }
  19  
  20    function setUp() {
  21      parent::setUp('common_test');
  22    }
  23  
  24    function testDrupalAlter() {
  25      // This test depends on Bartik, so make sure that it is always the current
  26      // active theme.
  27      global $theme, $base_theme_info;
  28      $theme = 'bartik';
  29      $base_theme_info = array();
  30  
  31      $array = array('foo' => 'bar');
  32      $entity = new stdClass();
  33      $entity->foo = 'bar';
  34  
  35      // Verify alteration of a single argument.
  36      $array_copy = $array;
  37      $array_expected = array('foo' => 'Drupal theme');
  38      drupal_alter('drupal_alter', $array_copy);
  39      $this->assertEqual($array_copy, $array_expected, t('Single array was altered.'));
  40  
  41      $entity_copy = clone $entity;
  42      $entity_expected = clone $entity;
  43      $entity_expected->foo = 'Drupal theme';
  44      drupal_alter('drupal_alter', $entity_copy);
  45      $this->assertEqual($entity_copy, $entity_expected, t('Single object was altered.'));
  46  
  47      // Verify alteration of multiple arguments.
  48      $array_copy = $array;
  49      $array_expected = array('foo' => 'Drupal theme');
  50      $entity_copy = clone $entity;
  51      $entity_expected = clone $entity;
  52      $entity_expected->foo = 'Drupal theme';
  53      $array2_copy = $array;
  54      $array2_expected = array('foo' => 'Drupal theme');
  55      drupal_alter('drupal_alter', $array_copy, $entity_copy, $array2_copy);
  56      $this->assertEqual($array_copy, $array_expected, t('First argument to drupal_alter() was altered.'));
  57      $this->assertEqual($entity_copy, $entity_expected, t('Second argument to drupal_alter() was altered.'));
  58      $this->assertEqual($array2_copy, $array2_expected, t('Third argument to drupal_alter() was altered.'));
  59  
  60      // Verify alteration order when passing an array of types to drupal_alter().
  61      // common_test_module_implements_alter() places 'block' implementation after
  62      // other modules.
  63      $array_copy = $array;
  64      $array_expected = array('foo' => 'Drupal block theme');
  65      drupal_alter(array('drupal_alter', 'drupal_alter_foo'), $array_copy);
  66      $this->assertEqual($array_copy, $array_expected, t('hook_TYPE_alter() implementations ran in correct order.'));
  67    }
  68  }
  69  
  70  /**
  71   * Tests for URL generation functions.
  72   *
  73   * url() calls module_implements(), which may issue a db query, which requires
  74   * inheriting from a web test case rather than a unit test case.
  75   */
  76  class CommonURLUnitTest extends DrupalWebTestCase {
  77    public static function getInfo() {
  78      return array(
  79        'name' => 'URL generation tests',
  80        'description' => 'Confirm that url(), drupal_get_query_parameters(), drupal_http_build_query(), and l() work correctly with various input.',
  81        'group' => 'System',
  82      );
  83    }
  84  
  85    /**
  86     * Confirm that invalid text given as $path is filtered.
  87     */
  88    function testLXSS() {
  89      $text = $this->randomName();
  90      $path = "<SCRIPT>alert('XSS')</SCRIPT>";
  91      $link = l($text, $path);
  92      $sanitized_path = check_url(url($path));
  93      $this->assertTrue(strpos($link, $sanitized_path) !== FALSE, t('XSS attack @path was filtered', array('@path' => $path)));
  94    }
  95  
  96    /*
  97     * Tests for active class in l() function.
  98     */
  99    function testLActiveClass() {
 100      $link = l($this->randomName(), $_GET['q']);
 101      $this->assertTrue($this->hasClass($link, 'active'), t('Class @class is present on link to the current page', array('@class' => 'active')));
 102    }
 103  
 104    /**
 105     * Tests for custom class in l() function.
 106     */
 107    function testLCustomClass() {
 108      $class = $this->randomName();
 109      $link = l($this->randomName(), $_GET['q'], array('attributes' => array('class' => array($class))));
 110      $this->assertTrue($this->hasClass($link, $class), t('Custom class @class is present on link when requested', array('@class' => $class)));
 111      $this->assertTrue($this->hasClass($link, 'active'), t('Class @class is present on link to the current page', array('@class' => 'active')));
 112    }
 113  
 114    private function hasClass($link, $class) {
 115      return preg_match('|class="([^\"\s]+\s+)*' . $class . '|', $link);
 116    }
 117  
 118    /**
 119     * Test drupal_get_query_parameters().
 120     */
 121    function testDrupalGetQueryParameters() {
 122      $original = array(
 123        'a' => 1,
 124        'b' => array(
 125          'd' => 4,
 126          'e' => array(
 127            'f' => 5,
 128          ),
 129        ),
 130        'c' => 3,
 131        'q' => 'foo/bar',
 132      );
 133  
 134      // Default arguments.
 135      $result = $_GET;
 136      unset($result['q']);
 137      $this->assertEqual(drupal_get_query_parameters(), $result, t("\$_GET['q'] was removed."));
 138  
 139      // Default exclusion.
 140      $result = $original;
 141      unset($result['q']);
 142      $this->assertEqual(drupal_get_query_parameters($original), $result, t("'q' was removed."));
 143  
 144      // First-level exclusion.
 145      $result = $original;
 146      unset($result['b']);
 147      $this->assertEqual(drupal_get_query_parameters($original, array('b')), $result, t("'b' was removed."));
 148  
 149      // Second-level exclusion.
 150      $result = $original;
 151      unset($result['b']['d']);
 152      $this->assertEqual(drupal_get_query_parameters($original, array('b[d]')), $result, t("'b[d]' was removed."));
 153  
 154      // Third-level exclusion.
 155      $result = $original;
 156      unset($result['b']['e']['f']);
 157      $this->assertEqual(drupal_get_query_parameters($original, array('b[e][f]')), $result, t("'b[e][f]' was removed."));
 158  
 159      // Multiple exclusions.
 160      $result = $original;
 161      unset($result['a'], $result['b']['e'], $result['c']);
 162      $this->assertEqual(drupal_get_query_parameters($original, array('a', 'b[e]', 'c')), $result, t("'a', 'b[e]', 'c' were removed."));
 163    }
 164  
 165    /**
 166     * Test drupal_http_build_query().
 167     */
 168    function testDrupalHttpBuildQuery() {
 169      $this->assertEqual(drupal_http_build_query(array('a' => ' &#//+%20@۞')), 'a=%20%26%23//%2B%2520%40%DB%9E', t('Value was properly encoded.'));
 170      $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.'));
 171      $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.'));
 172      $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.'));
 173    }
 174  
 175    /**
 176     * Test drupal_parse_url().
 177     */
 178    function testDrupalParseUrl() {
 179      // Relative URL.
 180      $url = 'foo/bar?foo=bar&bar=baz&baz#foo';
 181      $result = array(
 182        'path' => 'foo/bar',
 183        'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
 184        'fragment' => 'foo',
 185      );
 186      $this->assertEqual(drupal_parse_url($url), $result, t('Relative URL parsed correctly.'));
 187  
 188      // Relative URL that is known to confuse parse_url().
 189      $url = 'foo/bar:1';
 190      $result = array(
 191        'path' => 'foo/bar:1',
 192        'query' => array(),
 193        'fragment' => '',
 194      );
 195      $this->assertEqual(drupal_parse_url($url), $result, t('Relative URL parsed correctly.'));
 196  
 197      // Absolute URL.
 198      $url = '/foo/bar?foo=bar&bar=baz&baz#foo';
 199      $result = array(
 200        'path' => '/foo/bar',
 201        'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
 202        'fragment' => 'foo',
 203      );
 204      $this->assertEqual(drupal_parse_url($url), $result, t('Absolute URL parsed correctly.'));
 205  
 206      // External URL testing.
 207      $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
 208  
 209      // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
 210      $this->assertTrue(url_is_external($url), t('Correctly identified an external URL.'));
 211  
 212      // Test the parsing of absolute URLs.
 213      $result = array(
 214        'path' => 'http://drupal.org/foo/bar',
 215        'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
 216        'fragment' => 'foo',
 217      );
 218      $this->assertEqual(drupal_parse_url($url), $result, t('External URL parsed correctly.'));
 219  
 220      // Verify proper parsing of URLs when clean URLs are disabled.
 221      $result = array(
 222        'path' => 'foo/bar',
 223        'query' => array('bar' => 'baz'),
 224        'fragment' => 'foo',
 225      );
 226      // Non-clean URLs #1: Absolute URL generated by url().
 227      $url = $GLOBALS['base_url'] . '/?q=foo/bar&bar=baz#foo';
 228      $this->assertEqual(drupal_parse_url($url), $result, t('Absolute URL with clean URLs disabled parsed correctly.'));
 229  
 230      // Non-clean URLs #2: Relative URL generated by url().
 231      $url = '?q=foo/bar&bar=baz#foo';
 232      $this->assertEqual(drupal_parse_url($url), $result, t('Relative URL with clean URLs disabled parsed correctly.'));
 233  
 234      // Non-clean URLs #3: URL generated by url() on non-Apache webserver.
 235      $url = 'index.php?q=foo/bar&bar=baz#foo';
 236      $this->assertEqual(drupal_parse_url($url), $result, t('Relative URL on non-Apache webserver with clean URLs disabled parsed correctly.'));
 237  
 238      // Test that drupal_parse_url() does not allow spoofing a URL to force a malicious redirect.
 239      $parts = drupal_parse_url('forged:http://cwe.mitre.org/data/definitions/601.html');
 240      $this->assertFalse(valid_url($parts['path'], TRUE), t('drupal_parse_url() correctly parsed a forged URL.'));
 241    }
 242  
 243    /**
 244     * Test url() with/without query, with/without fragment, absolute on/off and
 245     * assert all that works when clean URLs are on and off.
 246     */
 247    function testUrl() {
 248      global $base_url;
 249  
 250      foreach (array(FALSE, TRUE) as $absolute) {
 251        // Get the expected start of the path string.
 252        $base = $absolute ? $base_url . '/' : base_path();
 253        $absolute_string = $absolute ? 'absolute' : NULL;
 254  
 255        // Disable Clean URLs.
 256        $GLOBALS['conf']['clean_url'] = 0;
 257  
 258        $url = $base . '?q=node/123';
 259        $result = url('node/123', array('absolute' => $absolute));
 260        $this->assertEqual($url, $result, "$url == $result");
 261  
 262        $url = $base . '?q=node/123#foo';
 263        $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
 264        $this->assertEqual($url, $result, "$url == $result");
 265  
 266        $url = $base . '?q=node/123&foo';
 267        $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
 268        $this->assertEqual($url, $result, "$url == $result");
 269  
 270        $url = $base . '?q=node/123&foo=bar&bar=baz';
 271        $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
 272        $this->assertEqual($url, $result, "$url == $result");
 273  
 274        $url = $base . '?q=node/123&foo#bar';
 275        $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
 276        $this->assertEqual($url, $result, "$url == $result");
 277  
 278        $url = $base . '?q=node/123&foo#0';
 279        $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => '0', 'absolute' => $absolute));
 280        $this->assertEqual($url, $result, "$url == $result");
 281  
 282        $url = $base . '?q=node/123&foo';
 283        $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => '', 'absolute' => $absolute));
 284        $this->assertEqual($url, $result, "$url == $result");
 285  
 286        $url = $base;
 287        $result = url('<front>', array('absolute' => $absolute));
 288        $this->assertEqual($url, $result, "$url == $result");
 289  
 290        // Enable Clean URLs.
 291        $GLOBALS['conf']['clean_url'] = 1;
 292  
 293        $url = $base . 'node/123';
 294        $result = url('node/123', array('absolute' => $absolute));
 295        $this->assertEqual($url, $result, "$url == $result");
 296  
 297        $url = $base . 'node/123#foo';
 298        $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
 299        $this->assertEqual($url, $result, "$url == $result");
 300  
 301        $url = $base . 'node/123?foo';
 302        $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
 303        $this->assertEqual($url, $result, "$url == $result");
 304  
 305        $url = $base . 'node/123?foo=bar&bar=baz';
 306        $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
 307        $this->assertEqual($url, $result, "$url == $result");
 308  
 309        $url = $base . 'node/123?foo#bar';
 310        $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
 311        $this->assertEqual($url, $result, "$url == $result");
 312  
 313        $url = $base;
 314        $result = url('<front>', array('absolute' => $absolute));
 315        $this->assertEqual($url, $result, "$url == $result");
 316      }
 317    }
 318  
 319    /**
 320     * Test external URL handling.
 321     */
 322    function testExternalUrls() {
 323      $test_url = 'http://drupal.org/';
 324  
 325      // Verify external URL can contain a fragment.
 326      $url = $test_url . '#drupal';
 327      $result = url($url);
 328      $this->assertEqual($url, $result, t('External URL with fragment works without a fragment in $options.'));
 329  
 330      // Verify fragment can be overidden in an external URL.
 331      $url = $test_url . '#drupal';
 332      $fragment = $this->randomName(10);
 333      $result = url($url, array('fragment' => $fragment));
 334      $this->assertEqual($test_url . '#' . $fragment, $result, t('External URL fragment is overidden with a custom fragment in $options.'));
 335  
 336      // Verify external URL can contain a query string.
 337      $url = $test_url . '?drupal=awesome';
 338      $result = url($url);
 339      $this->assertEqual($url, $result, t('External URL with query string works without a query string in $options.'));
 340  
 341      // Verify external URL can be extended with a query string.
 342      $url = $test_url;
 343      $query = array($this->randomName(5) => $this->randomName(5));
 344      $result = url($url, array('query' => $query));
 345      $this->assertEqual($url . '?' . http_build_query($query, '', '&'), $result, t('External URL can be extended with a query string in $options.'));
 346  
 347      // Verify query string can be extended in an external URL.
 348      $url = $test_url . '?drupal=awesome';
 349      $query = array($this->randomName(5) => $this->randomName(5));
 350      $result = url($url, array('query' => $query));
 351      $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result, t('External URL query string can be extended with a custom query string in $options.'));
 352    }
 353  }
 354  
 355  /**
 356   * Tests for check_plain(), filter_xss(), format_string(), and check_url().
 357   */
 358  class CommonXssUnitTest extends DrupalUnitTestCase {
 359  
 360    public static function getInfo() {
 361      return array(
 362        'name' => 'String filtering tests',
 363        'description' => 'Confirm that check_plain(), filter_xss(), format_string() and check_url() work correctly, including invalid multi-byte sequences.',
 364        'group' => 'System',
 365      );
 366    }
 367  
 368    /**
 369     * Check that invalid multi-byte sequences are rejected.
 370     */
 371    function testInvalidMultiByte() {
 372       // Ignore PHP 5.3+ invalid multibyte sequence warning.
 373       $text = @check_plain("Foo\xC0barbaz");
 374       $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "Foo\xC0barbaz"');
 375       // Ignore PHP 5.3+ invalid multibyte sequence warning.
 376       $text = @check_plain("\xc2\"");
 377       $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "\xc2\""');
 378       $text = check_plain("Fooÿñ");
 379       $this->assertEqual($text, "Fooÿñ", 'check_plain() accepts valid sequence "Fooÿñ"');
 380       $text = filter_xss("Foo\xC0barbaz");
 381       $this->assertEqual($text, '', 'filter_xss() rejects invalid sequence "Foo\xC0barbaz"');
 382       $text = filter_xss("Fooÿñ");
 383       $this->assertEqual($text, "Fooÿñ", 'filter_xss() accepts valid sequence Fooÿñ');
 384    }
 385  
 386    /**
 387     * Check that special characters are escaped.
 388     */
 389    function testEscaping() {
 390       $text = check_plain("<script>");
 391       $this->assertEqual($text, '&lt;script&gt;', 'check_plain() escapes &lt;script&gt;');
 392       $text = check_plain('<>&"\'');
 393       $this->assertEqual($text, '&lt;&gt;&amp;&quot;&#039;', 'check_plain() escapes reserved HTML characters.');
 394    }
 395  
 396    /**
 397     * Test t() and format_string() replacement functionality.
 398     */
 399    function testFormatStringAndT() {
 400      foreach (array('format_string', 't') as $function) {
 401        $text = $function('Simple text');
 402        $this->assertEqual($text, 'Simple text', $function . ' leaves simple text alone.');
 403        $text = $function('Escaped text: @value', array('@value' => '<script>'));
 404        $this->assertEqual($text, 'Escaped text: &lt;script&gt;', $function . ' replaces and escapes string.');
 405        $text = $function('Placeholder text: %value', array('%value' => '<script>'));
 406        $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', $function . ' replaces, escapes and themes string.');
 407        $text = $function('Verbatim text: !value', array('!value' => '<script>'));
 408        $this->assertEqual($text, 'Verbatim text: <script>', $function . ' replaces verbatim string as-is.');
 409      }
 410    }
 411  
 412    /**
 413     * Check that harmful protocols are stripped.
 414     */
 415    function testBadProtocolStripping() {
 416      // Ensure that check_url() strips out harmful protocols, and encodes for
 417      // HTML. Ensure drupal_strip_dangerous_protocols() can be used to return a
 418      // plain-text string stripped of harmful protocols.
 419      $url = 'javascript:http://www.example.com/?x=1&y=2';
 420      $expected_plain = 'http://www.example.com/?x=1&y=2';
 421      $expected_html = 'http://www.example.com/?x=1&amp;y=2';
 422      $this->assertIdentical(check_url($url), $expected_html, t('check_url() filters a URL and encodes it for HTML.'));
 423      $this->assertIdentical(drupal_strip_dangerous_protocols($url), $expected_plain, t('drupal_strip_dangerous_protocols() filters a URL and returns plain text.'));
 424    }
 425  }
 426  
 427  /**
 428   * Tests file size parsing and formatting functions.
 429   */
 430  class CommonSizeTestCase extends DrupalUnitTestCase {
 431    protected $exact_test_cases;
 432    protected $rounded_test_cases;
 433  
 434    public static function getInfo() {
 435      return array(
 436        'name' => 'Size parsing test',
 437        'description' => 'Parse a predefined amount of bytes and compare the output with the expected value.',
 438        'group' => 'System'
 439      );
 440    }
 441  
 442    function setUp() {
 443      $kb = DRUPAL_KILOBYTE;
 444      $this->exact_test_cases = array(
 445        '1 byte' => 1,
 446        '1 KB'   => $kb,
 447        '1 MB'   => $kb * $kb,
 448        '1 GB'   => $kb * $kb * $kb,
 449        '1 TB'   => $kb * $kb * $kb * $kb,
 450        '1 PB'   => $kb * $kb * $kb * $kb * $kb,
 451        '1 EB'   => $kb * $kb * $kb * $kb * $kb * $kb,
 452        '1 ZB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
 453        '1 YB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
 454      );
 455      $this->rounded_test_cases = array(
 456        '2 bytes' => 2,
 457        '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
 458        round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651, // megabytes
 459        round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
 460        round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
 461      );
 462      parent::setUp();
 463    }
 464  
 465    /**
 466     * Check that format_size() returns the expected string.
 467     */
 468    function testCommonFormatSize() {
 469      foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
 470        foreach ($test_cases as $expected => $input) {
 471          $this->assertEqual(
 472            ($result = format_size($input, NULL)),
 473            $expected,
 474            $expected . ' == ' . $result . ' (' . $input . ' bytes)'
 475          );
 476        }
 477      }
 478    }
 479  
 480    /**
 481     * Check that parse_size() returns the proper byte sizes.
 482     */
 483    function testCommonParseSize() {
 484      foreach ($this->exact_test_cases as $string => $size) {
 485        $this->assertEqual(
 486          $parsed_size = parse_size($string),
 487          $size,
 488          $size . ' == ' . $parsed_size . ' (' . $string . ')'
 489        );
 490      }
 491  
 492      // Some custom parsing tests
 493      $string = '23476892 bytes';
 494      $this->assertEqual(
 495        ($parsed_size = parse_size($string)),
 496        $size = 23476892,
 497        $string . ' == ' . $parsed_size . ' bytes'
 498      );
 499      $string = '76MRandomStringThatShouldBeIgnoredByParseSize.'; // 76 MB
 500      $this->assertEqual(
 501        $parsed_size = parse_size($string),
 502        $size = 79691776,
 503        $string . ' == ' . $parsed_size . ' bytes'
 504      );
 505      $string = '76.24 Giggabyte'; // Misspeld text -> 76.24 GB
 506      $this->assertEqual(
 507        $parsed_size = parse_size($string),
 508        $size = 81862076662,
 509        $string . ' == ' . $parsed_size . ' bytes'
 510      );
 511    }
 512  
 513    /**
 514     * Cross-test parse_size() and format_size().
 515     */
 516    function testCommonParseSizeFormatSize() {
 517      foreach ($this->exact_test_cases as $size) {
 518        $this->assertEqual(
 519          $size,
 520          ($parsed_size = parse_size($string = format_size($size, NULL))),
 521          $size . ' == ' . $parsed_size . ' (' . $string . ')'
 522        );
 523      }
 524    }
 525  }
 526  
 527  /**
 528   * Test drupal_explode_tags() and drupal_implode_tags().
 529   */
 530  class DrupalTagsHandlingTestCase extends DrupalUnitTestCase {
 531    var $validTags = array(
 532      'Drupal' => 'Drupal',
 533      'Drupal with some spaces' => 'Drupal with some spaces',
 534      '"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
 535      '"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
 536    );
 537  
 538    public static function getInfo() {
 539      return array(
 540        'name' => 'Drupal tags handling',
 541        'description' => "Performs tests on Drupal's handling of tags, both explosion and implosion tactics used.",
 542        'group' => 'System'
 543      );
 544    }
 545  
 546    /**
 547     * Explode a series of tags.
 548     */
 549    function testDrupalExplodeTags() {
 550      $string = implode(', ', array_keys($this->validTags));
 551      $tags = drupal_explode_tags($string);
 552      $this->assertTags($tags);
 553    }
 554  
 555    /**
 556     * Implode a series of tags.
 557     */
 558    function testDrupalImplodeTags() {
 559      $tags = array_values($this->validTags);
 560      // Let's explode and implode to our heart's content.
 561      for ($i = 0; $i < 10; $i++) {
 562        $string = drupal_implode_tags($tags);
 563        $tags = drupal_explode_tags($string);
 564      }
 565      $this->assertTags($tags);
 566    }
 567  
 568    /**
 569     * Helper function: asserts that the ending array of tags is what we wanted.
 570     */
 571    function assertTags($tags) {
 572      $original = $this->validTags;
 573      foreach ($tags as $tag) {
 574        $key = array_search($tag, $original);
 575        $this->assertTrue($key, t('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
 576        unset($original[$key]);
 577      }
 578      foreach ($original as $leftover) {
 579        $this->fail(t('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
 580      }
 581    }
 582  }
 583  
 584  /**
 585   * Test the Drupal CSS system.
 586   */
 587  class CascadingStylesheetsTestCase extends DrupalWebTestCase {
 588    public static function getInfo() {
 589      return array(
 590        'name' => 'Cascading stylesheets',
 591        'description' => 'Tests adding various cascading stylesheets to the page.',
 592        'group' => 'System',
 593      );
 594    }
 595  
 596    function setUp() {
 597      parent::setUp('php', 'locale', 'common_test');
 598      // Reset drupal_add_css() before each test.
 599      drupal_static_reset('drupal_add_css');
 600    }
 601  
 602    /**
 603     * Check default stylesheets as empty.
 604     */
 605    function testDefault() {
 606      $this->assertEqual(array(), drupal_add_css(), t('Default CSS is empty.'));
 607    }
 608  
 609    /**
 610     * Test that stylesheets in module .info files are loaded.
 611     */
 612    function testModuleInfo() {
 613      $this->drupalGet('');
 614  
 615      // Verify common_test.css in a STYLE media="all" tag.
 616      $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
 617        ':media' => 'all',
 618        ':filename' => 'tests/common_test.css',
 619      ));
 620      $this->assertTrue(count($elements), "Stylesheet with media 'all' in module .info file found.");
 621  
 622      // Verify common_test.print.css in a STYLE media="print" tag.
 623      $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
 624        ':media' => 'print',
 625        ':filename' => 'tests/common_test.print.css',
 626      ));
 627      $this->assertTrue(count($elements), "Stylesheet with media 'print' in module .info file found.");
 628    }
 629  
 630    /**
 631     * Tests adding a file stylesheet.
 632     */
 633    function testAddFile() {
 634      $path = drupal_get_path('module', 'simpletest') . '/simpletest.css';
 635      $css = drupal_add_css($path);
 636      $this->assertEqual($css[$path]['data'], $path, t('Adding a CSS file caches it properly.'));
 637    }
 638  
 639    /**
 640     * Tests adding an external stylesheet.
 641     */
 642    function testAddExternal() {
 643      $path = 'http://example.com/style.css';
 644      $css = drupal_add_css($path, 'external');
 645      $this->assertEqual($css[$path]['type'], 'external', t('Adding an external CSS file caches it properly.'));
 646    }
 647  
 648    /**
 649     * Makes sure that reseting the CSS empties the cache.
 650     */
 651    function testReset() {
 652      drupal_static_reset('drupal_add_css');
 653      $this->assertEqual(array(), drupal_add_css(), t('Resetting the CSS empties the cache.'));
 654    }
 655  
 656    /**
 657     * Tests rendering the stylesheets.
 658     */
 659    function testRenderFile() {
 660      $css = drupal_get_path('module', 'simpletest') . '/simpletest.css';
 661      drupal_add_css($css);
 662      $styles = drupal_get_css();
 663      $this->assertTrue(strpos($styles, $css) > 0, t('Rendered CSS includes the added stylesheet.'));
 664    }
 665  
 666    /**
 667     * Tests rendering an external stylesheet.
 668     */
 669    function testRenderExternal() {
 670      $css = 'http://example.com/style.css';
 671      drupal_add_css($css, 'external');
 672      $styles = drupal_get_css();
 673      // Stylesheet URL may be the href of a LINK tag or in an @import statement
 674      // of a STYLE tag.
 675      $this->assertTrue(strpos($styles, 'href="' . $css) > 0 || strpos($styles, '@import url("' . $css . '")') > 0, t('Rendering an external CSS file.'));
 676    }
 677  
 678    /**
 679     * Tests rendering inline stylesheets with preprocessing on.
 680     */
 681    function testRenderInlinePreprocess() {
 682      $css = 'body { padding: 0px; }';
 683      $css_preprocessed = '<style type="text/css" media="all">' . "\n<!--/*--><![CDATA[/*><!--*/\n" . drupal_load_stylesheet_content($css, TRUE) . "\n/*]]>*/-->\n" . '</style>';
 684      drupal_add_css($css, array('type' => 'inline'));
 685      $styles = drupal_get_css();
 686      $this->assertEqual(trim($styles), $css_preprocessed, t('Rendering preprocessed inline CSS adds it to the page.'));
 687    }
 688  
 689    /**
 690     * Tests rendering inline stylesheets with preprocessing off.
 691     */
 692    function testRenderInlineNoPreprocess() {
 693      $css = 'body { padding: 0px; }';
 694      drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
 695      $styles = drupal_get_css();
 696      $this->assertTrue(strpos($styles, $css) > 0, t('Rendering non-preprocessed inline CSS adds it to the page.'));
 697    }
 698  
 699    /**
 700     * Tests rendering inline stylesheets through a full page request.
 701     */
 702    function testRenderInlineFullPage() {
 703      $css = 'body { font-size: 254px; }';
 704      // Inline CSS is minified unless 'preprocess' => FALSE is passed as a
 705      // drupal_add_css() option.
 706      $expected = 'body{font-size:254px;}';
 707  
 708      // Create a node, using the PHP filter that tests drupal_add_css().
 709      $php_format_id = 'php_code';
 710      $settings = array(
 711        'type' => 'page',
 712        'body' => array(
 713          LANGUAGE_NONE => array(
 714            array(
 715              'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
 716              'format' => $php_format_id,
 717            ),
 718          ),
 719        ),
 720        'promote' => 1,
 721      );
 722      $node = $this->drupalCreateNode($settings);
 723  
 724      // Fetch the page.
 725      $this->drupalGet('node/' . $node->nid);
 726      $this->assertRaw($expected, t('Inline stylesheets appear in the full page rendering.'));
 727    }
 728  
 729    /**
 730     * Test CSS ordering.
 731     */
 732    function testRenderOrder() {
 733      // A module CSS file.
 734      drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
 735      // A few system CSS files, ordered in a strange way.
 736      $system_path = drupal_get_path('module', 'system');
 737      drupal_add_css($system_path . '/system.menus.css', array('group' => CSS_SYSTEM));
 738      drupal_add_css($system_path . '/system.base.css', array('group' => CSS_SYSTEM, 'weight' => -10));
 739      drupal_add_css($system_path . '/system.theme.css', array('group' => CSS_SYSTEM));
 740  
 741      $expected = array(
 742        $system_path . '/system.base.css',
 743        $system_path . '/system.menus.css',
 744        $system_path . '/system.theme.css',
 745        drupal_get_path('module', 'simpletest') . '/simpletest.css',
 746      );
 747  
 748  
 749      $styles = drupal_get_css();
 750      // Stylesheet URL may be the href of a LINK tag or in an @import statement
 751      // of a STYLE tag.
 752      if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
 753        $result = $matches[2];
 754      }
 755      else {
 756        $result = array();
 757      }
 758  
 759      $this->assertIdentical($result, $expected, t('The CSS files are in the expected order.'));
 760    }
 761  
 762    /**
 763     * Test CSS override.
 764     */
 765    function testRenderOverride() {
 766      $system = drupal_get_path('module', 'system');
 767      $simpletest = drupal_get_path('module', 'simpletest');
 768  
 769      drupal_add_css($system . '/system.base.css');
 770      drupal_add_css($simpletest . '/tests/system.base.css');
 771  
 772      // The dummy stylesheet should be the only one included.
 773      $styles = drupal_get_css();
 774      $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') !== FALSE, t('The overriding CSS file is output.'));
 775      $this->assert(strpos($styles, $system . '/system.base.css') === FALSE, t('The overridden CSS file is not output.'));
 776  
 777      drupal_add_css($simpletest . '/tests/system.base.css');
 778      drupal_add_css($system . '/system.base.css');
 779  
 780      // The standard stylesheet should be the only one included.
 781      $styles = drupal_get_css();
 782      $this->assert(strpos($styles, $system . '/system.base.css') !== FALSE, t('The overriding CSS file is output.'));
 783      $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') === FALSE, t('The overridden CSS file is not output.'));
 784    }
 785  
 786    /**
 787     * Tests Locale module's CSS Alter to include RTL overrides.
 788     */
 789    function testAlter() {
 790      // Switch the language to a right to left language and add system.base.css.
 791      global $language;
 792      $language->direction = LANGUAGE_RTL;
 793      $path = drupal_get_path('module', 'system');
 794      drupal_add_css($path . '/system.base.css');
 795  
 796      // Check to see if system.base-rtl.css was also added.
 797      $styles = drupal_get_css();
 798      $this->assert(strpos($styles, $path . '/system.base-rtl.css') !== FALSE, t('CSS is alterable as right to left overrides are added.'));
 799  
 800      // Change the language back to left to right.
 801      $language->direction = LANGUAGE_LTR;
 802    }
 803  
 804    /**
 805     * Tests that the query string remains intact when adding CSS files that have
 806     * query string parameters.
 807     */
 808    function testAddCssFileWithQueryString() {
 809      $this->drupalGet('common-test/query-string');
 810      $query_string = variable_get('css_js_query_string', '0');
 811      $this->assertRaw(drupal_get_path('module', 'node') . '/node.css?' . $query_string, t('Query string was appended correctly to css.'));
 812      $this->assertRaw(drupal_get_path('module', 'node') . '/node-fake.css?arg1=value1&amp;arg2=value2', t('Query string not escaped on a URI.'));
 813    }
 814  }
 815  
 816  /**
 817   * Test for cleaning HTML identifiers.
 818   */
 819  class DrupalHTMLIdentifierTestCase extends DrupalUnitTestCase {
 820    public static function getInfo() {
 821      return array(
 822        'name' => 'HTML identifiers',
 823        'description' => 'Test the functions drupal_html_class(), drupal_html_id() and drupal_clean_css_identifier() for expected behavior',
 824        'group' => 'System',
 825      );
 826    }
 827  
 828    /**
 829     * Tests that drupal_clean_css_identifier() cleans the identifier properly.
 830     */
 831    function testDrupalCleanCSSIdentifier() {
 832      // Verify that no valid ASCII characters are stripped from the identifier.
 833      $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
 834      $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, t('Verify valid ASCII characters pass through.'));
 835  
 836      // Verify that valid UTF-8 characters are not stripped from the identifier.
 837      $identifier = '¡¢£¤¥';
 838      $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, t('Verify valid UTF-8 characters pass through.'));
 839  
 840      // Verify that invalid characters (including non-breaking space) are stripped from the identifier.
 841      $this->assertIdentical(drupal_clean_css_identifier('invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', array()), 'invalididentifier', t('Strip invalid characters.'));
 842    }
 843  
 844    /**
 845     * Tests that drupal_html_class() cleans the class name properly.
 846     */
 847    function testDrupalHTMLClass() {
 848      // Verify Drupal coding standards are enforced.
 849      $this->assertIdentical(drupal_html_class('CLASS NAME_[Ü]'), 'class-name--ü', t('Enforce Drupal coding standards.'));
 850    }
 851  
 852    /**
 853     * Tests that drupal_html_id() cleans the ID properly.
 854     */
 855    function testDrupalHTMLId() {
 856      // Verify that letters, digits, and hyphens are not stripped from the ID.
 857      $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
 858      $this->assertIdentical(drupal_html_id($id), $id, t('Verify valid characters pass through.'));
 859  
 860      // Verify that invalid characters are stripped from the ID.
 861      $this->assertIdentical(drupal_html_id('invalid,./:@\\^`{Üidentifier'), 'invalididentifier', t('Strip invalid characters.'));
 862  
 863      // Verify Drupal coding standards are enforced.
 864      $this->assertIdentical(drupal_html_id('ID NAME_[1]'), 'id-name-1', t('Enforce Drupal coding standards.'));
 865  
 866      // Reset the static cache so we can ensure the unique id count is at zero.
 867      drupal_static_reset('drupal_html_id');
 868  
 869      // Clean up IDs with invalid starting characters.
 870      $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id', t('Test the uniqueness of IDs #1.'));
 871      $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--2', t('Test the uniqueness of IDs #2.'));
 872      $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--3', t('Test the uniqueness of IDs #3.'));
 873    }
 874  }
 875  
 876  /**
 877   * CSS Unit Tests.
 878   */
 879  class CascadingStylesheetsUnitTest extends DrupalUnitTestCase {
 880    public static function getInfo() {
 881      return array(
 882        'name' => 'CSS Unit Tests',
 883        'description' => 'Unit tests on CSS functions like aggregation.',
 884        'group' => 'System',
 885      );
 886    }
 887  
 888    /**
 889     * Tests basic CSS loading with and without optimization via drupal_load_stylesheet().
 890     *
 891     * Known tests:
 892     * - Retain white-space in selectors. (http://drupal.org/node/472820)
 893     * - Proper URLs in imported files. (http://drupal.org/node/265719)
 894     * - Retain pseudo-selectors. (http://drupal.org/node/460448)
 895     */
 896    function testLoadCssBasic() {
 897      // Array of files to test living in 'simpletest/files/css_test_files/'.
 898      // - Original: name.css
 899      // - Unoptimized expected content: name.css.unoptimized.css
 900      // - Optimized expected content: name.css.optimized.css
 901      $testfiles = array(
 902        'css_input_without_import.css',
 903        'css_input_with_import.css',
 904        'comment_hacks.css'
 905      );
 906      $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
 907      foreach ($testfiles as $file) {
 908        $expected = file_get_contents("$path/$file.unoptimized.css");
 909        $unoptimized_output = drupal_load_stylesheet("$path/$file.unoptimized.css", FALSE);
 910        $this->assertEqual($unoptimized_output, $expected, t('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
 911  
 912        $expected = file_get_contents("$path/$file.optimized.css");
 913        $optimized_output = drupal_load_stylesheet("$path/$file", TRUE);
 914        $this->assertEqual($optimized_output, $expected, t('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
 915  
 916        // Repeat the tests by accessing the stylesheets by URL.
 917        $expected = file_get_contents("$path/$file.unoptimized.css");
 918        $unoptimized_output_url = drupal_load_stylesheet($GLOBALS['base_url'] . "/$path/$file.unoptimized.css", FALSE);
 919        $this->assertEqual($unoptimized_output, $expected, t('Unoptimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
 920  
 921        $expected = file_get_contents("$path/$file.optimized.css");
 922        $optimized_output = drupal_load_stylesheet($GLOBALS['base_url'] . "/$path/$file", TRUE);
 923        $this->assertEqual($optimized_output, $expected, t('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
 924      }
 925    }
 926  }
 927  
 928  /**
 929   * Test drupal_http_request().
 930   */
 931  class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
 932    public static function getInfo() {
 933      return array(
 934        'name' => 'Drupal HTTP request',
 935        'description' => "Performs tests on Drupal's HTTP request mechanism.",
 936        'group' => 'System'
 937      );
 938    }
 939  
 940    function setUp() {
 941      parent::setUp('system_test', 'locale');
 942    }
 943  
 944    function testDrupalHTTPRequest() {
 945      global $is_https;
 946  
 947      // Parse URL schema.
 948      $missing_scheme = drupal_http_request('example.com/path');
 949      $this->assertEqual($missing_scheme->code, -1002, t('Returned with "-1002" error code.'));
 950      $this->assertEqual($missing_scheme->error, 'missing schema', t('Returned with "missing schema" error message.'));
 951  
 952      $unable_to_parse = drupal_http_request('http:///path');
 953      $this->assertEqual($unable_to_parse->code, -1001, t('Returned with "-1001" error code.'));
 954      $this->assertEqual($unable_to_parse->error, 'unable to parse URL', t('Returned with "unable to parse URL" error message.'));
 955  
 956      // Fetch page.
 957      $result = drupal_http_request(url('node', array('absolute' => TRUE)));
 958      $this->assertEqual($result->code, 200, t('Fetched page successfully.'));
 959      $this->drupalSetContent($result->data);
 960      $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), t('Site title matches.'));
 961  
 962      // Test that code and status message is returned.
 963      $result = drupal_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
 964      $this->assertTrue(!empty($result->protocol),  t('Result protocol is returned.'));
 965      $this->assertEqual($result->code, '404', t('Result code is 404'));
 966      $this->assertEqual($result->status_message, 'Not Found', t('Result status message is "Not Found"'));
 967  
 968      // Skip the timeout tests when the testing environment is HTTPS because
 969      // stream_set_timeout() does not work for SSL connections.
 970      // @link http://bugs.php.net/bug.php?id=47929
 971      if (!$is_https) {
 972        // Test that timeout is respected. The test machine is expected to be able
 973        // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
 974        // return within a total of 5 seconds. If the test machine is extremely
 975        // slow, the test will fail. fsockopen() has been seen to time out in
 976        // slightly less than the specified timeout, so allow a little slack on
 977        // the minimum expected time (i.e. 1.8 instead of 2).
 978        timer_start(__METHOD__);
 979        $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
 980        $time = timer_read(__METHOD__) / 1000;
 981        $this->assertTrue(1.8 < $time && $time < 5, t('Request timed out (%time seconds).', array('%time' => $time)));
 982        $this->assertTrue($result->error, t('An error message was returned.'));
 983        $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, t('Proper error code was returned.'));
 984      }
 985    }
 986  
 987    function testDrupalHTTPRequestBasicAuth() {
 988      $username = $this->randomName();
 989      $password = $this->randomName();
 990      $url = url('system-test/auth', array('absolute' => TRUE));
 991  
 992      $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
 993      $result = drupal_http_request($auth);
 994  
 995      $this->drupalSetContent($result->data);
 996      $this->assertRaw($username, t('$_SERVER["PHP_AUTH_USER"] is passed correctly.'));
 997      $this->assertRaw($password, t('$_SERVER["PHP_AUTH_PW"] is passed correctly.'));
 998    }
 999  
1000    function testDrupalHTTPRequestRedirect() {
1001      $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
1002      $this->assertEqual($redirect_301->redirect_code, 301, t('drupal_http_request follows the 301 redirect.'));
1003  
1004      $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 0));
1005      $this->assertFalse(isset($redirect_301->redirect_code), t('drupal_http_request does not follow 301 redirect if max_redirects = 0.'));
1006  
1007      $redirect_invalid = drupal_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
1008      $this->assertEqual($redirect_invalid->code, -1002, t('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
1009      $this->assertEqual($redirect_invalid->error, 'missing schema', t('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
1010  
1011      $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
1012      $this->assertEqual($redirect_invalid->code, -1001, t('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
1013      $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)));
1014  
1015      $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
1016      $this->assertEqual($redirect_invalid->code, -1003, t('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
1017      $this->assertEqual($redirect_invalid->error, 'invalid schema ftp', t('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
1018  
1019      $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 1));
1020      $this->assertEqual($redirect_302->redirect_code, 302, t('drupal_http_request follows the 302 redirect.'));
1021  
1022      $redirect_302 = drupal_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 0));
1023      $this->assertFalse(isset($redirect_302->redirect_code), t('drupal_http_request does not follow 302 redirect if $retry = 0.'));
1024  
1025      $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 1));
1026      $this->assertEqual($redirect_307->redirect_code, 307, t('drupal_http_request follows the 307 redirect.'));
1027  
1028      $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
1029      $this->assertFalse(isset($redirect_307->redirect_code), t('drupal_http_request does not follow 307 redirect if max_redirects = 0.'));
1030  
1031      $multiple_redirect_final_url = url('system-test/multiple-redirects/0', array('absolute' => TRUE));
1032      $multiple_redirect_1 = drupal_http_request(url('system-test/multiple-redirects/1', array('absolute' => TRUE)), array('max_redirects' => 1));
1033      $this->assertEqual($multiple_redirect_1->redirect_url, $multiple_redirect_final_url, t('redirect_url contains the final redirection location after 1 redirect.'));
1034  
1035      $multiple_redirect_3 = drupal_http_request(url('system-test/multiple-redirects/3', array('absolute' => TRUE)), array('max_redirects' => 3));
1036      $this->assertEqual($multiple_redirect_3->redirect_url, $multiple_redirect_final_url, t('redirect_url contains the final redirection location after 3 redirects.'));
1037    }
1038  
1039    /**
1040     * Tests Content-language headers generated by Drupal.
1041     */
1042    function testDrupalHTTPRequestHeaders() {
1043      // Check the default header.
1044      $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1045      $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
1046  
1047      // Add German language and set as default.
1048      locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
1049  
1050      // Request front page and check for matching Content-Language.
1051      $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1052      $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
1053    }
1054  }
1055  
1056  /**
1057   * Testing drupal_add_region_content and drupal_get_region_content.
1058   */
1059  class DrupalSetContentTestCase extends DrupalWebTestCase {
1060    public static function getInfo() {
1061      return array(
1062        'name' => 'Drupal set/get regions',
1063        'description' => 'Performs tests on setting and retrieiving content from theme regions.',
1064        'group' => 'System'
1065      );
1066    }
1067  
1068  
1069    /**
1070     * Test setting and retrieving content for theme regions.
1071     */
1072    function testRegions() {
1073      global $theme_key;
1074  
1075      $block_regions = array_keys(system_region_list($theme_key));
1076      $delimiter = $this->randomName(32);
1077      $values = array();
1078      // Set some random content for each region available.
1079      foreach ($block_regions as $region) {
1080        $first_chunk = $this->randomName(32);
1081        drupal_add_region_content($region, $first_chunk);
1082        $second_chunk = $this->randomName(32);
1083        drupal_add_region_content($region, $second_chunk);
1084        // Store the expected result for a drupal_get_region_content call for this region.
1085        $values[$region] = $first_chunk . $delimiter . $second_chunk;
1086      }
1087  
1088      // Ensure drupal_get_region_content returns expected results when fetching all regions.
1089      $content = drupal_get_region_content(NULL, $delimiter);
1090      foreach ($content as $region => $region_content) {
1091        $this->assertEqual($region_content, $values[$region], t('@region region text verified when fetching all regions', array('@region' => $region)));
1092      }
1093  
1094      // Ensure drupal_get_region_content returns expected results when fetching a single region.
1095      foreach ($block_regions as $region) {
1096        $region_content = drupal_get_region_content($region, $delimiter);
1097        $this->assertEqual($region_content, $values[$region], t('@region region text verified when fetching single region.', array('@region' => $region)));
1098      }
1099    }
1100  }
1101  
1102  /**
1103   * Testing drupal_goto and hook_drupal_goto_alter().
1104   */
1105  class DrupalGotoTest extends DrupalWebTestCase {
1106    public static function getInfo() {
1107      return array(
1108        'name' => 'Drupal goto',
1109        'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
1110        'group' => 'System'
1111      );
1112    }
1113  
1114    function setUp() {
1115      parent::setUp('common_test');
1116    }
1117  
1118    /**
1119     * Test drupal_goto().
1120     */
1121    function testDrupalGoto() {
1122      $this->drupalGet('common-test/drupal_goto/redirect');
1123      $headers = $this->drupalGetHeaders(TRUE);
1124      list(, $status) = explode(' ', $headers[0][':status'], 3);
1125      $this->assertEqual($status, 302, t('Expected response code was sent.'));
1126      $this->assertText('drupal_goto', t('Drupal goto redirect succeeded.'));
1127      $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), t('Drupal goto redirected to expected URL.'));
1128  
1129      $this->drupalGet('common-test/drupal_goto/redirect_advanced');
1130      $headers = $this->drupalGetHeaders(TRUE);
1131      list(, $status) = explode(' ', $headers[0][':status'], 3);
1132      $this->assertEqual($status, 301, t('Expected response code was sent.'));
1133      $this->assertText('drupal_goto', t('Drupal goto redirect succeeded.'));
1134      $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), t('Drupal goto redirected to expected URL.'));
1135  
1136      // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
1137      // to test that the path is encoded and decoded properly.
1138      $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
1139      $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
1140      $this->assertText('drupal_goto', t('Drupal goto redirect with destination succeeded.'));
1141      $this->assertEqual($this->getUrl(), url('common-test/drupal_goto/destination', array('query' => array('foo' => '%25', 'bar' => '123'), 'absolute' => TRUE)), t('Drupal goto redirected to given query string destination.'));
1142    }
1143  
1144    /**
1145     * Test hook_drupal_goto_alter().
1146     */
1147    function testDrupalGotoAlter() {
1148      $this->drupalGet('common-test/drupal_goto/redirect_fail');
1149  
1150      $this->assertNoText(t("Drupal goto failed to stop program"), t("Drupal goto stopped program."));
1151      $this->assertNoText('drupal_goto_fail', t("Drupal goto redirect failed."));
1152    }
1153  
1154    /**
1155     * Test drupal_get_destination().
1156     */
1157    function testDrupalGetDestination() {
1158      $query = $this->randomName(10);
1159  
1160      // Verify that a 'destination' query string is used as destination.
1161      $this->drupalGet('common-test/destination', array('query' => array('destination' => $query)));
1162      $this->assertText('The destination: ' . $query, t('The given query string destination is determined as destination.'));
1163  
1164      // Verify that the current path is used as destination.
1165      $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
1166      $url = 'common-test/destination?' . $query;
1167      $this->assertText('The destination: ' . $url, t('The current path is determined as destination.'));
1168    }
1169  }
1170  
1171  /**
1172   * Tests for the JavaScript system.
1173   */
1174  class JavaScriptTestCase extends DrupalWebTestCase {
1175    /**
1176     * Store configured value for JavaScript preprocessing.
1177     */
1178    protected $preprocess_js = NULL;
1179  
1180    public static function getInfo() {
1181      return array(
1182        'name' => 'JavaScript',
1183        'description' => 'Tests the JavaScript system.',
1184        'group' => 'System'
1185      );
1186    }
1187  
1188    function setUp() {
1189      // Enable Locale and SimpleTest in the test environment.
1190      parent::setUp('locale', 'simpletest', 'common_test');
1191  
1192      // Disable preprocessing
1193      $this->preprocess_js = variable_get('preprocess_js', 0);
1194      variable_set('preprocess_js', 0);
1195  
1196      // Reset drupal_add_js() and drupal_add_library() statics before each test.
1197      drupal_static_reset('drupal_add_js');
1198      drupal_static_reset('drupal_add_library');
1199    }
1200  
1201    function tearDown() {
1202      // Restore configured value for JavaScript preprocessing.
1203      variable_set('preprocess_js', $this->preprocess_js);
1204      parent::tearDown();
1205    }
1206  
1207    /**
1208     * Test default JavaScript is empty.
1209     */
1210    function testDefault() {
1211      $this->assertEqual(array(), drupal_add_js(), t('Default JavaScript is empty.'));
1212    }
1213  
1214    /**
1215     * Test adding a JavaScript file.
1216     */
1217    function testAddFile() {
1218      $javascript = drupal_add_js('misc/collapse.js');
1219      $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), t('jQuery is added when a file is added.'));
1220      $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), t('Drupal.js is added when file is added.'));
1221      $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), t('JavaScript files are correctly added.'));
1222      $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], t('Base path JavaScript setting is correctly set.'));
1223      url('', array('prefix' => &$prefix));
1224      $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], t('Path prefix JavaScript setting is correctly set.'));
1225    }
1226  
1227    /**
1228     * Test adding settings.
1229     */
1230    function testAddSetting() {
1231      $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
1232      $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], t('JavaScript setting is set correctly.'));
1233      $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], t('The other JavaScript setting is set correctly.'));
1234    }
1235  
1236    /**
1237     * Tests adding an external JavaScript File.
1238     */
1239    function testAddExternal() {
1240      $path = 'http://example.com/script.js';
1241      $javascript = drupal_add_js($path, 'external');
1242      $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), t('Added an external JavaScript file.'));
1243    }
1244  
1245    /**
1246     * Test drupal_get_js() for JavaScript settings.
1247     */
1248    function testHeaderSetting() {
1249      // Only the second of these two entries should appear in Drupal.settings.
1250      drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
1251      drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
1252      // All three of these entries should appear in Drupal.settings.
1253      drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
1254      drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
1255      drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
1256      // Only the second of these two entries should appear in Drupal.settings.
1257      drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
1258      drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
1259  
1260      $javascript = drupal_get_js('header');
1261      $this->assertTrue(strpos($javascript, 'basePath') > 0, t('Rendered JavaScript header returns basePath setting.'));
1262      $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, t('Rendered JavaScript header includes jQuery.'));
1263      $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, t('Rendered JavaScript header returns pathPrefix setting.'));
1264  
1265      // Test whether drupal_add_js can be used to override a previous setting.
1266      $this->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, t('Rendered JavaScript header returns custom setting.'));
1267      $this->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, t('drupal_add_js() correctly overrides a custom setting.'));
1268  
1269      // Test whether drupal_add_js can be used to add numerically indexed values
1270      // to an array.
1271      $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
1272      $this->assertTrue($array_values_appear, t('drupal_add_js() correctly adds settings to the end of an indexed array.'));
1273  
1274      // Test whether drupal_add_js can be used to override the entry for an
1275      // existing key in an associative array.
1276      $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
1277      $this->assertTrue($associative_array_override, t('drupal_add_js() correctly overrides settings within an associative array.'));
1278    }
1279  
1280    /**
1281     * Test to see if resetting the JavaScript empties the cache.
1282     */
1283    function testReset() {
1284      drupal_add_js('misc/collapse.js');
1285      drupal_static_reset('drupal_add_js');
1286      $this->assertEqual(array(), drupal_add_js(), t('Resetting the JavaScript correctly empties the cache.'));
1287    }
1288  
1289    /**
1290     * Test adding inline scripts.
1291     */
1292    function testAddInline() {
1293      $inline = 'jQuery(function () { });';
1294      $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1295      $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), t('jQuery is added when inline scripts are added.'));
1296      $data = end($javascript);
1297      $this->assertEqual($inline, $data['data'], t('Inline JavaScript is correctly added to the footer.'));
1298    }
1299  
1300    /**
1301     * Test rendering an external JavaScript file.
1302     */
1303    function testRenderExternal() {
1304      $external = 'http://example.com/example.js';
1305      drupal_add_js($external, 'external');
1306      $javascript = drupal_get_js();
1307      // Local files have a base_path() prefix, external files should not.
1308      $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, t('Rendering an external JavaScript file.'));
1309    }
1310  
1311    /**
1312     * Test drupal_get_js() with a footer scope.
1313     */
1314    function testFooterHTML() {
1315      $inline = 'jQuery(function () { });';
1316      drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1317      $javascript = drupal_get_js('footer');
1318      $this->assertTrue(strpos($javascript, $inline) > 0, t('Rendered JavaScript footer returns the inline code.'));
1319    }
1320  
1321    /**
1322     * Test drupal_add_js() sets preproccess to false when cache is set to false.
1323     */
1324    function testNoCache() {
1325      $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
1326      $this->assertFalse($javascript['misc/collapse.js']['preprocess'], t('Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.'));
1327    }
1328  
1329    /**
1330     * Test adding a JavaScript file with a different group.
1331     */
1332    function testDifferentGroup() {
1333      $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
1334      $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, t('Adding a JavaScript file with a different group caches the given group.'));
1335    }
1336  
1337    /**
1338     * Test adding a JavaScript file with a different weight.
1339     */
1340    function testDifferentWeight() {
1341      $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
1342      $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, t('Adding a JavaScript file with a different weight caches the given weight.'));
1343    }
1344  
1345    /**
1346     * Tests JavaScript aggregation when files are added to a different scope.
1347     */
1348    function testAggregationOrder() {
1349      // Enable JavaScript aggregation.
1350      variable_set('preprocess_js', 1);
1351      drupal_static_reset('drupal_add_js');
1352  
1353      // Add two JavaScript files to the current request and build the cache.
1354      drupal_add_js('misc/ajax.js');
1355      drupal_add_js('misc/autocomplete.js');
1356  
1357      $js_items = drupal_add_js();
1358      drupal_build_js_cache(array(
1359        'misc/ajax.js' => $js_items['misc/ajax.js'],
1360        'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1361      ));
1362  
1363      // Store the expected key for the first item in the cache.
1364      $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1365      $expected_key = $cache[0];
1366  
1367      // Reset variables and add a file in a different scope first.
1368      variable_del('drupal_js_cache_files');
1369      drupal_static_reset('drupal_add_js');
1370      drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
1371      drupal_add_js('misc/ajax.js');
1372      drupal_add_js('misc/autocomplete.js');
1373  
1374      // Rebuild the cache.
1375      $js_items = drupal_add_js();
1376      drupal_build_js_cache(array(
1377        'misc/ajax.js' => $js_items['misc/ajax.js'],
1378        'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1379      ));
1380  
1381      // Compare the expected key for the first file to the current one.
1382      $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1383      $key = $cache[0];
1384      $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
1385    }
1386  
1387    /**
1388     * Test JavaScript ordering.
1389     */
1390    function testRenderOrder() {
1391      // Add a bunch of JavaScript in strange ordering.
1392      drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1393      drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1394      drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1395      drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1396      drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1397      drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1398      drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
1399      drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1400      drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1401      drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1402  
1403      // Construct the expected result from the regex.
1404      $expected = array(
1405        "-8 #1",
1406        "-8 #2",
1407        "-8 #3",
1408        "-8 #4",
1409        "-5 #1", // The external script.
1410        "0 #1",
1411        "0 #2",
1412        "0 #3",
1413        "5 #1",
1414        "5 #2",
1415      );
1416  
1417      // Retrieve the rendered JavaScript and test against the regex.
1418      $js = drupal_get_js('footer');
1419      $matches = array();
1420      if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
1421        $result = $matches[1];
1422      }
1423      else {
1424        $result = array();
1425      }
1426      $this->assertIdentical($result, $expected, t('JavaScript is added in the expected weight order.'));
1427    }
1428  
1429    /**
1430     * Test rendering the JavaScript with a file's weight above jQuery's.
1431     */
1432    function testRenderDifferentWeight() {
1433      // JavaScript files are sorted first by group, then by the 'every_page'
1434      // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
1435      // weight, we need the other two options to be the same.
1436      drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
1437      $javascript = drupal_get_js();
1438      $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), t('Rendering a JavaScript file above jQuery.'));
1439    }
1440  
1441    /**
1442     * Test altering a JavaScript's weight via hook_js_alter().
1443     *
1444     * @see simpletest_js_alter()
1445     */
1446    function testAlter() {
1447      // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
1448      drupal_add_js('misc/tableselect.js');
1449      drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
1450  
1451      // Render the JavaScript, testing if simpletest.js was altered to be before
1452      // tableselect.js. See simpletest_js_alter() to see where this alteration
1453      // takes place.
1454      $javascript = drupal_get_js();
1455      $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), t('Altering JavaScript weight through the alter hook.'));
1456    }
1457  
1458    /**
1459     * Adds a library to the page and tests for both its JavaScript and its CSS.
1460     */
1461    function testLibraryRender() {
1462      $result = drupal_add_library('system', 'farbtastic');
1463      $this->assertTrue($result !== FALSE, t('Library was added without errors.'));
1464      $scripts = drupal_get_js();
1465      $styles = drupal_get_css();
1466      $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), t('JavaScript of library was added to the page.'));
1467      $this->assertTrue(strpos($styles, 'misc/farbtastic/farbtastic.css'), t('Stylesheet of library was added to the page.'));
1468    }
1469  
1470    /**
1471     * Adds a JavaScript library to the page and alters it.
1472     *
1473     * @see common_test_library_alter()
1474     */
1475    function testLibraryAlter() {
1476      // Verify that common_test altered the title of Farbtastic.
1477      $library = drupal_get_library('system', 'farbtastic');
1478      $this->assertEqual($library['title'], 'Farbtastic: Altered Library', t('Registered libraries were altered.'));
1479  
1480      // common_test_library_alter() also added a dependency on jQuery Form.
1481      drupal_add_library('system', 'farbtastic');
1482      $scripts = drupal_get_js();
1483      $this->assertTrue(strpos($scripts, 'misc/jquery.form.js'), t('Altered library dependencies are added to the page.'));
1484    }
1485  
1486    /**
1487     * Tests that multiple modules can implement the same library.
1488     *
1489     * @see common_test_library()
1490     */
1491    function testLibraryNameConflicts() {
1492      $farbtastic = drupal_get_library('common_test', 'farbtastic');
1493      $this->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', t('Alternative libraries can be added to the page.'));
1494    }
1495  
1496    /**
1497     * Tests non-existing libraries.
1498     */
1499    function testLibraryUnknown() {
1500      $result = drupal_get_library('unknown', 'unknown');
1501      $this->assertFalse($result, t('Unknown library returned FALSE.'));
1502      drupal_static_reset('drupal_get_library');
1503  
1504      $result = drupal_add_library('unknown', 'unknown');
1505      $this->assertFalse($result, t('Unknown library returned FALSE.'));
1506      $scripts = drupal_get_js();
1507      $this->assertTrue(strpos($scripts, 'unknown') === FALSE, t('Unknown library was not added to the page.'));
1508    }
1509  
1510    /**
1511     * Tests the addition of libraries through the #attached['library'] property.
1512     */
1513    function testAttachedLibrary() {
1514      $element['#attached']['library'][] = array('system', 'farbtastic');
1515      drupal_render($element);
1516      $scripts = drupal_get_js();
1517      $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), t('The attached_library property adds the additional libraries.'));
1518    }
1519  
1520    /**
1521     * Tests retrieval of libraries via drupal_get_library().
1522     */
1523    function testGetLibrary() {
1524      // Retrieve all libraries registered by a module.
1525      $libraries = drupal_get_library('common_test');
1526      $this->assertTrue(isset($libraries['farbtastic']), t('Retrieved all module libraries.'));
1527      // Retrieve all libraries for a module not implementing hook_library().
1528      // Note: This test installs Locale module.
1529      $libraries = drupal_get_library('locale');
1530      $this->assertEqual($libraries, array(), t('Retrieving libraries from a module not implementing hook_library() returns an emtpy array.'));
1531  
1532      // Retrieve a specific library by module and name.
1533      $farbtastic = drupal_get_library('common_test', 'farbtastic');
1534      $this->assertEqual($farbtastic['version'], '5.3', t('Retrieved a single library.'));
1535      // Retrieve a non-existing library by module and name.
1536      $farbtastic = drupal_get_library('common_test', 'foo');
1537      $this->assertIdentical($farbtastic, FALSE, t('Retrieving a non-existing library returns FALSE.'));
1538    }
1539  
1540    /**
1541     * Tests that the query string remains intact when adding JavaScript files
1542     *  that have query string parameters.
1543     */
1544    function testAddJsFileWithQueryString() {
1545      $this->drupalGet('common-test/query-string');
1546      $query_string = variable_get('css_js_query_string', '0');
1547      $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, t('Query string was appended correctly to js.'));
1548    }
1549  }
1550  
1551  /**
1552   * Tests for drupal_render().
1553   */
1554  class DrupalRenderTestCase extends DrupalWebTestCase {
1555    public static function getInfo() {
1556      return array(
1557        'name' => 'drupal_render()',
1558        'description' => 'Performs functional tests on drupal_render().',
1559        'group' => 'System',
1560      );
1561    }
1562  
1563    function setUp() {
1564      parent::setUp('common_test');
1565    }
1566  
1567    /**
1568     * Test sorting by weight.
1569     */
1570    function testDrupalRenderSorting() {
1571      $first = $this->randomName();
1572      $second = $this->randomName();
1573      // Build an array with '#weight' set for each element.
1574      $elements = array(
1575        'second' => array(
1576          '#weight' => 10,
1577          '#markup' => $second,
1578        ),
1579        'first' => array(
1580          '#weight' => 0,
1581          '#markup' => $first,
1582        ),
1583      );
1584      $output = drupal_render($elements);
1585  
1586      // The lowest weight element should appear last in $output.
1587      $this->assertTrue(strpos($output, $second) > strpos($output, $first), t('Elements were sorted correctly by weight.'));
1588  
1589      // Confirm that the $elements array has '#sorted' set to TRUE.
1590      $this->assertTrue($elements['#sorted'], t("'#sorted' => TRUE was added to the array"));
1591  
1592      // Pass $elements through element_children() and ensure it remains
1593      // sorted in the correct order. drupal_render() will return an empty string
1594      // if used on the same array in the same request.
1595      $children = element_children($elements);
1596      $this->assertTrue(array_shift($children) == 'first', t('Child found in the correct order.'));
1597      $this->assertTrue(array_shift($children) == 'second', t('Child found in the correct order.'));
1598  
1599  
1600      // The same array structure again, but with #sorted set to TRUE.
1601      $elements = array(
1602        'second' => array(
1603          '#weight' => 10,
1604          '#markup' => $second,
1605        ),
1606        'first' => array(
1607          '#weight' => 0,
1608          '#markup' => $first,
1609        ),
1610        '#sorted' => TRUE,
1611      );
1612      $output = drupal_render($elements);
1613  
1614      // The elements should appear in output in the same order as the array.
1615      $this->assertTrue(strpos($output, $second) < strpos($output, $first), t('Elements were not sorted.'));
1616    }
1617  
1618    /**
1619     * Test #attached functionality in children elements.
1620     */
1621    function testDrupalRenderChildrenAttached() {
1622      // The cache system is turned off for POST requests.
1623      $request_method = $_SERVER['REQUEST_METHOD'];
1624      $_SERVER['REQUEST_METHOD'] = 'GET';
1625  
1626      // Create an element with a child and subchild.  Each element loads a
1627      // different JavaScript file using #attached.
1628      $parent_js = drupal_get_path('module', 'user') . '/user.js';
1629      $child_js = drupal_get_path('module', 'forum') . '/forum.js';
1630      $subchild_js = drupal_get_path('module', 'book') . '/book.js';
1631      $element = array(
1632        '#type' => 'fieldset',
1633        '#cache' => array(
1634          'keys' => array('simpletest', 'drupal_render', 'children_attached'),
1635        ),
1636        '#attached' => array('js' => array($parent_js)),
1637        '#title' => 'Parent',
1638      );
1639      $element['child'] = array(
1640        '#type' => 'fieldset',
1641        '#attached' => array('js' => array($child_js)),
1642        '#title' => 'Child',
1643      );
1644      $element['child']['subchild'] = array(
1645        '#attached' => array('js' => array($subchild_js)),
1646        '#markup' => 'Subchild',
1647      );
1648  
1649      // Render the element and verify the presence of #attached JavaScript.
1650      drupal_render($element);
1651      $scripts = drupal_get_js();
1652      $this->assertTrue(strpos($scripts, $parent_js), t('The element #attached JavaScript was included.'));
1653      $this->assertTrue(strpos($scripts, $child_js), t('The child #attached JavaScript was included.'));
1654      $this->assertTrue(strpos($scripts, $subchild_js), t('The subchild #attached JavaScript was included.'));
1655  
1656      // Load the element from cache and verify the presence of the #attached
1657      // JavaScript.
1658      drupal_static_reset('drupal_add_js');
1659      $this->assertTrue(drupal_render_cache_get($element), t('The element was retrieved from cache.'));
1660      $scripts = drupal_get_js();
1661      $this->assertTrue(strpos($scripts, $parent_js), t('The element #attached JavaScript was included when loading from cache.'));
1662      $this->assertTrue(strpos($scripts, $child_js), t('The child #attached JavaScript was included when loading from cache.'));
1663      $this->assertTrue(strpos($scripts, $subchild_js), t('The subchild #attached JavaScript was included when loading from cache.'));
1664  
1665      $_SERVER['REQUEST_METHOD'] = $request_method;
1666    }
1667  
1668    /**
1669     * Test passing arguments to the theme function.
1670     */
1671    function testDrupalRenderThemeArguments() {
1672      $element = array(
1673        '#theme' => 'common_test_foo',
1674      );
1675      // Test that defaults work.
1676      $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
1677      $element = array(
1678        '#theme' => 'common_test_foo',
1679        '#foo' => $this->randomName(),
1680        '#bar' => $this->randomName(),
1681      );
1682      // Test that passing arguments to the theme function works.
1683      $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
1684    }
1685  
1686    /**
1687     * Test rendering form elements without passing through form_builder().
1688     */
1689    function testDrupalRenderFormElements() {
1690      // Define a series of form elements.
1691      $element = array(
1692        '#type' => 'button',
1693        '#value' => $this->randomName(),
1694      );
1695      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
1696  
1697      $element = array(
1698        '#type' => 'textfield',
1699        '#title' => $this->randomName(),
1700        '#value' => $this->randomName(),
1701      );
1702      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
1703  
1704      $element = array(
1705        '#type' => 'password',
1706        '#title' => $this->randomName(),
1707      );
1708      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
1709  
1710      $element = array(
1711        '#type' => 'textarea',
1712        '#title' => $this->randomName(),
1713        '#value' => $this->randomName(),
1714      );
1715      $this->assertRenderedElement($element, '//textarea');
1716  
1717      $element = array(
1718        '#type' => 'radio',
1719        '#title' => $this->randomName(),
1720        '#value' => FALSE,
1721      );
1722      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
1723  
1724      $element = array(
1725        '#type' => 'checkbox',
1726        '#title' => $this->randomName(),
1727      );
1728      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
1729  
1730      $element = array(
1731        '#type' => 'select',
1732        '#title' => $this->randomName(),
1733        '#options' => array(
1734          0 => $this->randomName(),
1735          1 => $this->randomName(),
1736        ),
1737      );
1738      $this->assertRenderedElement($element, '//select');
1739  
1740      $element = array(
1741        '#type' => 'file',
1742        '#title' => $this->randomName(),
1743      );
1744      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
1745  
1746      $element = array(
1747        '#type' => 'item',
1748        '#title' => $this->randomName(),
1749        '#markup' => $this->randomName(),
1750      );
1751      $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
1752        ':class' => 'form-type-item',
1753        ':markup' => $element['#markup'],
1754        ':label' => $element['#title'],
1755      ));
1756  
1757      $element = array(
1758        '#type' => 'hidden',
1759        '#title' => $this->randomName(),
1760        '#value' => $this->randomName(),
1761      );
1762      $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
1763  
1764      $element = array(
1765        '#type' => 'link',
1766        '#title' => $this->randomName(),
1767        '#href' => $this->randomName(),
1768        '#options' => array(
1769          'absolute' => TRUE,
1770        ),
1771      );
1772      $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
1773        ':href' => url($element['#href'], array('absolute' => TRUE)),
1774        ':title' => $element['#title'],
1775      ));
1776  
1777      $element = array(
1778        '#type' => 'fieldset',
1779        '#title' => $this->randomName(),
1780      );
1781      $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
1782        ':title' => $element['#title'],
1783      ));
1784  
1785      $element['item'] = array(
1786        '#type' => 'item',
1787        '#title' => $this->randomName(),
1788        '#markup' => $this->randomName(),
1789      );
1790      $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
1791        ':class' => 'form-type-item',
1792        ':markup' => $element['item']['#markup'],
1793      ));
1794    }
1795  
1796    protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
1797      $original_element = $element;
1798      $this->drupalSetContent(drupal_render($element));
1799      $this->verbose('<pre>' .  check_plain(var_export($original_element, TRUE)) . '</pre>'
1800        . '<pre>' .  check_plain(var_export($element, TRUE)) . '</pre>'
1801        . '<hr />' . $this->drupalGetContent()
1802      );
1803  
1804      // @see DrupalWebTestCase::xpath()
1805      $xpath = $this->buildXPathQuery($xpath, $xpath_args);
1806      $element += array('#value' => NULL);
1807      $this->assertFieldByXPath($xpath, $element['#value'], t('#type @type was properly rendered.', array(
1808        '@type' => var_export($element['#type'], TRUE),
1809      )));
1810    }
1811  
1812    /**
1813     * Tests caching of an empty render item.
1814     */
1815    function testDrupalRenderCache() {
1816      // Force a request via GET.
1817      $request_method = $_SERVER['REQUEST_METHOD'];
1818      $_SERVER['REQUEST_METHOD'] = 'GET';
1819      // Create an empty element.
1820      $test_element = array(
1821        '#cache' => array(
1822          'cid' => 'render_cache_test',
1823        ),
1824        '#markup' => '',
1825      );
1826  
1827      // Render the element and confirm that it goes through the rendering
1828      // process (which will set $element['#printed']).
1829      $element = $test_element;
1830      drupal_render($element);
1831      $this->assertTrue(isset($element['#printed']), t('No cache hit'));
1832  
1833      // Render the element again and confirm that it is retrieved from the cache
1834      // instead (so $element['#printed'] will not be set).
1835      $element = $test_element;
1836      drupal_render($element);
1837      $this->assertFalse(isset($element['#printed']), t('Cache hit'));
1838  
1839      // Restore the previous request method.
1840      $_SERVER['REQUEST_METHOD'] = $request_method;
1841    }
1842  }
1843  
1844  /**
1845   * Test for valid_url().
1846   */
1847  class ValidUrlTestCase extends DrupalUnitTestCase {
1848    public static function getInfo() {
1849      return array(
1850        'name' => 'Valid URL',
1851        'description' => "Performs tests on Drupal's valid URL function.",
1852        'group' => 'System'
1853      );
1854    }
1855  
1856    /**
1857     * Test valid absolute URLs.
1858     */
1859    function testValidAbsolute() {
1860      $url_schemes = array('http', 'https', 'ftp');
1861      $valid_absolute_urls = array(
1862        'example.com',
1863        'www.example.com',
1864        'ex-ample.com',
1865        '3xampl3.com',
1866        'example.com/paren(the)sis',
1867        'example.com/index.html#pagetop',
1868        'example.com:8080',
1869        'subdomain.example.com',
1870        'example.com/index.php?q=node',
1871        'example.com/index.php?q=node&param=false',
1872        'user@www.example.com',
1873        'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
1874        '127.0.0.1',
1875        'example.org?',
1876        'john%20doe:secret:foo@example.org/',
1877        'example.org/~,$\'*;',
1878        'caf%C3%A9.example.org',
1879        '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
1880      );
1881  
1882      foreach ($url_schemes as $scheme) {
1883        foreach ($valid_absolute_urls as $url) {
1884          $test_url = $scheme . '://' . $url;
1885          $valid_url = valid_url($test_url, TRUE);
1886          $this->assertTrue($valid_url, t('@url is a valid url.', array('@url' => $test_url)));
1887        }
1888      }
1889    }
1890  
1891    /**
1892     * Test invalid absolute URLs.
1893     */
1894    function testInvalidAbsolute() {
1895      $url_schemes = array('http', 'https', 'ftp');
1896      $invalid_ablosule_urls = array(
1897        '',
1898        'ex!ample.com',
1899        'ex%ample.com',
1900      );
1901  
1902      foreach ($url_schemes as $scheme) {
1903        foreach ($invalid_ablosule_urls as $url) {
1904          $test_url = $scheme . '://' . $url;
1905          $valid_url = valid_url($test_url, TRUE);
1906          $this->assertFalse($valid_url, t('@url is NOT a valid url.', array('@url' => $test_url)));
1907        }
1908      }
1909    }
1910  
1911    /**
1912     * Test valid relative URLs.
1913     */
1914    function testValidRelative() {
1915      $valid_relative_urls = array(
1916        'paren(the)sis',
1917        'index.html#pagetop',
1918        'index.php?q=node',
1919        'index.php?q=node&param=false',
1920        'login.php?do=login&style=%23#pagetop',
1921      );
1922  
1923      foreach (array('', '/') as $front) {
1924        foreach ($valid_relative_urls as $url) {
1925          $test_url = $front . $url;
1926          $valid_url = valid_url($test_url);
1927          $this->assertTrue($valid_url, t('@url is a valid url.', array('@url' => $test_url)));
1928        }
1929      }
1930    }
1931  
1932    /**
1933     * Test invalid relative URLs.
1934     */
1935    function testInvalidRelative() {
1936      $invalid_relative_urls = array(
1937        'ex^mple',
1938        'example<>',
1939        'ex%ample',
1940      );
1941  
1942      foreach (array('', '/') as $front) {
1943        foreach ($invalid_relative_urls as $url) {
1944          $test_url = $front . $url;
1945          $valid_url = valid_url($test_url);
1946          $this->assertFALSE($valid_url, t('@url is NOT a valid url.', array('@url' => $test_url)));
1947        }
1948      }
1949    }
1950  }
1951  
1952  /**
1953   * Tests for CRUD API functions.
1954   */
1955  class DrupalDataApiTest extends DrupalWebTestCase {
1956    public static function getInfo() {
1957      return array(
1958        'name' => 'Data API functions',
1959        'description' => 'Tests the performance of CRUD APIs.',
1960        'group' => 'System',
1961      );
1962    }
1963  
1964    function setUp() {
1965      parent::setUp('database_test');
1966    }
1967  
1968    /**
1969     * Test the drupal_write_record() API function.
1970     */
1971    function testDrupalWriteRecord() {
1972      // Insert a record - no columns allow NULL values.
1973      $person = new stdClass();
1974      $person->name = 'John';
1975      $person->unknown_column = 123;
1976      $insert_result = drupal_write_record('test', $person);
1977      $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.'));
1978      $this->assertTrue(isset($person->id), t('Primary key is set on record created with drupal_write_record().'));
1979      $this->assertIdentical($person->age, 0, t('Age field set to default value.'));
1980      $this->assertIdentical($person->job, 'Undefined', t('Job field set to default value.'));
1981  
1982      // Verify that the record was inserted.
1983      $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
1984      $this->assertIdentical($result->name, 'John', t('Name field set.'));
1985      $this->assertIdentical($result->age, '0', t('Age field set to default value.'));
1986      $this->assertIdentical($result->job, 'Undefined', t('Job field set to default value.'));
1987      $this->assertFalse(isset($result->unknown_column), t('Unknown column was ignored.'));
1988  
1989      // Update the newly created record.
1990      $person->name = 'Peter';
1991      $person->age = 27;
1992      $person->job = NULL;
1993      $update_result = drupal_write_record('test', $person, array('id'));
1994      $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.'));
1995  
1996      // Verify that the record was updated.
1997      $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
1998      $this->assertIdentical($result->name, 'Peter', t('Name field set.'));
1999      $this->assertIdentical($result->age, '27', t('Age field set.'));
2000      $this->assertIdentical($result->job, '', t('Job field set and cast to string.'));
2001  
2002      // Try to insert NULL in columns that does not allow this.
2003      $person = new stdClass();
2004      $person->name = 'Ringo';
2005      $person->age = NULL;
2006      $person->job = NULL;
2007      $insert_result = drupal_write_record('test', $person);
2008      $this->assertTrue(isset($person->id), t('Primary key is set on record created with drupal_write_record().'));
2009      $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2010      $this->assertIdentical($result->name, 'Ringo', t('Name field set.'));
2011      $this->assertIdentical($result->age, '0', t('Age field set.'));
2012      $this->assertIdentical($result->job, '', t('Job field set.'));
2013  
2014      // Insert a record - the "age" column allows NULL.
2015      $person = new stdClass();
2016      $person->name = 'Paul';
2017      $person->age = NULL;
2018      $insert_result = drupal_write_record('test_null', $person);
2019      $this->assertTrue(isset($person->id), t('Primary key is set on record created with drupal_write_record().'));
2020      $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2021      $this->assertIdentical($result->name, 'Paul', t('Name field set.'));
2022      $this->assertIdentical($result->age, NULL, t('Age field set.'));
2023  
2024      // Insert a record - do not specify the value of a column that allows NULL.
2025      $person = new stdClass();
2026      $person->name = 'Meredith';
2027      $insert_result = drupal_write_record('test_null', $person);
2028      $this->assertTrue(isset($person->id), t('Primary key is set on record created with drupal_write_record().'));
2029      $this->assertIdentical($person->age, 0, t('Age field set to default value.'));
2030      $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2031      $this->assertIdentical($result->name, 'Meredith', t('Name field set.'));
2032      $this->assertIdentical($result->age, '0', t('Age field set to default value.'));
2033  
2034      // Update the newly created record.
2035      $person->name = 'Mary';
2036      $person->age = NULL;
2037      $update_result = drupal_write_record('test_null', $person, array('id'));
2038      $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2039      $this->assertIdentical($result->name, 'Mary', t('Name field set.'));
2040      $this->assertIdentical($result->age, NULL, t('Age field set.'));
2041  
2042      // Insert a record - the "data" column should be serialized.
2043      $person = new stdClass();
2044      $person->name = 'Dave';
2045      $update_result = drupal_write_record('test_serialized', $person);
2046      $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2047      $this->assertIdentical($result->name, 'Dave', t('Name field set.'));
2048      $this->assertIdentical($result->info, NULL, t('Info field set.'));
2049  
2050      $person->info = array();
2051      $update_result = drupal_write_record('test_serialized', $person, array('id'));
2052      $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2053      $this->assertIdentical(unserialize($result->info), array(), t('Info field updated.'));
2054  
2055      // Update the serialized record.
2056      $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
2057      $person->info = $data;
2058      $update_result = drupal_write_record('test_serialized', $person, array('id'));
2059      $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2060      $this->assertIdentical(unserialize($result->info), $data, t('Info field updated.'));
2061  
2062      // Run an update query where no field values are changed. The database
2063      // layer should return zero for number of affected rows, but
2064      // db_write_record() should still return SAVED_UPDATED.
2065      $update_result = drupal_write_record('test_null', $person, array('id'));
2066      $this->assertTrue($update_result == SAVED_UPDATED, t('Correct value returned when a valid update is run without changing any values.'));
2067  
2068      // Insert an object record for a table with a multi-field primary key.
2069      $node_access = new stdClass();
2070      $node_access->nid = mt_rand();
2071      $node_access->gid = mt_rand();
2072      $node_access->realm = $this->randomName();
2073      $insert_result = drupal_write_record('node_access', $node_access);
2074      $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.'));
2075  
2076      // Update the record.
2077      $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
2078      $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.'));
2079    }
2080  
2081  }
2082  
2083  /**
2084   * Tests Simpletest error and exception collector.
2085   */
2086  class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
2087  
2088    /**
2089     * Errors triggered during the test.
2090     *
2091     * Errors are intercepted by the overriden implementation
2092     * of DrupalWebTestCase::error below.
2093     *
2094     * @var Array
2095     */
2096    protected $collectedErrors = array();
2097  
2098    public static function getInfo() {
2099      return array(
2100        'name' => 'SimpleTest error collector',
2101        'description' => 'Performs tests on the Simpletest error and exception collector.',
2102        'group' => 'SimpleTest',
2103      );
2104    }
2105  
2106    function setUp() {
2107      parent::setUp('system_test', 'error_test');
2108    }
2109  
2110    /**
2111     * Test that simpletest collects errors from the tested site.
2112     */
2113    function testErrorCollect() {
2114      $this->collectedErrors = array();
2115      $this->drupalGet('error-test/generate-warnings-with-report');
2116      $this->assertEqual(count($this->collectedErrors), 3, t('Three errors were collected'));
2117  
2118      if (count($this->collectedErrors) == 3) {
2119        $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
2120        $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
2121        $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
2122      }
2123      else {
2124        // Give back the errors to the log report.
2125        foreach ($this->collectedErrors as $error) {
2126          parent::error($error['message'], $error['group'], $error['caller']);
2127        }
2128      }
2129    }
2130  
2131    /**
2132     * Error handler that collects errors in an array.
2133     *
2134     * This test class is trying to verify that simpletest correctly sees errors
2135     * and warnings. However, it can't generate errors and warnings that
2136     * propagate up to the testing framework itself, or these tests would always
2137     * fail. So, this special copy of error() doesn't propagate the errors up
2138     * the class hierarchy. It just stuffs them into a protected collectedErrors
2139     * array for various assertions to inspect.
2140     */
2141    protected function error($message = '', $group = 'Other', array $caller = NULL) {
2142      // Due to a WTF elsewhere, simpletest treats debug() and verbose()
2143      // messages as if they were an 'error'. But, we don't want to collect
2144      // those here. This function just wants to collect the real errors (PHP
2145      // notices, PHP fatal errors, etc.), and let all the 'errors' from the
2146      // 'User notice' group bubble up to the parent classes to be handled (and
2147      // eventually displayed) as normal.
2148      if ($group == 'User notice') {
2149        parent::error($message, $group, $caller);
2150      }
2151      // Everything else should be collected but not propagated.
2152      else {
2153        $this->collectedErrors[] = array(
2154          'message' => $message,
2155          'group' => $group,
2156          'caller' => $caller
2157        );
2158      }
2159    }
2160  
2161    /**
2162     * Assert that a collected error matches what we are expecting.
2163     */
2164    function assertError($error, $group, $function, $file, $message = NULL) {
2165      $this->assertEqual($error['group'], $group, t("Group was %group", array('%group' => $group)));
2166      $this->assertEqual($error['caller']['function'], $function, t("Function was %function", array('%function' => $function)));
2167      $this->assertEqual(drupal_basename($error['caller']['file']), $file, t("File was %file", array('%file' => $file)));
2168      if (isset($message)) {
2169        $this->assertEqual($error['message'], $message, t("Message was %message", array('%message' => $message)));
2170      }
2171    }
2172  }
2173  
2174  /**
2175   * Test the drupal_parse_info_file() API function.
2176   */
2177  class ParseInfoFilesTestCase extends DrupalUnitTestCase {
2178    public static function getInfo() {
2179      return array(
2180        'name' => 'Parsing .info files',
2181        'description' => 'Tests parsing .info files.',
2182        'group' => 'System',
2183      );
2184    }
2185  
2186    /**
2187     * Parse an example .info file an verify the results.
2188     */
2189    function testParseInfoFile() {
2190      $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
2191      $this->assertEqual($info_values['simple_string'], 'A simple string', t('Simple string value was parsed correctly.'), t('System'));
2192      $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, t('Constant value was parsed correctly.'), t('System'));
2193      $this->assertEqual($info_values['double_colon'], 'dummyClassName::', t('Value containing double-colon was parsed correctly.'), t('System'));
2194    }
2195  }
2196  
2197  /**
2198   * Tests for the drupal_system_listing() function.
2199   */
2200  class DrupalSystemListingTestCase extends DrupalWebTestCase {
2201    /**
2202     * Use the testing profile; this is needed for testDirectoryPrecedence().
2203     */
2204    protected $profile = 'testing';
2205  
2206    public static function getInfo() {
2207      return array(
2208        'name' => 'Drupal system listing',
2209        'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
2210        'group' => 'System',
2211      );
2212    }
2213  
2214    /**
2215     * Test that files in different directories take precedence as expected.
2216     */
2217    function testDirectoryPrecedence() {
2218      // Define the module files we will search for, and the directory precedence
2219      // we expect.
2220      $expected_directories = array(
2221        // When the copy of the module in the profile directory is incompatible
2222        // with Drupal core, the copy in the core modules directory takes
2223        // precedence.
2224        'drupal_system_listing_incompatible_test' => array(
2225          'modules/simpletest/tests',
2226          'profiles/testing/modules',
2227        ),
2228        // When both copies of the module are compatible with Drupal core, the
2229        // copy in the profile directory takes precedence.
2230        'drupal_system_listing_compatible_test' => array(
2231          'profiles/testing/modules',
2232          'modules/simpletest/tests',
2233        ),
2234      );
2235  
2236      // This test relies on two versions of the same module existing in
2237      // different places in the filesystem. Without that, the test has no
2238      // meaning, so assert their presence first.
2239      foreach ($expected_directories as $module => $directories) {
2240        foreach ($directories as $directory) {
2241          $filename = "$directory/$module/$module.module";
2242          $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), t('@filename exists.', array('@filename' => $filename)));
2243        }
2244      }
2245  
2246      // Now scan the directories and check that the files take precedence as
2247      // expected.
2248      $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
2249      foreach ($expected_directories as $module => $directories) {
2250        $expected_directory = array_shift($directories);
2251        $expected_filename = "$expected_directory/$module/$module.module";
2252        $this->assertEqual($files[$module]->uri, $expected_filename, t('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
2253      }
2254    }
2255  }
2256  
2257  /**
2258   * Tests for the format_date() function.
2259   */
2260  class FormatDateUnitTest extends DrupalWebTestCase {
2261  
2262    /**
2263     * Arbitrary langcode for a custom language.
2264     */
2265    const LANGCODE = 'xx';
2266  
2267    public static function getInfo() {
2268      return array(
2269        'name' => 'Format date',
2270        'description' => 'Test the format_date() function.',
2271        'group' => 'System',
2272      );
2273    }
2274  
2275    function setUp() {
2276      parent::setUp('locale');
2277      variable_set('configurable_timezones', 1);
2278      variable_set('date_format_long', 'l, j. F Y - G:i');
2279      variable_set('date_format_medium', 'j. F Y - G:i');
2280      variable_set('date_format_short', 'Y M j - g:ia');
2281      variable_set('locale_custom_strings_' . self::LANGCODE, array(
2282        '' => array('Sunday' => 'domingo'),
2283        'Long month name' => array('March' => 'marzo'),
2284      ));
2285      $this->refreshVariables();
2286    }
2287  
2288    /**
2289     * Test admin-defined formats in format_date().
2290     */
2291    function testAdminDefinedFormatDate() {
2292      // Create an admin user.
2293      $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
2294      $this->drupalLogin($this->admin_user);
2295  
2296      // Add new date format.
2297      $admin_date_format = 'j M y';
2298      $edit = array('date_format' => $admin_date_format);
2299      $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
2300  
2301      // Add new date type.
2302      $edit = array(
2303        'date_type' => 'Example Style',
2304        'machine_name' => 'example_style',
2305        'date_format' => $admin_date_format,
2306      );
2307      $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
2308  
2309      $timestamp = strtotime('2007-03-10T00:00:00+00:00');
2310      $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', t('Test format_date() using an admin-defined date type.'));
2311      $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), t('Test format_date() defaulting to medium when $type not found.'));
2312    }
2313  
2314    /**
2315     * Tests for the format_date() function.
2316     */
2317    function testFormatDate() {
2318      global $user, $language;
2319  
2320      $timestamp = strtotime('2007-03-26T00:00:00+00:00');
2321      $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', t('Test all parameters.'));
2322      $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'domingo, 25-Mar-07 17:00:00 PDT', t('Test translated format.'));
2323      $this->assertIdentical(format_date($timestamp, 'custom', '\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'l, 25-Mar-07 17:00:00 PDT', t('Test an escaped format string.'));
2324      $this->assertIdentical(format_date($timestamp, 'custom', '\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\domingo, 25-Mar-07 17:00:00 PDT', t('Test format containing backslash character.'));
2325      $this->assertIdentical(format_date($timestamp, 'custom', '\\\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\l, 25-Mar-07 17:00:00 PDT', t('Test format containing backslash followed by escaped format string.'));
2326      $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Monday, 26-Mar-07 01:00:00 BST', t('Test a different time zone.'));
2327  
2328      // Create an admin user and add Spanish language.
2329      $admin_user = $this->drupalCreateUser(array('administer languages'));
2330      $this->drupalLogin($admin_user);
2331      $edit = array(
2332        'langcode' => self::LANGCODE,
2333        'name' => self::LANGCODE,
2334        'native' => self::LANGCODE,
2335        'direction' => LANGUAGE_LTR,
2336        'prefix' => self::LANGCODE,
2337      );
2338      $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
2339  
2340      // Create a test user to carry out the tests.
2341      $test_user = $this->drupalCreateUser();
2342      $this->drupalLogin($test_user);
2343      $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
2344      $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
2345  
2346      // Disable session saving as we are about to modify the global $user.
2347      drupal_save_session(FALSE);
2348      // Save the original user and language and then replace it with the test user and language.
2349      $real_user = $user;
2350      $user = user_load($test_user->uid, TRUE);
2351      $real_language = $language->language;
2352      $language->language = $user->language;
2353      // Simulate a Drupal bootstrap with the logged-in user.
2354      date_default_timezone_set(drupal_get_user_timezone());
2355  
2356      $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', t('Test a different language.'));
2357      $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London'), 'Monday, 26-Mar-07 01:00:00 BST', t('Test a different time zone.'));
2358      $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T'), 'domingo, 25-Mar-07 17:00:00 PDT', t('Test custom date format.'));
2359      $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', t('Test long date format.'));
2360      $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', t('Test medium date format.'));
2361      $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', t('Test short date format.'));
2362      $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', t('Test default date format.'));
2363  
2364      // Restore the original user and language, and enable session saving.
2365      $user = $real_user;
2366      $language->language = $real_language;
2367      // Restore default time zone.
2368      date_default_timezone_set(drupal_get_user_timezone());
2369      drupal_save_session(TRUE);
2370    }
2371  }
2372  
2373  /**
2374   * Tests for the format_date() function.
2375   */
2376  class DrupalAttributesUnitTest extends DrupalUnitTestCase {
2377    public static function getInfo() {
2378      return array(
2379        'name' => 'HTML Attributes',
2380        'description' => 'Perform unit tests on the drupal_attributes() function.',
2381        'group' => 'System',
2382      );
2383    }
2384  
2385    /**
2386     * Tests that drupal_html_class() cleans the class name properly.
2387     */
2388    function testDrupalAttributes() {
2389      // Verify that special characters are HTML encoded.
2390      $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', t('HTML encode attribute values.'));
2391  
2392      // Verify multi-value attributes are concatenated with spaces.
2393      $attributes = array('class' => array('first', 'last'));
2394      $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', t('Concatenate multi-value attributes.'));
2395  
2396      // Verify empty attribute values are rendered.
2397      $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', t('Empty attribute value #1.'));
2398      $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', t('Empty attribute value #2.'));
2399  
2400      // Verify multiple attributes are rendered.
2401      $attributes = array(
2402        'id' => 'id-test',
2403        'class' => array('first', 'last'),
2404        'alt' => 'Alternate',
2405      );
2406      $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', t('Multiple attributes.'));
2407  
2408      // Verify empty attributes array is rendered.
2409      $this->assertIdentical(drupal_attributes(array()), '', t('Empty attributes array.'));
2410    }
2411  }
2412  
2413  /**
2414   * Tests converting PHP variables to JSON strings and back.
2415   */
2416  class DrupalJSONTest extends DrupalUnitTestCase {
2417    public static function getInfo() {
2418      return array(
2419        'name' => 'JSON',
2420        'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
2421        'group' => 'System',
2422      );
2423    }
2424  
2425    /**
2426     * Tests converting PHP variables to JSON strings and back.
2427     */
2428    function testJSON() {
2429      // Setup a string with the full ASCII table.
2430      // @todo: Add tests for non-ASCII characters and Unicode.
2431      $str = '';
2432      for ($i=0; $i < 128; $i++) {
2433        $str .= chr($i);
2434      }
2435      // Characters that must be escaped.
2436      // We check for unescaped " separately.
2437      $html_unsafe = array('<', '>', '\'', '&');
2438      // The following are the encoded forms of: < > ' & "
2439      $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
2440  
2441      // Verify there aren't character encoding problems with the source string.
2442      $this->assertIdentical(strlen($str), 128, t('A string with the full ASCII table has the correct length.'));
2443      foreach ($html_unsafe as $char) {
2444        $this->assertTrue(strpos($str, $char) > 0, t('A string with the full ASCII table includes @s.', array('@s' => $char)));
2445      }
2446  
2447      // Verify that JSON encoding produces a string with all of the characters.
2448      $json = drupal_json_encode($str);
2449      $this->assertTrue(strlen($json) > strlen($str), t('A JSON encoded string is larger than the source string.'));
2450  
2451      // The first and last characters should be ", and no others.
2452      $this->assertTrue($json[0] == '"', t('A JSON encoded string begins with ".'));
2453      $this->assertTrue($json[strlen($json) - 1] == '"', t('A JSON encoded string ends with ".'));
2454      $this->assertTrue(substr_count($json, '"') == 2, t('A JSON encoded string contains exactly two ".'));
2455  
2456      // Verify that encoding/decoding is reversible.
2457      $json_decoded = drupal_json_decode($json);
2458      $this->assertIdentical($str, $json_decoded, t('Encoding a string to JSON and decoding back results in the original string.'));
2459  
2460      // Verify reversibility for structured data. Also verify that necessary
2461      // characters are escaped.
2462      $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
2463      $json = drupal_json_encode($source);
2464      foreach ($html_unsafe as $char) {
2465        $this->assertTrue(strpos($json, $char) === FALSE, t('A JSON encoded string does not contain @s.', array('@s' => $char)));
2466      }
2467      // Verify that JSON encoding escapes the HTML unsafe characters
2468      foreach ($html_unsafe_escaped as $char) {
2469        $this->assertTrue(strpos($json, $char) > 0, t('A JSON encoded string contains @s.', array('@s' => $char)));
2470      }
2471      $json_decoded = drupal_json_decode($json);
2472      $this->assertNotIdentical($source, $json, t('An array encoded in JSON is not identical to the source.'));
2473      $this->assertIdentical($source, $json_decoded, t('Encoding structured data to JSON and decoding back results in the original data.'));
2474    }
2475  }
2476  
2477  /**
2478   * Tests for RDF namespaces XML serialization.
2479   */
2480  class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
2481    public static function getInfo() {
2482      return array(
2483        'name' => 'RDF namespaces XML serialization tests',
2484        'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
2485        'group' => 'System',
2486      );
2487    }
2488  
2489    function setUp() {
2490      parent::setUp('rdf', 'rdf_test');
2491    }
2492  
2493    /**
2494     * Test RDF namespaces.
2495     */
2496    function testGetRdfNamespaces() {
2497      // Fetches the front page and extracts XML namespaces.
2498      $this->drupalGet('');
2499      $xml = new SimpleXMLElement($this->content);
2500      $ns = $xml->getDocNamespaces();
2501  
2502      $this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', t('A prefix declared once is displayed.'));
2503      $this->assertEqual($ns['foaf'], 'http://xmlns.com/foaf/0.1/', t('The same prefix declared in several implementations of hook_rdf_namespaces() is valid as long as all the namespaces are the same.'));
2504      $this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', t('Two prefixes can be assigned the same namespace.'));
2505      $this->assertTrue(!isset($ns['dc']), t('A prefix with conflicting namespaces is discarded.'));
2506    }
2507  }
2508  
2509  /**
2510   * Basic tests for drupal_add_feed().
2511   */
2512  class DrupalAddFeedTestCase extends DrupalWebTestCase {
2513    public static function getInfo() {
2514      return array(
2515        'name' => 'drupal_add_feed() tests',
2516        'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
2517        'group' => 'System',
2518      );
2519    }
2520  
2521    /**
2522     * Test drupal_add_feed() with paths, URLs, and titles.
2523     */
2524    function testBasicFeedAddNoTitle() {
2525      $path = $this->randomName(12);
2526      $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2527      $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
2528  
2529      $path_for_title = $this->randomName(12);
2530      $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2531      $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
2532  
2533      // Possible permutations of drupal_add_feed() to test.
2534      // - 'input_url': the path passed to drupal_add_feed(),
2535      // - 'output_url': the expected URL to be found in the header.
2536      // - 'title' == the title of the feed as passed into drupal_add_feed().
2537      $urls = array(
2538        'path without title' => array(
2539          'input_url' => $path,
2540          'output_url' => url($path, array('absolute' => TRUE)),
2541          'title' => '',
2542        ),
2543        'external URL without title' => array(
2544          'input_url' => $external_url,
2545          'output_url' => $external_url,
2546          'title' => '',
2547        ),
2548        'local URL without title' => array(
2549          'input_url' => $fully_qualified_local_url,
2550          'output_url' => $fully_qualified_local_url,
2551          'title' => '',
2552        ),
2553        'path with title' => array(
2554          'input_url' => $path_for_title,
2555          'output_url' => url($path_for_title, array('absolute' => TRUE)),
2556          'title' => $this->randomName(12),
2557        ),
2558        'external URL with title' => array(
2559          'input_url' => $external_for_title,
2560          'output_url' => $external_for_title,
2561          'title' => $this->randomName(12),
2562        ),
2563        'local URL with title' => array(
2564          'input_url' => $fully_qualified_for_title,
2565          'output_url' => $fully_qualified_for_title,
2566          'title' => $this->randomName(12),
2567        ),
2568      );
2569  
2570      foreach ($urls as $description => $feed_info) {
2571        drupal_add_feed($feed_info['input_url'], $feed_info['title']);
2572      }
2573  
2574      $this->drupalSetContent(drupal_get_html_head());
2575      foreach ($urls as $description => $feed_info) {
2576        $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), t('Found correct feed header for %description', array('%description' => $description)));
2577      }
2578    }
2579  
2580    /**
2581     * Create a pattern representing the RSS feed in the page.
2582     */
2583    function urlToRSSLinkPattern($url, $title = '') {
2584      // Escape any regular expression characters in the URL ('?' is the worst).
2585      $url = preg_replace('/([+?.*])/', '[$0]', $url);
2586      $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
2587      return $generated_pattern;
2588    }
2589  }
2590  
2591  /**
2592   * Test for theme_feed_icon().
2593   */
2594  class FeedIconTest extends DrupalWebTestCase {
2595  
2596    public static function getInfo() {
2597      return array(
2598        'name' => 'Feed icon',
2599        'description' => 'Check escaping of theme_feed_icon()',
2600        'group' => 'System',
2601      );
2602    }
2603  
2604    /**
2605     * Check that special characters are correctly escaped. Test for issue #1211668.
2606     */
2607    function testFeedIconEscaping() {
2608      $variables = array();
2609      $variables['url'] = 'node';
2610      $variables['title'] = '<>&"\'';
2611      $text = theme_feed_icon($variables);
2612      preg_match('/title="(.*?)"/', $text, $matches);
2613      $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
2614    }
2615  
2616  }

title

Description

title

Description

title

Description

title

title

Body