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