Skip navigation
Help

common.test

  1. drupal
    1. 7 drupal/modules/simpletest/tests/common.test

Tests for common.inc functionality.

Classes

NameDescription
CascadingStylesheetsTestCaseTest the Drupal CSS system.
CascadingStylesheetsUnitTestCSS Unit Tests.
CommonSizeTestCase
CommonURLUnitTestTests for URL generation functions.
CommonXssUnitTestTests for the check_plain() and filter_xss() functions.
DrupalAddFeedTestCaseBasic tests for drupal_add_feed().
DrupalAlterTestCaseTests for URL generation functions.
DrupalAttributesUnitTestTests for the format_date() function.
DrupalDataApiTestTests for CRUD API functions.
DrupalErrorCollectionUnitTestTests Simpletest error and exception collector.
DrupalGetRdfNamespacesTestCaseTests for RDF namespaces XML serialization.
DrupalGotoTestTesting drupal_goto and hook_drupal_goto_alter().
DrupalHTMLIdentifierTestCaseTest for cleaning HTML identifiers.
DrupalHTTPRequestTestCaseTest drupal_http_request().
DrupalJSONTestTests converting PHP variables to JSON strings and back.
DrupalRenderTestCaseTests for drupal_render().
DrupalSetContentTestCaseTesting drupal_add_region_content and drupal_get_region_content.
DrupalSystemListingTestCaseTests for the drupal_system_listing() function.
DrupalTagsHandlingTestCaseTest drupal_explode_tags() and drupal_implode_tags().
FormatDateUnitTestTests for the format_date() function.
JavaScriptTestCaseTests for the JavaScript system.
ParseInfoFilesTestCaseTest the drupal_parse_info_file() API function.
ValidUrlTestCaseTest for valid_url().

File

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