Projet

Général

Profil

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

root / drupal7 / modules / simpletest / tests / common.test @ 4444412d

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
    // Test the parsing of absolute URLs.
213
    $result = array(
214
      'path' => 'http://drupal.org/foo/bar',
215
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
216
      'fragment' => 'foo',
217
    );
218
    $this->assertEqual(drupal_parse_url($url), $result, 'External URL parsed correctly.');
219

    
220
    // Verify proper parsing of URLs when clean URLs are disabled.
221
    $result = array(
222
      'path' => 'foo/bar',
223
      'query' => array('bar' => 'baz'),
224
      'fragment' => 'foo',
225
    );
226
    // Non-clean URLs #1: Absolute URL generated by url().
227
    $url = $GLOBALS['base_url'] . '/?q=foo/bar&bar=baz#foo';
228
    $this->assertEqual(drupal_parse_url($url), $result, 'Absolute URL with clean URLs disabled parsed correctly.');
229

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

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

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

    
243
  /**
244
   * Test url() with/without query, with/without fragment, absolute on/off and
245
   * assert all that works when clean URLs are on and off.
246
   */
247
  function testUrl() {
248
    global $base_url;
249

    
250
    foreach (array(FALSE, TRUE) as $absolute) {
251
      // Get the expected start of the path string.
252
      $base = $absolute ? $base_url . '/' : base_path();
253
      $absolute_string = $absolute ? 'absolute' : NULL;
254

    
255
      // Disable Clean URLs.
256
      $GLOBALS['conf']['clean_url'] = 0;
257

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

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

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

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

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

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

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

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

    
290
      // Enable Clean URLs.
291
      $GLOBALS['conf']['clean_url'] = 1;
292

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

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

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

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

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

    
313
      $url = $base;
314
      $result = url('<front>', array('absolute' => $absolute));
315
      $this->assertEqual($url, $result, "$url == $result");
316
    }
317
  }
318

    
319
  /**
320
   * Test external URL handling.
321
   */
322
  function testExternalUrls() {
323
    $test_url = 'http://drupal.org/';
324

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

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

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

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

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

    
355
/**
356
 * Tests for check_plain(), filter_xss(), format_string(), and check_url().
357
 */
358
class CommonXssUnitTest extends DrupalUnitTestCase {
359

    
360
  public static function getInfo() {
361
    return array(
362
      'name' => 'String filtering tests',
363
      'description' => 'Confirm that check_plain(), filter_xss(), format_string() and check_url() work correctly, including invalid multi-byte sequences.',
364
      'group' => 'System',
365
    );
366
  }
367

    
368
  /**
369
   * Check that invalid multi-byte sequences are rejected.
370
   */
371
  function testInvalidMultiByte() {
372
     // Ignore PHP 5.3+ invalid multibyte sequence warning.
373
     $text = @check_plain("Foo\xC0barbaz");
374
     $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "Foo\xC0barbaz"');
375
     // Ignore PHP 5.3+ invalid multibyte sequence warning.
376
     $text = @check_plain("\xc2\"");
377
     $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "\xc2\""');
378
     $text = check_plain("Fooÿñ");
379
     $this->assertEqual($text, "Fooÿñ", 'check_plain() accepts valid sequence "Fooÿñ"');
380
     $text = filter_xss("Foo\xC0barbaz");
381
     $this->assertEqual($text, '', 'filter_xss() rejects invalid sequence "Foo\xC0barbaz"');
382
     $text = filter_xss("Fooÿñ");
383
     $this->assertEqual($text, "Fooÿñ", 'filter_xss() accepts valid sequence Fooÿñ');
384
  }
385

    
386
  /**
387
   * Check that special characters are escaped.
388
   */
389
  function testEscaping() {
390
     $text = check_plain("<script>");
391
     $this->assertEqual($text, '&lt;script&gt;', 'check_plain() escapes &lt;script&gt;');
392
     $text = check_plain('<>&"\'');
393
     $this->assertEqual($text, '&lt;&gt;&amp;&quot;&#039;', 'check_plain() escapes reserved HTML characters.');
394
  }
395

    
396
  /**
397
   * Test t() and format_string() replacement functionality.
398
   */
399
  function testFormatStringAndT() {
400
    foreach (array('format_string', 't') as $function) {
401
      $text = $function('Simple text');
402
      $this->assertEqual($text, 'Simple text', $function . ' leaves simple text alone.');
403
      $text = $function('Escaped text: @value', array('@value' => '<script>'));
404
      $this->assertEqual($text, 'Escaped text: &lt;script&gt;', $function . ' replaces and escapes string.');
405
      $text = $function('Placeholder text: %value', array('%value' => '<script>'));
406
      $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', $function . ' replaces, escapes and themes string.');
407
      $text = $function('Verbatim text: !value', array('!value' => '<script>'));
408
      $this->assertEqual($text, 'Verbatim text: <script>', $function . ' replaces verbatim string as-is.');
409
    }
410
  }
411

    
412
  /**
413
   * Check that harmful protocols are stripped.
414
   */
415
  function testBadProtocolStripping() {
416
    // Ensure that check_url() strips out harmful protocols, and encodes for
417
    // HTML. Ensure drupal_strip_dangerous_protocols() can be used to return a
418
    // plain-text string stripped of harmful protocols.
419
    $url = 'javascript:http://www.example.com/?x=1&y=2';
420
    $expected_plain = 'http://www.example.com/?x=1&y=2';
421
    $expected_html = 'http://www.example.com/?x=1&amp;y=2';
422
    $this->assertIdentical(check_url($url), $expected_html, 'check_url() filters a URL and encodes it for HTML.');
423
    $this->assertIdentical(drupal_strip_dangerous_protocols($url), $expected_plain, 'drupal_strip_dangerous_protocols() filters a URL and returns plain text.');
424
  }
425
}
426

    
427
/**
428
 * Tests file size parsing and formatting functions.
429
 */
430
class CommonSizeTestCase extends DrupalUnitTestCase {
431
  protected $exact_test_cases;
432
  protected $rounded_test_cases;
433

    
434
  public static function getInfo() {
435
    return array(
436
      'name' => 'Size parsing test',
437
      'description' => 'Parse a predefined amount of bytes and compare the output with the expected value.',
438
      'group' => 'System'
439
    );
440
  }
441

    
442
  function setUp() {
443
    $kb = DRUPAL_KILOBYTE;
444
    $this->exact_test_cases = array(
445
      '1 byte' => 1,
446
      '1 KB'   => $kb,
447
      '1 MB'   => $kb * $kb,
448
      '1 GB'   => $kb * $kb * $kb,
449
      '1 TB'   => $kb * $kb * $kb * $kb,
450
      '1 PB'   => $kb * $kb * $kb * $kb * $kb,
451
      '1 EB'   => $kb * $kb * $kb * $kb * $kb * $kb,
452
      '1 ZB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
453
      '1 YB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
454
    );
455
    $this->rounded_test_cases = array(
456
      '2 bytes' => 2,
457
      '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
458
      round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651, // megabytes
459
      round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
460
      round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
461
    );
462
    parent::setUp();
463
  }
464

    
465
  /**
466
   * Check that format_size() returns the expected string.
467
   */
468
  function testCommonFormatSize() {
469
    foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
470
      foreach ($test_cases as $expected => $input) {
471
        $this->assertEqual(
472
          ($result = format_size($input, NULL)),
473
          $expected,
474
          $expected . ' == ' . $result . ' (' . $input . ' bytes)'
475
        );
476
      }
477
    }
478
  }
479

    
480
  /**
481
   * Check that parse_size() returns the proper byte sizes.
482
   */
483
  function testCommonParseSize() {
484
    foreach ($this->exact_test_cases as $string => $size) {
485
      $this->assertEqual(
486
        $parsed_size = parse_size($string),
487
        $size,
488
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
489
      );
490
    }
491

    
492
    // Some custom parsing tests
493
    $string = '23476892 bytes';
494
    $this->assertEqual(
495
      ($parsed_size = parse_size($string)),
496
      $size = 23476892,
497
      $string . ' == ' . $parsed_size . ' bytes'
498
    );
499
    $string = '76MRandomStringThatShouldBeIgnoredByParseSize.'; // 76 MB
500
    $this->assertEqual(
501
      $parsed_size = parse_size($string),
502
      $size = 79691776,
503
      $string . ' == ' . $parsed_size . ' bytes'
504
    );
505
    $string = '76.24 Giggabyte'; // Misspeld text -> 76.24 GB
506
    $this->assertEqual(
507
      $parsed_size = parse_size($string),
508
      $size = 81862076662,
509
      $string . ' == ' . $parsed_size . ' bytes'
510
    );
511
  }
512

    
513
  /**
514
   * Cross-test parse_size() and format_size().
515
   */
516
  function testCommonParseSizeFormatSize() {
517
    foreach ($this->exact_test_cases as $size) {
518
      $this->assertEqual(
519
        $size,
520
        ($parsed_size = parse_size($string = format_size($size, NULL))),
521
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
522
      );
523
    }
524
  }
525
}
526

    
527
/**
528
 * Test drupal_explode_tags() and drupal_implode_tags().
529
 */
530
class DrupalTagsHandlingTestCase extends DrupalUnitTestCase {
531
  var $validTags = array(
532
    'Drupal' => 'Drupal',
533
    'Drupal with some spaces' => 'Drupal with some spaces',
534
    '"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
535
    '"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
536
  );
537

    
538
  public static function getInfo() {
539
    return array(
540
      'name' => 'Drupal tags handling',
541
      'description' => "Performs tests on Drupal's handling of tags, both explosion and implosion tactics used.",
542
      'group' => 'System'
543
    );
544
  }
545

    
546
  /**
547
   * Explode a series of tags.
548
   */
549
  function testDrupalExplodeTags() {
550
    $string = implode(', ', array_keys($this->validTags));
551
    $tags = drupal_explode_tags($string);
552
    $this->assertTags($tags);
553
  }
554

    
555
  /**
556
   * Implode a series of tags.
557
   */
558
  function testDrupalImplodeTags() {
559
    $tags = array_values($this->validTags);
560
    // Let's explode and implode to our heart's content.
561
    for ($i = 0; $i < 10; $i++) {
562
      $string = drupal_implode_tags($tags);
563
      $tags = drupal_explode_tags($string);
564
    }
565
    $this->assertTags($tags);
566
  }
567

    
568
  /**
569
   * Helper function: asserts that the ending array of tags is what we wanted.
570
   */
571
  function assertTags($tags) {
572
    $original = $this->validTags;
573
    foreach ($tags as $tag) {
574
      $key = array_search($tag, $original);
575
      $this->assertTrue($key, format_string('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
576
      unset($original[$key]);
577
    }
578
    foreach ($original as $leftover) {
579
      $this->fail(format_string('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
580
    }
581
  }
582
}
583

    
584
/**
585
 * Test the Drupal CSS system.
586
 */
587
class CascadingStylesheetsTestCase extends DrupalWebTestCase {
588
  public static function getInfo() {
589
    return array(
590
      'name' => 'Cascading stylesheets',
591
      'description' => 'Tests adding various cascading stylesheets to the page.',
592
      'group' => 'System',
593
    );
594
  }
595

    
596
  function setUp() {
597
    parent::setUp('php', 'locale', 'common_test');
598
    // Reset drupal_add_css() before each test.
599
    drupal_static_reset('drupal_add_css');
600
  }
601

    
602
  /**
603
   * Check default stylesheets as empty.
604
   */
605
  function testDefault() {
606
    $this->assertEqual(array(), drupal_add_css(), 'Default CSS is empty.');
607
  }
608

    
609
  /**
610
   * Test that stylesheets in module .info files are loaded.
611
   */
612
  function testModuleInfo() {
613
    $this->drupalGet('');
614

    
615
    // Verify common_test.css in a STYLE media="all" tag.
616
    $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
617
      ':media' => 'all',
618
      ':filename' => 'tests/common_test.css',
619
    ));
620
    $this->assertTrue(count($elements), "Stylesheet with media 'all' in module .info file found.");
621

    
622
    // Verify common_test.print.css in a STYLE media="print" tag.
623
    $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
624
      ':media' => 'print',
625
      ':filename' => 'tests/common_test.print.css',
626
    ));
627
    $this->assertTrue(count($elements), "Stylesheet with media 'print' in module .info file found.");
628
  }
629

    
630
  /**
631
   * Tests adding a file stylesheet.
632
   */
633
  function testAddFile() {
634
    $path = drupal_get_path('module', 'simpletest') . '/simpletest.css';
635
    $css = drupal_add_css($path);
636
    $this->assertEqual($css[$path]['data'], $path, 'Adding a CSS file caches it properly.');
637
  }
638

    
639
  /**
640
   * Tests adding an external stylesheet.
641
   */
642
  function testAddExternal() {
643
    $path = 'http://example.com/style.css';
644
    $css = drupal_add_css($path, 'external');
645
    $this->assertEqual($css[$path]['type'], 'external', 'Adding an external CSS file caches it properly.');
646
  }
647

    
648
  /**
649
   * Makes sure that reseting the CSS empties the cache.
650
   */
651
  function testReset() {
652
    drupal_static_reset('drupal_add_css');
653
    $this->assertEqual(array(), drupal_add_css(), 'Resetting the CSS empties the cache.');
654
  }
655

    
656
  /**
657
   * Tests rendering the stylesheets.
658
   */
659
  function testRenderFile() {
660
    $css = drupal_get_path('module', 'simpletest') . '/simpletest.css';
661
    drupal_add_css($css);
662
    $styles = drupal_get_css();
663
    $this->assertTrue(strpos($styles, $css) > 0, 'Rendered CSS includes the added stylesheet.');
664
  }
665

    
666
  /**
667
   * Tests rendering an external stylesheet.
668
   */
669
  function testRenderExternal() {
670
    $css = 'http://example.com/style.css';
671
    drupal_add_css($css, 'external');
672
    $styles = drupal_get_css();
673
    // Stylesheet URL may be the href of a LINK tag or in an @import statement
674
    // of a STYLE tag.
675
    $this->assertTrue(strpos($styles, 'href="' . $css) > 0 || strpos($styles, '@import url("' . $css . '")') > 0, 'Rendering an external CSS file.');
676
  }
677

    
678
  /**
679
   * Tests rendering inline stylesheets with preprocessing on.
680
   */
681
  function testRenderInlinePreprocess() {
682
    $css = 'body { padding: 0px; }';
683
    $css_preprocessed = '<style type="text/css" media="all">' . "\n<!--/*--><![CDATA[/*><!--*/\n" . drupal_load_stylesheet_content($css, TRUE) . "\n/*]]>*/-->\n" . '</style>';
684
    drupal_add_css($css, array('type' => 'inline'));
685
    $styles = drupal_get_css();
686
    $this->assertEqual(trim($styles), $css_preprocessed, 'Rendering preprocessed inline CSS adds it to the page.');
687
  }
688

    
689
  /**
690
   * Tests removing charset when rendering stylesheets with preprocessing on.
691
   */
692
  function testRenderRemoveCharsetPreprocess() {
693
    $cases = array(
694
      array(
695
        'asset' => '@charset "UTF-8";html{font-family:"sans-serif";}',
696
        'expected' => 'html{font-family:"sans-serif";}',
697
      ),
698
      // This asset contains extra \n character.
699
      array(
700
        'asset' => "@charset 'UTF-8';\nhtml{font-family:'sans-serif';}",
701
        'expected' => "\nhtml{font-family:'sans-serif';}",
702
      ),
703
    );
704

    
705
    foreach ($cases as $case) {
706
      $this->assertEqual(
707
        $case['expected'],
708
        drupal_load_stylesheet_content($case['asset']),
709
        'CSS optimizing correctly removes the charset declaration.'
710
      );
711
    }
712
  }
713

    
714
  /**
715
   * Tests rendering inline stylesheets with preprocessing off.
716
   */
717
  function testRenderInlineNoPreprocess() {
718
    $css = 'body { padding: 0px; }';
719
    drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
720
    $styles = drupal_get_css();
721
    $this->assertTrue(strpos($styles, $css) > 0, 'Rendering non-preprocessed inline CSS adds it to the page.');
722
  }
723

    
724
  /**
725
   * Tests rendering inline stylesheets through a full page request.
726
   */
727
  function testRenderInlineFullPage() {
728
    $css = 'body { font-size: 254px; }';
729
    // Inline CSS is minified unless 'preprocess' => FALSE is passed as a
730
    // drupal_add_css() option.
731
    $expected = 'body{font-size:254px;}';
732

    
733
    // Create a node, using the PHP filter that tests drupal_add_css().
734
    $php_format_id = 'php_code';
735
    $settings = array(
736
      'type' => 'page',
737
      'body' => array(
738
        LANGUAGE_NONE => array(
739
          array(
740
            'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
741
            'format' => $php_format_id,
742
          ),
743
        ),
744
      ),
745
      'promote' => 1,
746
    );
747
    $node = $this->drupalCreateNode($settings);
748

    
749
    // Fetch the page.
750
    $this->drupalGet('node/' . $node->nid);
751
    $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
752
  }
753

    
754
  /**
755
   * Test CSS ordering.
756
   */
757
  function testRenderOrder() {
758
    // A module CSS file.
759
    drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
760
    // A few system CSS files, ordered in a strange way.
761
    $system_path = drupal_get_path('module', 'system');
762
    drupal_add_css($system_path . '/system.menus.css', array('group' => CSS_SYSTEM));
763
    drupal_add_css($system_path . '/system.base.css', array('group' => CSS_SYSTEM, 'weight' => -10));
764
    drupal_add_css($system_path . '/system.theme.css', array('group' => CSS_SYSTEM));
765

    
766
    $expected = array(
767
      $system_path . '/system.base.css',
768
      $system_path . '/system.menus.css',
769
      $system_path . '/system.theme.css',
770
      drupal_get_path('module', 'simpletest') . '/simpletest.css',
771
    );
772

    
773

    
774
    $styles = drupal_get_css();
775
    // Stylesheet URL may be the href of a LINK tag or in an @import statement
776
    // of a STYLE tag.
777
    if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
778
      $result = $matches[2];
779
    }
780
    else {
781
      $result = array();
782
    }
783

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

    
787
  /**
788
   * Test CSS override.
789
   */
790
  function testRenderOverride() {
791
    $system = drupal_get_path('module', 'system');
792
    $simpletest = drupal_get_path('module', 'simpletest');
793

    
794
    drupal_add_css($system . '/system.base.css');
795
    drupal_add_css($simpletest . '/tests/system.base.css');
796

    
797
    // The dummy stylesheet should be the only one included.
798
    $styles = drupal_get_css();
799
    $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') !== FALSE, 'The overriding CSS file is output.');
800
    $this->assert(strpos($styles, $system . '/system.base.css') === FALSE, 'The overridden CSS file is not output.');
801

    
802
    drupal_add_css($simpletest . '/tests/system.base.css');
803
    drupal_add_css($system . '/system.base.css');
804

    
805
    // The standard stylesheet should be the only one included.
806
    $styles = drupal_get_css();
807
    $this->assert(strpos($styles, $system . '/system.base.css') !== FALSE, 'The overriding CSS file is output.');
808
    $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') === FALSE, 'The overridden CSS file is not output.');
809
  }
810

    
811
  /**
812
   * Tests Locale module's CSS Alter to include RTL overrides.
813
   */
814
  function testAlter() {
815
    // Switch the language to a right to left language and add system.base.css.
816
    global $language;
817
    $language->direction = LANGUAGE_RTL;
818
    $path = drupal_get_path('module', 'system');
819
    drupal_add_css($path . '/system.base.css');
820

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

    
825
    // Change the language back to left to right.
826
    $language->direction = LANGUAGE_LTR;
827
  }
828

    
829
  /**
830
   * Tests that the query string remains intact when adding CSS files that have
831
   * query string parameters.
832
   */
833
  function testAddCssFileWithQueryString() {
834
    $this->drupalGet('common-test/query-string');
835
    $query_string = variable_get('css_js_query_string', '0');
836
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.css?' . $query_string, 'Query string was appended correctly to css.');
837
    $this->assertRaw(drupal_get_path('module', 'node') . '/node-fake.css?arg1=value1&amp;arg2=value2', 'Query string not escaped on a URI.');
838
  }
839
}
840

    
841
/**
842
 * Test for cleaning HTML identifiers.
843
 */
844
class DrupalHTMLIdentifierTestCase extends DrupalUnitTestCase {
845
  public static function getInfo() {
846
    return array(
847
      'name' => 'HTML identifiers',
848
      'description' => 'Test the functions drupal_html_class(), drupal_html_id() and drupal_clean_css_identifier() for expected behavior',
849
      'group' => 'System',
850
    );
851
  }
852

    
853
  /**
854
   * Tests that drupal_clean_css_identifier() cleans the identifier properly.
855
   */
856
  function testDrupalCleanCSSIdentifier() {
857
    // Verify that no valid ASCII characters are stripped from the identifier.
858
    $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
859
    $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid ASCII characters pass through.');
860

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

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

    
869
  /**
870
   * Tests that drupal_html_class() cleans the class name properly.
871
   */
872
  function testDrupalHTMLClass() {
873
    // Verify Drupal coding standards are enforced.
874
    $this->assertIdentical(drupal_html_class('CLASS NAME_[Ü]'), 'class-name--ü', 'Enforce Drupal coding standards.');
875
  }
876

    
877
  /**
878
   * Tests that drupal_html_id() cleans the ID properly.
879
   */
880
  function testDrupalHTMLId() {
881
    // Verify that letters, digits, and hyphens are not stripped from the ID.
882
    $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
883
    $this->assertIdentical(drupal_html_id($id), $id, 'Verify valid characters pass through.');
884

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

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

    
891
    // Reset the static cache so we can ensure the unique id count is at zero.
892
    drupal_static_reset('drupal_html_id');
893

    
894
    // Clean up IDs with invalid starting characters.
895
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id', 'Test the uniqueness of IDs #1.');
896
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--2', 'Test the uniqueness of IDs #2.');
897
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--3', 'Test the uniqueness of IDs #3.');
898
  }
899
}
900

    
901
/**
902
 * CSS Unit Tests.
903
 */
904
class CascadingStylesheetsUnitTest extends DrupalUnitTestCase {
905
  public static function getInfo() {
906
    return array(
907
      'name' => 'CSS Unit Tests',
908
      'description' => 'Unit tests on CSS functions like aggregation.',
909
      'group' => 'System',
910
    );
911
  }
912

    
913
  /**
914
   * Tests basic CSS loading with and without optimization via drupal_load_stylesheet().
915
   *
916
   * Known tests:
917
   * - Retain white-space in selectors. (http://drupal.org/node/472820)
918
   * - Proper URLs in imported files. (http://drupal.org/node/265719)
919
   * - Retain pseudo-selectors. (http://drupal.org/node/460448)
920
   */
921
  function testLoadCssBasic() {
922
    // Array of files to test living in 'simpletest/files/css_test_files/'.
923
    // - Original: name.css
924
    // - Unoptimized expected content: name.css.unoptimized.css
925
    // - Optimized expected content: name.css.optimized.css
926
    $testfiles = array(
927
      'css_input_without_import.css',
928
      'css_input_with_import.css',
929
      'css_subfolder/css_input_with_import.css',
930
      'comment_hacks.css'
931
    );
932
    $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
933
    foreach ($testfiles as $file) {
934
      $file_path = $path . '/' . $file;
935
      $file_url = $GLOBALS['base_url'] . '/' . $file_path;
936

    
937
      $expected = file_get_contents($file_path . '.unoptimized.css');
938
      $unoptimized_output = drupal_load_stylesheet($file_path, FALSE);
939
      $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
940

    
941
      $expected = file_get_contents($file_path . '.optimized.css');
942
      $optimized_output = drupal_load_stylesheet($file_path, TRUE);
943
      $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
944

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

    
950
      $expected = file_get_contents($file_path . '.optimized.css');
951
      $optimized_output_url = drupal_load_stylesheet($file_url, TRUE);
952
      $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
953
    }
954
  }
955
}
956

    
957
/**
958
 * Test drupal_http_request().
959
 */
960
class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
961
  public static function getInfo() {
962
    return array(
963
      'name' => 'Drupal HTTP request',
964
      'description' => "Performs tests on Drupal's HTTP request mechanism.",
965
      'group' => 'System'
966
    );
967
  }
968

    
969
  function setUp() {
970
    parent::setUp('system_test', 'locale');
971
  }
972

    
973
  function testDrupalHTTPRequest() {
974
    global $is_https;
975

    
976
    // Parse URL schema.
977
    $missing_scheme = drupal_http_request('example.com/path');
978
    $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
979
    $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
980

    
981
    $unable_to_parse = drupal_http_request('http:///path');
982
    $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
983
    $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
984

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

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

    
997
    // Skip the timeout tests when the testing environment is HTTPS because
998
    // stream_set_timeout() does not work for SSL connections.
999
    // @link http://bugs.php.net/bug.php?id=47929
1000
    if (!$is_https) {
1001
      // Test that timeout is respected. The test machine is expected to be able
1002
      // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
1003
      // return within a total of 5 seconds. If the test machine is extremely
1004
      // slow, the test will fail. fsockopen() has been seen to time out in
1005
      // slightly less than the specified timeout, so allow a little slack on
1006
      // the minimum expected time (i.e. 1.8 instead of 2).
1007
      timer_start(__METHOD__);
1008
      $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
1009
      $time = timer_read(__METHOD__) / 1000;
1010
      $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
1011
      $this->assertTrue($result->error, 'An error message was returned.');
1012
      $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
1013
    }
1014
  }
1015

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

    
1021
    $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
1022
    $result = drupal_http_request($auth);
1023

    
1024
    $this->drupalSetContent($result->data);
1025
    $this->assertRaw($username, 'Username is passed correctly.');
1026
    $this->assertRaw($password, 'Password is passed correctly.');
1027
  }
1028

    
1029
  function testDrupalHTTPRequestRedirect() {
1030
    $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
1031
    $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
1032

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

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

    
1040
    $redirect_invalid = drupal_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
1041
    $this->assertEqual($redirect_invalid->code, -1001, format_string('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
1042
    $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)));
1043

    
1044
    $redirect_invalid = drupal_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
1045
    $this->assertEqual($redirect_invalid->code, -1003, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
1046
    $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)));
1047

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

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

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

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

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

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

    
1068
  /**
1069
   * Tests Content-language headers generated by Drupal.
1070
   */
1071
  function testDrupalHTTPRequestHeaders() {
1072
    // Check the default header.
1073
    $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1074
    $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
1075

    
1076
    // Add German language and set as default.
1077
    locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
1078

    
1079
    // Request front page and check for matching Content-Language.
1080
    $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1081
    $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
1082
  }
1083
}
1084

    
1085
/**
1086
 * Testing drupal_add_region_content and drupal_get_region_content.
1087
 */
1088
class DrupalSetContentTestCase extends DrupalWebTestCase {
1089
  public static function getInfo() {
1090
    return array(
1091
      'name' => 'Drupal set/get regions',
1092
      'description' => 'Performs tests on setting and retrieiving content from theme regions.',
1093
      'group' => 'System'
1094
    );
1095
  }
1096

    
1097

    
1098
  /**
1099
   * Test setting and retrieving content for theme regions.
1100
   */
1101
  function testRegions() {
1102
    global $theme_key;
1103

    
1104
    $block_regions = array_keys(system_region_list($theme_key));
1105
    $delimiter = $this->randomName(32);
1106
    $values = array();
1107
    // Set some random content for each region available.
1108
    foreach ($block_regions as $region) {
1109
      $first_chunk = $this->randomName(32);
1110
      drupal_add_region_content($region, $first_chunk);
1111
      $second_chunk = $this->randomName(32);
1112
      drupal_add_region_content($region, $second_chunk);
1113
      // Store the expected result for a drupal_get_region_content call for this region.
1114
      $values[$region] = $first_chunk . $delimiter . $second_chunk;
1115
    }
1116

    
1117
    // Ensure drupal_get_region_content returns expected results when fetching all regions.
1118
    $content = drupal_get_region_content(NULL, $delimiter);
1119
    foreach ($content as $region => $region_content) {
1120
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
1121
    }
1122

    
1123
    // Ensure drupal_get_region_content returns expected results when fetching a single region.
1124
    foreach ($block_regions as $region) {
1125
      $region_content = drupal_get_region_content($region, $delimiter);
1126
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
1127
    }
1128
  }
1129
}
1130

    
1131
/**
1132
 * Testing drupal_goto and hook_drupal_goto_alter().
1133
 */
1134
class DrupalGotoTest extends DrupalWebTestCase {
1135
  public static function getInfo() {
1136
    return array(
1137
      'name' => 'Drupal goto',
1138
      'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
1139
      'group' => 'System'
1140
    );
1141
  }
1142

    
1143
  function setUp() {
1144
    parent::setUp('common_test');
1145
  }
1146

    
1147
  /**
1148
   * Test drupal_goto().
1149
   */
1150
  function testDrupalGoto() {
1151
    $this->drupalGet('common-test/drupal_goto/redirect');
1152
    $headers = $this->drupalGetHeaders(TRUE);
1153
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1154
    $this->assertEqual($status, 302, 'Expected response code was sent.');
1155
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1156
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1157

    
1158
    $this->drupalGet('common-test/drupal_goto/redirect_advanced');
1159
    $headers = $this->drupalGetHeaders(TRUE);
1160
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1161
    $this->assertEqual($status, 301, 'Expected response code was sent.');
1162
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1163
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1164

    
1165
    // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
1166
    // to test that the path is encoded and decoded properly.
1167
    $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
1168
    $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
1169
    $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
1170
    $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.');
1171
  }
1172

    
1173
  /**
1174
   * Test hook_drupal_goto_alter().
1175
   */
1176
  function testDrupalGotoAlter() {
1177
    $this->drupalGet('common-test/drupal_goto/redirect_fail');
1178

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

    
1183
  /**
1184
   * Test drupal_get_destination().
1185
   */
1186
  function testDrupalGetDestination() {
1187
    $query = $this->randomName(10);
1188

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

    
1193
    // Verify that the current path is used as destination.
1194
    $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
1195
    $url = 'common-test/destination?' . $query;
1196
    $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
1197
  }
1198
}
1199

    
1200
/**
1201
 * Tests for the JavaScript system.
1202
 */
1203
class JavaScriptTestCase extends DrupalWebTestCase {
1204
  /**
1205
   * Store configured value for JavaScript preprocessing.
1206
   */
1207
  protected $preprocess_js = NULL;
1208

    
1209
  public static function getInfo() {
1210
    return array(
1211
      'name' => 'JavaScript',
1212
      'description' => 'Tests the JavaScript system.',
1213
      'group' => 'System'
1214
    );
1215
  }
1216

    
1217
  function setUp() {
1218
    // Enable Locale and SimpleTest in the test environment.
1219
    parent::setUp('locale', 'simpletest', 'common_test');
1220

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

    
1225
    // Reset drupal_add_js() and drupal_add_library() statics before each test.
1226
    drupal_static_reset('drupal_add_js');
1227
    drupal_static_reset('drupal_add_library');
1228
  }
1229

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

    
1236
  /**
1237
   * Test default JavaScript is empty.
1238
   */
1239
  function testDefault() {
1240
    $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
1241
  }
1242

    
1243
  /**
1244
   * Test adding a JavaScript file.
1245
   */
1246
  function testAddFile() {
1247
    $javascript = drupal_add_js('misc/collapse.js');
1248
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
1249
    $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
1250
    $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
1251
    $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
1252
    url('', array('prefix' => &$prefix));
1253
    $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
1254
  }
1255

    
1256
  /**
1257
   * Test adding settings.
1258
   */
1259
  function testAddSetting() {
1260
    $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
1261
    $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
1262
    $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
1263
  }
1264

    
1265
  /**
1266
   * Tests adding an external JavaScript File.
1267
   */
1268
  function testAddExternal() {
1269
    $path = 'http://example.com/script.js';
1270
    $javascript = drupal_add_js($path, 'external');
1271
    $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
1272
  }
1273

    
1274
  /**
1275
   * Test drupal_get_js() for JavaScript settings.
1276
   */
1277
  function testHeaderSetting() {
1278
    // Only the second of these two entries should appear in Drupal.settings.
1279
    drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
1280
    drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
1281
    // All three of these entries should appear in Drupal.settings.
1282
    drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
1283
    drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
1284
    drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
1285
    // Only the second of these two entries should appear in Drupal.settings.
1286
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
1287
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
1288

    
1289
    $javascript = drupal_get_js('header');
1290
    $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
1291
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
1292
    $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
1293

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

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

    
1303
    // Test whether drupal_add_js can be used to override the entry for an
1304
    // existing key in an associative array.
1305
    $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
1306
    $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
1307
  }
1308

    
1309
  /**
1310
   * Test to see if resetting the JavaScript empties the cache.
1311
   */
1312
  function testReset() {
1313
    drupal_add_js('misc/collapse.js');
1314
    drupal_static_reset('drupal_add_js');
1315
    $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
1316
  }
1317

    
1318
  /**
1319
   * Test adding inline scripts.
1320
   */
1321
  function testAddInline() {
1322
    $inline = 'jQuery(function () { });';
1323
    $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1324
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
1325
    $data = end($javascript);
1326
    $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
1327
  }
1328

    
1329
  /**
1330
   * Test rendering an external JavaScript file.
1331
   */
1332
  function testRenderExternal() {
1333
    $external = 'http://example.com/example.js';
1334
    drupal_add_js($external, 'external');
1335
    $javascript = drupal_get_js();
1336
    // Local files have a base_path() prefix, external files should not.
1337
    $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
1338
  }
1339

    
1340
  /**
1341
   * Test drupal_get_js() with a footer scope.
1342
   */
1343
  function testFooterHTML() {
1344
    $inline = 'jQuery(function () { });';
1345
    drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1346
    $javascript = drupal_get_js('footer');
1347
    $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
1348
  }
1349

    
1350
  /**
1351
   * Test drupal_add_js() sets preproccess to false when cache is set to false.
1352
   */
1353
  function testNoCache() {
1354
    $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
1355
    $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
1356
  }
1357

    
1358
  /**
1359
   * Test adding a JavaScript file with a different group.
1360
   */
1361
  function testDifferentGroup() {
1362
    $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
1363
    $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
1364
  }
1365

    
1366
  /**
1367
   * Test adding a JavaScript file with a different weight.
1368
   */
1369
  function testDifferentWeight() {
1370
    $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
1371
    $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
1372
  }
1373

    
1374
  /**
1375
   * Tests JavaScript aggregation when files are added to a different scope.
1376
   */
1377
  function testAggregationOrder() {
1378
    // Enable JavaScript aggregation.
1379
    variable_set('preprocess_js', 1);
1380
    drupal_static_reset('drupal_add_js');
1381

    
1382
    // Add two JavaScript files to the current request and build the cache.
1383
    drupal_add_js('misc/ajax.js');
1384
    drupal_add_js('misc/autocomplete.js');
1385

    
1386
    $js_items = drupal_add_js();
1387
    drupal_build_js_cache(array(
1388
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1389
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1390
    ));
1391

    
1392
    // Store the expected key for the first item in the cache.
1393
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1394
    $expected_key = $cache[0];
1395

    
1396
    // Reset variables and add a file in a different scope first.
1397
    variable_del('drupal_js_cache_files');
1398
    drupal_static_reset('drupal_add_js');
1399
    drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
1400
    drupal_add_js('misc/ajax.js');
1401
    drupal_add_js('misc/autocomplete.js');
1402

    
1403
    // Rebuild the cache.
1404
    $js_items = drupal_add_js();
1405
    drupal_build_js_cache(array(
1406
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1407
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1408
    ));
1409

    
1410
    // Compare the expected key for the first file to the current one.
1411
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1412
    $key = $cache[0];
1413
    $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
1414
  }
1415

    
1416
  /**
1417
   * Test JavaScript ordering.
1418
   */
1419
  function testRenderOrder() {
1420
    // Add a bunch of JavaScript in strange ordering.
1421
    drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1422
    drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1423
    drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1424
    drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1425
    drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1426
    drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1427
    drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
1428
    drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1429
    drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1430
    drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1431

    
1432
    // Construct the expected result from the regex.
1433
    $expected = array(
1434
      "-8 #1",
1435
      "-8 #2",
1436
      "-8 #3",
1437
      "-8 #4",
1438
      "-5 #1", // The external script.
1439
      "0 #1",
1440
      "0 #2",
1441
      "0 #3",
1442
      "5 #1",
1443
      "5 #2",
1444
    );
1445

    
1446
    // Retrieve the rendered JavaScript and test against the regex.
1447
    $js = drupal_get_js('footer');
1448
    $matches = array();
1449
    if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
1450
      $result = $matches[1];
1451
    }
1452
    else {
1453
      $result = array();
1454
    }
1455
    $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
1456
  }
1457

    
1458
  /**
1459
   * Test rendering the JavaScript with a file's weight above jQuery's.
1460
   */
1461
  function testRenderDifferentWeight() {
1462
    // JavaScript files are sorted first by group, then by the 'every_page'
1463
    // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
1464
    // weight, we need the other two options to be the same.
1465
    drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
1466
    $javascript = drupal_get_js();
1467
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
1468
  }
1469

    
1470
  /**
1471
   * Test altering a JavaScript's weight via hook_js_alter().
1472
   *
1473
   * @see simpletest_js_alter()
1474
   */
1475
  function testAlter() {
1476
    // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
1477
    drupal_add_js('misc/tableselect.js');
1478
    drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
1479

    
1480
    // Render the JavaScript, testing if simpletest.js was altered to be before
1481
    // tableselect.js. See simpletest_js_alter() to see where this alteration
1482
    // takes place.
1483
    $javascript = drupal_get_js();
1484
    $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
1485
  }
1486

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

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

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

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

    
1525
  /**
1526
   * Tests non-existing libraries.
1527
   */
1528
  function testLibraryUnknown() {
1529
    $result = drupal_get_library('unknown', 'unknown');
1530
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1531
    drupal_static_reset('drupal_get_library');
1532

    
1533
    $result = drupal_add_library('unknown', 'unknown');
1534
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1535
    $scripts = drupal_get_js();
1536
    $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
1537
  }
1538

    
1539
  /**
1540
   * Tests the addition of libraries through the #attached['library'] property.
1541
   */
1542
  function testAttachedLibrary() {
1543
    $element['#attached']['library'][] = array('system', 'farbtastic');
1544
    drupal_render($element);
1545
    $scripts = drupal_get_js();
1546
    $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
1547
  }
1548

    
1549
  /**
1550
   * Tests retrieval of libraries via drupal_get_library().
1551
   */
1552
  function testGetLibrary() {
1553
    // Retrieve all libraries registered by a module.
1554
    $libraries = drupal_get_library('common_test');
1555
    $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
1556
    // Retrieve all libraries for a module not implementing hook_library().
1557
    // Note: This test installs Locale module.
1558
    $libraries = drupal_get_library('locale');
1559
    $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
1560

    
1561
    // Retrieve a specific library by module and name.
1562
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
1563
    $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
1564
    // Retrieve a non-existing library by module and name.
1565
    $farbtastic = drupal_get_library('common_test', 'foo');
1566
    $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
1567
  }
1568

    
1569
  /**
1570
   * Tests that the query string remains intact when adding JavaScript files
1571
   *  that have query string parameters.
1572
   */
1573
  function testAddJsFileWithQueryString() {
1574
    $this->drupalGet('common-test/query-string');
1575
    $query_string = variable_get('css_js_query_string', '0');
1576
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
1577
  }
1578
}
1579

    
1580
/**
1581
 * Tests for drupal_render().
1582
 */
1583
class DrupalRenderTestCase extends DrupalWebTestCase {
1584
  public static function getInfo() {
1585
    return array(
1586
      'name' => 'drupal_render()',
1587
      'description' => 'Performs functional tests on drupal_render().',
1588
      'group' => 'System',
1589
    );
1590
  }
1591

    
1592
  function setUp() {
1593
    parent::setUp('common_test');
1594
  }
1595

    
1596
  /**
1597
   * Tests the output drupal_render() for some elementary input values.
1598
   */
1599
  function testDrupalRenderBasics() {
1600
    $types = array(
1601
      array(
1602
        'name' => 'null',
1603
        'value' => NULL,
1604
        'expected' => '',
1605
      ),
1606
      array(
1607
        'name' => 'no value',
1608
        'expected' => '',
1609
      ),
1610
      array(
1611
        'name' => 'empty string',
1612
        'value' => '',
1613
        'expected' => '',
1614
      ),
1615
      array(
1616
        'name' => 'no access',
1617
        'value' => array(
1618
          '#markup' => 'foo',
1619
          '#access' => FALSE,
1620
        ),
1621
        'expected' => '',
1622
      ),
1623
      array(
1624
        'name' => 'previously printed',
1625
        'value' => array(
1626
          '#markup' => 'foo',
1627
          '#printed' => TRUE,
1628
        ),
1629
        'expected' => '',
1630
      ),
1631
      array(
1632
        'name' => 'printed in prerender',
1633
        'value' => array(
1634
          '#markup' => 'foo',
1635
          '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
1636
        ),
1637
        'expected' => '',
1638
      ),
1639
      array(
1640
        'name' => 'basic renderable array',
1641
        'value' => array('#markup' => 'foo'),
1642
        'expected' => 'foo',
1643
      ),
1644
    );
1645
    foreach($types as $type) {
1646
      $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
1647
    }
1648
  }
1649

    
1650
  /**
1651
   * Test sorting by weight.
1652
   */
1653
  function testDrupalRenderSorting() {
1654
    $first = $this->randomName();
1655
    $second = $this->randomName();
1656
    // Build an array with '#weight' set for each element.
1657
    $elements = array(
1658
      'second' => array(
1659
        '#weight' => 10,
1660
        '#markup' => $second,
1661
      ),
1662
      'first' => array(
1663
        '#weight' => 0,
1664
        '#markup' => $first,
1665
      ),
1666
    );
1667
    $output = drupal_render($elements);
1668

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

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

    
1675
    // Pass $elements through element_children() and ensure it remains
1676
    // sorted in the correct order. drupal_render() will return an empty string
1677
    // if used on the same array in the same request.
1678
    $children = element_children($elements);
1679
    $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
1680
    $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
1681

    
1682

    
1683
    // The same array structure again, but with #sorted set to TRUE.
1684
    $elements = array(
1685
      'second' => array(
1686
        '#weight' => 10,
1687
        '#markup' => $second,
1688
      ),
1689
      'first' => array(
1690
        '#weight' => 0,
1691
        '#markup' => $first,
1692
      ),
1693
      '#sorted' => TRUE,
1694
    );
1695
    $output = drupal_render($elements);
1696

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

    
1701
  /**
1702
   * Test #attached functionality in children elements.
1703
   */
1704
  function testDrupalRenderChildrenAttached() {
1705
    // The cache system is turned off for POST requests.
1706
    $request_method = $_SERVER['REQUEST_METHOD'];
1707
    $_SERVER['REQUEST_METHOD'] = 'GET';
1708

    
1709
    // Create an element with a child and subchild.  Each element loads a
1710
    // different JavaScript file using #attached.
1711
    $parent_js = drupal_get_path('module', 'user') . '/user.js';
1712
    $child_js = drupal_get_path('module', 'forum') . '/forum.js';
1713
    $subchild_js = drupal_get_path('module', 'book') . '/book.js';
1714
    $element = array(
1715
      '#type' => 'fieldset',
1716
      '#cache' => array(
1717
        'keys' => array('simpletest', 'drupal_render', 'children_attached'),
1718
      ),
1719
      '#attached' => array('js' => array($parent_js)),
1720
      '#title' => 'Parent',
1721
    );
1722
    $element['child'] = array(
1723
      '#type' => 'fieldset',
1724
      '#attached' => array('js' => array($child_js)),
1725
      '#title' => 'Child',
1726
    );
1727
    $element['child']['subchild'] = array(
1728
      '#attached' => array('js' => array($subchild_js)),
1729
      '#markup' => 'Subchild',
1730
    );
1731

    
1732
    // Render the element and verify the presence of #attached JavaScript.
1733
    drupal_render($element);
1734
    $scripts = drupal_get_js();
1735
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
1736
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
1737
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
1738

    
1739
    // Load the element from cache and verify the presence of the #attached
1740
    // JavaScript.
1741
    drupal_static_reset('drupal_add_js');
1742
    $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
1743
    $scripts = drupal_get_js();
1744
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
1745
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
1746
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
1747

    
1748
    $_SERVER['REQUEST_METHOD'] = $request_method;
1749
  }
1750

    
1751
  /**
1752
   * Test passing arguments to the theme function.
1753
   */
1754
  function testDrupalRenderThemeArguments() {
1755
    $element = array(
1756
      '#theme' => 'common_test_foo',
1757
    );
1758
    // Test that defaults work.
1759
    $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
1760
    $element = array(
1761
      '#theme' => 'common_test_foo',
1762
      '#foo' => $this->randomName(),
1763
      '#bar' => $this->randomName(),
1764
    );
1765
    // Test that passing arguments to the theme function works.
1766
    $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
1767
  }
1768

    
1769
  /**
1770
   * Test rendering form elements without passing through form_builder().
1771
   */
1772
  function testDrupalRenderFormElements() {
1773
    // Define a series of form elements.
1774
    $element = array(
1775
      '#type' => 'button',
1776
      '#value' => $this->randomName(),
1777
    );
1778
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
1779

    
1780
    $element = array(
1781
      '#type' => 'textfield',
1782
      '#title' => $this->randomName(),
1783
      '#value' => $this->randomName(),
1784
    );
1785
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
1786

    
1787
    $element = array(
1788
      '#type' => 'password',
1789
      '#title' => $this->randomName(),
1790
    );
1791
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
1792

    
1793
    $element = array(
1794
      '#type' => 'textarea',
1795
      '#title' => $this->randomName(),
1796
      '#value' => $this->randomName(),
1797
    );
1798
    $this->assertRenderedElement($element, '//textarea');
1799

    
1800
    $element = array(
1801
      '#type' => 'radio',
1802
      '#title' => $this->randomName(),
1803
      '#value' => FALSE,
1804
    );
1805
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
1806

    
1807
    $element = array(
1808
      '#type' => 'checkbox',
1809
      '#title' => $this->randomName(),
1810
    );
1811
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
1812

    
1813
    $element = array(
1814
      '#type' => 'select',
1815
      '#title' => $this->randomName(),
1816
      '#options' => array(
1817
        0 => $this->randomName(),
1818
        1 => $this->randomName(),
1819
      ),
1820
    );
1821
    $this->assertRenderedElement($element, '//select');
1822

    
1823
    $element = array(
1824
      '#type' => 'file',
1825
      '#title' => $this->randomName(),
1826
    );
1827
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
1828

    
1829
    $element = array(
1830
      '#type' => 'item',
1831
      '#title' => $this->randomName(),
1832
      '#markup' => $this->randomName(),
1833
    );
1834
    $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
1835
      ':class' => 'form-type-item',
1836
      ':markup' => $element['#markup'],
1837
      ':label' => $element['#title'],
1838
    ));
1839

    
1840
    $element = array(
1841
      '#type' => 'hidden',
1842
      '#title' => $this->randomName(),
1843
      '#value' => $this->randomName(),
1844
    );
1845
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
1846

    
1847
    $element = array(
1848
      '#type' => 'link',
1849
      '#title' => $this->randomName(),
1850
      '#href' => $this->randomName(),
1851
      '#options' => array(
1852
        'absolute' => TRUE,
1853
      ),
1854
    );
1855
    $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
1856
      ':href' => url($element['#href'], array('absolute' => TRUE)),
1857
      ':title' => $element['#title'],
1858
    ));
1859

    
1860
    $element = array(
1861
      '#type' => 'fieldset',
1862
      '#title' => $this->randomName(),
1863
    );
1864
    $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
1865
      ':title' => $element['#title'],
1866
    ));
1867

    
1868
    $element['item'] = array(
1869
      '#type' => 'item',
1870
      '#title' => $this->randomName(),
1871
      '#markup' => $this->randomName(),
1872
    );
1873
    $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
1874
      ':class' => 'form-type-item',
1875
      ':markup' => $element['item']['#markup'],
1876
    ));
1877
  }
1878

    
1879
  protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
1880
    $original_element = $element;
1881
    $this->drupalSetContent(drupal_render($element));
1882
    $this->verbose('<pre>' .  check_plain(var_export($original_element, TRUE)) . '</pre>'
1883
      . '<pre>' .  check_plain(var_export($element, TRUE)) . '</pre>'
1884
      . '<hr />' . $this->drupalGetContent()
1885
    );
1886

    
1887
    // @see DrupalWebTestCase::xpath()
1888
    $xpath = $this->buildXPathQuery($xpath, $xpath_args);
1889
    $element += array('#value' => NULL);
1890
    $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
1891
      '@type' => var_export($element['#type'], TRUE),
1892
    )));
1893
  }
1894

    
1895
  /**
1896
   * Tests caching of an empty render item.
1897
   */
1898
  function testDrupalRenderCache() {
1899
    // Force a request via GET.
1900
    $request_method = $_SERVER['REQUEST_METHOD'];
1901
    $_SERVER['REQUEST_METHOD'] = 'GET';
1902
    // Create an empty element.
1903
    $test_element = array(
1904
      '#cache' => array(
1905
        'cid' => 'render_cache_test',
1906
      ),
1907
      '#markup' => '',
1908
    );
1909

    
1910
    // Render the element and confirm that it goes through the rendering
1911
    // process (which will set $element['#printed']).
1912
    $element = $test_element;
1913
    drupal_render($element);
1914
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
1915

    
1916
    // Render the element again and confirm that it is retrieved from the cache
1917
    // instead (so $element['#printed'] will not be set).
1918
    $element = $test_element;
1919
    drupal_render($element);
1920
    $this->assertFalse(isset($element['#printed']), 'Cache hit');
1921

    
1922
    // Restore the previous request method.
1923
    $_SERVER['REQUEST_METHOD'] = $request_method;
1924
  }
1925
}
1926

    
1927
/**
1928
 * Test for valid_url().
1929
 */
1930
class ValidUrlTestCase extends DrupalUnitTestCase {
1931
  public static function getInfo() {
1932
    return array(
1933
      'name' => 'Valid URL',
1934
      'description' => "Performs tests on Drupal's valid URL function.",
1935
      'group' => 'System'
1936
    );
1937
  }
1938

    
1939
  /**
1940
   * Test valid absolute URLs.
1941
   */
1942
  function testValidAbsolute() {
1943
    $url_schemes = array('http', 'https', 'ftp');
1944
    $valid_absolute_urls = array(
1945
      'example.com',
1946
      'www.example.com',
1947
      'ex-ample.com',
1948
      '3xampl3.com',
1949
      'example.com/paren(the)sis',
1950
      'example.com/index.html#pagetop',
1951
      'example.com:8080',
1952
      'subdomain.example.com',
1953
      'example.com/index.php?q=node',
1954
      'example.com/index.php?q=node&param=false',
1955
      'user@www.example.com',
1956
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
1957
      '127.0.0.1',
1958
      'example.org?',
1959
      'john%20doe:secret:foo@example.org/',
1960
      'example.org/~,$\'*;',
1961
      'caf%C3%A9.example.org',
1962
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
1963
    );
1964

    
1965
    foreach ($url_schemes as $scheme) {
1966
      foreach ($valid_absolute_urls as $url) {
1967
        $test_url = $scheme . '://' . $url;
1968
        $valid_url = valid_url($test_url, TRUE);
1969
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
1970
      }
1971
    }
1972
  }
1973

    
1974
  /**
1975
   * Test invalid absolute URLs.
1976
   */
1977
  function testInvalidAbsolute() {
1978
    $url_schemes = array('http', 'https', 'ftp');
1979
    $invalid_ablosule_urls = array(
1980
      '',
1981
      'ex!ample.com',
1982
      'ex%ample.com',
1983
    );
1984

    
1985
    foreach ($url_schemes as $scheme) {
1986
      foreach ($invalid_ablosule_urls as $url) {
1987
        $test_url = $scheme . '://' . $url;
1988
        $valid_url = valid_url($test_url, TRUE);
1989
        $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
1990
      }
1991
    }
1992
  }
1993

    
1994
  /**
1995
   * Test valid relative URLs.
1996
   */
1997
  function testValidRelative() {
1998
    $valid_relative_urls = array(
1999
      'paren(the)sis',
2000
      'index.html#pagetop',
2001
      'index.php?q=node',
2002
      'index.php?q=node&param=false',
2003
      'login.php?do=login&style=%23#pagetop',
2004
    );
2005

    
2006
    foreach (array('', '/') as $front) {
2007
      foreach ($valid_relative_urls as $url) {
2008
        $test_url = $front . $url;
2009
        $valid_url = valid_url($test_url);
2010
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2011
      }
2012
    }
2013
  }
2014

    
2015
  /**
2016
   * Test invalid relative URLs.
2017
   */
2018
  function testInvalidRelative() {
2019
    $invalid_relative_urls = array(
2020
      'ex^mple',
2021
      'example<>',
2022
      'ex%ample',
2023
    );
2024

    
2025
    foreach (array('', '/') as $front) {
2026
      foreach ($invalid_relative_urls as $url) {
2027
        $test_url = $front . $url;
2028
        $valid_url = valid_url($test_url);
2029
        $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2030
      }
2031
    }
2032
  }
2033
}
2034

    
2035
/**
2036
 * Tests for CRUD API functions.
2037
 */
2038
class DrupalDataApiTest extends DrupalWebTestCase {
2039
  public static function getInfo() {
2040
    return array(
2041
      'name' => 'Data API functions',
2042
      'description' => 'Tests the performance of CRUD APIs.',
2043
      'group' => 'System',
2044
    );
2045
  }
2046

    
2047
  function setUp() {
2048
    parent::setUp('database_test');
2049
  }
2050

    
2051
  /**
2052
   * Test the drupal_write_record() API function.
2053
   */
2054
  function testDrupalWriteRecord() {
2055
    // Insert a record - no columns allow NULL values.
2056
    $person = new stdClass();
2057
    $person->name = 'John';
2058
    $person->unknown_column = 123;
2059
    $insert_result = drupal_write_record('test', $person);
2060
    $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.');
2061
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2062
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2063
    $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
2064

    
2065
    // Verify that the record was inserted.
2066
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2067
    $this->assertIdentical($result->name, 'John', 'Name field set.');
2068
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2069
    $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
2070
    $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
2071

    
2072
    // Update the newly created record.
2073
    $person->name = 'Peter';
2074
    $person->age = 27;
2075
    $person->job = NULL;
2076
    $update_result = drupal_write_record('test', $person, array('id'));
2077
    $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
2078

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

    
2085
    // Try to insert NULL in columns that does not allow this.
2086
    $person = new stdClass();
2087
    $person->name = 'Ringo';
2088
    $person->age = NULL;
2089
    $person->job = NULL;
2090
    $insert_result = drupal_write_record('test', $person);
2091
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2092
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2093
    $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
2094
    $this->assertIdentical($result->age, '0', 'Age field set.');
2095
    $this->assertIdentical($result->job, '', 'Job field set.');
2096

    
2097
    // Insert a record - the "age" column allows NULL.
2098
    $person = new stdClass();
2099
    $person->name = 'Paul';
2100
    $person->age = NULL;
2101
    $insert_result = drupal_write_record('test_null', $person);
2102
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2103
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2104
    $this->assertIdentical($result->name, 'Paul', 'Name field set.');
2105
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2106

    
2107
    // Insert a record - do not specify the value of a column that allows NULL.
2108
    $person = new stdClass();
2109
    $person->name = 'Meredith';
2110
    $insert_result = drupal_write_record('test_null', $person);
2111
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2112
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2113
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2114
    $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
2115
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2116

    
2117
    // Update the newly created record.
2118
    $person->name = 'Mary';
2119
    $person->age = NULL;
2120
    $update_result = drupal_write_record('test_null', $person, array('id'));
2121
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2122
    $this->assertIdentical($result->name, 'Mary', 'Name field set.');
2123
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2124

    
2125
    // Insert a record - the "data" column should be serialized.
2126
    $person = new stdClass();
2127
    $person->name = 'Dave';
2128
    $update_result = drupal_write_record('test_serialized', $person);
2129
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2130
    $this->assertIdentical($result->name, 'Dave', 'Name field set.');
2131
    $this->assertIdentical($result->info, NULL, 'Info field set.');
2132

    
2133
    $person->info = array();
2134
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2135
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2136
    $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
2137

    
2138
    // Update the serialized record.
2139
    $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
2140
    $person->info = $data;
2141
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2142
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2143
    $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
2144

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

    
2151
    // Insert an object record for a table with a multi-field primary key.
2152
    $node_access = new stdClass();
2153
    $node_access->nid = mt_rand();
2154
    $node_access->gid = mt_rand();
2155
    $node_access->realm = $this->randomName();
2156
    $insert_result = drupal_write_record('node_access', $node_access);
2157
    $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.');
2158

    
2159
    // Update the record.
2160
    $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
2161
    $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.');
2162
  }
2163

    
2164
}
2165

    
2166
/**
2167
 * Tests Simpletest error and exception collector.
2168
 */
2169
class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
2170

    
2171
  /**
2172
   * Errors triggered during the test.
2173
   *
2174
   * Errors are intercepted by the overriden implementation
2175
   * of DrupalWebTestCase::error below.
2176
   *
2177
   * @var Array
2178
   */
2179
  protected $collectedErrors = array();
2180

    
2181
  public static function getInfo() {
2182
    return array(
2183
      'name' => 'SimpleTest error collector',
2184
      'description' => 'Performs tests on the Simpletest error and exception collector.',
2185
      'group' => 'SimpleTest',
2186
    );
2187
  }
2188

    
2189
  function setUp() {
2190
    parent::setUp('system_test', 'error_test');
2191
  }
2192

    
2193
  /**
2194
   * Test that simpletest collects errors from the tested site.
2195
   */
2196
  function testErrorCollect() {
2197
    $this->collectedErrors = array();
2198
    $this->drupalGet('error-test/generate-warnings-with-report');
2199
    $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
2200

    
2201
    if (count($this->collectedErrors) == 3) {
2202
      $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
2203
      $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
2204
      $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
2205
    }
2206
    else {
2207
      // Give back the errors to the log report.
2208
      foreach ($this->collectedErrors as $error) {
2209
        parent::error($error['message'], $error['group'], $error['caller']);
2210
      }
2211
    }
2212
  }
2213

    
2214
  /**
2215
   * Error handler that collects errors in an array.
2216
   *
2217
   * This test class is trying to verify that simpletest correctly sees errors
2218
   * and warnings. However, it can't generate errors and warnings that
2219
   * propagate up to the testing framework itself, or these tests would always
2220
   * fail. So, this special copy of error() doesn't propagate the errors up
2221
   * the class hierarchy. It just stuffs them into a protected collectedErrors
2222
   * array for various assertions to inspect.
2223
   */
2224
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
2225
    // Due to a WTF elsewhere, simpletest treats debug() and verbose()
2226
    // messages as if they were an 'error'. But, we don't want to collect
2227
    // those here. This function just wants to collect the real errors (PHP
2228
    // notices, PHP fatal errors, etc.), and let all the 'errors' from the
2229
    // 'User notice' group bubble up to the parent classes to be handled (and
2230
    // eventually displayed) as normal.
2231
    if ($group == 'User notice') {
2232
      parent::error($message, $group, $caller);
2233
    }
2234
    // Everything else should be collected but not propagated.
2235
    else {
2236
      $this->collectedErrors[] = array(
2237
        'message' => $message,
2238
        'group' => $group,
2239
        'caller' => $caller
2240
      );
2241
    }
2242
  }
2243

    
2244
  /**
2245
   * Assert that a collected error matches what we are expecting.
2246
   */
2247
  function assertError($error, $group, $function, $file, $message = NULL) {
2248
    $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
2249
    $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
2250
    $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
2251
    if (isset($message)) {
2252
      $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
2253
    }
2254
  }
2255
}
2256

    
2257
/**
2258
 * Test the drupal_parse_info_file() API function.
2259
 */
2260
class ParseInfoFilesTestCase extends DrupalUnitTestCase {
2261
  public static function getInfo() {
2262
    return array(
2263
      'name' => 'Parsing .info files',
2264
      'description' => 'Tests parsing .info files.',
2265
      'group' => 'System',
2266
    );
2267
  }
2268

    
2269
  /**
2270
   * Parse an example .info file an verify the results.
2271
   */
2272
  function testParseInfoFile() {
2273
    $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
2274
    $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
2275
    $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
2276
    $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
2277
  }
2278
}
2279

    
2280
/**
2281
 * Tests for the drupal_system_listing() function.
2282
 */
2283
class DrupalSystemListingTestCase extends DrupalWebTestCase {
2284
  /**
2285
   * Use the testing profile; this is needed for testDirectoryPrecedence().
2286
   */
2287
  protected $profile = 'testing';
2288

    
2289
  public static function getInfo() {
2290
    return array(
2291
      'name' => 'Drupal system listing',
2292
      'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
2293
      'group' => 'System',
2294
    );
2295
  }
2296

    
2297
  /**
2298
   * Test that files in different directories take precedence as expected.
2299
   */
2300
  function testDirectoryPrecedence() {
2301
    // Define the module files we will search for, and the directory precedence
2302
    // we expect.
2303
    $expected_directories = array(
2304
      // When the copy of the module in the profile directory is incompatible
2305
      // with Drupal core, the copy in the core modules directory takes
2306
      // precedence.
2307
      'drupal_system_listing_incompatible_test' => array(
2308
        'modules/simpletest/tests',
2309
        'profiles/testing/modules',
2310
      ),
2311
      // When both copies of the module are compatible with Drupal core, the
2312
      // copy in the profile directory takes precedence.
2313
      'drupal_system_listing_compatible_test' => array(
2314
        'profiles/testing/modules',
2315
        'modules/simpletest/tests',
2316
      ),
2317
    );
2318

    
2319
    // This test relies on two versions of the same module existing in
2320
    // different places in the filesystem. Without that, the test has no
2321
    // meaning, so assert their presence first.
2322
    foreach ($expected_directories as $module => $directories) {
2323
      foreach ($directories as $directory) {
2324
        $filename = "$directory/$module/$module.module";
2325
        $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
2326
      }
2327
    }
2328

    
2329
    // Now scan the directories and check that the files take precedence as
2330
    // expected.
2331
    $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
2332
    foreach ($expected_directories as $module => $directories) {
2333
      $expected_directory = array_shift($directories);
2334
      $expected_filename = "$expected_directory/$module/$module.module";
2335
      $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
2336
    }
2337
  }
2338
}
2339

    
2340
/**
2341
 * Tests for the format_date() function.
2342
 */
2343
class FormatDateUnitTest extends DrupalWebTestCase {
2344

    
2345
  /**
2346
   * Arbitrary langcode for a custom language.
2347
   */
2348
  const LANGCODE = 'xx';
2349

    
2350
  public static function getInfo() {
2351
    return array(
2352
      'name' => 'Format date',
2353
      'description' => 'Test the format_date() function.',
2354
      'group' => 'System',
2355
    );
2356
  }
2357

    
2358
  function setUp() {
2359
    parent::setUp('locale');
2360
    variable_set('configurable_timezones', 1);
2361
    variable_set('date_format_long', 'l, j. F Y - G:i');
2362
    variable_set('date_format_medium', 'j. F Y - G:i');
2363
    variable_set('date_format_short', 'Y M j - g:ia');
2364
    variable_set('locale_custom_strings_' . self::LANGCODE, array(
2365
      '' => array('Sunday' => 'domingo'),
2366
      'Long month name' => array('March' => 'marzo'),
2367
    ));
2368
    $this->refreshVariables();
2369
  }
2370

    
2371
  /**
2372
   * Test admin-defined formats in format_date().
2373
   */
2374
  function testAdminDefinedFormatDate() {
2375
    // Create an admin user.
2376
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
2377
    $this->drupalLogin($this->admin_user);
2378

    
2379
    // Add new date format.
2380
    $admin_date_format = 'j M y';
2381
    $edit = array('date_format' => $admin_date_format);
2382
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
2383

    
2384
    // Add a new date format which just differs in the case.
2385
    $admin_date_format_uppercase = 'j M Y';
2386
    $edit = array('date_format' => $admin_date_format_uppercase);
2387
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
2388
    $this->assertText(t('Custom date format added.'));
2389

    
2390
    // Add new date type.
2391
    $edit = array(
2392
      'date_type' => 'Example Style',
2393
      'machine_name' => 'example_style',
2394
      'date_format' => $admin_date_format,
2395
    );
2396
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
2397

    
2398
   // Add a second date format with a different case than the first.
2399
    $edit = array(
2400
      'machine_name' => 'example_style_uppercase',
2401
      'date_type' => 'Example Style Uppercase',
2402
      'date_format' => $admin_date_format_uppercase,
2403
    );
2404
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
2405
    $this->assertText(t('New date type added successfully.'));
2406

    
2407
    $timestamp = strtotime('2007-03-10T00:00:00+00:00');
2408
    $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', 'Test format_date() using an admin-defined date type.');
2409
    $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.');
2410
    $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), 'Test format_date() defaulting to medium when $type not found.');
2411
  }
2412

    
2413
  /**
2414
   * Tests for the format_date() function.
2415
   */
2416
  function testFormatDate() {
2417
    global $user, $language;
2418

    
2419
    $timestamp = strtotime('2007-03-26T00:00:00+00:00');
2420
    $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.');
2421
    $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.');
2422
    $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.');
2423
    $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.');
2424
    $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.');
2425
    $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.');
2426

    
2427
    // Create an admin user and add Spanish language.
2428
    $admin_user = $this->drupalCreateUser(array('administer languages'));
2429
    $this->drupalLogin($admin_user);
2430
    $edit = array(
2431
      'langcode' => self::LANGCODE,
2432
      'name' => self::LANGCODE,
2433
      'native' => self::LANGCODE,
2434
      'direction' => LANGUAGE_LTR,
2435
      'prefix' => self::LANGCODE,
2436
    );
2437
    $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
2438

    
2439
    // Create a test user to carry out the tests.
2440
    $test_user = $this->drupalCreateUser();
2441
    $this->drupalLogin($test_user);
2442
    $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
2443
    $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
2444

    
2445
    // Disable session saving as we are about to modify the global $user.
2446
    drupal_save_session(FALSE);
2447
    // Save the original user and language and then replace it with the test user and language.
2448
    $real_user = $user;
2449
    $user = user_load($test_user->uid, TRUE);
2450
    $real_language = $language->language;
2451
    $language->language = $user->language;
2452
    // Simulate a Drupal bootstrap with the logged-in user.
2453
    date_default_timezone_set(drupal_get_user_timezone());
2454

    
2455
    $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.');
2456
    $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.');
2457
    $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.');
2458
    $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
2459
    $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
2460
    $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
2461
    $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
2462

    
2463
    // Restore the original user and language, and enable session saving.
2464
    $user = $real_user;
2465
    $language->language = $real_language;
2466
    // Restore default time zone.
2467
    date_default_timezone_set(drupal_get_user_timezone());
2468
    drupal_save_session(TRUE);
2469
  }
2470
}
2471

    
2472
/**
2473
 * Tests for the format_date() function.
2474
 */
2475
class DrupalAttributesUnitTest extends DrupalUnitTestCase {
2476
  public static function getInfo() {
2477
    return array(
2478
      'name' => 'HTML Attributes',
2479
      'description' => 'Perform unit tests on the drupal_attributes() function.',
2480
      'group' => 'System',
2481
    );
2482
  }
2483

    
2484
  /**
2485
   * Tests that drupal_html_class() cleans the class name properly.
2486
   */
2487
  function testDrupalAttributes() {
2488
    // Verify that special characters are HTML encoded.
2489
    $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
2490

    
2491
    // Verify multi-value attributes are concatenated with spaces.
2492
    $attributes = array('class' => array('first', 'last'));
2493
    $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
2494

    
2495
    // Verify empty attribute values are rendered.
2496
    $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
2497
    $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
2498

    
2499
    // Verify multiple attributes are rendered.
2500
    $attributes = array(
2501
      'id' => 'id-test',
2502
      'class' => array('first', 'last'),
2503
      'alt' => 'Alternate',
2504
    );
2505
    $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
2506

    
2507
    // Verify empty attributes array is rendered.
2508
    $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
2509
  }
2510
}
2511

    
2512
/**
2513
 * Tests converting PHP variables to JSON strings and back.
2514
 */
2515
class DrupalJSONTest extends DrupalUnitTestCase {
2516
  public static function getInfo() {
2517
    return array(
2518
      'name' => 'JSON',
2519
      'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
2520
      'group' => 'System',
2521
    );
2522
  }
2523

    
2524
  /**
2525
   * Tests converting PHP variables to JSON strings and back.
2526
   */
2527
  function testJSON() {
2528
    // Setup a string with the full ASCII table.
2529
    // @todo: Add tests for non-ASCII characters and Unicode.
2530
    $str = '';
2531
    for ($i=0; $i < 128; $i++) {
2532
      $str .= chr($i);
2533
    }
2534
    // Characters that must be escaped.
2535
    // We check for unescaped " separately.
2536
    $html_unsafe = array('<', '>', '\'', '&');
2537
    // The following are the encoded forms of: < > ' & "
2538
    $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
2539

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

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

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

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

    
2559
    // Verify reversibility for structured data. Also verify that necessary
2560
    // characters are escaped.
2561
    $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
2562
    $json = drupal_json_encode($source);
2563
    foreach ($html_unsafe as $char) {
2564
      $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
2565
    }
2566
    // Verify that JSON encoding escapes the HTML unsafe characters
2567
    foreach ($html_unsafe_escaped as $char) {
2568
      $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
2569
    }
2570
    $json_decoded = drupal_json_decode($json);
2571
    $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
2572
    $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
2573
  }
2574
}
2575

    
2576
/**
2577
 * Tests for RDF namespaces XML serialization.
2578
 */
2579
class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
2580
  public static function getInfo() {
2581
    return array(
2582
      'name' => 'RDF namespaces XML serialization tests',
2583
      'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
2584
      'group' => 'System',
2585
    );
2586
  }
2587

    
2588
  function setUp() {
2589
    parent::setUp('rdf', 'rdf_test');
2590
  }
2591

    
2592
  /**
2593
   * Test RDF namespaces.
2594
   */
2595
  function testGetRdfNamespaces() {
2596
    // Fetches the front page and extracts XML namespaces.
2597
    $this->drupalGet('');
2598
    $xml = new SimpleXMLElement($this->content);
2599
    $ns = $xml->getDocNamespaces();
2600

    
2601
    $this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', 'A prefix declared once is displayed.');
2602
    $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.');
2603
    $this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', 'Two prefixes can be assigned the same namespace.');
2604
    $this->assertTrue(!isset($ns['dc']), 'A prefix with conflicting namespaces is discarded.');
2605
  }
2606
}
2607

    
2608
/**
2609
 * Basic tests for drupal_add_feed().
2610
 */
2611
class DrupalAddFeedTestCase extends DrupalWebTestCase {
2612
  public static function getInfo() {
2613
    return array(
2614
      'name' => 'drupal_add_feed() tests',
2615
      'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
2616
      'group' => 'System',
2617
    );
2618
  }
2619

    
2620
  /**
2621
   * Test drupal_add_feed() with paths, URLs, and titles.
2622
   */
2623
  function testBasicFeedAddNoTitle() {
2624
    $path = $this->randomName(12);
2625
    $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2626
    $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
2627

    
2628
    $path_for_title = $this->randomName(12);
2629
    $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2630
    $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
2631

    
2632
    // Possible permutations of drupal_add_feed() to test.
2633
    // - 'input_url': the path passed to drupal_add_feed(),
2634
    // - 'output_url': the expected URL to be found in the header.
2635
    // - 'title' == the title of the feed as passed into drupal_add_feed().
2636
    $urls = array(
2637
      'path without title' => array(
2638
        'input_url' => $path,
2639
        'output_url' => url($path, array('absolute' => TRUE)),
2640
        'title' => '',
2641
      ),
2642
      'external URL without title' => array(
2643
        'input_url' => $external_url,
2644
        'output_url' => $external_url,
2645
        'title' => '',
2646
      ),
2647
      'local URL without title' => array(
2648
        'input_url' => $fully_qualified_local_url,
2649
        'output_url' => $fully_qualified_local_url,
2650
        'title' => '',
2651
      ),
2652
      'path with title' => array(
2653
        'input_url' => $path_for_title,
2654
        'output_url' => url($path_for_title, array('absolute' => TRUE)),
2655
        'title' => $this->randomName(12),
2656
      ),
2657
      'external URL with title' => array(
2658
        'input_url' => $external_for_title,
2659
        'output_url' => $external_for_title,
2660
        'title' => $this->randomName(12),
2661
      ),
2662
      'local URL with title' => array(
2663
        'input_url' => $fully_qualified_for_title,
2664
        'output_url' => $fully_qualified_for_title,
2665
        'title' => $this->randomName(12),
2666
      ),
2667
    );
2668

    
2669
    foreach ($urls as $description => $feed_info) {
2670
      drupal_add_feed($feed_info['input_url'], $feed_info['title']);
2671
    }
2672

    
2673
    $this->drupalSetContent(drupal_get_html_head());
2674
    foreach ($urls as $description => $feed_info) {
2675
      $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
2676
    }
2677
  }
2678

    
2679
  /**
2680
   * Create a pattern representing the RSS feed in the page.
2681
   */
2682
  function urlToRSSLinkPattern($url, $title = '') {
2683
    // Escape any regular expression characters in the URL ('?' is the worst).
2684
    $url = preg_replace('/([+?.*])/', '[$0]', $url);
2685
    $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
2686
    return $generated_pattern;
2687
  }
2688
}
2689

    
2690
/**
2691
 * Test for theme_feed_icon().
2692
 */
2693
class FeedIconTest extends DrupalWebTestCase {
2694

    
2695
  public static function getInfo() {
2696
    return array(
2697
      'name' => 'Feed icon',
2698
      'description' => 'Check escaping of theme_feed_icon()',
2699
      'group' => 'System',
2700
    );
2701
  }
2702

    
2703
  /**
2704
   * Check that special characters are correctly escaped. Test for issue #1211668.
2705
   */
2706
  function testFeedIconEscaping() {
2707
    $variables = array();
2708
    $variables['url'] = 'node';
2709
    $variables['title'] = '<>&"\'';
2710
    $text = theme_feed_icon($variables);
2711
    preg_match('/title="(.*?)"/', $text, $matches);
2712
    $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
2713
  }
2714

    
2715
}
2716

    
2717
/**
2718
 * Test array diff functions.
2719
 */
2720
class ArrayDiffUnitTest extends DrupalUnitTestCase {
2721

    
2722
  /**
2723
   * Array to use for testing.
2724
   *
2725
   * @var array
2726
   */
2727
  protected $array1;
2728

    
2729
  /**
2730
   * Array to use for testing.
2731
   *
2732
   * @var array
2733
   */
2734
  protected $array2;
2735

    
2736
  public static function getInfo() {
2737
    return array(
2738
      'name' => 'Array differences',
2739
      'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
2740
      'group' => 'System',
2741
    );
2742
  }
2743

    
2744
  function setUp() {
2745
    parent::setUp();
2746

    
2747
    $this->array1 = array(
2748
      'same' => 'yes',
2749
      'different' => 'no',
2750
      'array_empty_diff' => array(),
2751
      'null' => NULL,
2752
      'int_diff' => 1,
2753
      'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
2754
      'array_compared_to_string' => array('value'),
2755
      'string_compared_to_array' => 'value',
2756
      'new' => 'new',
2757
    );
2758
    $this->array2 = array(
2759
      'same' => 'yes',
2760
      'different' => 'yes',
2761
      'array_empty_diff' => array(),
2762
      'null' => NULL,
2763
      'int_diff' => '1',
2764
      'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
2765
      'array_compared_to_string' => 'value',
2766
      'string_compared_to_array' => array('value'),
2767
    );
2768
  }
2769

    
2770

    
2771
  /**
2772
   * Tests drupal_array_diff_assoc_recursive().
2773
   */
2774
  public function testArrayDiffAssocRecursive() {
2775
    $expected = array(
2776
      'different' => 'no',
2777
      'int_diff' => 1,
2778
      // The 'array' key should not be returned, as it's the same.
2779
      'array_diff' => array('same' => 'same'),
2780
      'array_compared_to_string' => array('value'),
2781
      'string_compared_to_array' => 'value',
2782
      'new' => 'new',
2783
    );
2784

    
2785
    $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
2786
  }
2787
}
2788

    
2789
/**
2790
 * Tests the functionality of drupal_get_query_array().
2791
 */
2792
class DrupalGetQueryArrayTestCase extends DrupalWebTestCase {
2793

    
2794
  public static function getInfo() {
2795
    return array(
2796
      'name' => 'Query parsing using drupal_get_query_array()',
2797
      'description' => 'Tests that drupal_get_query_array() correctly parses query parameters.',
2798
      'group' => 'System',
2799
    );
2800
  }
2801

    
2802
  /**
2803
   * Tests that drupal_get_query_array() correctly explodes query parameters.
2804
   */
2805
  public function testDrupalGetQueryArray() {
2806
    $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
2807
    $parsed = parse_url($url);
2808
    $result = drupal_get_query_array($parsed['query']);
2809
    $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'drupal_get_query_array() should only explode parameters on the first equals sign.');
2810
  }
2811

    
2812
}