Projet

Général

Profil

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

root / drupal7 / modules / simpletest / tests / common.test @ 27e02aed

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 unit 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%5Bb%5D=2&a%5Bc%5D=3&d=foo', 'Nested array was properly encoded.');
173
  }
174

    
175
  /**
176
   * Test drupal_parse_url().
177
   */
178
  function testDrupalParseUrl() {
179
    // Relative URL.
180
    $url = 'foo/bar?foo=bar&bar=baz&baz#foo';
181
    $result = array(
182
      'path' => 'foo/bar',
183
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
184
      'fragment' => 'foo',
185
    );
186
    $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL parsed correctly.');
187

    
188
    // Relative URL that is known to confuse parse_url().
189
    $url = 'foo/bar:1';
190
    $result = array(
191
      'path' => 'foo/bar:1',
192
      'query' => array(),
193
      'fragment' => '',
194
    );
195
    $this->assertEqual(drupal_parse_url($url), $result, 'Relative URL parsed correctly.');
196

    
197
    // Absolute URL.
198
    $url = '/foo/bar?foo=bar&bar=baz&baz#foo';
199
    $result = array(
200
      'path' => '/foo/bar',
201
      'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
202
      'fragment' => 'foo',
203
    );
204
    $this->assertEqual(drupal_parse_url($url), $result, 'Absolute URL parsed correctly.');
205

    
206
    // External URL testing.
207
    $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
208

    
209
    // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
210
    $this->assertTrue(url_is_external($url), 'Correctly identified an external URL.');
211

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
375
/**
376
 * Web tests for URL generation functions.
377
 */
378
class CommonURLWebTest extends DrupalWebTestCase {
379
  public static function getInfo() {
380
    return array(
381
      'name' => 'URL generation web tests',
382
      'description' => 'Confirm that URL-generating functions work correctly on specific site paths.',
383
      'group' => 'System',
384
    );
385
  }
386

    
387
  function setUp() {
388
    parent::setUp('common_test');
389
  }
390

    
391
  /**
392
   * Tests the url() function on internal paths which mimic external URLs.
393
   */
394
  function testInternalPathMimicsExternal() {
395
    // Ensure that calling url(current_path()) on "/http://example.com" (an
396
    // internal path which mimics an external URL) always links to the internal
397
    // path, not the external URL. This helps protect against external URL link
398
    // injection vulnerabilities.
399
    variable_set('common_test_link_to_current_path', TRUE);
400
    $this->drupalGet('/http://example.com');
401
    $this->clickLink('link which should point to the current path');
402
    $this->assertUrl('/http://example.com');
403
    $this->assertText('link which should point to the current path');
404
  }
405
}
406

    
407
/**
408
 * Tests url_is_external().
409
 */
410
class UrlIsExternalUnitTest extends DrupalUnitTestCase {
411

    
412
  public static function getInfo() {
413
    return array(
414
      'name' => 'External URL checking',
415
      'description' => 'Performs tests on url_is_external().',
416
      'group' => 'System',
417
    );
418
  }
419

    
420
  /**
421
   * Tests if each URL is external or not.
422
   */
423
  function testUrlIsExternal() {
424
    foreach ($this->examples() as $path => $expected) {
425
      $this->assertIdentical(url_is_external($path), $expected, $path);
426
    }
427
  }
428

    
429
  /**
430
   * Provides data for testUrlIsExternal().
431
   *
432
   * @return array
433
   *   An array of test data, keyed by a path, with the expected value where
434
   *   TRUE is external, and FALSE is not external.
435
   */
436
  protected function examples() {
437
    return array(
438
      // Simple external URLs.
439
      'http://example.com' => TRUE,
440
      'https://example.com' => TRUE,
441
      'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo' => TRUE,
442
      '//drupal.org' => TRUE,
443
      // Some browsers ignore or strip leading control characters.
444
      "\x00//www.example.com" => TRUE,
445
      "\x08//www.example.com" => TRUE,
446
      "\x1F//www.example.com" => TRUE,
447
      "\n//www.example.com" => TRUE,
448
      // JSON supports decoding directly from UTF-8 code points.
449
      json_decode('"\u00AD"') . "//www.example.com" => TRUE,
450
      json_decode('"\u200E"') . "//www.example.com" => TRUE,
451
      json_decode('"\uE0020"') . "//www.example.com" => TRUE,
452
      json_decode('"\uE000"')  . "//www.example.com" => TRUE,
453
      // Backslashes should be normalized to forward.
454
      '\\\\example.com' => TRUE,
455
      // Local URLs.
456
      'node' => FALSE,
457
      '/system/ajax' => FALSE,
458
      '?q=foo:bar' => FALSE,
459
      'node/edit:me' => FALSE,
460
      '/drupal.org' => FALSE,
461
      '<front>' => FALSE,
462
    );
463
  }
464
}
465

    
466
/**
467
 * Tests for check_plain(), filter_xss(), format_string(), and check_url().
468
 */
469
class CommonXssUnitTest extends DrupalUnitTestCase {
470

    
471
  public static function getInfo() {
472
    return array(
473
      'name' => 'String filtering tests',
474
      'description' => 'Confirm that check_plain(), filter_xss(), format_string() and check_url() work correctly, including invalid multi-byte sequences.',
475
      'group' => 'System',
476
    );
477
  }
478

    
479
  /**
480
   * Check that invalid multi-byte sequences are rejected.
481
   */
482
  function testInvalidMultiByte() {
483
     // Ignore PHP 5.3+ invalid multibyte sequence warning.
484
     $text = @check_plain("Foo\xC0barbaz");
485
     $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "Foo\xC0barbaz"');
486
     // Ignore PHP 5.3+ invalid multibyte sequence warning.
487
     $text = @check_plain("\xc2\"");
488
     $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "\xc2\""');
489
     $text = check_plain("Fooÿñ");
490
     $this->assertEqual($text, "Fooÿñ", 'check_plain() accepts valid sequence "Fooÿñ"');
491
     $text = filter_xss("Foo\xC0barbaz");
492
     $this->assertEqual($text, '', 'filter_xss() rejects invalid sequence "Foo\xC0barbaz"');
493
     $text = filter_xss("Fooÿñ");
494
     $this->assertEqual($text, "Fooÿñ", 'filter_xss() accepts valid sequence Fooÿñ');
495
  }
496

    
497
  /**
498
   * Check that special characters are escaped.
499
   */
500
  function testEscaping() {
501
     $text = check_plain("<script>");
502
     $this->assertEqual($text, '&lt;script&gt;', 'check_plain() escapes &lt;script&gt;');
503
     $text = check_plain('<>&"\'');
504
     $this->assertEqual($text, '&lt;&gt;&amp;&quot;&#039;', 'check_plain() escapes reserved HTML characters.');
505
  }
506

    
507
  /**
508
   * Test t() and format_string() replacement functionality.
509
   */
510
  function testFormatStringAndT() {
511
    foreach (array('format_string', 't') as $function) {
512
      $text = $function('Simple text');
513
      $this->assertEqual($text, 'Simple text', $function . ' leaves simple text alone.');
514
      $text = $function('Escaped text: @value', array('@value' => '<script>'));
515
      $this->assertEqual($text, 'Escaped text: &lt;script&gt;', $function . ' replaces and escapes string.');
516
      $text = $function('Placeholder text: %value', array('%value' => '<script>'));
517
      $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', $function . ' replaces, escapes and themes string.');
518
      $text = $function('Verbatim text: !value', array('!value' => '<script>'));
519
      $this->assertEqual($text, 'Verbatim text: <script>', $function . ' replaces verbatim string as-is.');
520
    }
521
  }
522

    
523
  /**
524
   * Check that harmful protocols are stripped.
525
   */
526
  function testBadProtocolStripping() {
527
    // Ensure that check_url() strips out harmful protocols, and encodes for
528
    // HTML. Ensure drupal_strip_dangerous_protocols() can be used to return a
529
    // plain-text string stripped of harmful protocols.
530
    $url = 'javascript:http://www.example.com/?x=1&y=2';
531
    $expected_plain = 'http://www.example.com/?x=1&y=2';
532
    $expected_html = 'http://www.example.com/?x=1&amp;y=2';
533
    $this->assertIdentical(check_url($url), $expected_html, 'check_url() filters a URL and encodes it for HTML.');
534
    $this->assertIdentical(drupal_strip_dangerous_protocols($url), $expected_plain, 'drupal_strip_dangerous_protocols() filters a URL and returns plain text.');
535
  }
536
}
537

    
538
/**
539
 * Tests file size parsing and formatting functions.
540
 */
541
class CommonSizeTestCase extends DrupalUnitTestCase {
542
  protected $exact_test_cases;
543
  protected $rounded_test_cases;
544

    
545
  public static function getInfo() {
546
    return array(
547
      'name' => 'Size parsing test',
548
      'description' => 'Parse a predefined amount of bytes and compare the output with the expected value.',
549
      'group' => 'System'
550
    );
551
  }
552

    
553
  function setUp() {
554
    $kb = DRUPAL_KILOBYTE;
555
    $this->exact_test_cases = array(
556
      '1 byte' => 1,
557
      '1 KB'   => $kb,
558
      '1 MB'   => $kb * $kb,
559
      '1 GB'   => $kb * $kb * $kb,
560
      '1 TB'   => $kb * $kb * $kb * $kb,
561
      '1 PB'   => $kb * $kb * $kb * $kb * $kb,
562
      '1 EB'   => $kb * $kb * $kb * $kb * $kb * $kb,
563
      '1 ZB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
564
      '1 YB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
565
    );
566
    $this->rounded_test_cases = array(
567
      '2 bytes' => 2,
568
      '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
569
      round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651, // megabytes
570
      round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
571
      round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
572
    );
573
    parent::setUp();
574
  }
575

    
576
  /**
577
   * Check that format_size() returns the expected string.
578
   */
579
  function testCommonFormatSize() {
580
    foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
581
      foreach ($test_cases as $expected => $input) {
582
        $this->assertEqual(
583
          ($result = format_size($input, NULL)),
584
          $expected,
585
          $expected . ' == ' . $result . ' (' . $input . ' bytes)'
586
        );
587
      }
588
    }
589
  }
590

    
591
  /**
592
   * Check that parse_size() returns the proper byte sizes.
593
   */
594
  function testCommonParseSize() {
595
    foreach ($this->exact_test_cases as $string => $size) {
596
      $this->assertEqual(
597
        $parsed_size = parse_size($string),
598
        $size,
599
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
600
      );
601
    }
602

    
603
    // Some custom parsing tests
604
    $string = '23476892 bytes';
605
    $this->assertEqual(
606
      ($parsed_size = parse_size($string)),
607
      $size = 23476892,
608
      $string . ' == ' . $parsed_size . ' bytes'
609
    );
610
    $string = '76MRandomStringThatShouldBeIgnoredByParseSize.'; // 76 MB
611
    $this->assertEqual(
612
      $parsed_size = parse_size($string),
613
      $size = 79691776,
614
      $string . ' == ' . $parsed_size . ' bytes'
615
    );
616
    $string = '76.24 Giggabyte'; // Misspeld text -> 76.24 GB
617
    $this->assertEqual(
618
      $parsed_size = parse_size($string),
619
      $size = 81862076662,
620
      $string . ' == ' . $parsed_size . ' bytes'
621
    );
622
  }
623

    
624
  /**
625
   * Cross-test parse_size() and format_size().
626
   */
627
  function testCommonParseSizeFormatSize() {
628
    foreach ($this->exact_test_cases as $size) {
629
      $this->assertEqual(
630
        $size,
631
        ($parsed_size = parse_size($string = format_size($size, NULL))),
632
        $size . ' == ' . $parsed_size . ' (' . $string . ')'
633
      );
634
    }
635
  }
636
}
637

    
638
/**
639
 * Test drupal_explode_tags() and drupal_implode_tags().
640
 */
641
class DrupalTagsHandlingTestCase extends DrupalUnitTestCase {
642
  var $validTags = array(
643
    'Drupal' => 'Drupal',
644
    'Drupal with some spaces' => 'Drupal with some spaces',
645
    '"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
646
    '"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
647
  );
648

    
649
  public static function getInfo() {
650
    return array(
651
      'name' => 'Drupal tags handling',
652
      'description' => "Performs tests on Drupal's handling of tags, both explosion and implosion tactics used.",
653
      'group' => 'System'
654
    );
655
  }
656

    
657
  /**
658
   * Explode a series of tags.
659
   */
660
  function testDrupalExplodeTags() {
661
    $string = implode(', ', array_keys($this->validTags));
662
    $tags = drupal_explode_tags($string);
663
    $this->assertTags($tags);
664
  }
665

    
666
  /**
667
   * Implode a series of tags.
668
   */
669
  function testDrupalImplodeTags() {
670
    $tags = array_values($this->validTags);
671
    // Let's explode and implode to our heart's content.
672
    for ($i = 0; $i < 10; $i++) {
673
      $string = drupal_implode_tags($tags);
674
      $tags = drupal_explode_tags($string);
675
    }
676
    $this->assertTags($tags);
677
  }
678

    
679
  /**
680
   * Helper function: asserts that the ending array of tags is what we wanted.
681
   */
682
  function assertTags($tags) {
683
    $original = $this->validTags;
684
    foreach ($tags as $tag) {
685
      $key = array_search($tag, $original);
686
      $this->assertTrue($key, format_string('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
687
      unset($original[$key]);
688
    }
689
    foreach ($original as $leftover) {
690
      $this->fail(format_string('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
691
    }
692
  }
693
}
694

    
695
/**
696
 * Test the Drupal CSS system.
697
 */
698
class CascadingStylesheetsTestCase extends DrupalWebTestCase {
699
  public static function getInfo() {
700
    return array(
701
      'name' => 'Cascading stylesheets',
702
      'description' => 'Tests adding various cascading stylesheets to the page.',
703
      'group' => 'System',
704
    );
705
  }
706

    
707
  function setUp() {
708
    parent::setUp('php', 'locale', 'common_test');
709
    // Reset drupal_add_css() before each test.
710
    drupal_static_reset('drupal_add_css');
711
  }
712

    
713
  /**
714
   * Check default stylesheets as empty.
715
   */
716
  function testDefault() {
717
    $this->assertEqual(array(), drupal_add_css(), 'Default CSS is empty.');
718
  }
719

    
720
  /**
721
   * Test that stylesheets in module .info files are loaded.
722
   */
723
  function testModuleInfo() {
724
    $this->drupalGet('');
725

    
726
    // Verify common_test.css in a STYLE media="all" tag.
727
    $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
728
      ':media' => 'all',
729
      ':filename' => 'tests/common_test.css',
730
    ));
731
    $this->assertTrue(count($elements), "Stylesheet with media 'all' in module .info file found.");
732

    
733
    // Verify common_test.print.css in a STYLE media="print" tag.
734
    $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
735
      ':media' => 'print',
736
      ':filename' => 'tests/common_test.print.css',
737
    ));
738
    $this->assertTrue(count($elements), "Stylesheet with media 'print' in module .info file found.");
739
  }
740

    
741
  /**
742
   * Tests adding a file stylesheet.
743
   */
744
  function testAddFile() {
745
    $path = drupal_get_path('module', 'simpletest') . '/simpletest.css';
746
    $css = drupal_add_css($path);
747
    $this->assertEqual($css[$path]['data'], $path, 'Adding a CSS file caches it properly.');
748
  }
749

    
750
  /**
751
   * Tests adding an external stylesheet.
752
   */
753
  function testAddExternal() {
754
    $path = 'http://example.com/style.css';
755
    $css = drupal_add_css($path, 'external');
756
    $this->assertEqual($css[$path]['type'], 'external', 'Adding an external CSS file caches it properly.');
757
  }
758

    
759
  /**
760
   * Makes sure that reseting the CSS empties the cache.
761
   */
762
  function testReset() {
763
    drupal_static_reset('drupal_add_css');
764
    $this->assertEqual(array(), drupal_add_css(), 'Resetting the CSS empties the cache.');
765
  }
766

    
767
  /**
768
   * Tests rendering the stylesheets.
769
   */
770
  function testRenderFile() {
771
    $css = drupal_get_path('module', 'simpletest') . '/simpletest.css';
772
    drupal_add_css($css);
773
    $styles = drupal_get_css();
774
    $this->assertTrue(strpos($styles, $css) > 0, 'Rendered CSS includes the added stylesheet.');
775
    // Verify that newlines are properly added inside style tags.
776
    $query_string = variable_get('css_js_query_string', '0');
777
    $css_processed = "<style type=\"text/css\" media=\"all\">\n@import url(\"" . check_plain(file_create_url($css)) . "?" . $query_string ."\");\n</style>";
778
    $this->assertEqual(trim($styles), $css_processed, 'Rendered CSS includes newlines inside style tags for JavaScript use.');
779
  }
780

    
781
  /**
782
   * Tests rendering an external stylesheet.
783
   */
784
  function testRenderExternal() {
785
    $css = 'http://example.com/style.css';
786
    drupal_add_css($css, 'external');
787
    $styles = drupal_get_css();
788
    // Stylesheet URL may be the href of a LINK tag or in an @import statement
789
    // of a STYLE tag.
790
    $this->assertTrue(strpos($styles, 'href="' . $css) > 0 || strpos($styles, '@import url("' . $css . '")') > 0, 'Rendering an external CSS file.');
791
  }
792

    
793
  /**
794
   * Tests rendering inline stylesheets with preprocessing on.
795
   */
796
  function testRenderInlinePreprocess() {
797
    $css = 'body { padding: 0px; }';
798
    $css_preprocessed = '<style type="text/css" media="all">' . "\n<!--/*--><![CDATA[/*><!--*/\n" . drupal_load_stylesheet_content($css, TRUE) . "\n/*]]>*/-->\n" . '</style>';
799
    drupal_add_css($css, array('type' => 'inline'));
800
    $styles = drupal_get_css();
801
    $this->assertEqual(trim($styles), $css_preprocessed, 'Rendering preprocessed inline CSS adds it to the page.');
802
  }
803

    
804
  /**
805
   * Tests removing charset when rendering stylesheets with preprocessing on.
806
   */
807
  function testRenderRemoveCharsetPreprocess() {
808
    $cases = array(
809
      array(
810
        'asset' => '@charset "UTF-8";html{font-family:"sans-serif";}',
811
        'expected' => 'html{font-family:"sans-serif";}',
812
      ),
813
      // This asset contains extra \n character.
814
      array(
815
        'asset' => "@charset 'UTF-8';\nhtml{font-family:'sans-serif';}",
816
        'expected' => "\nhtml{font-family:'sans-serif';}",
817
      ),
818
    );
819

    
820
    foreach ($cases as $case) {
821
      $this->assertEqual(
822
        $case['expected'],
823
        drupal_load_stylesheet_content($case['asset']),
824
        'CSS optimizing correctly removes the charset declaration.'
825
      );
826
    }
827
  }
828

    
829
  /**
830
   * Tests rendering inline stylesheets with preprocessing off.
831
   */
832
  function testRenderInlineNoPreprocess() {
833
    $css = 'body { padding: 0px; }';
834
    drupal_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
835
    $styles = drupal_get_css();
836
    $this->assertTrue(strpos($styles, $css) > 0, 'Rendering non-preprocessed inline CSS adds it to the page.');
837
  }
838

    
839
  /**
840
   * Tests rendering inline stylesheets through a full page request.
841
   */
842
  function testRenderInlineFullPage() {
843
    $css = 'body { font-size: 254px; }';
844
    // Inline CSS is minified unless 'preprocess' => FALSE is passed as a
845
    // drupal_add_css() option.
846
    $expected = 'body{font-size:254px;}';
847

    
848
    // Create a node, using the PHP filter that tests drupal_add_css().
849
    $php_format_id = 'php_code';
850
    $settings = array(
851
      'type' => 'page',
852
      'body' => array(
853
        LANGUAGE_NONE => array(
854
          array(
855
            'value' => t('This tests the inline CSS!') . "<?php drupal_add_css('$css', 'inline'); ?>",
856
            'format' => $php_format_id,
857
          ),
858
        ),
859
      ),
860
      'promote' => 1,
861
    );
862
    $node = $this->drupalCreateNode($settings);
863

    
864
    // Fetch the page.
865
    $this->drupalGet('node/' . $node->nid);
866
    $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
867
  }
868

    
869
  /**
870
   * Test CSS ordering.
871
   */
872
  function testRenderOrder() {
873
    // A module CSS file.
874
    drupal_add_css(drupal_get_path('module', 'simpletest') . '/simpletest.css');
875
    // A few system CSS files, ordered in a strange way.
876
    $system_path = drupal_get_path('module', 'system');
877
    drupal_add_css($system_path . '/system.menus.css', array('group' => CSS_SYSTEM));
878
    drupal_add_css($system_path . '/system.base.css', array('group' => CSS_SYSTEM, 'weight' => -10));
879
    drupal_add_css($system_path . '/system.theme.css', array('group' => CSS_SYSTEM));
880

    
881
    $expected = array(
882
      $system_path . '/system.base.css',
883
      $system_path . '/system.menus.css',
884
      $system_path . '/system.theme.css',
885
      drupal_get_path('module', 'simpletest') . '/simpletest.css',
886
    );
887

    
888

    
889
    $styles = drupal_get_css();
890
    // Stylesheet URL may be the href of a LINK tag or in an @import statement
891
    // of a STYLE tag.
892
    if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
893
      $result = $matches[2];
894
    }
895
    else {
896
      $result = array();
897
    }
898

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

    
902
  /**
903
   * Test CSS override.
904
   */
905
  function testRenderOverride() {
906
    $system = drupal_get_path('module', 'system');
907
    $simpletest = drupal_get_path('module', 'simpletest');
908

    
909
    drupal_add_css($system . '/system.base.css');
910
    drupal_add_css($simpletest . '/tests/system.base.css');
911

    
912
    // The dummy stylesheet should be the only one included.
913
    $styles = drupal_get_css();
914
    $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') !== FALSE, 'The overriding CSS file is output.');
915
    $this->assert(strpos($styles, $system . '/system.base.css') === FALSE, 'The overridden CSS file is not output.');
916

    
917
    drupal_add_css($simpletest . '/tests/system.base.css');
918
    drupal_add_css($system . '/system.base.css');
919

    
920
    // The standard stylesheet should be the only one included.
921
    $styles = drupal_get_css();
922
    $this->assert(strpos($styles, $system . '/system.base.css') !== FALSE, 'The overriding CSS file is output.');
923
    $this->assert(strpos($styles, $simpletest . '/tests/system.base.css') === FALSE, 'The overridden CSS file is not output.');
924
  }
925

    
926
  /**
927
   * Tests Locale module's CSS Alter to include RTL overrides.
928
   */
929
  function testAlter() {
930
    // Switch the language to a right to left language and add system.base.css.
931
    global $language;
932
    $language->direction = LANGUAGE_RTL;
933
    $path = drupal_get_path('module', 'system');
934
    drupal_add_css($path . '/system.base.css');
935

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

    
940
    // Change the language back to left to right.
941
    $language->direction = LANGUAGE_LTR;
942
  }
943

    
944
  /**
945
   * Tests that the query string remains intact when adding CSS files that have
946
   * query string parameters.
947
   */
948
  function testAddCssFileWithQueryString() {
949
    $this->drupalGet('common-test/query-string');
950
    $query_string = variable_get('css_js_query_string', '0');
951
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.css?' . $query_string, 'Query string was appended correctly to css.');
952
    $this->assertRaw(drupal_get_path('module', 'node') . '/node-fake.css?arg1=value1&amp;arg2=value2', 'Query string not escaped on a URI.');
953
  }
954
}
955

    
956
/**
957
 * Test for cleaning HTML identifiers.
958
 */
959
class DrupalHTMLIdentifierTestCase extends DrupalUnitTestCase {
960
  public static function getInfo() {
961
    return array(
962
      'name' => 'HTML identifiers',
963
      'description' => 'Test the functions drupal_html_class(), drupal_html_id() and drupal_clean_css_identifier() for expected behavior',
964
      'group' => 'System',
965
    );
966
  }
967

    
968
  /**
969
   * Tests that drupal_clean_css_identifier() cleans the identifier properly.
970
   */
971
  function testDrupalCleanCSSIdentifier() {
972
    // Verify that no valid ASCII characters are stripped from the identifier.
973
    $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
974
    $this->assertIdentical(drupal_clean_css_identifier($identifier, array()), $identifier, 'Verify valid ASCII characters pass through.');
975

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

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

    
983
    // Verify that double underscores are replaced in the identifier by default.
984
    $identifier = 'css__identifier__with__double__underscores';
985
    $expected = 'css--identifier--with--double--underscores';
986
    $this->assertIdentical(drupal_clean_css_identifier($identifier), $expected, 'Verify double underscores are replaced with double hyphens by default.');
987

    
988
    // Verify that double underscores are preserved in the identifier if the
989
    // variable allow_css_double_underscores is set to TRUE.
990
    $this->setAllowCSSDoubleUnderscores(TRUE);
991
    $this->assertIdentical(drupal_clean_css_identifier($identifier), $identifier, 'Verify double underscores are preserved if the allow_css_double_underscores set to TRUE.');
992

    
993
    // To avoid affecting other test cases, set the variable
994
    // allow_css_double_underscores to FALSE which is the default value.
995
    $this->setAllowCSSDoubleUnderscores(FALSE);
996
  }
997

    
998
  /**
999
   * Set the variable allow_css_double_underscores and reset the cache.
1000
   *
1001
   * @param $value bool
1002
   *   A new value to be set to allow_css_double_underscores.
1003
   */
1004
  function setAllowCSSDoubleUnderscores($value) {
1005
    $GLOBALS['conf']['allow_css_double_underscores'] = $value;
1006
    drupal_static_reset('drupal_clean_css_identifier:allow_css_double_underscores');
1007
  }
1008

    
1009
  /**
1010
   * Tests that drupal_html_class() cleans the class name properly.
1011
   */
1012
  function testDrupalHTMLClass() {
1013
    // Verify Drupal coding standards are enforced.
1014
    $this->assertIdentical(drupal_html_class('CLASS NAME_[Ü]'), 'class-name--ü', 'Enforce Drupal coding standards.');
1015
  }
1016

    
1017
  /**
1018
   * Tests that drupal_html_id() cleans the ID properly.
1019
   */
1020
  function testDrupalHTMLId() {
1021
    // Verify that letters, digits, and hyphens are not stripped from the ID.
1022
    $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
1023
    $this->assertIdentical(drupal_html_id($id), $id, 'Verify valid characters pass through.');
1024

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

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

    
1031
    // Reset the static cache so we can ensure the unique id count is at zero.
1032
    drupal_static_reset('drupal_html_id');
1033

    
1034
    // Clean up IDs with invalid starting characters.
1035
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id', 'Test the uniqueness of IDs #1.');
1036
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--2', 'Test the uniqueness of IDs #2.');
1037
    $this->assertIdentical(drupal_html_id('test-unique-id'), 'test-unique-id--3', 'Test the uniqueness of IDs #3.');
1038
  }
1039
}
1040

    
1041
/**
1042
 * CSS Unit Tests.
1043
 */
1044
class CascadingStylesheetsUnitTest extends DrupalUnitTestCase {
1045
  public static function getInfo() {
1046
    return array(
1047
      'name' => 'CSS Unit Tests',
1048
      'description' => 'Unit tests on CSS functions like aggregation.',
1049
      'group' => 'System',
1050
    );
1051
  }
1052

    
1053
  /**
1054
   * Tests basic CSS loading with and without optimization via drupal_load_stylesheet().
1055
   *
1056
   * Known tests:
1057
   * - Retain white-space in selectors. (https://drupal.org/node/472820)
1058
   * - Proper URLs in imported files. (https://drupal.org/node/265719)
1059
   * - Retain pseudo-selectors. (https://drupal.org/node/460448)
1060
   * - Don't adjust data URIs. (https://drupal.org/node/2142441)
1061
   * - Files imported from external URLs. (https://drupal.org/node/2014851)
1062
   */
1063
  function testLoadCssBasic() {
1064
    // Array of files to test living in 'simpletest/files/css_test_files/'.
1065
    // - Original: name.css
1066
    // - Unoptimized expected content: name.css.unoptimized.css
1067
    // - Optimized expected content: name.css.optimized.css
1068
    $testfiles = array(
1069
      'css_input_without_import.css',
1070
      'css_input_with_import.css',
1071
      'css_subfolder/css_input_with_import.css',
1072
      'comment_hacks.css'
1073
    );
1074
    $path = drupal_get_path('module', 'simpletest') . '/files/css_test_files';
1075
    foreach ($testfiles as $file) {
1076
      $file_path = $path . '/' . $file;
1077
      $file_url = $GLOBALS['base_url'] . '/' . $file_path;
1078

    
1079
      $expected = file_get_contents($file_path . '.unoptimized.css');
1080
      $unoptimized_output = drupal_load_stylesheet($file_path, FALSE);
1081
      $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
1082

    
1083
      $expected = file_get_contents($file_path . '.optimized.css');
1084
      $optimized_output = drupal_load_stylesheet($file_path, TRUE);
1085
      $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
1086

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

    
1092
      $expected = file_get_contents($file_path . '.optimized.css');
1093
      $optimized_output_url = drupal_load_stylesheet($file_url, TRUE);
1094
      $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
1095
    }
1096
  }
1097
}
1098

    
1099
/**
1100
 * Test drupal_http_request().
1101
 */
1102
class DrupalHTTPRequestTestCase extends DrupalWebTestCase {
1103
  public static function getInfo() {
1104
    return array(
1105
      'name' => 'Drupal HTTP request',
1106
      'description' => "Performs tests on Drupal's HTTP request mechanism.",
1107
      'group' => 'System'
1108
    );
1109
  }
1110

    
1111
  function setUp() {
1112
    parent::setUp('system_test', 'locale');
1113
  }
1114

    
1115
  function testDrupalHTTPRequest() {
1116
    global $is_https;
1117

    
1118
    // Parse URL schema.
1119
    $missing_scheme = drupal_http_request('example.com/path');
1120
    $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
1121
    $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
1122

    
1123
    $unable_to_parse = drupal_http_request('http:///path');
1124
    $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
1125
    $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
1126

    
1127
    // Fetch page and check that the data parameter works with both array and string.
1128
    $data_array = array($this->randomName() => $this->randomString() . ' "\'');
1129
    $data_string = drupal_http_build_query($data_array);
1130
    $result = drupal_http_request(url('node', array('absolute' => TRUE)), array('data' => $data_array));
1131
    $this->assertEqual($result->code, 200, 'Fetched page successfully.');
1132
    $this->assertTrue(substr($result->request, -strlen($data_string)) === $data_string, 'Request ends with URL-encoded data when drupal_http_request() called using array.');
1133
    $result = drupal_http_request(url('node', array('absolute' => TRUE)), array('data' => $data_string));
1134
    $this->assertTrue(substr($result->request, -strlen($data_string)) === $data_string, 'Request ends with URL-encoded data when drupal_http_request() called using string.');
1135

    
1136
    $this->drupalSetContent($result->data);
1137
    $this->assertTitle(t('Welcome to @site-name | @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), 'Site title matches.');
1138

    
1139
    // Test that code and status message is returned.
1140
    $result = drupal_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
1141
    $this->assertTrue(!empty($result->protocol),  'Result protocol is returned.');
1142
    $this->assertEqual($result->code, '404', 'Result code is 404');
1143
    $this->assertEqual($result->status_message, 'Not Found', 'Result status message is "Not Found"');
1144

    
1145
    // Skip the timeout tests when the testing environment is HTTPS because
1146
    // stream_set_timeout() does not work for SSL connections.
1147
    // @link http://bugs.php.net/bug.php?id=47929
1148
    if (!$is_https) {
1149
      // Test that timeout is respected. The test machine is expected to be able
1150
      // to make the connection (i.e. complete the fsockopen()) in 2 seconds and
1151
      // return within a total of 5 seconds. If the test machine is extremely
1152
      // slow, the test will fail. fsockopen() has been seen to time out in
1153
      // slightly less than the specified timeout, so allow a little slack on
1154
      // the minimum expected time (i.e. 1.8 instead of 2).
1155
      timer_start(__METHOD__);
1156
      $result = drupal_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
1157
      $time = timer_read(__METHOD__) / 1000;
1158
      $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
1159
      $this->assertTrue($result->error, 'An error message was returned.');
1160
      $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
1161
    }
1162
  }
1163

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

    
1169
    $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
1170
    $result = drupal_http_request($auth);
1171

    
1172
    $this->drupalSetContent($result->data);
1173
    $this->assertRaw($username, 'Username is passed correctly.');
1174
    $this->assertRaw($password, 'Password is passed correctly.');
1175
  }
1176

    
1177
  function testDrupalHTTPRequestRedirect() {
1178
    $redirect_301 = drupal_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
1179
    $this->assertEqual($redirect_301->redirect_code, 301, 'drupal_http_request follows the 301 redirect.');
1180

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

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

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

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

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

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

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

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

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

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

    
1216
  /**
1217
   * Tests Content-language headers generated by Drupal.
1218
   */
1219
  function testDrupalHTTPRequestHeaders() {
1220
    // Check the default header.
1221
    $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1222
    $this->assertEqual($request->headers['content-language'], 'en', 'Content-Language HTTP header is English.');
1223

    
1224
    // Add German language and set as default.
1225
    locale_add_language('de', 'German', 'Deutsch', LANGUAGE_LTR, '', '', TRUE, TRUE);
1226

    
1227
    // Request front page and check for matching Content-Language.
1228
    $request = drupal_http_request(url('<front>', array('absolute' => TRUE)));
1229
    $this->assertEqual($request->headers['content-language'], 'de', 'Content-Language HTTP header is German.');
1230
  }
1231
}
1232

    
1233
/**
1234
 * Tests parsing of the HTTP response status line.
1235
 */
1236
class DrupalHTTPResponseStatusLineTest extends DrupalUnitTestCase {
1237
  public static function getInfo() {
1238
    return array(
1239
      'name' => 'Drupal HTTP request response status parsing',
1240
      'description' => 'Perform unit tests on _drupal_parse_response_status().',
1241
      'group' => 'System',
1242
    );
1243
  }
1244

    
1245
  /**
1246
   * Tests parsing HTTP response status line.
1247
   */
1248
  public function testStatusLine() {
1249
    // Grab the big array of test data from statusLineData().
1250
    $data = $this->statusLineData();
1251
    foreach($data as $test_case) {
1252
      $test_data = array_shift($test_case);
1253
      $expected = array_shift($test_case);
1254

    
1255
      $outcome = _drupal_parse_response_status($test_data);
1256

    
1257
      foreach(array_keys($expected) as $key) {
1258
        $this->assertIdentical($outcome[$key], $expected[$key]);
1259
      }
1260
    }
1261
  }
1262

    
1263
  /**
1264
   * Data provider for testStatusLine().
1265
   *
1266
   * @return array
1267
   *   Test data.
1268
   */
1269
  protected function statusLineData() {
1270
    return array(
1271
      array(
1272
        'HTTP/1.1 200 OK',
1273
        array(
1274
          'http_version' => 'HTTP/1.1',
1275
          'response_code' => '200',
1276
          'reason_phrase' => 'OK',
1277
        ),
1278
      ),
1279
      // Data set with no reason phrase.
1280
      array(
1281
        'HTTP/1.1 200',
1282
        array(
1283
          'http_version' => 'HTTP/1.1',
1284
          'response_code' => '200',
1285
          'reason_phrase' => '',
1286
        ),
1287
      ),
1288
      // Arbitrary strings.
1289
      array(
1290
        'version code multi word explanation',
1291
        array(
1292
          'http_version' => 'version',
1293
          'response_code' => 'code',
1294
          'reason_phrase' => 'multi word explanation',
1295
        ),
1296
      ),
1297
    );
1298
  }
1299
}
1300

    
1301
/**
1302
 * Testing drupal_add_region_content and drupal_get_region_content.
1303
 */
1304
class DrupalSetContentTestCase extends DrupalWebTestCase {
1305
  public static function getInfo() {
1306
    return array(
1307
      'name' => 'Drupal set/get regions',
1308
      'description' => 'Performs tests on setting and retrieiving content from theme regions.',
1309
      'group' => 'System'
1310
    );
1311
  }
1312

    
1313

    
1314
  /**
1315
   * Test setting and retrieving content for theme regions.
1316
   */
1317
  function testRegions() {
1318
    global $theme_key;
1319

    
1320
    $block_regions = system_region_list($theme_key, REGIONS_ALL, FALSE);
1321
    $delimiter = $this->randomName(32);
1322
    $values = array();
1323
    // Set some random content for each region available.
1324
    foreach ($block_regions as $region) {
1325
      $first_chunk = $this->randomName(32);
1326
      drupal_add_region_content($region, $first_chunk);
1327
      $second_chunk = $this->randomName(32);
1328
      drupal_add_region_content($region, $second_chunk);
1329
      // Store the expected result for a drupal_get_region_content call for this region.
1330
      $values[$region] = $first_chunk . $delimiter . $second_chunk;
1331
    }
1332

    
1333
    // Ensure drupal_get_region_content returns expected results when fetching all regions.
1334
    $content = drupal_get_region_content(NULL, $delimiter);
1335
    foreach ($content as $region => $region_content) {
1336
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching all regions', array('@region' => $region)));
1337
    }
1338

    
1339
    // Ensure drupal_get_region_content returns expected results when fetching a single region.
1340
    foreach ($block_regions as $region) {
1341
      $region_content = drupal_get_region_content($region, $delimiter);
1342
      $this->assertEqual($region_content, $values[$region], format_string('@region region text verified when fetching single region.', array('@region' => $region)));
1343
    }
1344
  }
1345
}
1346

    
1347
/**
1348
 * Testing drupal_goto and hook_drupal_goto_alter().
1349
 */
1350
class DrupalGotoTest extends DrupalWebTestCase {
1351
  public static function getInfo() {
1352
    return array(
1353
      'name' => 'Drupal goto',
1354
      'description' => 'Performs tests on the drupal_goto function and hook_drupal_goto_alter',
1355
      'group' => 'System'
1356
    );
1357
  }
1358

    
1359
  function setUp() {
1360
    parent::setUp('common_test');
1361
  }
1362

    
1363
  /**
1364
   * Test drupal_goto().
1365
   */
1366
  function testDrupalGoto() {
1367
    $this->drupalGet('common-test/drupal_goto/redirect');
1368
    $headers = $this->drupalGetHeaders(TRUE);
1369
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1370
    $this->assertEqual($status, 302, 'Expected response code was sent.');
1371
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1372
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1373

    
1374
    $this->drupalGet('common-test/drupal_goto/redirect_advanced');
1375
    $headers = $this->drupalGetHeaders(TRUE);
1376
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1377
    $this->assertEqual($status, 301, 'Expected response code was sent.');
1378
    $this->assertText('drupal_goto', 'Drupal goto redirect succeeded.');
1379
    $this->assertEqual($this->getUrl(), url('common-test/drupal_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Drupal goto redirected to expected URL.');
1380

    
1381
    // Test that calling drupal_goto() on the current path is not dangerous.
1382
    variable_set('common_test_redirect_current_path', TRUE);
1383
    $this->drupalGet('', array('query' => array('q' => 'http://www.example.com/')));
1384
    $headers = $this->drupalGetHeaders(TRUE);
1385
    list(, $status) = explode(' ', $headers[0][':status'], 3);
1386
    $this->assertEqual($status, 302, 'Expected response code was sent.');
1387
    $this->assertNotEqual($this->getUrl(), 'http://www.example.com/', 'Drupal goto did not redirect to external URL.');
1388
    $this->assertTrue(strpos($this->getUrl(), url('<front>', array('absolute' => TRUE))) === 0, 'Drupal redirected to itself.');
1389
    variable_del('common_test_redirect_current_path');
1390
    // Test that drupal_goto() respects ?destination=xxx. Use an complicated URL
1391
    // to test that the path is encoded and decoded properly.
1392
    $destination = 'common-test/drupal_goto/destination?foo=%2525&bar=123';
1393
    $this->drupalGet('common-test/drupal_goto/redirect', array('query' => array('destination' => $destination)));
1394
    $this->assertText('drupal_goto', 'Drupal goto redirect with destination succeeded.');
1395
    $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.');
1396
  }
1397

    
1398
  /**
1399
   * Test hook_drupal_goto_alter().
1400
   */
1401
  function testDrupalGotoAlter() {
1402
    $this->drupalGet('common-test/drupal_goto/redirect_fail');
1403

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

    
1408
  /**
1409
   * Test drupal_get_destination().
1410
   */
1411
  function testDrupalGetDestination() {
1412
    $query = $this->randomName(10);
1413

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

    
1418
    // Verify that the current path is used as destination.
1419
    $this->drupalGet('common-test/destination', array('query' => array($query => NULL)));
1420
    $url = 'common-test/destination?' . $query;
1421
    $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
1422
  }
1423
}
1424

    
1425
/**
1426
 * Tests for the JavaScript system.
1427
 */
1428
class JavaScriptTestCase extends DrupalWebTestCase {
1429
  /**
1430
   * Store configured value for JavaScript preprocessing.
1431
   */
1432
  protected $preprocess_js = NULL;
1433

    
1434
  public static function getInfo() {
1435
    return array(
1436
      'name' => 'JavaScript',
1437
      'description' => 'Tests the JavaScript system.',
1438
      'group' => 'System'
1439
    );
1440
  }
1441

    
1442
  function setUp() {
1443
    // Enable Locale and SimpleTest in the test environment.
1444
    parent::setUp('locale', 'simpletest', 'common_test');
1445

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

    
1450
    // Reset drupal_add_js() and drupal_add_library() statics before each test.
1451
    drupal_static_reset('drupal_add_js');
1452
    drupal_static_reset('drupal_add_library');
1453
  }
1454

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

    
1461
  /**
1462
   * Test default JavaScript is empty.
1463
   */
1464
  function testDefault() {
1465
    $this->assertEqual(array(), drupal_add_js(), 'Default JavaScript is empty.');
1466
  }
1467

    
1468
  /**
1469
   * Test adding a JavaScript file.
1470
   */
1471
  function testAddFile() {
1472
    $javascript = drupal_add_js('misc/collapse.js');
1473
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
1474
    $this->assertTrue(array_key_exists('misc/drupal.js', $javascript), 'Drupal.js is added when file is added.');
1475
    $this->assertTrue(array_key_exists('misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
1476
    $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
1477
    url('', array('prefix' => &$prefix));
1478
    $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
1479
  }
1480

    
1481
  /**
1482
   * Test adding settings.
1483
   */
1484
  function testAddSetting() {
1485
    $javascript = drupal_add_js(array('drupal' => 'rocks', 'dries' => 280342800), 'setting');
1486
    $this->assertEqual(280342800, $javascript['settings']['data'][2]['dries'], 'JavaScript setting is set correctly.');
1487
    $this->assertEqual('rocks', $javascript['settings']['data'][2]['drupal'], 'The other JavaScript setting is set correctly.');
1488
  }
1489

    
1490
  /**
1491
   * Tests adding an external JavaScript File.
1492
   */
1493
  function testAddExternal() {
1494
    $path = 'http://example.com/script.js';
1495
    $javascript = drupal_add_js($path, 'external');
1496
    $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
1497
  }
1498

    
1499
  /**
1500
   * Test drupal_get_js() for JavaScript settings.
1501
   */
1502
  function testHeaderSetting() {
1503
    // Only the second of these two entries should appear in Drupal.settings.
1504
    drupal_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
1505
    drupal_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
1506
    // All three of these entries should appear in Drupal.settings.
1507
    drupal_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
1508
    drupal_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
1509
    drupal_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
1510
    // Only the second of these two entries should appear in Drupal.settings.
1511
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
1512
    drupal_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
1513

    
1514
    $javascript = drupal_get_js('header');
1515
    $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
1516
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
1517
    $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
1518

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

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

    
1528
    // Test whether drupal_add_js can be used to override the entry for an
1529
    // existing key in an associative array.
1530
    $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
1531
    $this->assertTrue($associative_array_override, 'drupal_add_js() correctly overrides settings within an associative array.');
1532
  }
1533

    
1534
  /**
1535
   * Test to see if resetting the JavaScript empties the cache.
1536
   */
1537
  function testReset() {
1538
    drupal_add_js('misc/collapse.js');
1539
    drupal_static_reset('drupal_add_js');
1540
    $this->assertEqual(array(), drupal_add_js(), 'Resetting the JavaScript correctly empties the cache.');
1541
  }
1542

    
1543
  /**
1544
   * Test adding inline scripts.
1545
   */
1546
  function testAddInline() {
1547
    $inline = 'jQuery(function () { });';
1548
    $javascript = drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1549
    $this->assertTrue(array_key_exists('misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
1550
    $data = end($javascript);
1551
    $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
1552
  }
1553

    
1554
  /**
1555
   * Test rendering an external JavaScript file.
1556
   */
1557
  function testRenderExternal() {
1558
    $external = 'http://example.com/example.js';
1559
    drupal_add_js($external, 'external');
1560
    $javascript = drupal_get_js();
1561
    // Local files have a base_path() prefix, external files should not.
1562
    $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
1563
  }
1564

    
1565
  /**
1566
   * Test drupal_get_js() with a footer scope.
1567
   */
1568
  function testFooterHTML() {
1569
    $inline = 'jQuery(function () { });';
1570
    drupal_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
1571
    $javascript = drupal_get_js('footer');
1572
    $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
1573
  }
1574

    
1575
  /**
1576
   * Test the 'javascript_always_use_jquery' variable.
1577
   */
1578
  function testJavaScriptAlwaysUseJQuery() {
1579
    // The default front page of the site should use jQuery and other standard
1580
    // scripts and settings.
1581
    $this->drupalGet('');
1582
    $this->assertRaw('misc/jquery.js', 'Default behavior: The front page of the site includes jquery.js.');
1583
    $this->assertRaw('misc/drupal.js', 'Default behavior: The front page of the site includes drupal.js.');
1584
    $this->assertRaw('Drupal.settings', 'Default behavior: The front page of the site includes Drupal settings.');
1585
    $this->assertRaw('basePath', 'Default behavior: The front page of the site includes the basePath Drupal setting.');
1586

    
1587
    // The default front page should not use jQuery and other standard scripts
1588
    // and settings when the 'javascript_always_use_jquery' variable is set to
1589
    // FALSE.
1590
    variable_set('javascript_always_use_jquery', FALSE);
1591
    $this->drupalGet('');
1592
    $this->assertNoRaw('misc/jquery.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include jquery.js.');
1593
    $this->assertNoRaw('misc/drupal.js', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include drupal.js.');
1594
    $this->assertNoRaw('Drupal.settings', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include Drupal settings.');
1595
    $this->assertNoRaw('basePath', 'When "javascript_always_use_jquery" is FALSE: The front page of the site does not include the basePath Drupal setting.');
1596
    variable_del('javascript_always_use_jquery');
1597

    
1598
    // When only settings have been added via drupal_add_js(), drupal_get_js()
1599
    // should still return jQuery and other standard scripts and settings.
1600
    $this->resetStaticVariables();
1601
    drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
1602
    $javascript = drupal_get_js();
1603
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes jquery.js.');
1604
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes drupal.js.');
1605
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes Drupal.settings.');
1606
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the basePath Drupal setting.');
1607
    $this->assertTrue(strpos($javascript, 'testJavaScriptSetting') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when only settings have been added includes the added Drupal settings.');
1608

    
1609
    // When only settings have been added via drupal_add_js() and the
1610
    // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
1611
    // should not return jQuery and other standard scripts and settings, nor
1612
    // should it return the requested settings (since they cannot actually be
1613
    // addded to the page without jQuery).
1614
    $this->resetStaticVariables();
1615
    variable_set('javascript_always_use_jquery', FALSE);
1616
    drupal_add_js(array('testJavaScriptSetting' => 'test'), 'setting');
1617
    $javascript = drupal_get_js();
1618
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include jquery.js.');
1619
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include drupal.js.');
1620
    $this->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include Drupal.settings.');
1621
    $this->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the basePath Drupal setting.');
1622
    $this->assertTrue(strpos($javascript, 'testJavaScriptSetting') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when only settings have been added does not include the added Drupal settings.');
1623
    variable_del('javascript_always_use_jquery');
1624

    
1625
    // When a regular file has been added via drupal_add_js(), drupal_get_js()
1626
    // should return jQuery and other standard scripts and settings.
1627
    $this->resetStaticVariables();
1628
    drupal_add_js('misc/collapse.js');
1629
    $javascript = drupal_get_js();
1630
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
1631
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
1632
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
1633
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
1634
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
1635

    
1636
    // When a regular file has been added via drupal_add_js() and the
1637
    // 'javascript_always_use_jquery' variable is set to FALSE, drupal_get_js()
1638
    // should still return jQuery and other standard scripts and settings
1639
    // (since the file is assumed to require jQuery by default).
1640
    $this->resetStaticVariables();
1641
    variable_set('javascript_always_use_jquery', FALSE);
1642
    drupal_add_js('misc/collapse.js');
1643
    $javascript = drupal_get_js();
1644
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes jquery.js.');
1645
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes drupal.js.');
1646
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes Drupal.settings.');
1647
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the basePath Drupal setting.');
1648
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file has been added includes the custom file.');
1649
    variable_del('javascript_always_use_jquery');
1650

    
1651
    // When a file that does not require jQuery has been added via
1652
    // drupal_add_js(), drupal_get_js() should still return jQuery and other
1653
    // standard scripts and settings by default.
1654
    $this->resetStaticVariables();
1655
    drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
1656
    $javascript = drupal_get_js();
1657
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes jquery.js.');
1658
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes drupal.js.');
1659
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes Drupal.settings.');
1660
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the basePath Drupal setting.');
1661
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'Default behavior: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
1662

    
1663
    // When a file that does not require jQuery has been added via
1664
    // drupal_add_js() and the 'javascript_always_use_jquery' variable is set
1665
    // to FALSE, drupal_get_js() should not return jQuery and other standard
1666
    // scripts and setting, but it should still return the requested file.
1667
    $this->resetStaticVariables();
1668
    variable_set('javascript_always_use_jquery', FALSE);
1669
    drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
1670
    $javascript = drupal_get_js();
1671
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include jquery.js.');
1672
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include drupal.js.');
1673
    $this->assertTrue(strpos($javascript, 'Drupal.settings') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include Drupal.settings.');
1674
    $this->assertTrue(strpos($javascript, 'basePath') === FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added does not include the basePath Drupal setting.');
1675
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when a custom JavaScript file that does not require jQuery has been added includes the custom file.');
1676
    variable_del('javascript_always_use_jquery');
1677

    
1678
    // When 'javascript_always_use_jquery' is set to FALSE and a file that does
1679
    // not require jQuery is added, followed by one that does, drupal_get_js()
1680
    // should return jQuery and other standard scripts and settings, in
1681
    // addition to both of the requested files.
1682
    $this->resetStaticVariables();
1683
    variable_set('javascript_always_use_jquery', FALSE);
1684
    drupal_add_js('misc/collapse.js', array('requires_jquery' => FALSE));
1685
    drupal_add_js('misc/ajax.js');
1686
    $javascript = drupal_get_js();
1687
    $this->assertTrue(strpos($javascript, 'misc/jquery.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes jquery.js.');
1688
    $this->assertTrue(strpos($javascript, 'misc/drupal.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes drupal.js.');
1689
    $this->assertTrue(strpos($javascript, 'Drupal.settings') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes Drupal.settings.');
1690
    $this->assertTrue(strpos($javascript, 'basePath') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the basePath Drupal setting.');
1691
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the first custom file.');
1692
    $this->assertTrue(strpos($javascript, 'misc/ajax.js') !== FALSE, 'When "javascript_always_use_jquery" is FALSE: The JavaScript returned by drupal_get_js() when at least one custom JavaScript file that requires jQuery has been added includes the second custom file.');
1693
    variable_del('javascript_always_use_jquery');
1694
  }
1695

    
1696
  /**
1697
   * Test drupal_add_js() sets preproccess to false when cache is set to false.
1698
   */
1699
  function testNoCache() {
1700
    $javascript = drupal_add_js('misc/collapse.js', array('cache' => FALSE));
1701
    $this->assertFalse($javascript['misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets proprocess to FALSE when adding JavaScript.');
1702
  }
1703

    
1704
  /**
1705
   * Test adding a JavaScript file with a different group.
1706
   */
1707
  function testDifferentGroup() {
1708
    $javascript = drupal_add_js('misc/collapse.js', array('group' => JS_THEME));
1709
    $this->assertEqual($javascript['misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
1710
  }
1711

    
1712
  /**
1713
   * Test adding a JavaScript file with a different weight.
1714
   */
1715
  function testDifferentWeight() {
1716
    $javascript = drupal_add_js('misc/collapse.js', array('weight' => 2));
1717
    $this->assertEqual($javascript['misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
1718
  }
1719

    
1720
  /**
1721
   * Tests JavaScript aggregation when files are added to a different scope.
1722
   */
1723
  function testAggregationOrder() {
1724
    // Enable JavaScript aggregation.
1725
    variable_set('preprocess_js', 1);
1726
    drupal_static_reset('drupal_add_js');
1727

    
1728
    // Add two JavaScript files to the current request and build the cache.
1729
    drupal_add_js('misc/ajax.js');
1730
    drupal_add_js('misc/autocomplete.js');
1731

    
1732
    $js_items = drupal_add_js();
1733
    drupal_build_js_cache(array(
1734
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1735
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1736
    ));
1737

    
1738
    // Store the expected key for the first item in the cache.
1739
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1740
    $expected_key = $cache[0];
1741

    
1742
    // Reset variables and add a file in a different scope first.
1743
    variable_del('drupal_js_cache_files');
1744
    drupal_static_reset('drupal_add_js');
1745
    drupal_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
1746
    drupal_add_js('misc/ajax.js');
1747
    drupal_add_js('misc/autocomplete.js');
1748

    
1749
    // Rebuild the cache.
1750
    $js_items = drupal_add_js();
1751
    drupal_build_js_cache(array(
1752
      'misc/ajax.js' => $js_items['misc/ajax.js'],
1753
      'misc/autocomplete.js' => $js_items['misc/autocomplete.js']
1754
    ));
1755

    
1756
    // Compare the expected key for the first file to the current one.
1757
    $cache = array_keys(variable_get('drupal_js_cache_files', array()));
1758
    $key = $cache[0];
1759
    $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
1760
  }
1761

    
1762
  /**
1763
   * Test JavaScript ordering.
1764
   */
1765
  function testRenderOrder() {
1766
    // Add a bunch of JavaScript in strange ordering.
1767
    drupal_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1768
    drupal_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1769
    drupal_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1770
    drupal_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1771
    drupal_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1772
    drupal_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1773
    drupal_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
1774
    drupal_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
1775
    drupal_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
1776
    drupal_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
1777

    
1778
    // Construct the expected result from the regex.
1779
    $expected = array(
1780
      "-8 #1",
1781
      "-8 #2",
1782
      "-8 #3",
1783
      "-8 #4",
1784
      "-5 #1", // The external script.
1785
      "0 #1",
1786
      "0 #2",
1787
      "0 #3",
1788
      "5 #1",
1789
      "5 #2",
1790
    );
1791

    
1792
    // Retrieve the rendered JavaScript and test against the regex.
1793
    $js = drupal_get_js('footer');
1794
    $matches = array();
1795
    if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
1796
      $result = $matches[1];
1797
    }
1798
    else {
1799
      $result = array();
1800
    }
1801
    $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
1802
  }
1803

    
1804
  /**
1805
   * Test rendering the JavaScript with a file's weight above jQuery's.
1806
   */
1807
  function testRenderDifferentWeight() {
1808
    // JavaScript files are sorted first by group, then by the 'every_page'
1809
    // flag, then by weight (see drupal_sort_css_js()), so to test the effect of
1810
    // weight, we need the other two options to be the same.
1811
    drupal_add_js('misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
1812
    $javascript = drupal_get_js();
1813
    $this->assertTrue(strpos($javascript, 'misc/collapse.js') < strpos($javascript, 'misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
1814
  }
1815

    
1816
  /**
1817
   * Test altering a JavaScript's weight via hook_js_alter().
1818
   *
1819
   * @see simpletest_js_alter()
1820
   */
1821
  function testAlter() {
1822
    // Add both tableselect.js and simpletest.js, with a larger weight on SimpleTest.
1823
    drupal_add_js('misc/tableselect.js');
1824
    drupal_add_js(drupal_get_path('module', 'simpletest') . '/simpletest.js', array('weight' => 9999));
1825

    
1826
    // Render the JavaScript, testing if simpletest.js was altered to be before
1827
    // tableselect.js. See simpletest_js_alter() to see where this alteration
1828
    // takes place.
1829
    $javascript = drupal_get_js();
1830
    $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
1831
  }
1832

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

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

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

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

    
1871
  /**
1872
   * Tests non-existing libraries.
1873
   */
1874
  function testLibraryUnknown() {
1875
    $result = drupal_get_library('unknown', 'unknown');
1876
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1877
    drupal_static_reset('drupal_get_library');
1878

    
1879
    $result = drupal_add_library('unknown', 'unknown');
1880
    $this->assertFalse($result, 'Unknown library returned FALSE.');
1881
    $scripts = drupal_get_js();
1882
    $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
1883
  }
1884

    
1885
  /**
1886
   * Tests the addition of libraries through the #attached['library'] property.
1887
   */
1888
  function testAttachedLibrary() {
1889
    $element['#attached']['library'][] = array('system', 'farbtastic');
1890
    drupal_render($element);
1891
    $scripts = drupal_get_js();
1892
    $this->assertTrue(strpos($scripts, 'misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
1893
  }
1894

    
1895
  /**
1896
   * Tests retrieval of libraries via drupal_get_library().
1897
   */
1898
  function testGetLibrary() {
1899
    // Retrieve all libraries registered by a module.
1900
    $libraries = drupal_get_library('common_test');
1901
    $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
1902
    // Retrieve all libraries for a module not implementing hook_library().
1903
    // Note: This test installs Locale module.
1904
    $libraries = drupal_get_library('locale');
1905
    $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library() returns an emtpy array.');
1906

    
1907
    // Retrieve a specific library by module and name.
1908
    $farbtastic = drupal_get_library('common_test', 'farbtastic');
1909
    $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
1910
    // Retrieve a non-existing library by module and name.
1911
    $farbtastic = drupal_get_library('common_test', 'foo');
1912
    $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
1913
  }
1914

    
1915
  /**
1916
   * Tests that the query string remains intact when adding JavaScript files
1917
   *  that have query string parameters.
1918
   */
1919
  function testAddJsFileWithQueryString() {
1920
    $this->drupalGet('common-test/query-string');
1921
    $query_string = variable_get('css_js_query_string', '0');
1922
    $this->assertRaw(drupal_get_path('module', 'node') . '/node.js?' . $query_string, 'Query string was appended correctly to js.');
1923
  }
1924

    
1925
  /**
1926
   * Resets static variables related to adding JavaScript to a page.
1927
   */
1928
  function resetStaticVariables() {
1929
    drupal_static_reset('drupal_add_js');
1930
    drupal_static_reset('drupal_add_library');
1931
    drupal_static_reset('drupal_get_library');
1932
  }
1933
}
1934

    
1935
/**
1936
 * Tests for drupal_render().
1937
 */
1938
class DrupalRenderTestCase extends DrupalWebTestCase {
1939
  public static function getInfo() {
1940
    return array(
1941
      'name' => 'drupal_render()',
1942
      'description' => 'Performs functional tests on drupal_render().',
1943
      'group' => 'System',
1944
    );
1945
  }
1946

    
1947
  function setUp() {
1948
    parent::setUp('common_test');
1949
  }
1950

    
1951
  /**
1952
   * Tests the output drupal_render() for some elementary input values.
1953
   */
1954
  function testDrupalRenderBasics() {
1955
    $types = array(
1956
      array(
1957
        'name' => 'null',
1958
        'value' => NULL,
1959
        'expected' => '',
1960
      ),
1961
      array(
1962
        'name' => 'no value',
1963
        'expected' => '',
1964
      ),
1965
      array(
1966
        'name' => 'empty string',
1967
        'value' => '',
1968
        'expected' => '',
1969
      ),
1970
      array(
1971
        'name' => 'no access',
1972
        'value' => array(
1973
          '#markup' => 'foo',
1974
          '#access' => FALSE,
1975
        ),
1976
        'expected' => '',
1977
      ),
1978
      array(
1979
        'name' => 'previously printed',
1980
        'value' => array(
1981
          '#markup' => 'foo',
1982
          '#printed' => TRUE,
1983
        ),
1984
        'expected' => '',
1985
      ),
1986
      array(
1987
        'name' => 'printed in prerender',
1988
        'value' => array(
1989
          '#markup' => 'foo',
1990
          '#pre_render' => array('common_test_drupal_render_printing_pre_render'),
1991
        ),
1992
        'expected' => '',
1993
      ),
1994
      array(
1995
        'name' => 'basic renderable array',
1996
        'value' => array('#markup' => 'foo'),
1997
        'expected' => 'foo',
1998
      ),
1999
    );
2000
    foreach($types as $type) {
2001
      $this->assertIdentical(drupal_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by drupal_render().');
2002
    }
2003
  }
2004

    
2005
  /**
2006
   * Test sorting by weight.
2007
   */
2008
  function testDrupalRenderSorting() {
2009
    $first = $this->randomName();
2010
    $second = $this->randomName();
2011
    // Build an array with '#weight' set for each element.
2012
    $elements = array(
2013
      'second' => array(
2014
        '#weight' => 10,
2015
        '#markup' => $second,
2016
      ),
2017
      'first' => array(
2018
        '#weight' => 0,
2019
        '#markup' => $first,
2020
      ),
2021
    );
2022
    $output = drupal_render($elements);
2023

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

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

    
2030
    // Pass $elements through element_children() and ensure it remains
2031
    // sorted in the correct order. drupal_render() will return an empty string
2032
    // if used on the same array in the same request.
2033
    $children = element_children($elements);
2034
    $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
2035
    $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
2036

    
2037

    
2038
    // The same array structure again, but with #sorted set to TRUE.
2039
    $elements = array(
2040
      'second' => array(
2041
        '#weight' => 10,
2042
        '#markup' => $second,
2043
      ),
2044
      'first' => array(
2045
        '#weight' => 0,
2046
        '#markup' => $first,
2047
      ),
2048
      '#sorted' => TRUE,
2049
    );
2050
    $output = drupal_render($elements);
2051

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

    
2056
  /**
2057
   * Test #attached functionality in children elements.
2058
   */
2059
  function testDrupalRenderChildrenAttached() {
2060
    // The cache system is turned off for POST requests.
2061
    $request_method = $_SERVER['REQUEST_METHOD'];
2062
    $_SERVER['REQUEST_METHOD'] = 'GET';
2063

    
2064
    // Create an element with a child and subchild.  Each element loads a
2065
    // different JavaScript file using #attached.
2066
    $parent_js = drupal_get_path('module', 'user') . '/user.js';
2067
    $child_js = drupal_get_path('module', 'forum') . '/forum.js';
2068
    $subchild_js = drupal_get_path('module', 'book') . '/book.js';
2069
    $element = array(
2070
      '#type' => 'fieldset',
2071
      '#cache' => array(
2072
        'keys' => array('simpletest', 'drupal_render', 'children_attached'),
2073
      ),
2074
      '#attached' => array('js' => array($parent_js)),
2075
      '#title' => 'Parent',
2076
    );
2077
    $element['child'] = array(
2078
      '#type' => 'fieldset',
2079
      '#attached' => array('js' => array($child_js)),
2080
      '#title' => 'Child',
2081
    );
2082
    $element['child']['subchild'] = array(
2083
      '#attached' => array('js' => array($subchild_js)),
2084
      '#markup' => 'Subchild',
2085
    );
2086

    
2087
    // Render the element and verify the presence of #attached JavaScript.
2088
    drupal_render($element);
2089
    $scripts = drupal_get_js();
2090
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
2091
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
2092
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
2093

    
2094
    // Load the element from cache and verify the presence of the #attached
2095
    // JavaScript.
2096
    drupal_static_reset('drupal_add_js');
2097
    $this->assertTrue(drupal_render_cache_get($element), 'The element was retrieved from cache.');
2098
    $scripts = drupal_get_js();
2099
    $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
2100
    $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
2101
    $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
2102

    
2103
    $_SERVER['REQUEST_METHOD'] = $request_method;
2104
  }
2105

    
2106
  /**
2107
   * Test passing arguments to the theme function.
2108
   */
2109
  function testDrupalRenderThemeArguments() {
2110
    $element = array(
2111
      '#theme' => 'common_test_foo',
2112
    );
2113
    // Test that defaults work.
2114
    $this->assertEqual(drupal_render($element), 'foobar', 'Defaults work');
2115
    $element = array(
2116
      '#theme' => 'common_test_foo',
2117
      '#foo' => $this->randomName(),
2118
      '#bar' => $this->randomName(),
2119
    );
2120
    // Test that passing arguments to the theme function works.
2121
    $this->assertEqual(drupal_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
2122
  }
2123

    
2124
  /**
2125
   * Test rendering form elements without passing through form_builder().
2126
   */
2127
  function testDrupalRenderFormElements() {
2128
    // Define a series of form elements.
2129
    $element = array(
2130
      '#type' => 'button',
2131
      '#value' => $this->randomName(),
2132
    );
2133
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
2134

    
2135
    $element = array(
2136
      '#type' => 'textfield',
2137
      '#title' => $this->randomName(),
2138
      '#value' => $this->randomName(),
2139
    );
2140
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
2141

    
2142
    $element = array(
2143
      '#type' => 'password',
2144
      '#title' => $this->randomName(),
2145
    );
2146
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
2147

    
2148
    $element = array(
2149
      '#type' => 'textarea',
2150
      '#title' => $this->randomName(),
2151
      '#value' => $this->randomName(),
2152
    );
2153
    $this->assertRenderedElement($element, '//textarea');
2154

    
2155
    $element = array(
2156
      '#type' => 'radio',
2157
      '#title' => $this->randomName(),
2158
      '#value' => FALSE,
2159
    );
2160
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
2161

    
2162
    $element = array(
2163
      '#type' => 'checkbox',
2164
      '#title' => $this->randomName(),
2165
    );
2166
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
2167

    
2168
    $element = array(
2169
      '#type' => 'select',
2170
      '#title' => $this->randomName(),
2171
      '#options' => array(
2172
        0 => $this->randomName(),
2173
        1 => $this->randomName(),
2174
      ),
2175
    );
2176
    $this->assertRenderedElement($element, '//select');
2177

    
2178
    $element = array(
2179
      '#type' => 'file',
2180
      '#title' => $this->randomName(),
2181
    );
2182
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
2183

    
2184
    $element = array(
2185
      '#type' => 'item',
2186
      '#title' => $this->randomName(),
2187
      '#markup' => $this->randomName(),
2188
    );
2189
    $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
2190
      ':class' => 'form-type-item',
2191
      ':markup' => $element['#markup'],
2192
      ':label' => $element['#title'],
2193
    ));
2194

    
2195
    $element = array(
2196
      '#type' => 'hidden',
2197
      '#title' => $this->randomName(),
2198
      '#value' => $this->randomName(),
2199
    );
2200
    $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
2201

    
2202
    $element = array(
2203
      '#type' => 'link',
2204
      '#title' => $this->randomName(),
2205
      '#href' => $this->randomName(),
2206
      '#options' => array(
2207
        'absolute' => TRUE,
2208
      ),
2209
    );
2210
    $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
2211
      ':href' => url($element['#href'], array('absolute' => TRUE)),
2212
      ':title' => $element['#title'],
2213
    ));
2214

    
2215
    $element = array(
2216
      '#type' => 'fieldset',
2217
      '#title' => $this->randomName(),
2218
    );
2219
    $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
2220
      ':title' => $element['#title'],
2221
    ));
2222

    
2223
    $element['item'] = array(
2224
      '#type' => 'item',
2225
      '#title' => $this->randomName(),
2226
      '#markup' => $this->randomName(),
2227
    );
2228
    $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
2229
      ':class' => 'form-type-item',
2230
      ':markup' => $element['item']['#markup'],
2231
    ));
2232
  }
2233

    
2234
  protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
2235
    $original_element = $element;
2236
    $this->drupalSetContent(drupal_render($element));
2237
    $this->verbose('<pre>' .  check_plain(var_export($original_element, TRUE)) . '</pre>'
2238
      . '<pre>' .  check_plain(var_export($element, TRUE)) . '</pre>'
2239
      . '<hr />' . $this->drupalGetContent()
2240
    );
2241

    
2242
    // @see DrupalWebTestCase::xpath()
2243
    $xpath = $this->buildXPathQuery($xpath, $xpath_args);
2244
    $element += array('#value' => NULL);
2245
    $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
2246
      '@type' => var_export($element['#type'], TRUE),
2247
    )));
2248
  }
2249

    
2250
  /**
2251
   * Tests caching of render items.
2252
   */
2253
  function testDrupalRenderCache() {
2254
    // Force a request via GET.
2255
    $request_method = $_SERVER['REQUEST_METHOD'];
2256
    $_SERVER['REQUEST_METHOD'] = 'GET';
2257
    // Create an empty element.
2258
    $test_element = array(
2259
      '#cache' => array(
2260
        'cid' => 'render_cache_test',
2261
      ),
2262
      '#markup' => '',
2263
    );
2264

    
2265
    // Render the element and confirm that it goes through the rendering
2266
    // process (which will set $element['#printed']).
2267
    $element = $test_element;
2268
    drupal_render($element);
2269
    $this->assertTrue(isset($element['#printed']), 'No cache hit');
2270

    
2271
    // Render the element again and confirm that it is retrieved from the cache
2272
    // instead (so $element['#printed'] will not be set).
2273
    $element = $test_element;
2274
    drupal_render($element);
2275
    $this->assertFalse(isset($element['#printed']), 'Cache hit');
2276

    
2277
    // Test that user 1 does not share the cache with other users who have the
2278
    // same roles, even when DRUPAL_CACHE_PER_ROLE is used.
2279
    $user1 = user_load(1);
2280
    $first_authenticated_user = $this->drupalCreateUser();
2281
    $second_authenticated_user = $this->drupalCreateUser();
2282
    $user1->roles = array_intersect_key($user1->roles, array(DRUPAL_AUTHENTICATED_RID => TRUE));
2283
    user_save($user1);
2284
    // Load all the accounts again, to make sure we have complete account
2285
    // objects.
2286
    $user1 = user_load(1);
2287
    $first_authenticated_user = user_load($first_authenticated_user->uid);
2288
    $second_authenticated_user = user_load($second_authenticated_user->uid);
2289
    $this->assertEqual($user1->roles, $first_authenticated_user->roles, 'User 1 has the same roles as an authenticated user.');
2290
    // Impersonate user 1 and render content that only user 1 should have
2291
    // permission to see.
2292
    $original_user = $GLOBALS['user'];
2293
    $original_session_state = drupal_save_session();
2294
    drupal_save_session(FALSE);
2295
    $GLOBALS['user'] = $user1;
2296
    $test_element = array(
2297
      '#cache' => array(
2298
        'keys' => array('test'),
2299
        'granularity' => DRUPAL_CACHE_PER_ROLE,
2300
      ),
2301
    );
2302
    $element = $test_element;
2303
    $element['#markup'] = 'content for user 1';
2304
    $output = drupal_render($element);
2305
    $this->assertEqual($output, 'content for user 1');
2306
    // Verify the cache is working by rendering the same element but with
2307
    // different markup passed in; the result should be the same.
2308
    $element = $test_element;
2309
    $element['#markup'] = 'should not be used';
2310
    $output = drupal_render($element);
2311
    $this->assertEqual($output, 'content for user 1');
2312
    // Verify that the first authenticated user does not see the same content
2313
    // as user 1.
2314
    $GLOBALS['user'] = $first_authenticated_user;
2315
    $element = $test_element;
2316
    $element['#markup'] = 'content for authenticated users';
2317
    $output = drupal_render($element);
2318
    $this->assertEqual($output, 'content for authenticated users');
2319
    // Verify that the second authenticated user shares the cache with the
2320
    // first authenticated user.
2321
    $GLOBALS['user'] = $second_authenticated_user;
2322
    $element = $test_element;
2323
    $element['#markup'] = 'should not be used';
2324
    $output = drupal_render($element);
2325
    $this->assertEqual($output, 'content for authenticated users');
2326
    // Restore the original logged-in user.
2327
    $GLOBALS['user'] = $original_user;
2328
    drupal_save_session($original_session_state);
2329

    
2330
    // Restore the previous request method.
2331
    $_SERVER['REQUEST_METHOD'] = $request_method;
2332
  }
2333
}
2334

    
2335
/**
2336
 * Test for valid_url().
2337
 */
2338
class ValidUrlTestCase extends DrupalUnitTestCase {
2339
  public static function getInfo() {
2340
    return array(
2341
      'name' => 'Valid URL',
2342
      'description' => "Performs tests on Drupal's valid URL function.",
2343
      'group' => 'System'
2344
    );
2345
  }
2346

    
2347
  /**
2348
   * Test valid absolute URLs.
2349
   */
2350
  function testValidAbsolute() {
2351
    $url_schemes = array('http', 'https', 'ftp');
2352
    $valid_absolute_urls = array(
2353
      'example.com',
2354
      'www.example.com',
2355
      'ex-ample.com',
2356
      '3xampl3.com',
2357
      'example.com/paren(the)sis',
2358
      'example.com/index.html#pagetop',
2359
      'example.com:8080',
2360
      'subdomain.example.com',
2361
      'example.com/index.php?q=node',
2362
      'example.com/index.php?q=node&param=false',
2363
      'user@www.example.com',
2364
      'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
2365
      '127.0.0.1',
2366
      'example.org?',
2367
      'john%20doe:secret:foo@example.org/',
2368
      'example.org/~,$\'*;',
2369
      'caf%C3%A9.example.org',
2370
      '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
2371
    );
2372

    
2373
    foreach ($url_schemes as $scheme) {
2374
      foreach ($valid_absolute_urls as $url) {
2375
        $test_url = $scheme . '://' . $url;
2376
        $valid_url = valid_url($test_url, TRUE);
2377
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2378
      }
2379
    }
2380
  }
2381

    
2382
  /**
2383
   * Test invalid absolute URLs.
2384
   */
2385
  function testInvalidAbsolute() {
2386
    $url_schemes = array('http', 'https', 'ftp');
2387
    $invalid_ablosule_urls = array(
2388
      '',
2389
      'ex!ample.com',
2390
      'ex%ample.com',
2391
    );
2392

    
2393
    foreach ($url_schemes as $scheme) {
2394
      foreach ($invalid_ablosule_urls as $url) {
2395
        $test_url = $scheme . '://' . $url;
2396
        $valid_url = valid_url($test_url, TRUE);
2397
        $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2398
      }
2399
    }
2400
  }
2401

    
2402
  /**
2403
   * Test valid relative URLs.
2404
   */
2405
  function testValidRelative() {
2406
    $valid_relative_urls = array(
2407
      'paren(the)sis',
2408
      'index.html#pagetop',
2409
      'index.php?q=node',
2410
      'index.php?q=node&param=false',
2411
      'login.php?do=login&style=%23#pagetop',
2412
    );
2413

    
2414
    foreach (array('', '/') as $front) {
2415
      foreach ($valid_relative_urls as $url) {
2416
        $test_url = $front . $url;
2417
        $valid_url = valid_url($test_url);
2418
        $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
2419
      }
2420
    }
2421
  }
2422

    
2423
  /**
2424
   * Test invalid relative URLs.
2425
   */
2426
  function testInvalidRelative() {
2427
    $invalid_relative_urls = array(
2428
      'ex^mple',
2429
      'example<>',
2430
      'ex%ample',
2431
    );
2432

    
2433
    foreach (array('', '/') as $front) {
2434
      foreach ($invalid_relative_urls as $url) {
2435
        $test_url = $front . $url;
2436
        $valid_url = valid_url($test_url);
2437
        $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
2438
      }
2439
    }
2440
  }
2441
}
2442

    
2443
/**
2444
 * Tests for CRUD API functions.
2445
 */
2446
class DrupalDataApiTest extends DrupalWebTestCase {
2447
  public static function getInfo() {
2448
    return array(
2449
      'name' => 'Data API functions',
2450
      'description' => 'Tests the performance of CRUD APIs.',
2451
      'group' => 'System',
2452
    );
2453
  }
2454

    
2455
  function setUp() {
2456
    parent::setUp('database_test');
2457
  }
2458

    
2459
  /**
2460
   * Test the drupal_write_record() API function.
2461
   */
2462
  function testDrupalWriteRecord() {
2463
    // Insert a record - no columns allow NULL values.
2464
    $person = new stdClass();
2465
    $person->name = 'John';
2466
    $person->unknown_column = 123;
2467
    $insert_result = drupal_write_record('test', $person);
2468
    $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.');
2469
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2470
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2471
    $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
2472

    
2473
    // Verify that the record was inserted.
2474
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2475
    $this->assertIdentical($result->name, 'John', 'Name field set.');
2476
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2477
    $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
2478
    $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
2479

    
2480
    // Update the newly created record.
2481
    $person->name = 'Peter';
2482
    $person->age = 27;
2483
    $person->job = NULL;
2484
    $update_result = drupal_write_record('test', $person, array('id'));
2485
    $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with drupal_write_record() for table with single-field primary key.');
2486

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

    
2493
    // Try to insert NULL in columns that does not allow this.
2494
    $person = new stdClass();
2495
    $person->name = 'Ringo';
2496
    $person->age = NULL;
2497
    $person->job = NULL;
2498
    $insert_result = drupal_write_record('test', $person);
2499
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2500
    $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2501
    $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
2502
    $this->assertIdentical($result->age, '0', 'Age field set.');
2503
    $this->assertIdentical($result->job, '', 'Job field set.');
2504

    
2505
    // Insert a record - the "age" column allows NULL.
2506
    $person = new stdClass();
2507
    $person->name = 'Paul';
2508
    $person->age = NULL;
2509
    $insert_result = drupal_write_record('test_null', $person);
2510
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2511
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2512
    $this->assertIdentical($result->name, 'Paul', 'Name field set.');
2513
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2514

    
2515
    // Insert a record - do not specify the value of a column that allows NULL.
2516
    $person = new stdClass();
2517
    $person->name = 'Meredith';
2518
    $insert_result = drupal_write_record('test_null', $person);
2519
    $this->assertTrue(isset($person->id), 'Primary key is set on record created with drupal_write_record().');
2520
    $this->assertIdentical($person->age, 0, 'Age field set to default value.');
2521
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2522
    $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
2523
    $this->assertIdentical($result->age, '0', 'Age field set to default value.');
2524

    
2525
    // Update the newly created record.
2526
    $person->name = 'Mary';
2527
    $person->age = NULL;
2528
    $update_result = drupal_write_record('test_null', $person, array('id'));
2529
    $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2530
    $this->assertIdentical($result->name, 'Mary', 'Name field set.');
2531
    $this->assertIdentical($result->age, NULL, 'Age field set.');
2532

    
2533
    // Insert a record - the "data" column should be serialized.
2534
    $person = new stdClass();
2535
    $person->name = 'Dave';
2536
    $update_result = drupal_write_record('test_serialized', $person);
2537
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2538
    $this->assertIdentical($result->name, 'Dave', 'Name field set.');
2539
    $this->assertIdentical($result->info, NULL, 'Info field set.');
2540

    
2541
    $person->info = array();
2542
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2543
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2544
    $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
2545

    
2546
    // Update the serialized record.
2547
    $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
2548
    $person->info = $data;
2549
    $update_result = drupal_write_record('test_serialized', $person, array('id'));
2550
    $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
2551
    $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
2552

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

    
2559
    // Insert an object record for a table with a multi-field primary key.
2560
    $node_access = new stdClass();
2561
    $node_access->nid = mt_rand();
2562
    $node_access->gid = mt_rand();
2563
    $node_access->realm = $this->randomName();
2564
    $insert_result = drupal_write_record('node_access', $node_access);
2565
    $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.');
2566

    
2567
    // Update the record.
2568
    $update_result = drupal_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
2569
    $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.');
2570
  }
2571

    
2572
}
2573

    
2574
/**
2575
 * Tests Simpletest error and exception collector.
2576
 */
2577
class DrupalErrorCollectionUnitTest extends DrupalWebTestCase {
2578

    
2579
  /**
2580
   * Errors triggered during the test.
2581
   *
2582
   * Errors are intercepted by the overriden implementation
2583
   * of DrupalWebTestCase::error below.
2584
   *
2585
   * @var Array
2586
   */
2587
  protected $collectedErrors = array();
2588

    
2589
  public static function getInfo() {
2590
    return array(
2591
      'name' => 'SimpleTest error collector',
2592
      'description' => 'Performs tests on the Simpletest error and exception collector.',
2593
      'group' => 'SimpleTest',
2594
    );
2595
  }
2596

    
2597
  function setUp() {
2598
    parent::setUp('system_test', 'error_test');
2599
  }
2600

    
2601
  /**
2602
   * Test that simpletest collects errors from the tested site.
2603
   */
2604
  function testErrorCollect() {
2605
    $this->collectedErrors = array();
2606
    $this->drupalGet('error-test/generate-warnings-with-report');
2607
    $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
2608

    
2609
    if (count($this->collectedErrors) == 3) {
2610
      $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Undefined variable: bananas');
2611
      $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', 'Division by zero');
2612
      $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Drupal is awesome');
2613
    }
2614
    else {
2615
      // Give back the errors to the log report.
2616
      foreach ($this->collectedErrors as $error) {
2617
        parent::error($error['message'], $error['group'], $error['caller']);
2618
      }
2619
    }
2620
  }
2621

    
2622
  /**
2623
   * Error handler that collects errors in an array.
2624
   *
2625
   * This test class is trying to verify that simpletest correctly sees errors
2626
   * and warnings. However, it can't generate errors and warnings that
2627
   * propagate up to the testing framework itself, or these tests would always
2628
   * fail. So, this special copy of error() doesn't propagate the errors up
2629
   * the class hierarchy. It just stuffs them into a protected collectedErrors
2630
   * array for various assertions to inspect.
2631
   */
2632
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
2633
    // Due to a WTF elsewhere, simpletest treats debug() and verbose()
2634
    // messages as if they were an 'error'. But, we don't want to collect
2635
    // those here. This function just wants to collect the real errors (PHP
2636
    // notices, PHP fatal errors, etc.), and let all the 'errors' from the
2637
    // 'User notice' group bubble up to the parent classes to be handled (and
2638
    // eventually displayed) as normal.
2639
    if ($group == 'User notice') {
2640
      parent::error($message, $group, $caller);
2641
    }
2642
    // Everything else should be collected but not propagated.
2643
    else {
2644
      $this->collectedErrors[] = array(
2645
        'message' => $message,
2646
        'group' => $group,
2647
        'caller' => $caller
2648
      );
2649
    }
2650
  }
2651

    
2652
  /**
2653
   * Assert that a collected error matches what we are expecting.
2654
   */
2655
  function assertError($error, $group, $function, $file, $message = NULL) {
2656
    $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
2657
    $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
2658
    $this->assertEqual(drupal_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
2659
    if (isset($message)) {
2660
      $this->assertEqual($error['message'], $message, format_string("Message was %message", array('%message' => $message)));
2661
    }
2662
  }
2663
}
2664

    
2665
/**
2666
 * Test the drupal_parse_info_file() API function.
2667
 */
2668
class ParseInfoFilesTestCase extends DrupalUnitTestCase {
2669
  public static function getInfo() {
2670
    return array(
2671
      'name' => 'Parsing .info files',
2672
      'description' => 'Tests parsing .info files.',
2673
      'group' => 'System',
2674
    );
2675
  }
2676

    
2677
  /**
2678
   * Parse an example .info file an verify the results.
2679
   */
2680
  function testParseInfoFile() {
2681
    $info_values = drupal_parse_info_file(drupal_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
2682
    $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
2683
    $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
2684
    $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
2685
  }
2686
}
2687

    
2688
/**
2689
 * Tests for the drupal_system_listing() function.
2690
 */
2691
class DrupalSystemListingTestCase extends DrupalWebTestCase {
2692
  /**
2693
   * Use the testing profile; this is needed for testDirectoryPrecedence().
2694
   */
2695
  protected $profile = 'testing';
2696

    
2697
  public static function getInfo() {
2698
    return array(
2699
      'name' => 'Drupal system listing',
2700
      'description' => 'Tests the mechanism for scanning system directories in drupal_system_listing().',
2701
      'group' => 'System',
2702
    );
2703
  }
2704

    
2705
  /**
2706
   * Test that files in different directories take precedence as expected.
2707
   */
2708
  function testDirectoryPrecedence() {
2709
    // Define the module files we will search for, and the directory precedence
2710
    // we expect.
2711
    $expected_directories = array(
2712
      // When the copy of the module in the profile directory is incompatible
2713
      // with Drupal core, the copy in the core modules directory takes
2714
      // precedence.
2715
      'drupal_system_listing_incompatible_test' => array(
2716
        'modules/simpletest/tests',
2717
        'profiles/testing/modules',
2718
      ),
2719
      // When both copies of the module are compatible with Drupal core, the
2720
      // copy in the profile directory takes precedence.
2721
      'drupal_system_listing_compatible_test' => array(
2722
        'profiles/testing/modules',
2723
        'modules/simpletest/tests',
2724
      ),
2725
    );
2726

    
2727
    // This test relies on two versions of the same module existing in
2728
    // different places in the filesystem. Without that, the test has no
2729
    // meaning, so assert their presence first.
2730
    foreach ($expected_directories as $module => $directories) {
2731
      foreach ($directories as $directory) {
2732
        $filename = "$directory/$module/$module.module";
2733
        $this->assertTrue(file_exists(DRUPAL_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
2734
      }
2735
    }
2736

    
2737
    // Now scan the directories and check that the files take precedence as
2738
    // expected.
2739
    $files = drupal_system_listing('/\.module$/', 'modules', 'name', 1);
2740
    foreach ($expected_directories as $module => $directories) {
2741
      $expected_directory = array_shift($directories);
2742
      $expected_filename = "$expected_directory/$module/$module.module";
2743
      $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
2744
    }
2745
  }
2746
}
2747

    
2748
/**
2749
 * Tests for the format_date() function.
2750
 */
2751
class FormatDateUnitTest extends DrupalWebTestCase {
2752

    
2753
  /**
2754
   * Arbitrary langcode for a custom language.
2755
   */
2756
  const LANGCODE = 'xx';
2757

    
2758
  public static function getInfo() {
2759
    return array(
2760
      'name' => 'Format date',
2761
      'description' => 'Test the format_date() function.',
2762
      'group' => 'System',
2763
    );
2764
  }
2765

    
2766
  function setUp() {
2767
    parent::setUp('locale');
2768
    variable_set('configurable_timezones', 1);
2769
    variable_set('date_format_long', 'l, j. F Y - G:i');
2770
    variable_set('date_format_medium', 'j. F Y - G:i');
2771
    variable_set('date_format_short', 'Y M j - g:ia');
2772
    variable_set('locale_custom_strings_' . self::LANGCODE, array(
2773
      '' => array('Sunday' => 'domingo'),
2774
      'Long month name' => array('March' => 'marzo'),
2775
    ));
2776
    $this->refreshVariables();
2777
  }
2778

    
2779
  /**
2780
   * Test admin-defined formats in format_date().
2781
   */
2782
  function testAdminDefinedFormatDate() {
2783
    // Create an admin user.
2784
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
2785
    $this->drupalLogin($this->admin_user);
2786

    
2787
    // Add new date format.
2788
    $admin_date_format = 'j M y';
2789
    $edit = array('date_format' => $admin_date_format);
2790
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, 'Add format');
2791

    
2792
    // Add a new date format which just differs in the case.
2793
    $admin_date_format_uppercase = 'j M Y';
2794
    $edit = array('date_format' => $admin_date_format_uppercase);
2795
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
2796
    $this->assertText(t('Custom date format added.'));
2797

    
2798
    // Add new date type.
2799
    $edit = array(
2800
      'date_type' => 'Example Style',
2801
      'machine_name' => 'example_style',
2802
      'date_format' => $admin_date_format,
2803
    );
2804
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, 'Add date type');
2805

    
2806
   // Add a second date format with a different case than the first.
2807
    $edit = array(
2808
      'machine_name' => 'example_style_uppercase',
2809
      'date_type' => 'Example Style Uppercase',
2810
      'date_format' => $admin_date_format_uppercase,
2811
    );
2812
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
2813
    $this->assertText(t('New date type added successfully.'));
2814

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

    
2821
  /**
2822
   * Tests for the format_date() function.
2823
   */
2824
  function testFormatDate() {
2825
    global $user, $language;
2826

    
2827
    $timestamp = strtotime('2007-03-26T00:00:00+00:00');
2828
    $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.');
2829
    $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.');
2830
    $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.');
2831
    $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.');
2832
    $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.');
2833
    $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.');
2834

    
2835
    // Create an admin user and add Spanish language.
2836
    $admin_user = $this->drupalCreateUser(array('administer languages'));
2837
    $this->drupalLogin($admin_user);
2838
    $edit = array(
2839
      'langcode' => self::LANGCODE,
2840
      'name' => self::LANGCODE,
2841
      'native' => self::LANGCODE,
2842
      'direction' => LANGUAGE_LTR,
2843
      'prefix' => self::LANGCODE,
2844
    );
2845
    $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
2846

    
2847
    // Create a test user to carry out the tests.
2848
    $test_user = $this->drupalCreateUser();
2849
    $this->drupalLogin($test_user);
2850
    $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
2851
    $this->drupalPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
2852

    
2853
    // Disable session saving as we are about to modify the global $user.
2854
    drupal_save_session(FALSE);
2855
    // Save the original user and language and then replace it with the test user and language.
2856
    $real_user = $user;
2857
    $user = user_load($test_user->uid, TRUE);
2858
    $real_language = $language->language;
2859
    $language->language = $user->language;
2860
    // Simulate a Drupal bootstrap with the logged-in user.
2861
    date_default_timezone_set(drupal_get_user_timezone());
2862

    
2863
    $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.');
2864
    $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.');
2865
    $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.');
2866
    $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
2867
    $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
2868
    $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
2869
    $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
2870

    
2871
    // Restore the original user and language, and enable session saving.
2872
    $user = $real_user;
2873
    $language->language = $real_language;
2874
    // Restore default time zone.
2875
    date_default_timezone_set(drupal_get_user_timezone());
2876
    drupal_save_session(TRUE);
2877
  }
2878
}
2879

    
2880
/**
2881
 * Tests for the format_date() function.
2882
 */
2883
class DrupalAttributesUnitTest extends DrupalUnitTestCase {
2884
  public static function getInfo() {
2885
    return array(
2886
      'name' => 'HTML Attributes',
2887
      'description' => 'Perform unit tests on the drupal_attributes() function.',
2888
      'group' => 'System',
2889
    );
2890
  }
2891

    
2892
  /**
2893
   * Tests that drupal_html_class() cleans the class name properly.
2894
   */
2895
  function testDrupalAttributes() {
2896
    // Verify that special characters are HTML encoded.
2897
    $this->assertIdentical(drupal_attributes(array('title' => '&"\'<>')), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.');
2898

    
2899
    // Verify multi-value attributes are concatenated with spaces.
2900
    $attributes = array('class' => array('first', 'last'));
2901
    $this->assertIdentical(drupal_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
2902

    
2903
    // Verify empty attribute values are rendered.
2904
    $this->assertIdentical(drupal_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
2905
    $this->assertIdentical(drupal_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
2906

    
2907
    // Verify multiple attributes are rendered.
2908
    $attributes = array(
2909
      'id' => 'id-test',
2910
      'class' => array('first', 'last'),
2911
      'alt' => 'Alternate',
2912
    );
2913
    $this->assertIdentical(drupal_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
2914

    
2915
    // Verify empty attributes array is rendered.
2916
    $this->assertIdentical(drupal_attributes(array()), '', 'Empty attributes array.');
2917
  }
2918
}
2919

    
2920
/**
2921
 * Tests converting PHP variables to JSON strings and back.
2922
 */
2923
class DrupalJSONTest extends DrupalUnitTestCase {
2924
  public static function getInfo() {
2925
    return array(
2926
      'name' => 'JSON',
2927
      'description' => 'Perform unit tests on the drupal_json_encode() and drupal_json_decode() functions.',
2928
      'group' => 'System',
2929
    );
2930
  }
2931

    
2932
  /**
2933
   * Tests converting PHP variables to JSON strings and back.
2934
   */
2935
  function testJSON() {
2936
    // Setup a string with the full ASCII table.
2937
    // @todo: Add tests for non-ASCII characters and Unicode.
2938
    $str = '';
2939
    for ($i=0; $i < 128; $i++) {
2940
      $str .= chr($i);
2941
    }
2942
    // Characters that must be escaped.
2943
    // We check for unescaped " separately.
2944
    $html_unsafe = array('<', '>', '\'', '&');
2945
    // The following are the encoded forms of: < > ' & "
2946
    $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
2947

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

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

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

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

    
2967
    // Verify reversibility for structured data. Also verify that necessary
2968
    // characters are escaped.
2969
    $source = array(TRUE, FALSE, 0, 1, '0', '1', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
2970
    $json = drupal_json_encode($source);
2971
    foreach ($html_unsafe as $char) {
2972
      $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
2973
    }
2974
    // Verify that JSON encoding escapes the HTML unsafe characters
2975
    foreach ($html_unsafe_escaped as $char) {
2976
      $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
2977
    }
2978
    $json_decoded = drupal_json_decode($json);
2979
    $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
2980
    $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
2981
  }
2982
}
2983

    
2984
/**
2985
 * Tests for RDF namespaces XML serialization.
2986
 */
2987
class DrupalGetRdfNamespacesTestCase extends DrupalWebTestCase {
2988
  public static function getInfo() {
2989
    return array(
2990
      'name' => 'RDF namespaces XML serialization tests',
2991
      'description' => 'Confirm that the serialization of RDF namespaces via drupal_get_rdf_namespaces() is output and parsed correctly in the XHTML document.',
2992
      'group' => 'System',
2993
    );
2994
  }
2995

    
2996
  function setUp() {
2997
    parent::setUp('rdf', 'rdf_test');
2998
  }
2999

    
3000
  /**
3001
   * Test RDF namespaces.
3002
   */
3003
  function testGetRdfNamespaces() {
3004
    // Fetches the front page and extracts XML namespaces.
3005
    $this->drupalGet('');
3006
    $xml = new SimpleXMLElement($this->content);
3007
    $ns = $xml->getDocNamespaces();
3008

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

    
3016
/**
3017
 * Basic tests for drupal_add_feed().
3018
 */
3019
class DrupalAddFeedTestCase extends DrupalWebTestCase {
3020
  public static function getInfo() {
3021
    return array(
3022
      'name' => 'drupal_add_feed() tests',
3023
      'description' => 'Make sure that drupal_add_feed() works correctly with various constructs.',
3024
      'group' => 'System',
3025
    );
3026
  }
3027

    
3028
  /**
3029
   * Test drupal_add_feed() with paths, URLs, and titles.
3030
   */
3031
  function testBasicFeedAddNoTitle() {
3032
    $path = $this->randomName(12);
3033
    $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
3034
    $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
3035

    
3036
    $path_for_title = $this->randomName(12);
3037
    $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
3038
    $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
3039

    
3040
    // Possible permutations of drupal_add_feed() to test.
3041
    // - 'input_url': the path passed to drupal_add_feed(),
3042
    // - 'output_url': the expected URL to be found in the header.
3043
    // - 'title' == the title of the feed as passed into drupal_add_feed().
3044
    $urls = array(
3045
      'path without title' => array(
3046
        'input_url' => $path,
3047
        'output_url' => url($path, array('absolute' => TRUE)),
3048
        'title' => '',
3049
      ),
3050
      'external URL without title' => array(
3051
        'input_url' => $external_url,
3052
        'output_url' => $external_url,
3053
        'title' => '',
3054
      ),
3055
      'local URL without title' => array(
3056
        'input_url' => $fully_qualified_local_url,
3057
        'output_url' => $fully_qualified_local_url,
3058
        'title' => '',
3059
      ),
3060
      'path with title' => array(
3061
        'input_url' => $path_for_title,
3062
        'output_url' => url($path_for_title, array('absolute' => TRUE)),
3063
        'title' => $this->randomName(12),
3064
      ),
3065
      'external URL with title' => array(
3066
        'input_url' => $external_for_title,
3067
        'output_url' => $external_for_title,
3068
        'title' => $this->randomName(12),
3069
      ),
3070
      'local URL with title' => array(
3071
        'input_url' => $fully_qualified_for_title,
3072
        'output_url' => $fully_qualified_for_title,
3073
        'title' => $this->randomName(12),
3074
      ),
3075
    );
3076

    
3077
    foreach ($urls as $description => $feed_info) {
3078
      drupal_add_feed($feed_info['input_url'], $feed_info['title']);
3079
    }
3080

    
3081
    $this->drupalSetContent(drupal_get_html_head());
3082
    foreach ($urls as $description => $feed_info) {
3083
      $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
3084
    }
3085
  }
3086

    
3087
  /**
3088
   * Create a pattern representing the RSS feed in the page.
3089
   */
3090
  function urlToRSSLinkPattern($url, $title = '') {
3091
    // Escape any regular expression characters in the URL ('?' is the worst).
3092
    $url = preg_replace('/([+?.*])/', '[$0]', $url);
3093
    $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
3094
    return $generated_pattern;
3095
  }
3096
}
3097

    
3098
/**
3099
 * Test for theme_feed_icon().
3100
 */
3101
class FeedIconTest extends DrupalWebTestCase {
3102

    
3103
  public static function getInfo() {
3104
    return array(
3105
      'name' => 'Feed icon',
3106
      'description' => 'Check escaping of theme_feed_icon()',
3107
      'group' => 'System',
3108
    );
3109
  }
3110

    
3111
  /**
3112
   * Check that special characters are correctly escaped. Test for issue #1211668.
3113
   */
3114
  function testFeedIconEscaping() {
3115
    $variables = array();
3116
    $variables['url'] = 'node';
3117
    $variables['title'] = '<>&"\'';
3118
    $text = theme_feed_icon($variables);
3119
    preg_match('/title="(.*?)"/', $text, $matches);
3120
    $this->assertEqual($matches[1], 'Subscribe to &amp;&quot;&#039;', 'theme_feed_icon() escapes reserved HTML characters.');
3121
  }
3122

    
3123
}
3124

    
3125
/**
3126
 * Test array diff functions.
3127
 */
3128
class ArrayDiffUnitTest extends DrupalUnitTestCase {
3129

    
3130
  /**
3131
   * Array to use for testing.
3132
   *
3133
   * @var array
3134
   */
3135
  protected $array1;
3136

    
3137
  /**
3138
   * Array to use for testing.
3139
   *
3140
   * @var array
3141
   */
3142
  protected $array2;
3143

    
3144
  public static function getInfo() {
3145
    return array(
3146
      'name' => 'Array differences',
3147
      'description' => 'Performs tests on drupal_array_diff_assoc_recursive().',
3148
      'group' => 'System',
3149
    );
3150
  }
3151

    
3152
  function setUp() {
3153
    parent::setUp();
3154

    
3155
    $this->array1 = array(
3156
      'same' => 'yes',
3157
      'different' => 'no',
3158
      'array_empty_diff' => array(),
3159
      'null' => NULL,
3160
      'int_diff' => 1,
3161
      'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
3162
      'array_compared_to_string' => array('value'),
3163
      'string_compared_to_array' => 'value',
3164
      'new' => 'new',
3165
    );
3166
    $this->array2 = array(
3167
      'same' => 'yes',
3168
      'different' => 'yes',
3169
      'array_empty_diff' => array(),
3170
      'null' => NULL,
3171
      'int_diff' => '1',
3172
      'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
3173
      'array_compared_to_string' => 'value',
3174
      'string_compared_to_array' => array('value'),
3175
    );
3176
  }
3177

    
3178

    
3179
  /**
3180
   * Tests drupal_array_diff_assoc_recursive().
3181
   */
3182
  public function testArrayDiffAssocRecursive() {
3183
    $expected = array(
3184
      'different' => 'no',
3185
      'int_diff' => 1,
3186
      // The 'array' key should not be returned, as it's the same.
3187
      'array_diff' => array('same' => 'same'),
3188
      'array_compared_to_string' => array('value'),
3189
      'string_compared_to_array' => 'value',
3190
      'new' => 'new',
3191
    );
3192

    
3193
    $this->assertIdentical(drupal_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
3194
  }
3195
}
3196

    
3197
/**
3198
 * Tests the functionality of drupal_get_query_array().
3199
 */
3200
class DrupalGetQueryArrayTestCase extends DrupalWebTestCase {
3201

    
3202
  public static function getInfo() {
3203
    return array(
3204
      'name' => 'Query parsing using drupal_get_query_array()',
3205
      'description' => 'Tests that drupal_get_query_array() correctly parses query parameters.',
3206
      'group' => 'System',
3207
    );
3208
  }
3209

    
3210
  /**
3211
   * Tests that drupal_get_query_array() correctly explodes query parameters.
3212
   */
3213
  public function testDrupalGetQueryArray() {
3214
    $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
3215
    $parsed = parse_url($url);
3216
    $result = drupal_get_query_array($parsed['query']);
3217
    $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'drupal_get_query_array() should only explode parameters on the first equals sign.');
3218
  }
3219

    
3220
}