Projet

Général

Profil

Paste
Télécharger (128 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / tests / common.test @ db2d93dd

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, '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, '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, 'First argument to drupal_alter() was altered.');
57
    $this->assertEqual($entity_copy, $entity_expected, 'Second argument to drupal_alter() was altered.');
58
    $this->assertEqual($array2_copy, $array2_expected, '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, '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, format_string('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'), format_string('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), format_string('Custom class @class is present on link when requested', array('@class' => $class)));
111
    $this->assertTrue($this->hasClass($link, 'active'), format_string('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, "\$_GET['q'] was removed.");
138

    
139
    // Default exclusion.
140
    $result = $original;
141
    unset($result['q']);
142
    $this->assertEqual(drupal_get_query_parameters($original), $result, "'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, "'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, "'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, "'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, "'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', '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', 'Key was properly encoded.');
171
    $this->assertEqual(drupal_http_build_query(array('a' => '1', 'b' => '2', 'c' => '3')), 'a=1&b=2&c=3', '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', '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, '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, '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, '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), 'Correctly identified an external URL.');
211

    
212
    // External URL without an explicit protocol.
213
    $url = '//drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
214
    $this->assertTrue(url_is_external($url), 'Correctly identified an external URL without a protocol part.');
215

    
216
    // Internal URL starting with a slash.
217
    $url = '/drupal.org';
218
    $this->assertFalse(url_is_external($url), 'Correctly identified an internal URL with a leading slash.');
219

    
220
    // Test the parsing of absolute URLs.
221
    $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
222
    $result = array(
223
      'path' => 'http://drupal.org/foo/bar',
224
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
225
      'fragment' => 'foo',
226
    );
227
    $this->assertEqual(drupal_parse_url($url), $result, 'External URL parsed correctly.');
228

    
229
    // Verify proper parsing of URLs when clean URLs are disabled.
230
    $result = array(
231
      'path' => 'foo/bar',
232
      'query' => array('bar' => 'baz'),
233
      'fragment' => 'foo',
234
    );
235
    // Non-clean URLs #1: Absolute URL generated by url().
236
    $url = $GLOBALS['base_url'] . '/?q=foo/bar&bar=baz#foo';
237
    $this->assertEqual(drupal_parse_url($url), $result, 'Absolute URL with clean URLs disabled parsed correctly.');
238

    
239
    // Non-clean URLs #2: Relative URL generated by url().
240
    $url = '?q=foo/bar&bar=baz#foo';
241
    $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL with clean URLs disabled parsed correctly.');
242

    
243
    // Non-clean URLs #3: URL generated by url() on non-Apache webserver.
244
    $url = 'index.php?q=foo/bar&bar=baz#foo';
245
    $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL on non-Apache webserver with clean URLs disabled parsed correctly.');
246

    
247
    // Test that drupal_parse_url() does not allow spoofing a URL to force a malicious redirect.
248
    $parts = drupal_parse_url('forged:http://cwe.mitre.org/data/definitions/601.html');
249
    $this->assertFalse(valid_url($parts['path'], TRUE), 'drupal_parse_url() correctly parsed a forged URL.');
250
  }
251

    
252
  /**
253
   * Test url() with/without query, with/without fragment, absolute on/off and
254
   * assert all that works when clean URLs are on and off.
255
   */
256
  function testUrl() {
257
    global $base_url;
258

    
259
    foreach (array(FALSE, TRUE) as $absolute) {
260
      // Get the expected start of the path string.
261
      $base = $absolute ? $base_url . '/' : base_path();
262
      $absolute_string = $absolute ? 'absolute' : NULL;
263

    
264
      // Disable Clean URLs.
265
      $GLOBALS['conf']['clean_url'] = 0;
266

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

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

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

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

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

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

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

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

    
299
      // Enable Clean URLs.
300
      $GLOBALS['conf']['clean_url'] = 1;
301

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

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

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

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

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

    
322
      $url = $base;
323
      $result = url('<front>', array('absolute' => $absolute));
324
      $this->assertEqual($url, $result, "$url == $result");
325
    }
326
  }
327

    
328
  /**
329
   * Test external URL handling.
330
   */
331
  function testExternalUrls() {
332
    $test_url = 'http://drupal.org/';
333

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

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

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

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

    
356
    // Verify query string can be extended in an external URL.
357
    $url = $test_url . '?drupal=awesome';
358
    $query = array($this->randomName(5) => $this->randomName(5));
359
    $result = url($url, array('query' => $query));
360
    $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result, 'External URL query string can be extended with a custom query string in $options.');
361

    
362
    // Verify that an internal URL does not result in an external URL without
363
    // protocol part.
364
    $url = '/drupal.org';
365
    $result = url($url);
366
    $this->assertTrue(strpos($result, '//') === FALSE, 'Internal URL does not turn into an external URL.');
367

    
368
    // Verify that an external URL without protocol part is recognized as such.
369
    $url = '//drupal.org';
370
    $result = url($url);
371
    $this->assertEqual($url, $result, 'External URL without protocol is not altered.');
372
  }
373
}
374

    
375
/**
376
 * Tests for check_plain(), filter_xss(), format_string(), and check_url().
377
 */
378
class CommonXssUnitTest extends DrupalUnitTestCase {
379

    
380
  public static function getInfo() {
381
    return array(
382
      'name' => 'String filtering tests',
383
      'description' => 'Confirm that check_plain(), filter_xss(), format_string() and check_url() work correctly, including invalid multi-byte sequences.',
384
      'group' => 'System',
385
    );
386
  }
387

    
388
  /**
389
   * Check that invalid multi-byte sequences are rejected.
390
   */
391
  function testInvalidMultiByte() {
392
     // Ignore PHP 5.3+ invalid multibyte sequence warning.
393
     $text = @check_plain("Foo\xC0barbaz");
394
     $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "Foo\xC0barbaz"');
395
     // Ignore PHP 5.3+ invalid multibyte sequence warning.
396
     $text = @check_plain("\xc2\"");
397
     $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "\xc2\""');
398
     $text = check_plain("Fooÿñ");
399
     $this->assertEqual($text, "Fooÿñ", 'check_plain() accepts valid sequence "Fooÿñ"');
400
     $text = filter_xss("Foo\xC0barbaz");
401
     $this->assertEqual($text, '', 'filter_xss() rejects invalid sequence "Foo\xC0barbaz"');
402
     $text = filter_xss("Fooÿñ");
403
     $this->assertEqual($text, "Fooÿñ", 'filter_xss() accepts valid sequence Fooÿñ');
404
  }
405

    
406
  /**
407
   * Check that special characters are escaped.
408
   */
409
  function testEscaping() {
410
     $text = check_plain("<script>");
411
     $this->assertEqual($text, '&lt;script&gt;', 'check_plain() escapes &lt;script&gt;');
412
     $text = check_plain('<>&"\'');
413
     $this->assertEqual($text, '&lt;&gt;&amp;&quot;&#039;', 'check_plain() escapes reserved HTML characters.');
414
  }
415

    
416
  /**
417
   * Test t() and format_string() replacement functionality.
418
   */
419
  function testFormatStringAndT() {
420
    foreach (array('format_string', 't') as $function) {
421
      $text = $function('Simple text');
422
      $this->assertEqual($text, 'Simple text', $function . ' leaves simple text alone.');
423
      $text = $function('Escaped text: @value', array('@value' => '<script>'));
424
      $this->assertEqual($text, 'Escaped text: &lt;script&gt;', $function . ' replaces and escapes string.');
425
      $text = $function('Placeholder text: %value', array('%value' => '<script>'));
426
      $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', $function . ' replaces, escapes and themes string.');
427
      $text = $function('Verbatim text: !value', array('!value' => '<script>'));
428
      $this->assertEqual($text, 'Verbatim text: <script>', $function . ' replaces verbatim string as-is.');
429
    }
430
  }
431

    
432
  /**
433
   * Check that harmful protocols are stripped.
434
   */
435
  function testBadProtocolStripping() {
436
    // Ensure that check_url() strips out harmful protocols, and encodes for
437
    // HTML. Ensure drupal_strip_dangerous_protocols() can be used to return a
438
    // plain-text string stripped of harmful protocols.
439
    $url = 'javascript:http://www.example.com/?x=1&y=2';
440
    $expected_plain = 'http://www.example.com/?x=1&y=2';
441
    $expected_html = 'http://www.example.com/?x=1&amp;y=2';
442
    $this->assertIdentical(check_url($url), $expected_html, 'check_url() filters a URL and encodes it for HTML.');
443
    $this->assertIdentical(drupal_strip_dangerous_protocols($url), $expected_plain, 'drupal_strip_dangerous_protocols() filters a URL and returns plain text.');
444
  }
445
}
446

    
447
/**
448
 * Tests file size parsing and formatting functions.
449
 */
450
class CommonSizeTestCase extends DrupalUnitTestCase {
451
  protected $exact_test_cases;
452
  protected $rounded_test_cases;
453

    
454
  public static function getInfo() {
455
    return array(
456
      'name' => 'Size parsing test',
457
      'description' => 'Parse a predefined amount of bytes and compare the output with the expected value.',
458
      'group' => 'System'
459
    );
460
  }
461

    
462
  function setUp() {
463
    $kb = DRUPAL_KILOBYTE;
464
    $this->exact_test_cases = array(
465
      '1 byte' => 1,
466
      '1 KB'   => $kb,
467
      '1 MB'   => $kb * $kb,
468
      '1 GB'   => $kb * $kb * $kb,
469
      '1 TB'   => $kb * $kb * $kb * $kb,
470
      '1 PB'   => $kb * $kb * $kb * $kb * $kb,
471
      '1 EB'   => $kb * $kb * $kb * $kb * $kb * $kb,
472
      '1 ZB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
473
      '1 YB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
474
    );
475
    $this->rounded_test_cases = array(
476
      '2 bytes' => 2,
477
      '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
478
      round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651, // megabytes
479
      round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
480
      round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
481
    );
482
    parent::setUp();
483
  }
484

    
485
  /**
486
   * Check that format_size() returns the expected string.
487
   */
488
  function testCommonFormatSize() {
489
    foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
490
      foreach ($test_cases as $expected => $input) {
491
        $this->assertEqual(
492
          ($result = format_size($input, NULL)),
493
          $expected,
494
          $expected . ' == ' . $result . ' (' . $input . ' bytes)'
495
        );
496
      }
497
    }
498
  }
499

    
500
  /**
501
   * Check that parse_size() returns the proper byte sizes.
502
   */
503
  function testCommonParseSize() {
504
    foreach ($this->exact_test_cases as $string => $size) {
505
      $this->assertEqual(
506
        $parsed_size = parse_size($string),
507
        $size,
508
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
509
      );
510
    }
511

    
512
    // Some custom parsing tests
513
    $string = '23476892 bytes';
514
    $this->assertEqual(
515
      ($parsed_size = parse_size($string)),
516
      $size = 23476892,
517
      $string . ' == ' . $parsed_size . ' bytes'
518
    );
519
    $string = '76MRandomStringThatShouldBeIgnoredByParseSize.'; // 76 MB
520
    $this->assertEqual(
521
      $parsed_size = parse_size($string),
522
      $size = 79691776,
523
      $string . ' == ' . $parsed_size . ' bytes'
524
    );
525
    $string = '76.24 Giggabyte'; // Misspeld text -> 76.24 GB
526
    $this->assertEqual(
527
      $parsed_size = parse_size($string),
528
      $size = 81862076662,
529
      $string . ' == ' . $parsed_size . ' bytes'
530
    );
531
  }
532

    
533
  /**
534
   * Cross-test parse_size() and format_size().
535
   */
536
  function testCommonParseSizeFormatSize() {
537
    foreach ($this->exact_test_cases as $size) {
538
      $this->assertEqual(
539
        $size,
540
        ($parsed_size = parse_size($string = format_size($size, NULL))),
541
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
542
      );
543
    }
544
  }
545
}
546

    
547
/**
548
 * Test drupal_explode_tags() and drupal_implode_tags().
549
 */
550
class DrupalTagsHandlingTestCase extends DrupalUnitTestCase {
551
  var $validTags = array(
552
    'Drupal' => 'Drupal',
553
    'Drupal with some spaces' => 'Drupal with some spaces',
554
    '"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
555
    '"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
556
  );
557

    
558
  public static function getInfo() {
559
    return array(
560
      'name' => 'Drupal tags handling',
561
      'description' => "Performs tests on Drupal's handling of tags, both explosion and implosion tactics used.",
562
      'group' => 'System'
563
    );
564
  }
565

    
566
  /**
567
   * Explode a series of tags.
568
   */
569
  function testDrupalExplodeTags() {
570
    $string = implode(', ', array_keys($this->validTags));
571
    $tags = drupal_explode_tags($string);
572
    $this->assertTags($tags);
573
  }
574

    
575
  /**
576
   * Implode a series of tags.
577
   */
578
  function testDrupalImplodeTags() {
579
    $tags = array_values($this->validTags);
580
    // Let's explode and implode to our heart's content.
581
    for ($i = 0; $i < 10; $i++) {
582
      $string = drupal_implode_tags($tags);
583
      $tags = drupal_explode_tags($string);
584
    }
585
    $this->assertTags($tags);
586
  }
587

    
588
  /**
589
   * Helper function: asserts that the ending array of tags is what we wanted.
590
   */
591
  function assertTags($tags) {
592
    $original = $this->validTags;
593
    foreach ($tags as $tag) {
594
      $key = array_search($tag, $original);
595
      $this->assertTrue($key, format_string('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
596
      unset($original[$key]);
597
    }
598
    foreach ($original as $leftover) {
599
      $this->fail(format_string('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
600
    }
601
  }
602
}
603

    
604
/**
605
 * Test the Drupal CSS system.
606
 */
607
class CascadingStylesheetsTestCase extends DrupalWebTestCase {
608
  public static function getInfo() {
609
    return array(
610
      'name' => 'Cascading stylesheets',
611
      'description' => 'Tests adding various cascading stylesheets to the page.',
612
      'group' => 'System',
613
    );
614
  }
615

    
616
  function setUp() {
617
    parent::setUp('php', 'locale', 'common_test');
618
    // Reset drupal_add_css() before each test.
619
    drupal_static_reset('drupal_add_css');
620
  }
621

    
622
  /**
623
   * Check default stylesheets as empty.
624
   */
625
  function testDefault() {
626
    $this->assertEqual(array(), drupal_add_css(), 'Default CSS is empty.');
627
  }
628

    
629
  /**
630
   * Test that stylesheets in module .info files are loaded.
631
   */
632
  function testModuleInfo() {
633
    $this->drupalGet('');
634

    
635
    // Verify common_test.css in a STYLE media="all" tag.
636
    $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
637
      ':media' => 'all',
638
      ':filename' => 'tests/common_test.css',
639
    ));
640
    $this->assertTrue(count($elements), "Stylesheet with media 'all' in module .info file found.");
641

    
642
    // Verify common_test.print.css in a STYLE media="print" tag.
643
    $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
644
      ':media' => 'print',
645
      ':filename' => 'tests/common_test.print.css',
646
    ));
647
    $this->assertTrue(count($elements), "Stylesheet with media 'print' in module .info file found.");
648
  }
649

    
650
  /**
651
   * Tests adding a file stylesheet.
652
   */
653
  function testAddFile() {
654
    $path = drupal_get_path('module', 'simpletest') . '/simpletest.css';
655
    $css = drupal_add_css($path);
656
    $this->assertEqual($css[$path]['data'], $path, 'Adding a CSS file caches it properly.');
657
  }
658

    
659
  /**
660
   * Tests adding an external stylesheet.
661
   */
662
  function testAddExternal() {
663
    $path = 'http://example.com/style.css';
664
    $css = drupal_add_css($path, 'external');
665
    $this->assertEqual($css[$path]['type'], 'external', 'Adding an external CSS file caches it properly.');
666
  }
667

    
668
  /**
669
   * Makes sure that reseting the CSS empties the cache.
670
   */
671
  function testReset() {
672
    drupal_static_reset('drupal_add_css');
673
    $this->assertEqual(array(), drupal_add_css(), 'Resetting the CSS empties the cache.');
674
  }
675

    
676
  /**
677
   * Tests rendering the stylesheets.
678
   */
679
  function testRenderFile() {
680
    $css = drupal_get_path('module', 'simpletest') . '/simpletest.css';
681
    drupal_add_css($css);
682
    $styles = drupal_get_css();
683
    $this->assertTrue(strpos($styles, $css) > 0, 'Rendered CSS includes the added stylesheet.');
684
    // Verify that newlines are properly added inside style tags.
685
    $query_string = variable_get('css_js_query_string', '0');
686
    $css_processed = "<style type=\"text/css\" media=\"all\">\n@import url(\"" . check_plain(file_create_url($css)) . "?" . $query_string ."\");\n</style>";
687
    $this->assertEqual(trim($styles), $css_processed, 'Rendered CSS includes newlines inside style tags for JavaScript use.');
688
  }
689

    
690
  /**
691
   * Tests rendering an external stylesheet.
692
   */
693
  function testRenderExternal() {
694
    $css = 'http://example.com/style.css';
695
    drupal_add_css($css, 'external');
696
    $styles = drupal_get_css();
697
    // Stylesheet URL may be the href of a LINK tag or in an @import statement
698
    // of a STYLE tag.
699
    $this->assertTrue(strpos($styles, 'href="' . $css) > 0 || strpos($styles, '@import url("' . $css . '")') > 0, 'Rendering an external CSS file.');
700
  }
701

    
702
  /**
703
   * Tests rendering inline stylesheets with preprocessing on.
704
   */
705
  function testRenderInlinePreprocess() {
706
    $css = 'body { padding: 0px; }';
707
    $css_preprocessed = '<style type="text/css" media="all">' . "\n<!--/*--><![CDATA[/*><!--*/\n" . drupal_load_stylesheet_content($css, TRUE) . "\n/*]]>*/-->\n" . '</style>';
708
    drupal_add_css($css, array('type' => 'inline'));
709
    $styles = drupal_get_css();
710
    $this->assertEqual(trim($styles), $css_preprocessed, 'Rendering preprocessed inline CSS adds it to the page.');
711
  }
712

    
713
  /**
714
   * Tests removing charset when rendering stylesheets with preprocessing on.
715
   */
716
  function testRenderRemoveCharsetPreprocess() {
717
    $cases = array(
718
      array(
719
        'asset' => '@charset "UTF-8";html{font-family:"sans-serif";}',
720
        'expected' => 'html{font-family:"sans-serif";}',
721
      ),
722
      // This asset contains extra \n character.
723
      array(
724
        'asset' => "@charset 'UTF-8';\nhtml{font-family:'sans-serif';}",
725
        'expected' => "\nhtml{font-family:'sans-serif';}",
726
      ),
727
    );
728

    
729
    foreach ($cases as $case) {
730
      $this->assertEqual(
731
        $case['expected'],
732
        drupal_load_stylesheet_content($case['asset']),
733
        'CSS optimizing correctly removes the charset declaration.'
734
      );
735
    }
736
  }
737

    
738
  /**
739
   * Tests rendering inline stylesheets with preprocessing off.
740
   */
741
  function testRenderInlineNoPreprocess() {
742
    $css = 'body { padding: 0px; }';
743
    drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
744
    $styles = drupal_get_css();
745
    $this->assertTrue(strpos($styles, $css) > 0, 'Rendering non-preprocessed inline CSS adds it to the page.');
746
  }
747

    
748
  /**
749
   * Tests rendering inline stylesheets through a full page request.
750
   */
751
  function testRenderInlineFullPage() {
752
    $css = 'body { font-size: 254px; }';
753
    // Inline CSS is minified unless 'preprocess' => FALSE is passed as a
754
    // drupal_add_css() option.
755
    $expected = 'body{font-size:254px;}';
756

    
757
    // Create a node, using the PHP filter that tests drupal_add_css().
758
    $php_format_id = 'php_code';
759
    $settings = array(
760
      'type' => 'page',
761
      'body' => array(
762
        LANGUAGE_NONE => array(
763
          array(
764
            'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
765
            'format' => $php_format_id,
766
          ),
767
        ),
768
      ),
769
      'promote' => 1,
770
    );
771
    $node = $this->drupalCreateNode($settings);
772

    
773
    // Fetch the page.
774
    $this->drupalGet('node/' . $node->nid);
775
    $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
776
  }
777

    
778
  /**
779
   * Test CSS ordering.
780
   */
781
  function testRenderOrder() {
782
    // A module CSS file.
783
    drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
784
    // A few system CSS files, ordered in a strange way.
785
    $system_path = drupal_get_path('module', 'system');
786
    drupal_add_css($system_path . '/system.menus.css', array('group' => CSS_SYSTEM));
787
    drupal_add_css($system_path . '/system.base.css', array('group' => CSS_SYSTEM, 'weight' => -10));
788
    drupal_add_css($system_path . '/system.theme.css', array('group' => CSS_SYSTEM));
789

    
790
    $expected = array(
791
      $system_path . '/system.base.css',
792
      $system_path . '/system.menus.css',
793
      $system_path . '/system.theme.css',
794
      drupal_get_path('module', 'simpletest') . '/simpletest.css',
795
    );
796

    
797

    
798
    $styles = drupal_get_css();
799
    // Stylesheet URL may be the href of a LINK tag or in an @import statement
800
    // of a STYLE tag.
801
    if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
802
      $result = $matches[2];
803
    }
804
    else {
805
      $result = array();
806
    }
807

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

    
811
  /**
812
   * Test CSS override.
813
   */
814
  function testRenderOverride() {
815
    $system = drupal_get_path('module', 'system');
816
    $simpletest = drupal_get_path('module', 'simpletest');
817

    
818
    drupal_add_css($system . '/system.base.css');
819
    drupal_add_css($simpletest . '/tests/system.base.css');
820

    
821
    // The dummy stylesheet should be the only one included.
822
    $styles = drupal_get_css();
823
    $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') !== FALSE, 'The overriding CSS file is output.');
824
    $this->assert(strpos($styles, $system . '/system.base.css') === FALSE, 'The overridden CSS file is not output.');
825

    
826
    drupal_add_css($simpletest . '/tests/system.base.css');
827
    drupal_add_css($system . '/system.base.css');
828

    
829
    // The standard stylesheet should be the only one included.
830
    $styles = drupal_get_css();
831
    $this->assert(strpos($styles, $system . '/system.base.css') !== FALSE, 'The overriding CSS file is output.');
832
    $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') === FALSE, 'The overridden CSS file is not output.');
833
  }
834

    
835
  /**
836
   * Tests Locale module's CSS Alter to include RTL overrides.
837
   */
838
  function testAlter() {
839
    // Switch the language to a right to left language and add system.base.css.
840
    global $language;
841
    $language->direction = LANGUAGE_RTL;
842
    $path = drupal_get_path('module', 'system');
843
    drupal_add_css($path . '/system.base.css');
844

    
845
    // Check to see if system.base-rtl.css was also added.
846
    $styles = drupal_get_css();
847
    $this->assert(strpos($styles, $path . '/system.base-rtl.css') !== FALSE, 'CSS is alterable as right to left overrides are added.');
848

    
849
    // Change the language back to left to right.
850
    $language->direction = LANGUAGE_LTR;
851
  }
852

    
853
  /**
854
   * Tests that the query string remains intact when adding CSS files that have
855
   * query string parameters.
856
   */
857
  function testAddCssFileWithQueryString() {
858
    $this->drupalGet('common-test/query-string');
859
    $query_string = variable_get('css_js_query_string', '0');
860
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.css?' . $query_string, 'Query string was appended correctly to css.');
861
    $this->assertRaw(drupal_get_path('module', 'node') . '/node-fake.css?arg1=value1&amp;arg2=value2', 'Query string not escaped on a URI.');
862
  }
863
}
864

    
865
/**
866
 * Test for cleaning HTML identifiers.
867
 */
868
class DrupalHTMLIdentifierTestCase extends DrupalUnitTestCase {
869
  public static function getInfo() {
870
    return array(
871
      'name' => 'HTML identifiers',
872
      'description' => 'Test the functions drupal_html_class(), drupal_html_id() and drupal_clean_css_identifier() for expected behavior',
873
      'group' => 'System',
874
    );
875
  }
876

    
877
  /**
878
   * Tests that drupal_clean_css_identifier() cleans the identifier properly.
879
   */
880
  function testDrupalCleanCSSIdentifier() {
881
    // Verify that no valid ASCII characters are stripped from the identifier.
882
    $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
883
    $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid ASCII characters pass through.');
884

    
885
    // Verify that valid UTF-8 characters are not stripped from the identifier.
886
    $identifier = '¡¢£¤¥';
887
    $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid UTF-8 characters pass through.');
888

    
889
    // Verify that invalid characters (including non-breaking space) are stripped from the identifier.
890
    $this->assertIdentical(drupal_clean_css_identifier('invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', array()), 'invalididentifier', 'Strip invalid characters.');
891
  }
892

    
893
  /**
894
   * Tests that drupal_html_class() cleans the class name properly.
895
   */
896
  function testDrupalHTMLClass() {
897
    // Verify Drupal coding standards are enforced.
898
    $this->assertIdentical(drupal_html_class('CLASS NAME_[Ü]'), 'class-name--ü', 'Enforce Drupal coding standards.');
899
  }
900

    
901
  /**
902
   * Tests that drupal_html_id() cleans the ID properly.
903
   */
904
  function testDrupalHTMLId() {
905
    // Verify that letters, digits, and hyphens are not stripped from the ID.
906
    $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
907
    $this->assertIdentical(drupal_html_id($id), $id, 'Verify valid characters pass through.');
908

    
909
    // Verify that invalid characters are stripped from the ID.
910
    $this->assertIdentical(drupal_html_id('invalid,./:@\\^`{Üidentifier'), 'invalididentifier', 'Strip invalid characters.');
911

    
912
    // Verify Drupal coding standards are enforced.
913
    $this->assertIdentical(drupal_html_id('ID NAME_[1]'), 'id-name-1', 'Enforce Drupal coding standards.');
914

    
915
    // Reset the static cache so we can ensure the unique id count is at zero.
916
    drupal_static_reset('drupal_html_id');
917

    
918
    // Clean up IDs with invalid starting characters.
919
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id', 'Test the uniqueness of IDs #1.');
920
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--2', 'Test the uniqueness of IDs #2.');
921
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--3', 'Test the uniqueness of IDs #3.');
922
  }
923
}
924

    
925
/**
926
 * CSS Unit Tests.
927
 */
928
class CascadingStylesheetsUnitTest extends DrupalUnitTestCase {
929
  public static function getInfo() {
930
    return array(
931
      'name' => 'CSS Unit Tests',
932
      'description' => 'Unit tests on CSS functions like aggregation.',
933
      'group' => 'System',
934
    );
935
  }
936

    
937
  /**
938
   * Tests basic CSS loading with and without optimization via drupal_load_stylesheet().
939
   *
940
   * Known tests:
941
   * - Retain white-space in selectors. (https://drupal.org/node/472820)
942
   * - Proper URLs in imported files. (https://drupal.org/node/265719)
943
   * - Retain pseudo-selectors. (https://drupal.org/node/460448)
944
   * - Don't adjust data URIs. (https://drupal.org/node/2142441)
945
   * - Files imported from external URLs. (https://drupal.org/node/2014851)
946
   */
947
  function testLoadCssBasic() {
948
    // Array of files to test living in 'simpletest/files/css_test_files/'.
949
    // - Original: name.css
950
    // - Unoptimized expected content: name.css.unoptimized.css
951
    // - Optimized expected content: name.css.optimized.css
952
    $testfiles = array(
953
      'css_input_without_import.css',
954
      'css_input_with_import.css',
955
      'css_subfolder/css_input_with_import.css',
956
      'comment_hacks.css'
957
    );
958
    $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
959
    foreach ($testfiles as $file) {
960
      $file_path = $path . '/' . $file;
961
      $file_url = $GLOBALS['base_url'] . '/' . $file_path;
962

    
963
      $expected = file_get_contents($file_path . '.unoptimized.css');
964
      $unoptimized_output = drupal_load_stylesheet($file_path, FALSE);
965
      $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
966

    
967
      $expected = file_get_contents($file_path . '.optimized.css');
968
      $optimized_output = drupal_load_stylesheet($file_path, TRUE);
969
      $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
970

    
971
      // Repeat the tests by accessing the stylesheets by URL.
972
      $expected = file_get_contents($file_path . '.unoptimized.css');
973
      $unoptimized_output_url = drupal_load_stylesheet($file_url, FALSE);
974
      $this->assertEqual($unoptimized_output_url, $expected, format_string('Unoptimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
975

    
976
      $expected = file_get_contents($file_path . '.optimized.css');
977
      $optimized_output_url = drupal_load_stylesheet($file_url, TRUE);
978
      $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
979
    }
980
  }
981
}
982

    
983
/**
984
 * Test drupal_http_request().
985
 */
986
class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
987
  public static function getInfo() {
988
    return array(
989
      'name' => 'Drupal HTTP request',
990
      'description' => "Performs tests on Drupal's HTTP request mechanism.",
991
      'group' => 'System'
992
    );
993
  }
994

    
995
  function setUp() {
996
    parent::setUp('system_test', 'locale');
997
  }
998

    
999
  function testDrupalHTTPRequest() {
1000
    global $is_https;
1001

    
1002
    // Parse URL schema.
1003
    $missing_scheme = drupal_http_request('example.com/path');
1004
    $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
1005
    $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
1006

    
1007
    $unable_to_parse = drupal_http_request('http:///path');
1008
    $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
1009
    $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
1010

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

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

    
1023
    // Skip the timeout tests when the testing environment is HTTPS because
1024
    // stream_set_timeout() does not work for SSL connections.
1025
    // @link http://bugs.php.net/bug.php?id=47929
1026
    if (!$is_https) {
1027
      // Test that timeout is respected. The test machine is expected to be able
1028
      // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
1029
      // return within a total of 5 seconds. If the test machine is extremely
1030
      // slow, the test will fail. fsockopen() has been seen to time out in
1031
      // slightly less than the specified timeout, so allow a little slack on
1032
      // the minimum expected time (i.e. 1.8 instead of 2).
1033
      timer_start(__METHOD__);
1034
      $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
1035
      $time = timer_read(__METHOD__) / 1000;
1036
      $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
1037
      $this->assertTrue($result->error, 'An error message was returned.');
1038
      $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
1039
    }
1040
  }
1041

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

    
1047
    $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
1048
    $result = drupal_http_request($auth);
1049

    
1050
    $this->drupalSetContent($result->data);
1051
    $this->assertRaw($username, 'Username is passed correctly.');
1052
    $this->assertRaw($password, 'Password is passed correctly.');
1053
  }
1054

    
1055
  function testDrupalHTTPRequestRedirect() {
1056
    $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
1057
    $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
1058

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

    
1062
    $redirect_invalid = drupal_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
1063
    $this->assertEqual($redirect_invalid->code, -1002, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
1064
    $this->assertEqual($redirect_invalid->error, 'missing schema', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
1065

    
1066
    $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
1067
    $this->assertEqual($redirect_invalid->code, -1001, format_string('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
1068
    $this->assertEqual($redirect_invalid->error, 'unable to parse URL', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
1069

    
1070
    $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
1071
    $this->assertEqual($redirect_invalid->code, -1003, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
1072
    $this->assertEqual($redirect_invalid->error, 'invalid schema ftp', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
1073

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

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

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

    
1083
    $redirect_307 = drupal_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
1084
    $this->assertFalse(isset($redirect_307->redirect_code), 'drupal_http_request does not follow 307 redirect if max_redirects = 0.');
1085

    
1086
    $multiple_redirect_final_url = url('system-test/multiple-redirects/0', array('absolute' => TRUE));
1087
    $multiple_redirect_1 = drupal_http_request(url('system-test/multiple-redirects/1', array('absolute' => TRUE)), array('max_redirects' => 1));
1088
    $this->assertEqual($multiple_redirect_1->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 1 redirect.');
1089

    
1090
    $multiple_redirect_3 = drupal_http_request(url('system-test/multiple-redirects/3', array('absolute' => TRUE)), array('max_redirects' => 3));
1091
    $this->assertEqual($multiple_redirect_3->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 3 redirects.');
1092
  }
1093

    
1094
  /**
1095
   * Tests Content-language headers generated by Drupal.
1096
   */
1097
  function testDrupalHTTPRequestHeaders() {
1098
    // Check the default header.
1099
    $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1100
    $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
1101

    
1102
    // Add German language and set as default.
1103
    locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
1104

    
1105
    // Request front page and check for matching Content-Language.
1106
    $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1107
    $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
1108
  }
1109
}
1110

    
1111
/**
1112
 * Tests parsing of the HTTP response status line.
1113
 */
1114
class DrupalHTTPResponseStatusLineTest extends DrupalUnitTestCase {
1115
  public static function getInfo() {
1116
    return array(
1117
      'name' => 'Drupal HTTP request response status parsing',
1118
      'description' => 'Perform unit tests on _drupal_parse_response_status().',
1119
      'group' => 'System',
1120
    );
1121
  }
1122

    
1123
  /**
1124
   * Tests parsing HTTP response status line.
1125
   */
1126
  public function testStatusLine() {
1127
    // Grab the big array of test data from statusLineData().
1128
    $data = $this->statusLineData();
1129
    foreach($data as $test_case) {
1130
      $test_data = array_shift($test_case);
1131
      $expected = array_shift($test_case);
1132

    
1133
      $outcome = _drupal_parse_response_status($test_data);
1134

    
1135
      foreach(array_keys($expected) as $key) {
1136
        $this->assertIdentical($outcome[$key], $expected[$key]);
1137
      }
1138
    }
1139
  }
1140

    
1141
  /**
1142
   * Data provider for testStatusLine().
1143
   *
1144
   * @return array
1145
   *   Test data.
1146
   */
1147
  protected function statusLineData() {
1148
    return array(
1149
      array(
1150
        'HTTP/1.1 200 OK',
1151
        array(
1152
          'http_version' => 'HTTP/1.1',
1153
          'response_code' => '200',
1154
          'reason_phrase' => 'OK',
1155
        ),
1156
      ),
1157
      // Data set with no reason phrase.
1158
      array(
1159
        'HTTP/1.1 200',
1160
        array(
1161
          'http_version' => 'HTTP/1.1',
1162
          'response_code' => '200',
1163
          'reason_phrase' => '',
1164
        ),
1165
      ),
1166
      // Arbitrary strings.
1167
      array(
1168
        'version code multi word explanation',
1169
        array(
1170
          'http_version' => 'version',
1171
          'response_code' => 'code',
1172
          'reason_phrase' => 'multi word explanation',
1173
        ),
1174
      ),
1175
    );
1176
  }
1177
}
1178

    
1179
/**
1180
 * Testing drupal_add_region_content and drupal_get_region_content.
1181
 */
1182
class DrupalSetContentTestCase extends DrupalWebTestCase {
1183
  public static function getInfo() {
1184
    return array(
1185
      'name' => 'Drupal set/get regions',
1186
      'description' => 'Performs tests on setting and retrieiving content from theme regions.',
1187
      'group' => 'System'
1188
    );
1189
  }
1190

    
1191

    
1192
  /**
1193
   * Test setting and retrieving content for theme regions.
1194
   */
1195
  function testRegions() {
1196
    global $theme_key;
1197

    
1198
    $block_regions = array_keys(system_region_list($theme_key));
1199
    $delimiter = $this->randomName(32);
1200
    $values = array();
1201
    // Set some random content for each region available.
1202
    foreach ($block_regions as $region) {
1203
      $first_chunk = $this->randomName(32);
1204
      drupal_add_region_content($region, $first_chunk);
1205
      $second_chunk = $this->randomName(32);
1206
      drupal_add_region_content($region, $second_chunk);
1207
      // Store the expected result for a drupal_get_region_content call for this region.
1208
      $values[$region] = $first_chunk . $delimiter . $second_chunk;
1209
    }
1210

    
1211
    // Ensure drupal_get_region_content returns expected results when fetching all regions.
1212
    $content = drupal_get_region_content(NULL, $delimiter);
1213
    foreach ($content as $region => $region_content) {
1214
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
1215
    }
1216

    
1217
    // Ensure drupal_get_region_content returns expected results when fetching a single region.
1218
    foreach ($block_regions as $region) {
1219
      $region_content = drupal_get_region_content($region, $delimiter);
1220
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
1221
    }
1222
  }
1223
}
1224

    
1225
/**
1226
 * Testing drupal_goto and hook_drupal_goto_alter().
1227
 */
1228
class DrupalGotoTest extends DrupalWebTestCase {
1229
  public static function getInfo() {
1230
    return array(
1231
      'name' => 'Drupal goto',
1232
      'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
1233
      'group' => 'System'
1234
    );
1235
  }
1236

    
1237
  function setUp() {
1238
    parent::setUp('common_test');
1239
  }
1240

    
1241
  /**
1242
   * Test drupal_goto().
1243
   */
1244
  function testDrupalGoto() {
1245
    $this->drupalGet('common-test/drupal_goto/redirect');
1246
    $headers = $this->drupalGetHeaders(TRUE);
1247
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1248
    $this->assertEqual($status, 302, 'Expected response code was sent.');
1249
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1250
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1251

    
1252
    $this->drupalGet('common-test/drupal_goto/redirect_advanced');
1253
    $headers = $this->drupalGetHeaders(TRUE);
1254
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1255
    $this->assertEqual($status, 301, 'Expected response code was sent.');
1256
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1257
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1258

    
1259
    // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
1260
    // to test that the path is encoded and decoded properly.
1261
    $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
1262
    $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
1263
    $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
1264
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto/destination', array('query' => array('foo' => '%25', 'bar' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to given query string destination.');
1265
  }
1266

    
1267
  /**
1268
   * Test hook_drupal_goto_alter().
1269
   */
1270
  function testDrupalGotoAlter() {
1271
    $this->drupalGet('common-test/drupal_goto/redirect_fail');
1272

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

    
1277
  /**
1278
   * Test drupal_get_destination().
1279
   */
1280
  function testDrupalGetDestination() {
1281
    $query = $this->randomName(10);
1282

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

    
1287
    // Verify that the current path is used as destination.
1288
    $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
1289
    $url = 'common-test/destination?' . $query;
1290
    $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
1291
  }
1292
}
1293

    
1294
/**
1295
 * Tests for the JavaScript system.
1296
 */
1297
class JavaScriptTestCase extends DrupalWebTestCase {
1298
  /**
1299
   * Store configured value for JavaScript preprocessing.
1300
   */
1301
  protected $preprocess_js = NULL;
1302

    
1303
  public static function getInfo() {
1304
    return array(
1305
      'name' => 'JavaScript',
1306
      'description' => 'Tests the JavaScript system.',
1307
      'group' => 'System'
1308
    );
1309
  }
1310

    
1311
  function setUp() {
1312
    // Enable Locale and SimpleTest in the test environment.
1313
    parent::setUp('locale', 'simpletest', 'common_test');
1314

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

    
1319
    // Reset drupal_add_js() and drupal_add_library() statics before each test.
1320
    drupal_static_reset('drupal_add_js');
1321
    drupal_static_reset('drupal_add_library');
1322
  }
1323

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

    
1330
  /**
1331
   * Test default JavaScript is empty.
1332
   */
1333
  function testDefault() {
1334
    $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
1335
  }
1336

    
1337
  /**
1338
   * Test adding a JavaScript file.
1339
   */
1340
  function testAddFile() {
1341
    $javascript = drupal_add_js('misc/collapse.js');
1342
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
1343
    $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
1344
    $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
1345
    $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
1346
    url('', array('prefix' => &$prefix));
1347
    $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
1348
  }
1349

    
1350
  /**
1351
   * Test adding settings.
1352
   */
1353
  function testAddSetting() {
1354
    $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
1355
    $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
1356
    $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
1357
  }
1358

    
1359
  /**
1360
   * Tests adding an external JavaScript File.
1361
   */
1362
  function testAddExternal() {
1363
    $path = 'http://example.com/script.js';
1364
    $javascript = drupal_add_js($path, 'external');
1365
    $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
1366
  }
1367

    
1368
  /**
1369
   * Test drupal_get_js() for JavaScript settings.
1370
   */
1371
  function testHeaderSetting() {
1372
    // Only the second of these two entries should appear in Drupal.settings.
1373
    drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
1374
    drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
1375
    // All three of these entries should appear in Drupal.settings.
1376
    drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
1377
    drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
1378
    drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
1379
    // Only the second of these two entries should appear in Drupal.settings.
1380
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
1381
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
1382

    
1383
    $javascript = drupal_get_js('header');
1384
    $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
1385
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
1386
    $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
1387

    
1388
    // Test whether drupal_add_js can be used to override a previous setting.
1389
    $this->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, 'Rendered JavaScript header returns custom setting.');
1390
    $this->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, 'drupal_add_js() correctly overrides a custom setting.');
1391

    
1392
    // Test whether drupal_add_js can be used to add numerically indexed values
1393
    // to an array.
1394
    $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
1395
    $this->assertTrue($array_values_appear, 'drupal_add_js() correctly adds settings to the end of an indexed array.');
1396

    
1397
    // Test whether drupal_add_js can be used to override the entry for an
1398
    // existing key in an associative array.
1399
    $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
1400
    $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
1401
  }
1402

    
1403
  /**
1404
   * Test to see if resetting the JavaScript empties the cache.
1405
   */
1406
  function testReset() {
1407
    drupal_add_js('misc/collapse.js');
1408
    drupal_static_reset('drupal_add_js');
1409
    $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
1410
  }
1411

    
1412
  /**
1413
   * Test adding inline scripts.
1414
   */
1415
  function testAddInline() {
1416
    $inline = 'jQuery(function () { });';
1417
    $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1418
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
1419
    $data = end($javascript);
1420
    $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
1421
  }
1422

    
1423
  /**
1424
   * Test rendering an external JavaScript file.
1425
   */
1426
  function testRenderExternal() {
1427
    $external = 'http://example.com/example.js';
1428
    drupal_add_js($external, 'external');
1429
    $javascript = drupal_get_js();
1430
    // Local files have a base_path() prefix, external files should not.
1431
    $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
1432
  }
1433

    
1434
  /**
1435
   * Test drupal_get_js() with a footer scope.
1436
   */
1437
  function testFooterHTML() {
1438
    $inline = 'jQuery(function () { });';
1439
    drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1440
    $javascript = drupal_get_js('footer');
1441
    $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
1442
  }
1443

    
1444
  /**
1445
   * Test the 'javascript_always_use_jquery' variable.
1446
   */
1447
  function testJavaScriptAlwaysUseJQuery() {
1448
    // The default front page of the site should use jQuery and other standard
1449
    // scripts and settings.
1450
    $this->drupalGet('');
1451
    $this->assertRaw('misc/jquery.js', 'Default behavior: The front page of the site includes jquery.js.');
1452
    $this->assertRaw('misc/drupal.js', 'Default behavior: The front page of the site includes drupal.js.');
1453
    $this->assertRaw('Drupal.settings', 'Default behavior: The front page of the site includes Drupal settings.');
1454
    $this->assertRaw('basePath', 'Default behavior: The front page of the site includes the basePath Drupal setting.');
1455

    
1456
    // The default front page should not use jQuery and other standard scripts
1457
    // and settings when the 'javascript_always_use_jquery' variable is set to
1458
    // FALSE.
1459
    variable_set('javascript_always_use_jquery', FALSE);
1460
    $this->drupalGet('');
1461
    $this->assertNoRaw('misc/jquery.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include jquery.js.');
1462
    $this->assertNoRaw('misc/drupal.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include drupal.js.');
1463
    $this->assertNoRaw('Drupal.settings', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include Drupal settings.');
1464
    $this->assertNoRaw('basePath', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include the basePath Drupal setting.');
1465
    variable_del('javascript_always_use_jquery');
1466

    
1467
    // When only settings have been added via drupal_add_js(), drupal_get_js()
1468
    // should still return jQuery and other standard scripts and settings.
1469
    $this->resetStaticVariables();
1470
    drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
1471
    $javascript = drupal_get_js();
1472
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes jquery.js.');
1473
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes drupal.js.');
1474
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes Drupal.settings.');
1475
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the basePath Drupal setting.');
1476
    $this->assertTrue(strpos($javascript, 'testJavaScriptSetting') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the added Drupal settings.');
1477

    
1478
    // When only settings have been added via drupal_add_js() and the
1479
    // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
1480
    // should not return jQuery and other standard scripts and settings, nor
1481
    // should it return the requested settings (since they cannot actually be
1482
    // addded to the page without jQuery).
1483
    $this->resetStaticVariables();
1484
    variable_set('javascript_always_use_jquery', FALSE);
1485
    drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
1486
    $javascript = drupal_get_js();
1487
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include jquery.js.');
1488
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include drupal.js.');
1489
    $this->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include Drupal.settings.');
1490
    $this->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the basePath Drupal setting.');
1491
    $this->assertTrue(strpos($javascript, 'testJavaScriptSetting') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the added Drupal settings.');
1492
    variable_del('javascript_always_use_jquery');
1493

    
1494
    // When a regular file has been added via drupal_add_js(), drupal_get_js()
1495
    // should return jQuery and other standard scripts and settings.
1496
    $this->resetStaticVariables();
1497
    drupal_add_js('misc/collapse.js');
1498
    $javascript = drupal_get_js();
1499
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
1500
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
1501
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
1502
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
1503
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
1504

    
1505
    // When a regular file has been added via drupal_add_js() and the
1506
    // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
1507
    // should still return jQuery and other standard scripts and settings
1508
    // (since the file is assumed to require jQuery by default).
1509
    $this->resetStaticVariables();
1510
    variable_set('javascript_always_use_jquery', FALSE);
1511
    drupal_add_js('misc/collapse.js');
1512
    $javascript = drupal_get_js();
1513
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
1514
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
1515
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
1516
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
1517
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
1518
    variable_del('javascript_always_use_jquery');
1519

    
1520
    // When a file that does not require jQuery has been added via
1521
    // drupal_add_js(), drupal_get_js() should still return jQuery and other
1522
    // standard scripts and settings by default.
1523
    $this->resetStaticVariables();
1524
    drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
1525
    $javascript = drupal_get_js();
1526
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes jquery.js.');
1527
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes drupal.js.');
1528
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes Drupal.settings.');
1529
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the basePath Drupal setting.');
1530
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
1531

    
1532
    // When a file that does not require jQuery has been added via
1533
    // drupal_add_js() and the 'javascript_always_use_jquery' variable is set
1534
    // to FALSE, drupal_get_js() should not return jQuery and other standard
1535
    // scripts and setting, but it should still return the requested file.
1536
    $this->resetStaticVariables();
1537
    variable_set('javascript_always_use_jquery', FALSE);
1538
    drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
1539
    $javascript = drupal_get_js();
1540
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include jquery.js.');
1541
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include drupal.js.');
1542
    $this->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include Drupal.settings.');
1543
    $this->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include the basePath Drupal setting.');
1544
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
1545
    variable_del('javascript_always_use_jquery');
1546

    
1547
    // When 'javascript_always_use_jquery' is set to FALSE and a file that does
1548
    // not require jQuery is added, followed by one that does, drupal_get_js()
1549
    // should return jQuery and other standard scripts and settings, in
1550
    // addition to both of the requested files.
1551
    $this->resetStaticVariables();
1552
    variable_set('javascript_always_use_jquery', FALSE);
1553
    drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
1554
    drupal_add_js('misc/ajax.js');
1555
    $javascript = drupal_get_js();
1556
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes jquery.js.');
1557
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes drupal.js.');
1558
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes Drupal.settings.');
1559
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the basePath Drupal setting.');
1560
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the first custom file.');
1561
    $this->assertTrue(strpos($javascript, 'misc/ajax.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the second custom file.');
1562
    variable_del('javascript_always_use_jquery');
1563
  }
1564

    
1565
  /**
1566
   * Test drupal_add_js() sets preproccess to false when cache is set to false.
1567
   */
1568
  function testNoCache() {
1569
    $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
1570
    $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
1571
  }
1572

    
1573
  /**
1574
   * Test adding a JavaScript file with a different group.
1575
   */
1576
  function testDifferentGroup() {
1577
    $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
1578
    $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
1579
  }
1580

    
1581
  /**
1582
   * Test adding a JavaScript file with a different weight.
1583
   */
1584
  function testDifferentWeight() {
1585
    $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
1586
    $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
1587
  }
1588

    
1589
  /**
1590
   * Tests JavaScript aggregation when files are added to a different scope.
1591
   */
1592
  function testAggregationOrder() {
1593
    // Enable JavaScript aggregation.
1594
    variable_set('preprocess_js', 1);
1595
    drupal_static_reset('drupal_add_js');
1596

    
1597
    // Add two JavaScript files to the current request and build the cache.
1598
    drupal_add_js('misc/ajax.js');
1599
    drupal_add_js('misc/autocomplete.js');
1600

    
1601
    $js_items = drupal_add_js();
1602
    drupal_build_js_cache(array(
1603
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1604
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1605
    ));
1606

    
1607
    // Store the expected key for the first item in the cache.
1608
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1609
    $expected_key = $cache[0];
1610

    
1611
    // Reset variables and add a file in a different scope first.
1612
    variable_del('drupal_js_cache_files');
1613
    drupal_static_reset('drupal_add_js');
1614
    drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
1615
    drupal_add_js('misc/ajax.js');
1616
    drupal_add_js('misc/autocomplete.js');
1617

    
1618
    // Rebuild the cache.
1619
    $js_items = drupal_add_js();
1620
    drupal_build_js_cache(array(
1621
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1622
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1623
    ));
1624

    
1625
    // Compare the expected key for the first file to the current one.
1626
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1627
    $key = $cache[0];
1628
    $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
1629
  }
1630

    
1631
  /**
1632
   * Test JavaScript ordering.
1633
   */
1634
  function testRenderOrder() {
1635
    // Add a bunch of JavaScript in strange ordering.
1636
    drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1637
    drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1638
    drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1639
    drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1640
    drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1641
    drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1642
    drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
1643
    drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1644
    drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1645
    drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1646

    
1647
    // Construct the expected result from the regex.
1648
    $expected = array(
1649
      "-8 #1",
1650
      "-8 #2",
1651
      "-8 #3",
1652
      "-8 #4",
1653
      "-5 #1", // The external script.
1654
      "0 #1",
1655
      "0 #2",
1656
      "0 #3",
1657
      "5 #1",
1658
      "5 #2",
1659
    );
1660

    
1661
    // Retrieve the rendered JavaScript and test against the regex.
1662
    $js = drupal_get_js('footer');
1663
    $matches = array();
1664
    if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
1665
      $result = $matches[1];
1666
    }
1667
    else {
1668
      $result = array();
1669
    }
1670
    $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
1671
  }
1672

    
1673
  /**
1674
   * Test rendering the JavaScript with a file's weight above jQuery's.
1675
   */
1676
  function testRenderDifferentWeight() {
1677
    // JavaScript files are sorted first by group, then by the 'every_page'
1678
    // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
1679
    // weight, we need the other two options to be the same.
1680
    drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
1681
    $javascript = drupal_get_js();
1682
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
1683
  }
1684

    
1685
  /**
1686
   * Test altering a JavaScript's weight via hook_js_alter().
1687
   *
1688
   * @see simpletest_js_alter()
1689
   */
1690
  function testAlter() {
1691
    // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
1692
    drupal_add_js('misc/tableselect.js');
1693
    drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
1694

    
1695
    // Render the JavaScript, testing if simpletest.js was altered to be before
1696
    // tableselect.js. See simpletest_js_alter() to see where this alteration
1697
    // takes place.
1698
    $javascript = drupal_get_js();
1699
    $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
1700
  }
1701

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

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

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

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

    
1740
  /**
1741
   * Tests non-existing libraries.
1742
   */
1743
  function testLibraryUnknown() {
1744
    $result = drupal_get_library('unknown', 'unknown');
1745
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1746
    drupal_static_reset('drupal_get_library');
1747

    
1748
    $result = drupal_add_library('unknown', 'unknown');
1749
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1750
    $scripts = drupal_get_js();
1751
    $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
1752
  }
1753

    
1754
  /**
1755
   * Tests the addition of libraries through the #attached['library'] property.
1756
   */
1757
  function testAttachedLibrary() {
1758
    $element['#attached']['library'][] = array('system', 'farbtastic');
1759
    drupal_render($element);
1760
    $scripts = drupal_get_js();
1761
    $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
1762
  }
1763

    
1764
  /**
1765
   * Tests retrieval of libraries via drupal_get_library().
1766
   */
1767
  function testGetLibrary() {
1768
    // Retrieve all libraries registered by a module.
1769
    $libraries = drupal_get_library('common_test');
1770
    $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
1771
    // Retrieve all libraries for a module not implementing hook_library().
1772
    // Note: This test installs Locale module.
1773
    $libraries = drupal_get_library('locale');
1774
    $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
1775

    
1776
    // Retrieve a specific library by module and name.
1777
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
1778
    $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
1779
    // Retrieve a non-existing library by module and name.
1780
    $farbtastic = drupal_get_library('common_test', 'foo');
1781
    $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
1782
  }
1783

    
1784
  /**
1785
   * Tests that the query string remains intact when adding JavaScript files
1786
   *  that have query string parameters.
1787
   */
1788
  function testAddJsFileWithQueryString() {
1789
    $this->drupalGet('common-test/query-string');
1790
    $query_string = variable_get('css_js_query_string', '0');
1791
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
1792
  }
1793

    
1794
  /**
1795
   * Resets static variables related to adding JavaScript to a page.
1796
   */
1797
  function resetStaticVariables() {
1798
    drupal_static_reset('drupal_add_js');
1799
    drupal_static_reset('drupal_add_library');
1800
    drupal_static_reset('drupal_get_library');
1801
  }
1802
}
1803

    
1804
/**
1805
 * Tests for drupal_render().
1806
 */
1807
class DrupalRenderTestCase extends DrupalWebTestCase {
1808
  public static function getInfo() {
1809
    return array(
1810
      'name' => 'drupal_render()',
1811
      'description' => 'Performs functional tests on drupal_render().',
1812
      'group' => 'System',
1813
    );
1814
  }
1815

    
1816
  function setUp() {
1817
    parent::setUp('common_test');
1818
  }
1819

    
1820
  /**
1821
   * Tests the output drupal_render() for some elementary input values.
1822
   */
1823
  function testDrupalRenderBasics() {
1824
    $types = array(
1825
      array(
1826
        'name' => 'null',
1827
        'value' => NULL,
1828
        'expected' => '',
1829
      ),
1830
      array(
1831
        'name' => 'no value',
1832
        'expected' => '',
1833
      ),
1834
      array(
1835
        'name' => 'empty string',
1836
        'value' => '',
1837
        'expected' => '',
1838
      ),
1839
      array(
1840
        'name' => 'no access',
1841
        'value' => array(
1842
          '#markup' => 'foo',
1843
          '#access' => FALSE,
1844
        ),
1845
        'expected' => '',
1846
      ),
1847
      array(
1848
        'name' => 'previously printed',
1849
        'value' => array(
1850
          '#markup' => 'foo',
1851
          '#printed' => TRUE,
1852
        ),
1853
        'expected' => '',
1854
      ),
1855
      array(
1856
        'name' => 'printed in prerender',
1857
        'value' => array(
1858
          '#markup' => 'foo',
1859
          '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
1860
        ),
1861
        'expected' => '',
1862
      ),
1863
      array(
1864
        'name' => 'basic renderable array',
1865
        'value' => array('#markup' => 'foo'),
1866
        'expected' => 'foo',
1867
      ),
1868
    );
1869
    foreach($types as $type) {
1870
      $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
1871
    }
1872
  }
1873

    
1874
  /**
1875
   * Test sorting by weight.
1876
   */
1877
  function testDrupalRenderSorting() {
1878
    $first = $this->randomName();
1879
    $second = $this->randomName();
1880
    // Build an array with '#weight' set for each element.
1881
    $elements = array(
1882
      'second' => array(
1883
        '#weight' => 10,
1884
        '#markup' => $second,
1885
      ),
1886
      'first' => array(
1887
        '#weight' => 0,
1888
        '#markup' => $first,
1889
      ),
1890
    );
1891
    $output = drupal_render($elements);
1892

    
1893
    // The lowest weight element should appear last in $output.
1894
    $this->assertTrue(strpos($output, $second) > strpos($output, $first), 'Elements were sorted correctly by weight.');
1895

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

    
1899
    // Pass $elements through element_children() and ensure it remains
1900
    // sorted in the correct order. drupal_render() will return an empty string
1901
    // if used on the same array in the same request.
1902
    $children = element_children($elements);
1903
    $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
1904
    $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
1905

    
1906

    
1907
    // The same array structure again, but with #sorted set to TRUE.
1908
    $elements = array(
1909
      'second' => array(
1910
        '#weight' => 10,
1911
        '#markup' => $second,
1912
      ),
1913
      'first' => array(
1914
        '#weight' => 0,
1915
        '#markup' => $first,
1916
      ),
1917
      '#sorted' => TRUE,
1918
    );
1919
    $output = drupal_render($elements);
1920

    
1921
    // The elements should appear in output in the same order as the array.
1922
    $this->assertTrue(strpos($output, $second) < strpos($output, $first), 'Elements were not sorted.');
1923
  }
1924

    
1925
  /**
1926
   * Test #attached functionality in children elements.
1927
   */
1928
  function testDrupalRenderChildrenAttached() {
1929
    // The cache system is turned off for POST requests.
1930
    $request_method = $_SERVER['REQUEST_METHOD'];
1931
    $_SERVER['REQUEST_METHOD'] = 'GET';
1932

    
1933
    // Create an element with a child and subchild.  Each element loads a
1934
    // different JavaScript file using #attached.
1935
    $parent_js = drupal_get_path('module', 'user') . '/user.js';
1936
    $child_js = drupal_get_path('module', 'forum') . '/forum.js';
1937
    $subchild_js = drupal_get_path('module', 'book') . '/book.js';
1938
    $element = array(
1939
      '#type' => 'fieldset',
1940
      '#cache' => array(
1941
        'keys' => array('simpletest', 'drupal_render', 'children_attached'),
1942
      ),
1943
      '#attached' => array('js' => array($parent_js)),
1944
      '#title' => 'Parent',
1945
    );
1946
    $element['child'] = array(
1947
      '#type' => 'fieldset',
1948
      '#attached' => array('js' => array($child_js)),
1949
      '#title' => 'Child',
1950
    );
1951
    $element['child']['subchild'] = array(
1952
      '#attached' => array('js' => array($subchild_js)),
1953
      '#markup' => 'Subchild',
1954
    );
1955

    
1956
    // Render the element and verify the presence of #attached JavaScript.
1957
    drupal_render($element);
1958
    $scripts = drupal_get_js();
1959
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
1960
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
1961
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
1962

    
1963
    // Load the element from cache and verify the presence of the #attached
1964
    // JavaScript.
1965
    drupal_static_reset('drupal_add_js');
1966
    $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
1967
    $scripts = drupal_get_js();
1968
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
1969
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
1970
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
1971

    
1972
    $_SERVER['REQUEST_METHOD'] = $request_method;
1973
  }
1974

    
1975
  /**
1976
   * Test passing arguments to the theme function.
1977
   */
1978
  function testDrupalRenderThemeArguments() {
1979
    $element = array(
1980
      '#theme' => 'common_test_foo',
1981
    );
1982
    // Test that defaults work.
1983
    $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
1984
    $element = array(
1985
      '#theme' => 'common_test_foo',
1986
      '#foo' => $this->randomName(),
1987
      '#bar' => $this->randomName(),
1988
    );
1989
    // Test that passing arguments to the theme function works.
1990
    $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
1991
  }
1992

    
1993
  /**
1994
   * Test rendering form elements without passing through form_builder().
1995
   */
1996
  function testDrupalRenderFormElements() {
1997
    // Define a series of form elements.
1998
    $element = array(
1999
      '#type' => 'button',
2000
      '#value' => $this->randomName(),
2001
    );
2002
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
2003

    
2004
    $element = array(
2005
      '#type' => 'textfield',
2006
      '#title' => $this->randomName(),
2007
      '#value' => $this->randomName(),
2008
    );
2009
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
2010

    
2011
    $element = array(
2012
      '#type' => 'password',
2013
      '#title' => $this->randomName(),
2014
    );
2015
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
2016

    
2017
    $element = array(
2018
      '#type' => 'textarea',
2019
      '#title' => $this->randomName(),
2020
      '#value' => $this->randomName(),
2021
    );
2022
    $this->assertRenderedElement($element, '//textarea');
2023

    
2024
    $element = array(
2025
      '#type' => 'radio',
2026
      '#title' => $this->randomName(),
2027
      '#value' => FALSE,
2028
    );
2029
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
2030

    
2031
    $element = array(
2032
      '#type' => 'checkbox',
2033
      '#title' => $this->randomName(),
2034
    );
2035
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
2036

    
2037
    $element = array(
2038
      '#type' => 'select',
2039
      '#title' => $this->randomName(),
2040
      '#options' => array(
2041
        0 => $this->randomName(),
2042
        1 => $this->randomName(),
2043
      ),
2044
    );
2045
    $this->assertRenderedElement($element, '//select');
2046

    
2047
    $element = array(
2048
      '#type' => 'file',
2049
      '#title' => $this->randomName(),
2050
    );
2051
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
2052

    
2053
    $element = array(
2054
      '#type' => 'item',
2055
      '#title' => $this->randomName(),
2056
      '#markup' => $this->randomName(),
2057
    );
2058
    $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
2059
      ':class' => 'form-type-item',
2060
      ':markup' => $element['#markup'],
2061
      ':label' => $element['#title'],
2062
    ));
2063

    
2064
    $element = array(
2065
      '#type' => 'hidden',
2066
      '#title' => $this->randomName(),
2067
      '#value' => $this->randomName(),
2068
    );
2069
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
2070

    
2071
    $element = array(
2072
      '#type' => 'link',
2073
      '#title' => $this->randomName(),
2074
      '#href' => $this->randomName(),
2075
      '#options' => array(
2076
        'absolute' => TRUE,
2077
      ),
2078
    );
2079
    $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
2080
      ':href' => url($element['#href'], array('absolute' => TRUE)),
2081
      ':title' => $element['#title'],
2082
    ));
2083

    
2084
    $element = array(
2085
      '#type' => 'fieldset',
2086
      '#title' => $this->randomName(),
2087
    );
2088
    $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
2089
      ':title' => $element['#title'],
2090
    ));
2091

    
2092
    $element['item'] = array(
2093
      '#type' => 'item',
2094
      '#title' => $this->randomName(),
2095
      '#markup' => $this->randomName(),
2096
    );
2097
    $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
2098
      ':class' => 'form-type-item',
2099
      ':markup' => $element['item']['#markup'],
2100
    ));
2101
  }
2102

    
2103
  protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
2104
    $original_element = $element;
2105
    $this->drupalSetContent(drupal_render($element));
2106
    $this->verbose('<pre>' .  check_plain(var_export($original_element, TRUE)) . '</pre>'
2107
      . '<pre>' .  check_plain(var_export($element, TRUE)) . '</pre>'
2108
      . '<hr />' . $this->drupalGetContent()
2109
    );
2110

    
2111
    // @see DrupalWebTestCase::xpath()
2112
    $xpath = $this->buildXPathQuery($xpath, $xpath_args);
2113
    $element += array('#value' => NULL);
2114
    $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
2115
      '@type' => var_export($element['#type'], TRUE),
2116
    )));
2117
  }
2118

    
2119
  /**
2120
   * Tests caching of an empty render item.
2121
   */
2122
  function testDrupalRenderCache() {
2123
    // Force a request via GET.
2124
    $request_method = $_SERVER['REQUEST_METHOD'];
2125
    $_SERVER['REQUEST_METHOD'] = 'GET';
2126
    // Create an empty element.
2127
    $test_element = array(
2128
      '#cache' => array(
2129
        'cid' => 'render_cache_test',
2130
      ),
2131
      '#markup' => '',
2132
    );
2133

    
2134
    // Render the element and confirm that it goes through the rendering
2135
    // process (which will set $element['#printed']).
2136
    $element = $test_element;
2137
    drupal_render($element);
2138
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
2139

    
2140
    // Render the element again and confirm that it is retrieved from the cache
2141
    // instead (so $element['#printed'] will not be set).
2142
    $element = $test_element;
2143
    drupal_render($element);
2144
    $this->assertFalse(isset($element['#printed']), 'Cache hit');
2145

    
2146
    // Restore the previous request method.
2147
    $_SERVER['REQUEST_METHOD'] = $request_method;
2148
  }
2149
}
2150

    
2151
/**
2152
 * Test for valid_url().
2153
 */
2154
class ValidUrlTestCase extends DrupalUnitTestCase {
2155
  public static function getInfo() {
2156
    return array(
2157
      'name' => 'Valid URL',
2158
      'description' => "Performs tests on Drupal's valid URL function.",
2159
      'group' => 'System'
2160
    );
2161
  }
2162

    
2163
  /**
2164
   * Test valid absolute URLs.
2165
   */
2166
  function testValidAbsolute() {
2167
    $url_schemes = array('http', 'https', 'ftp');
2168
    $valid_absolute_urls = array(
2169
      'example.com',
2170
      'www.example.com',
2171
      'ex-ample.com',
2172
      '3xampl3.com',
2173
      'example.com/paren(the)sis',
2174
      'example.com/index.html#pagetop',
2175
      'example.com:8080',
2176
      'subdomain.example.com',
2177
      'example.com/index.php?q=node',
2178
      'example.com/index.php?q=node&param=false',
2179
      'user@www.example.com',
2180
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
2181
      '127.0.0.1',
2182
      'example.org?',
2183
      'john%20doe:secret:foo@example.org/',
2184
      'example.org/~,$\'*;',
2185
      'caf%C3%A9.example.org',
2186
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
2187
    );
2188

    
2189
    foreach ($url_schemes as $scheme) {
2190
      foreach ($valid_absolute_urls as $url) {
2191
        $test_url = $scheme . '://' . $url;
2192
        $valid_url = valid_url($test_url, TRUE);
2193
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2194
      }
2195
    }
2196
  }
2197

    
2198
  /**
2199
   * Test invalid absolute URLs.
2200
   */
2201
  function testInvalidAbsolute() {
2202
    $url_schemes = array('http', 'https', 'ftp');
2203
    $invalid_ablosule_urls = array(
2204
      '',
2205
      'ex!ample.com',
2206
      'ex%ample.com',
2207
    );
2208

    
2209
    foreach ($url_schemes as $scheme) {
2210
      foreach ($invalid_ablosule_urls as $url) {
2211
        $test_url = $scheme . '://' . $url;
2212
        $valid_url = valid_url($test_url, TRUE);
2213
        $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2214
      }
2215
    }
2216
  }
2217

    
2218
  /**
2219
   * Test valid relative URLs.
2220
   */
2221
  function testValidRelative() {
2222
    $valid_relative_urls = array(
2223
      'paren(the)sis',
2224
      'index.html#pagetop',
2225
      'index.php?q=node',
2226
      'index.php?q=node&param=false',
2227
      'login.php?do=login&style=%23#pagetop',
2228
    );
2229

    
2230
    foreach (array('', '/') as $front) {
2231
      foreach ($valid_relative_urls as $url) {
2232
        $test_url = $front . $url;
2233
        $valid_url = valid_url($test_url);
2234
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2235
      }
2236
    }
2237
  }
2238

    
2239
  /**
2240
   * Test invalid relative URLs.
2241
   */
2242
  function testInvalidRelative() {
2243
    $invalid_relative_urls = array(
2244
      'ex^mple',
2245
      'example<>',
2246
      'ex%ample',
2247
    );
2248

    
2249
    foreach (array('', '/') as $front) {
2250
      foreach ($invalid_relative_urls as $url) {
2251
        $test_url = $front . $url;
2252
        $valid_url = valid_url($test_url);
2253
        $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2254
      }
2255
    }
2256
  }
2257
}
2258

    
2259
/**
2260
 * Tests for CRUD API functions.
2261
 */
2262
class DrupalDataApiTest extends DrupalWebTestCase {
2263
  public static function getInfo() {
2264
    return array(
2265
      'name' => 'Data API functions',
2266
      'description' => 'Tests the performance of CRUD APIs.',
2267
      'group' => 'System',
2268
    );
2269
  }
2270

    
2271
  function setUp() {
2272
    parent::setUp('database_test');
2273
  }
2274

    
2275
  /**
2276
   * Test the drupal_write_record() API function.
2277
   */
2278
  function testDrupalWriteRecord() {
2279
    // Insert a record - no columns allow NULL values.
2280
    $person = new stdClass();
2281
    $person->name = 'John';
2282
    $person->unknown_column = 123;
2283
    $insert_result = drupal_write_record('test', $person);
2284
    $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with drupal_write_record() for a table with a single-field primary key.');
2285
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2286
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2287
    $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
2288

    
2289
    // Verify that the record was inserted.
2290
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2291
    $this->assertIdentical($result->name, 'John', 'Name field set.');
2292
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2293
    $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
2294
    $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
2295

    
2296
    // Update the newly created record.
2297
    $person->name = 'Peter';
2298
    $person->age = 27;
2299
    $person->job = NULL;
2300
    $update_result = drupal_write_record('test', $person, array('id'));
2301
    $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
2302

    
2303
    // Verify that the record was updated.
2304
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2305
    $this->assertIdentical($result->name, 'Peter', 'Name field set.');
2306
    $this->assertIdentical($result->age, '27', 'Age field set.');
2307
    $this->assertIdentical($result->job, '', 'Job field set and cast to string.');
2308

    
2309
    // Try to insert NULL in columns that does not allow this.
2310
    $person = new stdClass();
2311
    $person->name = 'Ringo';
2312
    $person->age = NULL;
2313
    $person->job = NULL;
2314
    $insert_result = drupal_write_record('test', $person);
2315
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2316
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2317
    $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
2318
    $this->assertIdentical($result->age, '0', 'Age field set.');
2319
    $this->assertIdentical($result->job, '', 'Job field set.');
2320

    
2321
    // Insert a record - the "age" column allows NULL.
2322
    $person = new stdClass();
2323
    $person->name = 'Paul';
2324
    $person->age = NULL;
2325
    $insert_result = drupal_write_record('test_null', $person);
2326
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2327
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2328
    $this->assertIdentical($result->name, 'Paul', 'Name field set.');
2329
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2330

    
2331
    // Insert a record - do not specify the value of a column that allows NULL.
2332
    $person = new stdClass();
2333
    $person->name = 'Meredith';
2334
    $insert_result = drupal_write_record('test_null', $person);
2335
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2336
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2337
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2338
    $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
2339
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2340

    
2341
    // Update the newly created record.
2342
    $person->name = 'Mary';
2343
    $person->age = NULL;
2344
    $update_result = drupal_write_record('test_null', $person, array('id'));
2345
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2346
    $this->assertIdentical($result->name, 'Mary', 'Name field set.');
2347
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2348

    
2349
    // Insert a record - the "data" column should be serialized.
2350
    $person = new stdClass();
2351
    $person->name = 'Dave';
2352
    $update_result = drupal_write_record('test_serialized', $person);
2353
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2354
    $this->assertIdentical($result->name, 'Dave', 'Name field set.');
2355
    $this->assertIdentical($result->info, NULL, 'Info field set.');
2356

    
2357
    $person->info = array();
2358
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2359
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2360
    $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
2361

    
2362
    // Update the serialized record.
2363
    $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
2364
    $person->info = $data;
2365
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2366
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2367
    $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
2368

    
2369
    // Run an update query where no field values are changed. The database
2370
    // layer should return zero for number of affected rows, but
2371
    // db_write_record() should still return SAVED_UPDATED.
2372
    $update_result = drupal_write_record('test_null', $person, array('id'));
2373
    $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a valid update is run without changing any values.');
2374

    
2375
    // Insert an object record for a table with a multi-field primary key.
2376
    $node_access = new stdClass();
2377
    $node_access->nid = mt_rand();
2378
    $node_access->gid = mt_rand();
2379
    $node_access->realm = $this->randomName();
2380
    $insert_result = drupal_write_record('node_access', $node_access);
2381
    $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with drupal_write_record() for a table with a multi-field primary key.');
2382

    
2383
    // Update the record.
2384
    $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
2385
    $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record is updated with drupal_write_record() for a table with a multi-field primary key.');
2386
  }
2387

    
2388
}
2389

    
2390
/**
2391
 * Tests Simpletest error and exception collector.
2392
 */
2393
class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
2394

    
2395
  /**
2396
   * Errors triggered during the test.
2397
   *
2398
   * Errors are intercepted by the overriden implementation
2399
   * of DrupalWebTestCase::error below.
2400
   *
2401
   * @var Array
2402
   */
2403
  protected $collectedErrors = array();
2404

    
2405
  public static function getInfo() {
2406
    return array(
2407
      'name' => 'SimpleTest error collector',
2408
      'description' => 'Performs tests on the Simpletest error and exception collector.',
2409
      'group' => 'SimpleTest',
2410
    );
2411
  }
2412

    
2413
  function setUp() {
2414
    parent::setUp('system_test', 'error_test');
2415
  }
2416

    
2417
  /**
2418
   * Test that simpletest collects errors from the tested site.
2419
   */
2420
  function testErrorCollect() {
2421
    $this->collectedErrors = array();
2422
    $this->drupalGet('error-test/generate-warnings-with-report');
2423
    $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
2424

    
2425
    if (count($this->collectedErrors) == 3) {
2426
      $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
2427
      $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
2428
      $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
2429
    }
2430
    else {
2431
      // Give back the errors to the log report.
2432
      foreach ($this->collectedErrors as $error) {
2433
        parent::error($error['message'], $error['group'], $error['caller']);
2434
      }
2435
    }
2436
  }
2437

    
2438
  /**
2439
   * Error handler that collects errors in an array.
2440
   *
2441
   * This test class is trying to verify that simpletest correctly sees errors
2442
   * and warnings. However, it can't generate errors and warnings that
2443
   * propagate up to the testing framework itself, or these tests would always
2444
   * fail. So, this special copy of error() doesn't propagate the errors up
2445
   * the class hierarchy. It just stuffs them into a protected collectedErrors
2446
   * array for various assertions to inspect.
2447
   */
2448
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
2449
    // Due to a WTF elsewhere, simpletest treats debug() and verbose()
2450
    // messages as if they were an 'error'. But, we don't want to collect
2451
    // those here. This function just wants to collect the real errors (PHP
2452
    // notices, PHP fatal errors, etc.), and let all the 'errors' from the
2453
    // 'User notice' group bubble up to the parent classes to be handled (and
2454
    // eventually displayed) as normal.
2455
    if ($group == 'User notice') {
2456
      parent::error($message, $group, $caller);
2457
    }
2458
    // Everything else should be collected but not propagated.
2459
    else {
2460
      $this->collectedErrors[] = array(
2461
        'message' => $message,
2462
        'group' => $group,
2463
        'caller' => $caller
2464
      );
2465
    }
2466
  }
2467

    
2468
  /**
2469
   * Assert that a collected error matches what we are expecting.
2470
   */
2471
  function assertError($error, $group, $function, $file, $message = NULL) {
2472
    $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
2473
    $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
2474
    $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
2475
    if (isset($message)) {
2476
      $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
2477
    }
2478
  }
2479
}
2480

    
2481
/**
2482
 * Test the drupal_parse_info_file() API function.
2483
 */
2484
class ParseInfoFilesTestCase extends DrupalUnitTestCase {
2485
  public static function getInfo() {
2486
    return array(
2487
      'name' => 'Parsing .info files',
2488
      'description' => 'Tests parsing .info files.',
2489
      'group' => 'System',
2490
    );
2491
  }
2492

    
2493
  /**
2494
   * Parse an example .info file an verify the results.
2495
   */
2496
  function testParseInfoFile() {
2497
    $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
2498
    $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
2499
    $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
2500
    $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
2501
  }
2502
}
2503

    
2504
/**
2505
 * Tests for the drupal_system_listing() function.
2506
 */
2507
class DrupalSystemListingTestCase extends DrupalWebTestCase {
2508
  /**
2509
   * Use the testing profile; this is needed for testDirectoryPrecedence().
2510
   */
2511
  protected $profile = 'testing';
2512

    
2513
  public static function getInfo() {
2514
    return array(
2515
      'name' => 'Drupal system listing',
2516
      'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
2517
      'group' => 'System',
2518
    );
2519
  }
2520

    
2521
  /**
2522
   * Test that files in different directories take precedence as expected.
2523
   */
2524
  function testDirectoryPrecedence() {
2525
    // Define the module files we will search for, and the directory precedence
2526
    // we expect.
2527
    $expected_directories = array(
2528
      // When the copy of the module in the profile directory is incompatible
2529
      // with Drupal core, the copy in the core modules directory takes
2530
      // precedence.
2531
      'drupal_system_listing_incompatible_test' => array(
2532
        'modules/simpletest/tests',
2533
        'profiles/testing/modules',
2534
      ),
2535
      // When both copies of the module are compatible with Drupal core, the
2536
      // copy in the profile directory takes precedence.
2537
      'drupal_system_listing_compatible_test' => array(
2538
        'profiles/testing/modules',
2539
        'modules/simpletest/tests',
2540
      ),
2541
    );
2542

    
2543
    // This test relies on two versions of the same module existing in
2544
    // different places in the filesystem. Without that, the test has no
2545
    // meaning, so assert their presence first.
2546
    foreach ($expected_directories as $module => $directories) {
2547
      foreach ($directories as $directory) {
2548
        $filename = "$directory/$module/$module.module";
2549
        $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
2550
      }
2551
    }
2552

    
2553
    // Now scan the directories and check that the files take precedence as
2554
    // expected.
2555
    $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
2556
    foreach ($expected_directories as $module => $directories) {
2557
      $expected_directory = array_shift($directories);
2558
      $expected_filename = "$expected_directory/$module/$module.module";
2559
      $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
2560
    }
2561
  }
2562
}
2563

    
2564
/**
2565
 * Tests for the format_date() function.
2566
 */
2567
class FormatDateUnitTest extends DrupalWebTestCase {
2568

    
2569
  /**
2570
   * Arbitrary langcode for a custom language.
2571
   */
2572
  const LANGCODE = 'xx';
2573

    
2574
  public static function getInfo() {
2575
    return array(
2576
      'name' => 'Format date',
2577
      'description' => 'Test the format_date() function.',
2578
      'group' => 'System',
2579
    );
2580
  }
2581

    
2582
  function setUp() {
2583
    parent::setUp('locale');
2584
    variable_set('configurable_timezones', 1);
2585
    variable_set('date_format_long', 'l, j. F Y - G:i');
2586
    variable_set('date_format_medium', 'j. F Y - G:i');
2587
    variable_set('date_format_short', 'Y M j - g:ia');
2588
    variable_set('locale_custom_strings_' . self::LANGCODE, array(
2589
      '' => array('Sunday' => 'domingo'),
2590
      'Long month name' => array('March' => 'marzo'),
2591
    ));
2592
    $this->refreshVariables();
2593
  }
2594

    
2595
  /**
2596
   * Test admin-defined formats in format_date().
2597
   */
2598
  function testAdminDefinedFormatDate() {
2599
    // Create an admin user.
2600
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
2601
    $this->drupalLogin($this->admin_user);
2602

    
2603
    // Add new date format.
2604
    $admin_date_format = 'j M y';
2605
    $edit = array('date_format' => $admin_date_format);
2606
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
2607

    
2608
    // Add a new date format which just differs in the case.
2609
    $admin_date_format_uppercase = 'j M Y';
2610
    $edit = array('date_format' => $admin_date_format_uppercase);
2611
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
2612
    $this->assertText(t('Custom date format added.'));
2613

    
2614
    // Add new date type.
2615
    $edit = array(
2616
      'date_type' => 'Example Style',
2617
      'machine_name' => 'example_style',
2618
      'date_format' => $admin_date_format,
2619
    );
2620
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
2621

    
2622
   // Add a second date format with a different case than the first.
2623
    $edit = array(
2624
      'machine_name' => 'example_style_uppercase',
2625
      'date_type' => 'Example Style Uppercase',
2626
      'date_format' => $admin_date_format_uppercase,
2627
    );
2628
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
2629
    $this->assertText(t('New date type added successfully.'));
2630

    
2631
    $timestamp = strtotime('2007-03-10T00:00:00+00:00');
2632
    $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', 'Test format_date() using an admin-defined date type.');
2633
    $this->assertIdentical(format_date($timestamp, 'example_style_uppercase', '', 'America/Los_Angeles'), '9 Mar 2007', 'Test format_date() using an admin-defined date type with different case.');
2634
    $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), 'Test format_date() defaulting to medium when $type not found.');
2635
  }
2636

    
2637
  /**
2638
   * Tests for the format_date() function.
2639
   */
2640
  function testFormatDate() {
2641
    global $user, $language;
2642

    
2643
    $timestamp = strtotime('2007-03-26T00:00:00+00:00');
2644
    $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', 'Test all parameters.');
2645
    $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', 'Test translated format.');
2646
    $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', 'Test an escaped format string.');
2647
    $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', 'Test format containing backslash character.');
2648
    $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', 'Test format containing backslash followed by escaped format string.');
2649
    $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', 'Test a different time zone.');
2650

    
2651
    // Create an admin user and add Spanish language.
2652
    $admin_user = $this->drupalCreateUser(array('administer languages'));
2653
    $this->drupalLogin($admin_user);
2654
    $edit = array(
2655
      'langcode' => self::LANGCODE,
2656
      'name' => self::LANGCODE,
2657
      'native' => self::LANGCODE,
2658
      'direction' => LANGUAGE_LTR,
2659
      'prefix' => self::LANGCODE,
2660
    );
2661
    $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
2662

    
2663
    // Create a test user to carry out the tests.
2664
    $test_user = $this->drupalCreateUser();
2665
    $this->drupalLogin($test_user);
2666
    $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
2667
    $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
2668

    
2669
    // Disable session saving as we are about to modify the global $user.
2670
    drupal_save_session(FALSE);
2671
    // Save the original user and language and then replace it with the test user and language.
2672
    $real_user = $user;
2673
    $user = user_load($test_user->uid, TRUE);
2674
    $real_language = $language->language;
2675
    $language->language = $user->language;
2676
    // Simulate a Drupal bootstrap with the logged-in user.
2677
    date_default_timezone_set(drupal_get_user_timezone());
2678

    
2679
    $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', 'Test a different language.');
2680
    $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
2681
    $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T'), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test custom date format.');
2682
    $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
2683
    $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
2684
    $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
2685
    $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
2686

    
2687
    // Restore the original user and language, and enable session saving.
2688
    $user = $real_user;
2689
    $language->language = $real_language;
2690
    // Restore default time zone.
2691
    date_default_timezone_set(drupal_get_user_timezone());
2692
    drupal_save_session(TRUE);
2693
  }
2694
}
2695

    
2696
/**
2697
 * Tests for the format_date() function.
2698
 */
2699
class DrupalAttributesUnitTest extends DrupalUnitTestCase {
2700
  public static function getInfo() {
2701
    return array(
2702
      'name' => 'HTML Attributes',
2703
      'description' => 'Perform unit tests on the drupal_attributes() function.',
2704
      'group' => 'System',
2705
    );
2706
  }
2707

    
2708
  /**
2709
   * Tests that drupal_html_class() cleans the class name properly.
2710
   */
2711
  function testDrupalAttributes() {
2712
    // Verify that special characters are HTML encoded.
2713
    $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
2714

    
2715
    // Verify multi-value attributes are concatenated with spaces.
2716
    $attributes = array('class' => array('first', 'last'));
2717
    $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
2718

    
2719
    // Verify empty attribute values are rendered.
2720
    $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
2721
    $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
2722

    
2723
    // Verify multiple attributes are rendered.
2724
    $attributes = array(
2725
      'id' => 'id-test',
2726
      'class' => array('first', 'last'),
2727
      'alt' => 'Alternate',
2728
    );
2729
    $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
2730

    
2731
    // Verify empty attributes array is rendered.
2732
    $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
2733
  }
2734
}
2735

    
2736
/**
2737
 * Tests converting PHP variables to JSON strings and back.
2738
 */
2739
class DrupalJSONTest extends DrupalUnitTestCase {
2740
  public static function getInfo() {
2741
    return array(
2742
      'name' => 'JSON',
2743
      'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
2744
      'group' => 'System',
2745
    );
2746
  }
2747

    
2748
  /**
2749
   * Tests converting PHP variables to JSON strings and back.
2750
   */
2751
  function testJSON() {
2752
    // Setup a string with the full ASCII table.
2753
    // @todo: Add tests for non-ASCII characters and Unicode.
2754
    $str = '';
2755
    for ($i=0; $i < 128; $i++) {
2756
      $str .= chr($i);
2757
    }
2758
    // Characters that must be escaped.
2759
    // We check for unescaped " separately.
2760
    $html_unsafe = array('<', '>', '\'', '&');
2761
    // The following are the encoded forms of: < > ' & "
2762
    $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
2763

    
2764
    // Verify there aren't character encoding problems with the source string.
2765
    $this->assertIdentical(strlen($str), 128, 'A string with the full ASCII table has the correct length.');
2766
    foreach ($html_unsafe as $char) {
2767
      $this->assertTrue(strpos($str, $char) > 0, format_string('A string with the full ASCII table includes @s.', array('@s' => $char)));
2768
    }
2769

    
2770
    // Verify that JSON encoding produces a string with all of the characters.
2771
    $json = drupal_json_encode($str);
2772
    $this->assertTrue(strlen($json) > strlen($str), 'A JSON encoded string is larger than the source string.');
2773

    
2774
    // The first and last characters should be ", and no others.
2775
    $this->assertTrue($json[0] == '"', 'A JSON encoded string begins with ".');
2776
    $this->assertTrue($json[strlen($json) - 1] == '"', 'A JSON encoded string ends with ".');
2777
    $this->assertTrue(substr_count($json, '"') == 2, 'A JSON encoded string contains exactly two ".');
2778

    
2779
    // Verify that encoding/decoding is reversible.
2780
    $json_decoded = drupal_json_decode($json);
2781
    $this->assertIdentical($str, $json_decoded, 'Encoding a string to JSON and decoding back results in the original string.');
2782

    
2783
    // Verify reversibility for structured data. Also verify that necessary
2784
    // characters are escaped.
2785
    $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
2786
    $json = drupal_json_encode($source);
2787
    foreach ($html_unsafe as $char) {
2788
      $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
2789
    }
2790
    // Verify that JSON encoding escapes the HTML unsafe characters
2791
    foreach ($html_unsafe_escaped as $char) {
2792
      $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
2793
    }
2794
    $json_decoded = drupal_json_decode($json);
2795
    $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
2796
    $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
2797
  }
2798
}
2799

    
2800
/**
2801
 * Tests for RDF namespaces XML serialization.
2802
 */
2803
class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
2804
  public static function getInfo() {
2805
    return array(
2806
      'name' => 'RDF namespaces XML serialization tests',
2807
      'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
2808
      'group' => 'System',
2809
    );
2810
  }
2811

    
2812
  function setUp() {
2813
    parent::setUp('rdf', 'rdf_test');
2814
  }
2815

    
2816
  /**
2817
   * Test RDF namespaces.
2818
   */
2819
  function testGetRdfNamespaces() {
2820
    // Fetches the front page and extracts XML namespaces.
2821
    $this->drupalGet('');
2822
    $xml = new SimpleXMLElement($this->content);
2823
    $ns = $xml->getDocNamespaces();
2824

    
2825
    $this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', 'A prefix declared once is displayed.');
2826
    $this->assertEqual($ns['foaf'], 'http://xmlns.com/foaf/0.1/', 'The same prefix declared in several implementations of hook_rdf_namespaces() is valid as long as all the namespaces are the same.');
2827
    $this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', 'Two prefixes can be assigned the same namespace.');
2828
    $this->assertTrue(!isset($ns['dc']), 'A prefix with conflicting namespaces is discarded.');
2829
  }
2830
}
2831

    
2832
/**
2833
 * Basic tests for drupal_add_feed().
2834
 */
2835
class DrupalAddFeedTestCase extends DrupalWebTestCase {
2836
  public static function getInfo() {
2837
    return array(
2838
      'name' => 'drupal_add_feed() tests',
2839
      'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
2840
      'group' => 'System',
2841
    );
2842
  }
2843

    
2844
  /**
2845
   * Test drupal_add_feed() with paths, URLs, and titles.
2846
   */
2847
  function testBasicFeedAddNoTitle() {
2848
    $path = $this->randomName(12);
2849
    $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2850
    $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
2851

    
2852
    $path_for_title = $this->randomName(12);
2853
    $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2854
    $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
2855

    
2856
    // Possible permutations of drupal_add_feed() to test.
2857
    // - 'input_url': the path passed to drupal_add_feed(),
2858
    // - 'output_url': the expected URL to be found in the header.
2859
    // - 'title' == the title of the feed as passed into drupal_add_feed().
2860
    $urls = array(
2861
      'path without title' => array(
2862
        'input_url' => $path,
2863
        'output_url' => url($path, array('absolute' => TRUE)),
2864
        'title' => '',
2865
      ),
2866
      'external URL without title' => array(
2867
        'input_url' => $external_url,
2868
        'output_url' => $external_url,
2869
        'title' => '',
2870
      ),
2871
      'local URL without title' => array(
2872
        'input_url' => $fully_qualified_local_url,
2873
        'output_url' => $fully_qualified_local_url,
2874
        'title' => '',
2875
      ),
2876
      'path with title' => array(
2877
        'input_url' => $path_for_title,
2878
        'output_url' => url($path_for_title, array('absolute' => TRUE)),
2879
        'title' => $this->randomName(12),
2880
      ),
2881
      'external URL with title' => array(
2882
        'input_url' => $external_for_title,
2883
        'output_url' => $external_for_title,
2884
        'title' => $this->randomName(12),
2885
      ),
2886
      'local URL with title' => array(
2887
        'input_url' => $fully_qualified_for_title,
2888
        'output_url' => $fully_qualified_for_title,
2889
        'title' => $this->randomName(12),
2890
      ),
2891
    );
2892

    
2893
    foreach ($urls as $description => $feed_info) {
2894
      drupal_add_feed($feed_info['input_url'], $feed_info['title']);
2895
    }
2896

    
2897
    $this->drupalSetContent(drupal_get_html_head());
2898
    foreach ($urls as $description => $feed_info) {
2899
      $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
2900
    }
2901
  }
2902

    
2903
  /**
2904
   * Create a pattern representing the RSS feed in the page.
2905
   */
2906
  function urlToRSSLinkPattern($url, $title = '') {
2907
    // Escape any regular expression characters in the URL ('?' is the worst).
2908
    $url = preg_replace('/([+?.*])/', '[$0]', $url);
2909
    $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
2910
    return $generated_pattern;
2911
  }
2912
}
2913

    
2914
/**
2915
 * Test for theme_feed_icon().
2916
 */
2917
class FeedIconTest extends DrupalWebTestCase {
2918

    
2919
  public static function getInfo() {
2920
    return array(
2921
      'name' => 'Feed icon',
2922
      'description' => 'Check escaping of theme_feed_icon()',
2923
      'group' => 'System',
2924
    );
2925
  }
2926

    
2927
  /**
2928
   * Check that special characters are correctly escaped. Test for issue #1211668.
2929
   */
2930
  function testFeedIconEscaping() {
2931
    $variables = array();
2932
    $variables['url'] = 'node';
2933
    $variables['title'] = '<>&"\'';
2934
    $text = theme_feed_icon($variables);
2935
    preg_match('/title="(.*?)"/', $text, $matches);
2936
    $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
2937
  }
2938

    
2939
}
2940

    
2941
/**
2942
 * Test array diff functions.
2943
 */
2944
class ArrayDiffUnitTest extends DrupalUnitTestCase {
2945

    
2946
  /**
2947
   * Array to use for testing.
2948
   *
2949
   * @var array
2950
   */
2951
  protected $array1;
2952

    
2953
  /**
2954
   * Array to use for testing.
2955
   *
2956
   * @var array
2957
   */
2958
  protected $array2;
2959

    
2960
  public static function getInfo() {
2961
    return array(
2962
      'name' => 'Array differences',
2963
      'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
2964
      'group' => 'System',
2965
    );
2966
  }
2967

    
2968
  function setUp() {
2969
    parent::setUp();
2970

    
2971
    $this->array1 = array(
2972
      'same' => 'yes',
2973
      'different' => 'no',
2974
      'array_empty_diff' => array(),
2975
      'null' => NULL,
2976
      'int_diff' => 1,
2977
      'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
2978
      'array_compared_to_string' => array('value'),
2979
      'string_compared_to_array' => 'value',
2980
      'new' => 'new',
2981
    );
2982
    $this->array2 = array(
2983
      'same' => 'yes',
2984
      'different' => 'yes',
2985
      'array_empty_diff' => array(),
2986
      'null' => NULL,
2987
      'int_diff' => '1',
2988
      'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
2989
      'array_compared_to_string' => 'value',
2990
      'string_compared_to_array' => array('value'),
2991
    );
2992
  }
2993

    
2994

    
2995
  /**
2996
   * Tests drupal_array_diff_assoc_recursive().
2997
   */
2998
  public function testArrayDiffAssocRecursive() {
2999
    $expected = array(
3000
      'different' => 'no',
3001
      'int_diff' => 1,
3002
      // The 'array' key should not be returned, as it's the same.
3003
      'array_diff' => array('same' => 'same'),
3004
      'array_compared_to_string' => array('value'),
3005
      'string_compared_to_array' => 'value',
3006
      'new' => 'new',
3007
    );
3008

    
3009
    $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
3010
  }
3011
}
3012

    
3013
/**
3014
 * Tests the functionality of drupal_get_query_array().
3015
 */
3016
class DrupalGetQueryArrayTestCase extends DrupalWebTestCase {
3017

    
3018
  public static function getInfo() {
3019
    return array(
3020
      'name' => 'Query parsing using drupal_get_query_array()',
3021
      'description' => 'Tests that drupal_get_query_array() correctly parses query parameters.',
3022
      'group' => 'System',
3023
    );
3024
  }
3025

    
3026
  /**
3027
   * Tests that drupal_get_query_array() correctly explodes query parameters.
3028
   */
3029
  public function testDrupalGetQueryArray() {
3030
    $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
3031
    $parsed = parse_url($url);
3032
    $result = drupal_get_query_array($parsed['query']);
3033
    $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'drupal_get_query_array() should only explode parameters on the first equals sign.');
3034
  }
3035

    
3036
}