Projet

Général

Profil

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

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

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
    // Verify that newlines are properly added inside style tags.
665
    $query_string = variable_get('css_js_query_string', '0');
666
    $css_processed = "<style type=\"text/css\" media=\"all\">\n@import url(\"" . check_plain(file_create_url($css)) . "?" . $query_string ."\");\n</style>";
667
    $this->assertEqual(trim($styles), $css_processed, 'Rendered CSS includes newlines inside style tags for JavaScript use.');
668
  }
669

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

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

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

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

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

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

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

    
753
    // Fetch the page.
754
    $this->drupalGet('node/' . $node->nid);
755
    $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
756
  }
757

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

    
770
    $expected = array(
771
      $system_path . '/system.base.css',
772
      $system_path . '/system.menus.css',
773
      $system_path . '/system.theme.css',
774
      drupal_get_path('module', 'simpletest') . '/simpletest.css',
775
    );
776

    
777

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

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

    
791
  /**
792
   * Test CSS override.
793
   */
794
  function testRenderOverride() {
795
    $system = drupal_get_path('module', 'system');
796
    $simpletest = drupal_get_path('module', 'simpletest');
797

    
798
    drupal_add_css($system . '/system.base.css');
799
    drupal_add_css($simpletest . '/tests/system.base.css');
800

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

    
806
    drupal_add_css($simpletest . '/tests/system.base.css');
807
    drupal_add_css($system . '/system.base.css');
808

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

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

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

    
829
    // Change the language back to left to right.
830
    $language->direction = LANGUAGE_LTR;
831
  }
832

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

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

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

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

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

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

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

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

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

    
895
    // Reset the static cache so we can ensure the unique id count is at zero.
896
    drupal_static_reset('drupal_html_id');
897

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

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

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

    
942
      $expected = file_get_contents($file_path . '.unoptimized.css');
943
      $unoptimized_output = drupal_load_stylesheet($file_path, FALSE);
944
      $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
945

    
946
      $expected = file_get_contents($file_path . '.optimized.css');
947
      $optimized_output = drupal_load_stylesheet($file_path, TRUE);
948
      $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
949

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

    
955
      $expected = file_get_contents($file_path . '.optimized.css');
956
      $optimized_output_url = drupal_load_stylesheet($file_url, TRUE);
957
      $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
958
    }
959
  }
960
}
961

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

    
974
  function setUp() {
975
    parent::setUp('system_test', 'locale');
976
  }
977

    
978
  function testDrupalHTTPRequest() {
979
    global $is_https;
980

    
981
    // Parse URL schema.
982
    $missing_scheme = drupal_http_request('example.com/path');
983
    $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
984
    $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
985

    
986
    $unable_to_parse = drupal_http_request('http:///path');
987
    $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
988
    $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
989

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

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

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

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

    
1026
    $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
1027
    $result = drupal_http_request($auth);
1028

    
1029
    $this->drupalSetContent($result->data);
1030
    $this->assertRaw($username, 'Username is passed correctly.');
1031
    $this->assertRaw($password, 'Password is passed correctly.');
1032
  }
1033

    
1034
  function testDrupalHTTPRequestRedirect() {
1035
    $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
1036
    $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
1037

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

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

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

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

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

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

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

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

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

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

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

    
1081
    // Add German language and set as default.
1082
    locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
1083

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

    
1090
/**
1091
 * Tests parsing of the HTTP response status line.
1092
 */
1093
class DrupalHTTPResponseStatusLineTest extends DrupalUnitTestCase {
1094
  public static function getInfo() {
1095
    return array(
1096
      'name' => 'Drupal HTTP request response status parsing',
1097
      'description' => 'Perform unit tests on _drupal_parse_response_status().',
1098
      'group' => 'System',
1099
    );
1100
  }
1101

    
1102
  /**
1103
   * Tests parsing HTTP response status line.
1104
   */
1105
  public function testStatusLine() {
1106
    // Grab the big array of test data from statusLineData().
1107
    $data = $this->statusLineData();
1108
    foreach($data as $test_case) {
1109
      $test_data = array_shift($test_case);
1110
      $expected = array_shift($test_case);
1111

    
1112
      $outcome = _drupal_parse_response_status($test_data);
1113

    
1114
      foreach(array_keys($expected) as $key) {
1115
        $this->assertIdentical($outcome[$key], $expected[$key]);
1116
      }
1117
    }
1118
  }
1119

    
1120
  /**
1121
   * Data provider for testStatusLine().
1122
   *
1123
   * @return array
1124
   *   Test data.
1125
   */
1126
  protected function statusLineData() {
1127
    return array(
1128
      array(
1129
        'HTTP/1.1 200 OK',
1130
        array(
1131
          'http_version' => 'HTTP/1.1',
1132
          'response_code' => '200',
1133
          'reason_phrase' => 'OK',
1134
        ),
1135
      ),
1136
      // Data set with no reason phrase.
1137
      array(
1138
        'HTTP/1.1 200',
1139
        array(
1140
          'http_version' => 'HTTP/1.1',
1141
          'response_code' => '200',
1142
          'reason_phrase' => '',
1143
        ),
1144
      ),
1145
      // Arbitrary strings.
1146
      array(
1147
        'version code multi word explanation',
1148
        array(
1149
          'http_version' => 'version',
1150
          'response_code' => 'code',
1151
          'reason_phrase' => 'multi word explanation',
1152
        ),
1153
      ),
1154
    );
1155
  }
1156
}
1157

    
1158
/**
1159
 * Testing drupal_add_region_content and drupal_get_region_content.
1160
 */
1161
class DrupalSetContentTestCase extends DrupalWebTestCase {
1162
  public static function getInfo() {
1163
    return array(
1164
      'name' => 'Drupal set/get regions',
1165
      'description' => 'Performs tests on setting and retrieiving content from theme regions.',
1166
      'group' => 'System'
1167
    );
1168
  }
1169

    
1170

    
1171
  /**
1172
   * Test setting and retrieving content for theme regions.
1173
   */
1174
  function testRegions() {
1175
    global $theme_key;
1176

    
1177
    $block_regions = array_keys(system_region_list($theme_key));
1178
    $delimiter = $this->randomName(32);
1179
    $values = array();
1180
    // Set some random content for each region available.
1181
    foreach ($block_regions as $region) {
1182
      $first_chunk = $this->randomName(32);
1183
      drupal_add_region_content($region, $first_chunk);
1184
      $second_chunk = $this->randomName(32);
1185
      drupal_add_region_content($region, $second_chunk);
1186
      // Store the expected result for a drupal_get_region_content call for this region.
1187
      $values[$region] = $first_chunk . $delimiter . $second_chunk;
1188
    }
1189

    
1190
    // Ensure drupal_get_region_content returns expected results when fetching all regions.
1191
    $content = drupal_get_region_content(NULL, $delimiter);
1192
    foreach ($content as $region => $region_content) {
1193
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
1194
    }
1195

    
1196
    // Ensure drupal_get_region_content returns expected results when fetching a single region.
1197
    foreach ($block_regions as $region) {
1198
      $region_content = drupal_get_region_content($region, $delimiter);
1199
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
1200
    }
1201
  }
1202
}
1203

    
1204
/**
1205
 * Testing drupal_goto and hook_drupal_goto_alter().
1206
 */
1207
class DrupalGotoTest extends DrupalWebTestCase {
1208
  public static function getInfo() {
1209
    return array(
1210
      'name' => 'Drupal goto',
1211
      'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
1212
      'group' => 'System'
1213
    );
1214
  }
1215

    
1216
  function setUp() {
1217
    parent::setUp('common_test');
1218
  }
1219

    
1220
  /**
1221
   * Test drupal_goto().
1222
   */
1223
  function testDrupalGoto() {
1224
    $this->drupalGet('common-test/drupal_goto/redirect');
1225
    $headers = $this->drupalGetHeaders(TRUE);
1226
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1227
    $this->assertEqual($status, 302, 'Expected response code was sent.');
1228
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1229
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1230

    
1231
    $this->drupalGet('common-test/drupal_goto/redirect_advanced');
1232
    $headers = $this->drupalGetHeaders(TRUE);
1233
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1234
    $this->assertEqual($status, 301, 'Expected response code was sent.');
1235
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1236
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1237

    
1238
    // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
1239
    // to test that the path is encoded and decoded properly.
1240
    $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
1241
    $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
1242
    $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
1243
    $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.');
1244
  }
1245

    
1246
  /**
1247
   * Test hook_drupal_goto_alter().
1248
   */
1249
  function testDrupalGotoAlter() {
1250
    $this->drupalGet('common-test/drupal_goto/redirect_fail');
1251

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

    
1256
  /**
1257
   * Test drupal_get_destination().
1258
   */
1259
  function testDrupalGetDestination() {
1260
    $query = $this->randomName(10);
1261

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

    
1266
    // Verify that the current path is used as destination.
1267
    $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
1268
    $url = 'common-test/destination?' . $query;
1269
    $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
1270
  }
1271
}
1272

    
1273
/**
1274
 * Tests for the JavaScript system.
1275
 */
1276
class JavaScriptTestCase extends DrupalWebTestCase {
1277
  /**
1278
   * Store configured value for JavaScript preprocessing.
1279
   */
1280
  protected $preprocess_js = NULL;
1281

    
1282
  public static function getInfo() {
1283
    return array(
1284
      'name' => 'JavaScript',
1285
      'description' => 'Tests the JavaScript system.',
1286
      'group' => 'System'
1287
    );
1288
  }
1289

    
1290
  function setUp() {
1291
    // Enable Locale and SimpleTest in the test environment.
1292
    parent::setUp('locale', 'simpletest', 'common_test');
1293

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

    
1298
    // Reset drupal_add_js() and drupal_add_library() statics before each test.
1299
    drupal_static_reset('drupal_add_js');
1300
    drupal_static_reset('drupal_add_library');
1301
  }
1302

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

    
1309
  /**
1310
   * Test default JavaScript is empty.
1311
   */
1312
  function testDefault() {
1313
    $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
1314
  }
1315

    
1316
  /**
1317
   * Test adding a JavaScript file.
1318
   */
1319
  function testAddFile() {
1320
    $javascript = drupal_add_js('misc/collapse.js');
1321
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
1322
    $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
1323
    $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
1324
    $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
1325
    url('', array('prefix' => &$prefix));
1326
    $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
1327
  }
1328

    
1329
  /**
1330
   * Test adding settings.
1331
   */
1332
  function testAddSetting() {
1333
    $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
1334
    $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
1335
    $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
1336
  }
1337

    
1338
  /**
1339
   * Tests adding an external JavaScript File.
1340
   */
1341
  function testAddExternal() {
1342
    $path = 'http://example.com/script.js';
1343
    $javascript = drupal_add_js($path, 'external');
1344
    $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
1345
  }
1346

    
1347
  /**
1348
   * Test drupal_get_js() for JavaScript settings.
1349
   */
1350
  function testHeaderSetting() {
1351
    // Only the second of these two entries should appear in Drupal.settings.
1352
    drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
1353
    drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
1354
    // All three of these entries should appear in Drupal.settings.
1355
    drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
1356
    drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
1357
    drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
1358
    // Only the second of these two entries should appear in Drupal.settings.
1359
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
1360
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
1361

    
1362
    $javascript = drupal_get_js('header');
1363
    $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
1364
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
1365
    $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
1366

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

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

    
1376
    // Test whether drupal_add_js can be used to override the entry for an
1377
    // existing key in an associative array.
1378
    $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
1379
    $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
1380
  }
1381

    
1382
  /**
1383
   * Test to see if resetting the JavaScript empties the cache.
1384
   */
1385
  function testReset() {
1386
    drupal_add_js('misc/collapse.js');
1387
    drupal_static_reset('drupal_add_js');
1388
    $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
1389
  }
1390

    
1391
  /**
1392
   * Test adding inline scripts.
1393
   */
1394
  function testAddInline() {
1395
    $inline = 'jQuery(function () { });';
1396
    $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1397
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
1398
    $data = end($javascript);
1399
    $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
1400
  }
1401

    
1402
  /**
1403
   * Test rendering an external JavaScript file.
1404
   */
1405
  function testRenderExternal() {
1406
    $external = 'http://example.com/example.js';
1407
    drupal_add_js($external, 'external');
1408
    $javascript = drupal_get_js();
1409
    // Local files have a base_path() prefix, external files should not.
1410
    $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
1411
  }
1412

    
1413
  /**
1414
   * Test drupal_get_js() with a footer scope.
1415
   */
1416
  function testFooterHTML() {
1417
    $inline = 'jQuery(function () { });';
1418
    drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1419
    $javascript = drupal_get_js('footer');
1420
    $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
1421
  }
1422

    
1423
  /**
1424
   * Test drupal_add_js() sets preproccess to false when cache is set to false.
1425
   */
1426
  function testNoCache() {
1427
    $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
1428
    $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
1429
  }
1430

    
1431
  /**
1432
   * Test adding a JavaScript file with a different group.
1433
   */
1434
  function testDifferentGroup() {
1435
    $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
1436
    $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
1437
  }
1438

    
1439
  /**
1440
   * Test adding a JavaScript file with a different weight.
1441
   */
1442
  function testDifferentWeight() {
1443
    $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
1444
    $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
1445
  }
1446

    
1447
  /**
1448
   * Tests JavaScript aggregation when files are added to a different scope.
1449
   */
1450
  function testAggregationOrder() {
1451
    // Enable JavaScript aggregation.
1452
    variable_set('preprocess_js', 1);
1453
    drupal_static_reset('drupal_add_js');
1454

    
1455
    // Add two JavaScript files to the current request and build the cache.
1456
    drupal_add_js('misc/ajax.js');
1457
    drupal_add_js('misc/autocomplete.js');
1458

    
1459
    $js_items = drupal_add_js();
1460
    drupal_build_js_cache(array(
1461
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1462
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1463
    ));
1464

    
1465
    // Store the expected key for the first item in the cache.
1466
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1467
    $expected_key = $cache[0];
1468

    
1469
    // Reset variables and add a file in a different scope first.
1470
    variable_del('drupal_js_cache_files');
1471
    drupal_static_reset('drupal_add_js');
1472
    drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
1473
    drupal_add_js('misc/ajax.js');
1474
    drupal_add_js('misc/autocomplete.js');
1475

    
1476
    // Rebuild the cache.
1477
    $js_items = drupal_add_js();
1478
    drupal_build_js_cache(array(
1479
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1480
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1481
    ));
1482

    
1483
    // Compare the expected key for the first file to the current one.
1484
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1485
    $key = $cache[0];
1486
    $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
1487
  }
1488

    
1489
  /**
1490
   * Test JavaScript ordering.
1491
   */
1492
  function testRenderOrder() {
1493
    // Add a bunch of JavaScript in strange ordering.
1494
    drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1495
    drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1496
    drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1497
    drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1498
    drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1499
    drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1500
    drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
1501
    drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1502
    drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1503
    drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1504

    
1505
    // Construct the expected result from the regex.
1506
    $expected = array(
1507
      "-8 #1",
1508
      "-8 #2",
1509
      "-8 #3",
1510
      "-8 #4",
1511
      "-5 #1", // The external script.
1512
      "0 #1",
1513
      "0 #2",
1514
      "0 #3",
1515
      "5 #1",
1516
      "5 #2",
1517
    );
1518

    
1519
    // Retrieve the rendered JavaScript and test against the regex.
1520
    $js = drupal_get_js('footer');
1521
    $matches = array();
1522
    if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
1523
      $result = $matches[1];
1524
    }
1525
    else {
1526
      $result = array();
1527
    }
1528
    $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
1529
  }
1530

    
1531
  /**
1532
   * Test rendering the JavaScript with a file's weight above jQuery's.
1533
   */
1534
  function testRenderDifferentWeight() {
1535
    // JavaScript files are sorted first by group, then by the 'every_page'
1536
    // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
1537
    // weight, we need the other two options to be the same.
1538
    drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
1539
    $javascript = drupal_get_js();
1540
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
1541
  }
1542

    
1543
  /**
1544
   * Test altering a JavaScript's weight via hook_js_alter().
1545
   *
1546
   * @see simpletest_js_alter()
1547
   */
1548
  function testAlter() {
1549
    // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
1550
    drupal_add_js('misc/tableselect.js');
1551
    drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
1552

    
1553
    // Render the JavaScript, testing if simpletest.js was altered to be before
1554
    // tableselect.js. See simpletest_js_alter() to see where this alteration
1555
    // takes place.
1556
    $javascript = drupal_get_js();
1557
    $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
1558
  }
1559

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

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

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

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

    
1598
  /**
1599
   * Tests non-existing libraries.
1600
   */
1601
  function testLibraryUnknown() {
1602
    $result = drupal_get_library('unknown', 'unknown');
1603
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1604
    drupal_static_reset('drupal_get_library');
1605

    
1606
    $result = drupal_add_library('unknown', 'unknown');
1607
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1608
    $scripts = drupal_get_js();
1609
    $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
1610
  }
1611

    
1612
  /**
1613
   * Tests the addition of libraries through the #attached['library'] property.
1614
   */
1615
  function testAttachedLibrary() {
1616
    $element['#attached']['library'][] = array('system', 'farbtastic');
1617
    drupal_render($element);
1618
    $scripts = drupal_get_js();
1619
    $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
1620
  }
1621

    
1622
  /**
1623
   * Tests retrieval of libraries via drupal_get_library().
1624
   */
1625
  function testGetLibrary() {
1626
    // Retrieve all libraries registered by a module.
1627
    $libraries = drupal_get_library('common_test');
1628
    $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
1629
    // Retrieve all libraries for a module not implementing hook_library().
1630
    // Note: This test installs Locale module.
1631
    $libraries = drupal_get_library('locale');
1632
    $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
1633

    
1634
    // Retrieve a specific library by module and name.
1635
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
1636
    $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
1637
    // Retrieve a non-existing library by module and name.
1638
    $farbtastic = drupal_get_library('common_test', 'foo');
1639
    $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
1640
  }
1641

    
1642
  /**
1643
   * Tests that the query string remains intact when adding JavaScript files
1644
   *  that have query string parameters.
1645
   */
1646
  function testAddJsFileWithQueryString() {
1647
    $this->drupalGet('common-test/query-string');
1648
    $query_string = variable_get('css_js_query_string', '0');
1649
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
1650
  }
1651
}
1652

    
1653
/**
1654
 * Tests for drupal_render().
1655
 */
1656
class DrupalRenderTestCase extends DrupalWebTestCase {
1657
  public static function getInfo() {
1658
    return array(
1659
      'name' => 'drupal_render()',
1660
      'description' => 'Performs functional tests on drupal_render().',
1661
      'group' => 'System',
1662
    );
1663
  }
1664

    
1665
  function setUp() {
1666
    parent::setUp('common_test');
1667
  }
1668

    
1669
  /**
1670
   * Tests the output drupal_render() for some elementary input values.
1671
   */
1672
  function testDrupalRenderBasics() {
1673
    $types = array(
1674
      array(
1675
        'name' => 'null',
1676
        'value' => NULL,
1677
        'expected' => '',
1678
      ),
1679
      array(
1680
        'name' => 'no value',
1681
        'expected' => '',
1682
      ),
1683
      array(
1684
        'name' => 'empty string',
1685
        'value' => '',
1686
        'expected' => '',
1687
      ),
1688
      array(
1689
        'name' => 'no access',
1690
        'value' => array(
1691
          '#markup' => 'foo',
1692
          '#access' => FALSE,
1693
        ),
1694
        'expected' => '',
1695
      ),
1696
      array(
1697
        'name' => 'previously printed',
1698
        'value' => array(
1699
          '#markup' => 'foo',
1700
          '#printed' => TRUE,
1701
        ),
1702
        'expected' => '',
1703
      ),
1704
      array(
1705
        'name' => 'printed in prerender',
1706
        'value' => array(
1707
          '#markup' => 'foo',
1708
          '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
1709
        ),
1710
        'expected' => '',
1711
      ),
1712
      array(
1713
        'name' => 'basic renderable array',
1714
        'value' => array('#markup' => 'foo'),
1715
        'expected' => 'foo',
1716
      ),
1717
    );
1718
    foreach($types as $type) {
1719
      $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
1720
    }
1721
  }
1722

    
1723
  /**
1724
   * Test sorting by weight.
1725
   */
1726
  function testDrupalRenderSorting() {
1727
    $first = $this->randomName();
1728
    $second = $this->randomName();
1729
    // Build an array with '#weight' set for each element.
1730
    $elements = array(
1731
      'second' => array(
1732
        '#weight' => 10,
1733
        '#markup' => $second,
1734
      ),
1735
      'first' => array(
1736
        '#weight' => 0,
1737
        '#markup' => $first,
1738
      ),
1739
    );
1740
    $output = drupal_render($elements);
1741

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

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

    
1748
    // Pass $elements through element_children() and ensure it remains
1749
    // sorted in the correct order. drupal_render() will return an empty string
1750
    // if used on the same array in the same request.
1751
    $children = element_children($elements);
1752
    $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
1753
    $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
1754

    
1755

    
1756
    // The same array structure again, but with #sorted set to TRUE.
1757
    $elements = array(
1758
      'second' => array(
1759
        '#weight' => 10,
1760
        '#markup' => $second,
1761
      ),
1762
      'first' => array(
1763
        '#weight' => 0,
1764
        '#markup' => $first,
1765
      ),
1766
      '#sorted' => TRUE,
1767
    );
1768
    $output = drupal_render($elements);
1769

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

    
1774
  /**
1775
   * Test #attached functionality in children elements.
1776
   */
1777
  function testDrupalRenderChildrenAttached() {
1778
    // The cache system is turned off for POST requests.
1779
    $request_method = $_SERVER['REQUEST_METHOD'];
1780
    $_SERVER['REQUEST_METHOD'] = 'GET';
1781

    
1782
    // Create an element with a child and subchild.  Each element loads a
1783
    // different JavaScript file using #attached.
1784
    $parent_js = drupal_get_path('module', 'user') . '/user.js';
1785
    $child_js = drupal_get_path('module', 'forum') . '/forum.js';
1786
    $subchild_js = drupal_get_path('module', 'book') . '/book.js';
1787
    $element = array(
1788
      '#type' => 'fieldset',
1789
      '#cache' => array(
1790
        'keys' => array('simpletest', 'drupal_render', 'children_attached'),
1791
      ),
1792
      '#attached' => array('js' => array($parent_js)),
1793
      '#title' => 'Parent',
1794
    );
1795
    $element['child'] = array(
1796
      '#type' => 'fieldset',
1797
      '#attached' => array('js' => array($child_js)),
1798
      '#title' => 'Child',
1799
    );
1800
    $element['child']['subchild'] = array(
1801
      '#attached' => array('js' => array($subchild_js)),
1802
      '#markup' => 'Subchild',
1803
    );
1804

    
1805
    // Render the element and verify the presence of #attached JavaScript.
1806
    drupal_render($element);
1807
    $scripts = drupal_get_js();
1808
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
1809
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
1810
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
1811

    
1812
    // Load the element from cache and verify the presence of the #attached
1813
    // JavaScript.
1814
    drupal_static_reset('drupal_add_js');
1815
    $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
1816
    $scripts = drupal_get_js();
1817
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
1818
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
1819
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
1820

    
1821
    $_SERVER['REQUEST_METHOD'] = $request_method;
1822
  }
1823

    
1824
  /**
1825
   * Test passing arguments to the theme function.
1826
   */
1827
  function testDrupalRenderThemeArguments() {
1828
    $element = array(
1829
      '#theme' => 'common_test_foo',
1830
    );
1831
    // Test that defaults work.
1832
    $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
1833
    $element = array(
1834
      '#theme' => 'common_test_foo',
1835
      '#foo' => $this->randomName(),
1836
      '#bar' => $this->randomName(),
1837
    );
1838
    // Test that passing arguments to the theme function works.
1839
    $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
1840
  }
1841

    
1842
  /**
1843
   * Test rendering form elements without passing through form_builder().
1844
   */
1845
  function testDrupalRenderFormElements() {
1846
    // Define a series of form elements.
1847
    $element = array(
1848
      '#type' => 'button',
1849
      '#value' => $this->randomName(),
1850
    );
1851
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
1852

    
1853
    $element = array(
1854
      '#type' => 'textfield',
1855
      '#title' => $this->randomName(),
1856
      '#value' => $this->randomName(),
1857
    );
1858
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
1859

    
1860
    $element = array(
1861
      '#type' => 'password',
1862
      '#title' => $this->randomName(),
1863
    );
1864
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
1865

    
1866
    $element = array(
1867
      '#type' => 'textarea',
1868
      '#title' => $this->randomName(),
1869
      '#value' => $this->randomName(),
1870
    );
1871
    $this->assertRenderedElement($element, '//textarea');
1872

    
1873
    $element = array(
1874
      '#type' => 'radio',
1875
      '#title' => $this->randomName(),
1876
      '#value' => FALSE,
1877
    );
1878
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
1879

    
1880
    $element = array(
1881
      '#type' => 'checkbox',
1882
      '#title' => $this->randomName(),
1883
    );
1884
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
1885

    
1886
    $element = array(
1887
      '#type' => 'select',
1888
      '#title' => $this->randomName(),
1889
      '#options' => array(
1890
        0 => $this->randomName(),
1891
        1 => $this->randomName(),
1892
      ),
1893
    );
1894
    $this->assertRenderedElement($element, '//select');
1895

    
1896
    $element = array(
1897
      '#type' => 'file',
1898
      '#title' => $this->randomName(),
1899
    );
1900
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
1901

    
1902
    $element = array(
1903
      '#type' => 'item',
1904
      '#title' => $this->randomName(),
1905
      '#markup' => $this->randomName(),
1906
    );
1907
    $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
1908
      ':class' => 'form-type-item',
1909
      ':markup' => $element['#markup'],
1910
      ':label' => $element['#title'],
1911
    ));
1912

    
1913
    $element = array(
1914
      '#type' => 'hidden',
1915
      '#title' => $this->randomName(),
1916
      '#value' => $this->randomName(),
1917
    );
1918
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
1919

    
1920
    $element = array(
1921
      '#type' => 'link',
1922
      '#title' => $this->randomName(),
1923
      '#href' => $this->randomName(),
1924
      '#options' => array(
1925
        'absolute' => TRUE,
1926
      ),
1927
    );
1928
    $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
1929
      ':href' => url($element['#href'], array('absolute' => TRUE)),
1930
      ':title' => $element['#title'],
1931
    ));
1932

    
1933
    $element = array(
1934
      '#type' => 'fieldset',
1935
      '#title' => $this->randomName(),
1936
    );
1937
    $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
1938
      ':title' => $element['#title'],
1939
    ));
1940

    
1941
    $element['item'] = array(
1942
      '#type' => 'item',
1943
      '#title' => $this->randomName(),
1944
      '#markup' => $this->randomName(),
1945
    );
1946
    $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
1947
      ':class' => 'form-type-item',
1948
      ':markup' => $element['item']['#markup'],
1949
    ));
1950
  }
1951

    
1952
  protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
1953
    $original_element = $element;
1954
    $this->drupalSetContent(drupal_render($element));
1955
    $this->verbose('<pre>' .  check_plain(var_export($original_element, TRUE)) . '</pre>'
1956
      . '<pre>' .  check_plain(var_export($element, TRUE)) . '</pre>'
1957
      . '<hr />' . $this->drupalGetContent()
1958
    );
1959

    
1960
    // @see DrupalWebTestCase::xpath()
1961
    $xpath = $this->buildXPathQuery($xpath, $xpath_args);
1962
    $element += array('#value' => NULL);
1963
    $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
1964
      '@type' => var_export($element['#type'], TRUE),
1965
    )));
1966
  }
1967

    
1968
  /**
1969
   * Tests caching of an empty render item.
1970
   */
1971
  function testDrupalRenderCache() {
1972
    // Force a request via GET.
1973
    $request_method = $_SERVER['REQUEST_METHOD'];
1974
    $_SERVER['REQUEST_METHOD'] = 'GET';
1975
    // Create an empty element.
1976
    $test_element = array(
1977
      '#cache' => array(
1978
        'cid' => 'render_cache_test',
1979
      ),
1980
      '#markup' => '',
1981
    );
1982

    
1983
    // Render the element and confirm that it goes through the rendering
1984
    // process (which will set $element['#printed']).
1985
    $element = $test_element;
1986
    drupal_render($element);
1987
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
1988

    
1989
    // Render the element again and confirm that it is retrieved from the cache
1990
    // instead (so $element['#printed'] will not be set).
1991
    $element = $test_element;
1992
    drupal_render($element);
1993
    $this->assertFalse(isset($element['#printed']), 'Cache hit');
1994

    
1995
    // Restore the previous request method.
1996
    $_SERVER['REQUEST_METHOD'] = $request_method;
1997
  }
1998
}
1999

    
2000
/**
2001
 * Test for valid_url().
2002
 */
2003
class ValidUrlTestCase extends DrupalUnitTestCase {
2004
  public static function getInfo() {
2005
    return array(
2006
      'name' => 'Valid URL',
2007
      'description' => "Performs tests on Drupal's valid URL function.",
2008
      'group' => 'System'
2009
    );
2010
  }
2011

    
2012
  /**
2013
   * Test valid absolute URLs.
2014
   */
2015
  function testValidAbsolute() {
2016
    $url_schemes = array('http', 'https', 'ftp');
2017
    $valid_absolute_urls = array(
2018
      'example.com',
2019
      'www.example.com',
2020
      'ex-ample.com',
2021
      '3xampl3.com',
2022
      'example.com/paren(the)sis',
2023
      'example.com/index.html#pagetop',
2024
      'example.com:8080',
2025
      'subdomain.example.com',
2026
      'example.com/index.php?q=node',
2027
      'example.com/index.php?q=node&param=false',
2028
      'user@www.example.com',
2029
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
2030
      '127.0.0.1',
2031
      'example.org?',
2032
      'john%20doe:secret:foo@example.org/',
2033
      'example.org/~,$\'*;',
2034
      'caf%C3%A9.example.org',
2035
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
2036
    );
2037

    
2038
    foreach ($url_schemes as $scheme) {
2039
      foreach ($valid_absolute_urls as $url) {
2040
        $test_url = $scheme . '://' . $url;
2041
        $valid_url = valid_url($test_url, TRUE);
2042
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2043
      }
2044
    }
2045
  }
2046

    
2047
  /**
2048
   * Test invalid absolute URLs.
2049
   */
2050
  function testInvalidAbsolute() {
2051
    $url_schemes = array('http', 'https', 'ftp');
2052
    $invalid_ablosule_urls = array(
2053
      '',
2054
      'ex!ample.com',
2055
      'ex%ample.com',
2056
    );
2057

    
2058
    foreach ($url_schemes as $scheme) {
2059
      foreach ($invalid_ablosule_urls as $url) {
2060
        $test_url = $scheme . '://' . $url;
2061
        $valid_url = valid_url($test_url, TRUE);
2062
        $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2063
      }
2064
    }
2065
  }
2066

    
2067
  /**
2068
   * Test valid relative URLs.
2069
   */
2070
  function testValidRelative() {
2071
    $valid_relative_urls = array(
2072
      'paren(the)sis',
2073
      'index.html#pagetop',
2074
      'index.php?q=node',
2075
      'index.php?q=node&param=false',
2076
      'login.php?do=login&style=%23#pagetop',
2077
    );
2078

    
2079
    foreach (array('', '/') as $front) {
2080
      foreach ($valid_relative_urls as $url) {
2081
        $test_url = $front . $url;
2082
        $valid_url = valid_url($test_url);
2083
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2084
      }
2085
    }
2086
  }
2087

    
2088
  /**
2089
   * Test invalid relative URLs.
2090
   */
2091
  function testInvalidRelative() {
2092
    $invalid_relative_urls = array(
2093
      'ex^mple',
2094
      'example<>',
2095
      'ex%ample',
2096
    );
2097

    
2098
    foreach (array('', '/') as $front) {
2099
      foreach ($invalid_relative_urls as $url) {
2100
        $test_url = $front . $url;
2101
        $valid_url = valid_url($test_url);
2102
        $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2103
      }
2104
    }
2105
  }
2106
}
2107

    
2108
/**
2109
 * Tests for CRUD API functions.
2110
 */
2111
class DrupalDataApiTest extends DrupalWebTestCase {
2112
  public static function getInfo() {
2113
    return array(
2114
      'name' => 'Data API functions',
2115
      'description' => 'Tests the performance of CRUD APIs.',
2116
      'group' => 'System',
2117
    );
2118
  }
2119

    
2120
  function setUp() {
2121
    parent::setUp('database_test');
2122
  }
2123

    
2124
  /**
2125
   * Test the drupal_write_record() API function.
2126
   */
2127
  function testDrupalWriteRecord() {
2128
    // Insert a record - no columns allow NULL values.
2129
    $person = new stdClass();
2130
    $person->name = 'John';
2131
    $person->unknown_column = 123;
2132
    $insert_result = drupal_write_record('test', $person);
2133
    $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.');
2134
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2135
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2136
    $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
2137

    
2138
    // Verify that the record was inserted.
2139
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2140
    $this->assertIdentical($result->name, 'John', 'Name field set.');
2141
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2142
    $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
2143
    $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
2144

    
2145
    // Update the newly created record.
2146
    $person->name = 'Peter';
2147
    $person->age = 27;
2148
    $person->job = NULL;
2149
    $update_result = drupal_write_record('test', $person, array('id'));
2150
    $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
2151

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

    
2158
    // Try to insert NULL in columns that does not allow this.
2159
    $person = new stdClass();
2160
    $person->name = 'Ringo';
2161
    $person->age = NULL;
2162
    $person->job = NULL;
2163
    $insert_result = drupal_write_record('test', $person);
2164
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2165
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2166
    $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
2167
    $this->assertIdentical($result->age, '0', 'Age field set.');
2168
    $this->assertIdentical($result->job, '', 'Job field set.');
2169

    
2170
    // Insert a record - the "age" column allows NULL.
2171
    $person = new stdClass();
2172
    $person->name = 'Paul';
2173
    $person->age = NULL;
2174
    $insert_result = drupal_write_record('test_null', $person);
2175
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2176
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2177
    $this->assertIdentical($result->name, 'Paul', 'Name field set.');
2178
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2179

    
2180
    // Insert a record - do not specify the value of a column that allows NULL.
2181
    $person = new stdClass();
2182
    $person->name = 'Meredith';
2183
    $insert_result = drupal_write_record('test_null', $person);
2184
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2185
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2186
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2187
    $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
2188
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2189

    
2190
    // Update the newly created record.
2191
    $person->name = 'Mary';
2192
    $person->age = NULL;
2193
    $update_result = drupal_write_record('test_null', $person, array('id'));
2194
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2195
    $this->assertIdentical($result->name, 'Mary', 'Name field set.');
2196
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2197

    
2198
    // Insert a record - the "data" column should be serialized.
2199
    $person = new stdClass();
2200
    $person->name = 'Dave';
2201
    $update_result = drupal_write_record('test_serialized', $person);
2202
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2203
    $this->assertIdentical($result->name, 'Dave', 'Name field set.');
2204
    $this->assertIdentical($result->info, NULL, 'Info field set.');
2205

    
2206
    $person->info = array();
2207
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2208
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2209
    $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
2210

    
2211
    // Update the serialized record.
2212
    $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
2213
    $person->info = $data;
2214
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2215
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2216
    $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
2217

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

    
2224
    // Insert an object record for a table with a multi-field primary key.
2225
    $node_access = new stdClass();
2226
    $node_access->nid = mt_rand();
2227
    $node_access->gid = mt_rand();
2228
    $node_access->realm = $this->randomName();
2229
    $insert_result = drupal_write_record('node_access', $node_access);
2230
    $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.');
2231

    
2232
    // Update the record.
2233
    $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
2234
    $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.');
2235
  }
2236

    
2237
}
2238

    
2239
/**
2240
 * Tests Simpletest error and exception collector.
2241
 */
2242
class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
2243

    
2244
  /**
2245
   * Errors triggered during the test.
2246
   *
2247
   * Errors are intercepted by the overriden implementation
2248
   * of DrupalWebTestCase::error below.
2249
   *
2250
   * @var Array
2251
   */
2252
  protected $collectedErrors = array();
2253

    
2254
  public static function getInfo() {
2255
    return array(
2256
      'name' => 'SimpleTest error collector',
2257
      'description' => 'Performs tests on the Simpletest error and exception collector.',
2258
      'group' => 'SimpleTest',
2259
    );
2260
  }
2261

    
2262
  function setUp() {
2263
    parent::setUp('system_test', 'error_test');
2264
  }
2265

    
2266
  /**
2267
   * Test that simpletest collects errors from the tested site.
2268
   */
2269
  function testErrorCollect() {
2270
    $this->collectedErrors = array();
2271
    $this->drupalGet('error-test/generate-warnings-with-report');
2272
    $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
2273

    
2274
    if (count($this->collectedErrors) == 3) {
2275
      $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
2276
      $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
2277
      $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
2278
    }
2279
    else {
2280
      // Give back the errors to the log report.
2281
      foreach ($this->collectedErrors as $error) {
2282
        parent::error($error['message'], $error['group'], $error['caller']);
2283
      }
2284
    }
2285
  }
2286

    
2287
  /**
2288
   * Error handler that collects errors in an array.
2289
   *
2290
   * This test class is trying to verify that simpletest correctly sees errors
2291
   * and warnings. However, it can't generate errors and warnings that
2292
   * propagate up to the testing framework itself, or these tests would always
2293
   * fail. So, this special copy of error() doesn't propagate the errors up
2294
   * the class hierarchy. It just stuffs them into a protected collectedErrors
2295
   * array for various assertions to inspect.
2296
   */
2297
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
2298
    // Due to a WTF elsewhere, simpletest treats debug() and verbose()
2299
    // messages as if they were an 'error'. But, we don't want to collect
2300
    // those here. This function just wants to collect the real errors (PHP
2301
    // notices, PHP fatal errors, etc.), and let all the 'errors' from the
2302
    // 'User notice' group bubble up to the parent classes to be handled (and
2303
    // eventually displayed) as normal.
2304
    if ($group == 'User notice') {
2305
      parent::error($message, $group, $caller);
2306
    }
2307
    // Everything else should be collected but not propagated.
2308
    else {
2309
      $this->collectedErrors[] = array(
2310
        'message' => $message,
2311
        'group' => $group,
2312
        'caller' => $caller
2313
      );
2314
    }
2315
  }
2316

    
2317
  /**
2318
   * Assert that a collected error matches what we are expecting.
2319
   */
2320
  function assertError($error, $group, $function, $file, $message = NULL) {
2321
    $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
2322
    $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
2323
    $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
2324
    if (isset($message)) {
2325
      $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
2326
    }
2327
  }
2328
}
2329

    
2330
/**
2331
 * Test the drupal_parse_info_file() API function.
2332
 */
2333
class ParseInfoFilesTestCase extends DrupalUnitTestCase {
2334
  public static function getInfo() {
2335
    return array(
2336
      'name' => 'Parsing .info files',
2337
      'description' => 'Tests parsing .info files.',
2338
      'group' => 'System',
2339
    );
2340
  }
2341

    
2342
  /**
2343
   * Parse an example .info file an verify the results.
2344
   */
2345
  function testParseInfoFile() {
2346
    $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
2347
    $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
2348
    $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
2349
    $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
2350
  }
2351
}
2352

    
2353
/**
2354
 * Tests for the drupal_system_listing() function.
2355
 */
2356
class DrupalSystemListingTestCase extends DrupalWebTestCase {
2357
  /**
2358
   * Use the testing profile; this is needed for testDirectoryPrecedence().
2359
   */
2360
  protected $profile = 'testing';
2361

    
2362
  public static function getInfo() {
2363
    return array(
2364
      'name' => 'Drupal system listing',
2365
      'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
2366
      'group' => 'System',
2367
    );
2368
  }
2369

    
2370
  /**
2371
   * Test that files in different directories take precedence as expected.
2372
   */
2373
  function testDirectoryPrecedence() {
2374
    // Define the module files we will search for, and the directory precedence
2375
    // we expect.
2376
    $expected_directories = array(
2377
      // When the copy of the module in the profile directory is incompatible
2378
      // with Drupal core, the copy in the core modules directory takes
2379
      // precedence.
2380
      'drupal_system_listing_incompatible_test' => array(
2381
        'modules/simpletest/tests',
2382
        'profiles/testing/modules',
2383
      ),
2384
      // When both copies of the module are compatible with Drupal core, the
2385
      // copy in the profile directory takes precedence.
2386
      'drupal_system_listing_compatible_test' => array(
2387
        'profiles/testing/modules',
2388
        'modules/simpletest/tests',
2389
      ),
2390
    );
2391

    
2392
    // This test relies on two versions of the same module existing in
2393
    // different places in the filesystem. Without that, the test has no
2394
    // meaning, so assert their presence first.
2395
    foreach ($expected_directories as $module => $directories) {
2396
      foreach ($directories as $directory) {
2397
        $filename = "$directory/$module/$module.module";
2398
        $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
2399
      }
2400
    }
2401

    
2402
    // Now scan the directories and check that the files take precedence as
2403
    // expected.
2404
    $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
2405
    foreach ($expected_directories as $module => $directories) {
2406
      $expected_directory = array_shift($directories);
2407
      $expected_filename = "$expected_directory/$module/$module.module";
2408
      $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
2409
    }
2410
  }
2411
}
2412

    
2413
/**
2414
 * Tests for the format_date() function.
2415
 */
2416
class FormatDateUnitTest extends DrupalWebTestCase {
2417

    
2418
  /**
2419
   * Arbitrary langcode for a custom language.
2420
   */
2421
  const LANGCODE = 'xx';
2422

    
2423
  public static function getInfo() {
2424
    return array(
2425
      'name' => 'Format date',
2426
      'description' => 'Test the format_date() function.',
2427
      'group' => 'System',
2428
    );
2429
  }
2430

    
2431
  function setUp() {
2432
    parent::setUp('locale');
2433
    variable_set('configurable_timezones', 1);
2434
    variable_set('date_format_long', 'l, j. F Y - G:i');
2435
    variable_set('date_format_medium', 'j. F Y - G:i');
2436
    variable_set('date_format_short', 'Y M j - g:ia');
2437
    variable_set('locale_custom_strings_' . self::LANGCODE, array(
2438
      '' => array('Sunday' => 'domingo'),
2439
      'Long month name' => array('March' => 'marzo'),
2440
    ));
2441
    $this->refreshVariables();
2442
  }
2443

    
2444
  /**
2445
   * Test admin-defined formats in format_date().
2446
   */
2447
  function testAdminDefinedFormatDate() {
2448
    // Create an admin user.
2449
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
2450
    $this->drupalLogin($this->admin_user);
2451

    
2452
    // Add new date format.
2453
    $admin_date_format = 'j M y';
2454
    $edit = array('date_format' => $admin_date_format);
2455
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
2456

    
2457
    // Add a new date format which just differs in the case.
2458
    $admin_date_format_uppercase = 'j M Y';
2459
    $edit = array('date_format' => $admin_date_format_uppercase);
2460
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
2461
    $this->assertText(t('Custom date format added.'));
2462

    
2463
    // Add new date type.
2464
    $edit = array(
2465
      'date_type' => 'Example Style',
2466
      'machine_name' => 'example_style',
2467
      'date_format' => $admin_date_format,
2468
    );
2469
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
2470

    
2471
   // Add a second date format with a different case than the first.
2472
    $edit = array(
2473
      'machine_name' => 'example_style_uppercase',
2474
      'date_type' => 'Example Style Uppercase',
2475
      'date_format' => $admin_date_format_uppercase,
2476
    );
2477
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
2478
    $this->assertText(t('New date type added successfully.'));
2479

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

    
2486
  /**
2487
   * Tests for the format_date() function.
2488
   */
2489
  function testFormatDate() {
2490
    global $user, $language;
2491

    
2492
    $timestamp = strtotime('2007-03-26T00:00:00+00:00');
2493
    $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.');
2494
    $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.');
2495
    $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.');
2496
    $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.');
2497
    $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.');
2498
    $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.');
2499

    
2500
    // Create an admin user and add Spanish language.
2501
    $admin_user = $this->drupalCreateUser(array('administer languages'));
2502
    $this->drupalLogin($admin_user);
2503
    $edit = array(
2504
      'langcode' => self::LANGCODE,
2505
      'name' => self::LANGCODE,
2506
      'native' => self::LANGCODE,
2507
      'direction' => LANGUAGE_LTR,
2508
      'prefix' => self::LANGCODE,
2509
    );
2510
    $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
2511

    
2512
    // Create a test user to carry out the tests.
2513
    $test_user = $this->drupalCreateUser();
2514
    $this->drupalLogin($test_user);
2515
    $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
2516
    $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
2517

    
2518
    // Disable session saving as we are about to modify the global $user.
2519
    drupal_save_session(FALSE);
2520
    // Save the original user and language and then replace it with the test user and language.
2521
    $real_user = $user;
2522
    $user = user_load($test_user->uid, TRUE);
2523
    $real_language = $language->language;
2524
    $language->language = $user->language;
2525
    // Simulate a Drupal bootstrap with the logged-in user.
2526
    date_default_timezone_set(drupal_get_user_timezone());
2527

    
2528
    $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.');
2529
    $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.');
2530
    $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.');
2531
    $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
2532
    $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
2533
    $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
2534
    $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
2535

    
2536
    // Restore the original user and language, and enable session saving.
2537
    $user = $real_user;
2538
    $language->language = $real_language;
2539
    // Restore default time zone.
2540
    date_default_timezone_set(drupal_get_user_timezone());
2541
    drupal_save_session(TRUE);
2542
  }
2543
}
2544

    
2545
/**
2546
 * Tests for the format_date() function.
2547
 */
2548
class DrupalAttributesUnitTest extends DrupalUnitTestCase {
2549
  public static function getInfo() {
2550
    return array(
2551
      'name' => 'HTML Attributes',
2552
      'description' => 'Perform unit tests on the drupal_attributes() function.',
2553
      'group' => 'System',
2554
    );
2555
  }
2556

    
2557
  /**
2558
   * Tests that drupal_html_class() cleans the class name properly.
2559
   */
2560
  function testDrupalAttributes() {
2561
    // Verify that special characters are HTML encoded.
2562
    $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
2563

    
2564
    // Verify multi-value attributes are concatenated with spaces.
2565
    $attributes = array('class' => array('first', 'last'));
2566
    $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
2567

    
2568
    // Verify empty attribute values are rendered.
2569
    $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
2570
    $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
2571

    
2572
    // Verify multiple attributes are rendered.
2573
    $attributes = array(
2574
      'id' => 'id-test',
2575
      'class' => array('first', 'last'),
2576
      'alt' => 'Alternate',
2577
    );
2578
    $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
2579

    
2580
    // Verify empty attributes array is rendered.
2581
    $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
2582
  }
2583
}
2584

    
2585
/**
2586
 * Tests converting PHP variables to JSON strings and back.
2587
 */
2588
class DrupalJSONTest extends DrupalUnitTestCase {
2589
  public static function getInfo() {
2590
    return array(
2591
      'name' => 'JSON',
2592
      'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
2593
      'group' => 'System',
2594
    );
2595
  }
2596

    
2597
  /**
2598
   * Tests converting PHP variables to JSON strings and back.
2599
   */
2600
  function testJSON() {
2601
    // Setup a string with the full ASCII table.
2602
    // @todo: Add tests for non-ASCII characters and Unicode.
2603
    $str = '';
2604
    for ($i=0; $i < 128; $i++) {
2605
      $str .= chr($i);
2606
    }
2607
    // Characters that must be escaped.
2608
    // We check for unescaped " separately.
2609
    $html_unsafe = array('<', '>', '\'', '&');
2610
    // The following are the encoded forms of: < > ' & "
2611
    $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
2612

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

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

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

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

    
2632
    // Verify reversibility for structured data. Also verify that necessary
2633
    // characters are escaped.
2634
    $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
2635
    $json = drupal_json_encode($source);
2636
    foreach ($html_unsafe as $char) {
2637
      $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
2638
    }
2639
    // Verify that JSON encoding escapes the HTML unsafe characters
2640
    foreach ($html_unsafe_escaped as $char) {
2641
      $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
2642
    }
2643
    $json_decoded = drupal_json_decode($json);
2644
    $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
2645
    $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
2646
  }
2647
}
2648

    
2649
/**
2650
 * Tests for RDF namespaces XML serialization.
2651
 */
2652
class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
2653
  public static function getInfo() {
2654
    return array(
2655
      'name' => 'RDF namespaces XML serialization tests',
2656
      'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
2657
      'group' => 'System',
2658
    );
2659
  }
2660

    
2661
  function setUp() {
2662
    parent::setUp('rdf', 'rdf_test');
2663
  }
2664

    
2665
  /**
2666
   * Test RDF namespaces.
2667
   */
2668
  function testGetRdfNamespaces() {
2669
    // Fetches the front page and extracts XML namespaces.
2670
    $this->drupalGet('');
2671
    $xml = new SimpleXMLElement($this->content);
2672
    $ns = $xml->getDocNamespaces();
2673

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

    
2681
/**
2682
 * Basic tests for drupal_add_feed().
2683
 */
2684
class DrupalAddFeedTestCase extends DrupalWebTestCase {
2685
  public static function getInfo() {
2686
    return array(
2687
      'name' => 'drupal_add_feed() tests',
2688
      'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
2689
      'group' => 'System',
2690
    );
2691
  }
2692

    
2693
  /**
2694
   * Test drupal_add_feed() with paths, URLs, and titles.
2695
   */
2696
  function testBasicFeedAddNoTitle() {
2697
    $path = $this->randomName(12);
2698
    $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2699
    $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
2700

    
2701
    $path_for_title = $this->randomName(12);
2702
    $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
2703
    $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
2704

    
2705
    // Possible permutations of drupal_add_feed() to test.
2706
    // - 'input_url': the path passed to drupal_add_feed(),
2707
    // - 'output_url': the expected URL to be found in the header.
2708
    // - 'title' == the title of the feed as passed into drupal_add_feed().
2709
    $urls = array(
2710
      'path without title' => array(
2711
        'input_url' => $path,
2712
        'output_url' => url($path, array('absolute' => TRUE)),
2713
        'title' => '',
2714
      ),
2715
      'external URL without title' => array(
2716
        'input_url' => $external_url,
2717
        'output_url' => $external_url,
2718
        'title' => '',
2719
      ),
2720
      'local URL without title' => array(
2721
        'input_url' => $fully_qualified_local_url,
2722
        'output_url' => $fully_qualified_local_url,
2723
        'title' => '',
2724
      ),
2725
      'path with title' => array(
2726
        'input_url' => $path_for_title,
2727
        'output_url' => url($path_for_title, array('absolute' => TRUE)),
2728
        'title' => $this->randomName(12),
2729
      ),
2730
      'external URL with title' => array(
2731
        'input_url' => $external_for_title,
2732
        'output_url' => $external_for_title,
2733
        'title' => $this->randomName(12),
2734
      ),
2735
      'local URL with title' => array(
2736
        'input_url' => $fully_qualified_for_title,
2737
        'output_url' => $fully_qualified_for_title,
2738
        'title' => $this->randomName(12),
2739
      ),
2740
    );
2741

    
2742
    foreach ($urls as $description => $feed_info) {
2743
      drupal_add_feed($feed_info['input_url'], $feed_info['title']);
2744
    }
2745

    
2746
    $this->drupalSetContent(drupal_get_html_head());
2747
    foreach ($urls as $description => $feed_info) {
2748
      $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
2749
    }
2750
  }
2751

    
2752
  /**
2753
   * Create a pattern representing the RSS feed in the page.
2754
   */
2755
  function urlToRSSLinkPattern($url, $title = '') {
2756
    // Escape any regular expression characters in the URL ('?' is the worst).
2757
    $url = preg_replace('/([+?.*])/', '[$0]', $url);
2758
    $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
2759
    return $generated_pattern;
2760
  }
2761
}
2762

    
2763
/**
2764
 * Test for theme_feed_icon().
2765
 */
2766
class FeedIconTest extends DrupalWebTestCase {
2767

    
2768
  public static function getInfo() {
2769
    return array(
2770
      'name' => 'Feed icon',
2771
      'description' => 'Check escaping of theme_feed_icon()',
2772
      'group' => 'System',
2773
    );
2774
  }
2775

    
2776
  /**
2777
   * Check that special characters are correctly escaped. Test for issue #1211668.
2778
   */
2779
  function testFeedIconEscaping() {
2780
    $variables = array();
2781
    $variables['url'] = 'node';
2782
    $variables['title'] = '<>&"\'';
2783
    $text = theme_feed_icon($variables);
2784
    preg_match('/title="(.*?)"/', $text, $matches);
2785
    $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
2786
  }
2787

    
2788
}
2789

    
2790
/**
2791
 * Test array diff functions.
2792
 */
2793
class ArrayDiffUnitTest extends DrupalUnitTestCase {
2794

    
2795
  /**
2796
   * Array to use for testing.
2797
   *
2798
   * @var array
2799
   */
2800
  protected $array1;
2801

    
2802
  /**
2803
   * Array to use for testing.
2804
   *
2805
   * @var array
2806
   */
2807
  protected $array2;
2808

    
2809
  public static function getInfo() {
2810
    return array(
2811
      'name' => 'Array differences',
2812
      'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
2813
      'group' => 'System',
2814
    );
2815
  }
2816

    
2817
  function setUp() {
2818
    parent::setUp();
2819

    
2820
    $this->array1 = array(
2821
      'same' => 'yes',
2822
      'different' => 'no',
2823
      'array_empty_diff' => array(),
2824
      'null' => NULL,
2825
      'int_diff' => 1,
2826
      'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
2827
      'array_compared_to_string' => array('value'),
2828
      'string_compared_to_array' => 'value',
2829
      'new' => 'new',
2830
    );
2831
    $this->array2 = array(
2832
      'same' => 'yes',
2833
      'different' => 'yes',
2834
      'array_empty_diff' => array(),
2835
      'null' => NULL,
2836
      'int_diff' => '1',
2837
      'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
2838
      'array_compared_to_string' => 'value',
2839
      'string_compared_to_array' => array('value'),
2840
    );
2841
  }
2842

    
2843

    
2844
  /**
2845
   * Tests drupal_array_diff_assoc_recursive().
2846
   */
2847
  public function testArrayDiffAssocRecursive() {
2848
    $expected = array(
2849
      'different' => 'no',
2850
      'int_diff' => 1,
2851
      // The 'array' key should not be returned, as it's the same.
2852
      'array_diff' => array('same' => 'same'),
2853
      'array_compared_to_string' => array('value'),
2854
      'string_compared_to_array' => 'value',
2855
      'new' => 'new',
2856
    );
2857

    
2858
    $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
2859
  }
2860
}
2861

    
2862
/**
2863
 * Tests the functionality of drupal_get_query_array().
2864
 */
2865
class DrupalGetQueryArrayTestCase extends DrupalWebTestCase {
2866

    
2867
  public static function getInfo() {
2868
    return array(
2869
      'name' => 'Query parsing using drupal_get_query_array()',
2870
      'description' => 'Tests that drupal_get_query_array() correctly parses query parameters.',
2871
      'group' => 'System',
2872
    );
2873
  }
2874

    
2875
  /**
2876
   * Tests that drupal_get_query_array() correctly explodes query parameters.
2877
   */
2878
  public function testDrupalGetQueryArray() {
2879
    $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
2880
    $parsed = parse_url($url);
2881
    $result = drupal_get_query_array($parsed['query']);
2882
    $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'drupal_get_query_array() should only explode parameters on the first equals sign.');
2883
  }
2884

    
2885
}