- <?php
- * @file
- * Tests for common.inc functionality.
- */
-
- * Tests for URL generation functions.
- */
- class CommonBackdropAlterTestCase extends BackdropWebTestCase {
- function setUp() {
- parent::setUp('common_test');
- }
-
- function testBackdropAlter() {
-
-
- global $theme, $base_theme_info;
- $theme = 'bartik';
- $base_theme_info = array();
-
- $array = array('foo' => 'bar');
- $entity = new stdClass();
- $entity->foo = 'bar';
-
-
- $array_copy = $array;
- $array_expected = array('foo' => 'Backdrop theme');
- backdrop_alter('backdrop_alter', $array_copy);
- $this->assertEqual($array_copy, $array_expected, 'Single array was altered.');
-
- $entity_copy = clone $entity;
- $entity_expected = clone $entity;
- $entity_expected->foo = 'Backdrop theme';
- backdrop_alter('backdrop_alter', $entity_copy);
- $this->assertEqual($entity_copy, $entity_expected, 'Single object was altered.');
-
-
- $array_copy = $array;
- $array_expected = array('foo' => 'Backdrop theme');
- $entity_copy = clone $entity;
- $entity_expected = clone $entity;
- $entity_expected->foo = 'Backdrop theme';
- $array2_copy = $array;
- $array2_expected = array('foo' => 'Backdrop theme');
- backdrop_alter('backdrop_alter', $array_copy, $entity_copy, $array2_copy);
- $this->assertEqual($array_copy, $array_expected, 'First argument to backdrop_alter() was altered.');
- $this->assertEqual($entity_copy, $entity_expected, 'Second argument to backdrop_alter() was altered.');
- $this->assertEqual($array2_copy, $array2_expected, 'Third argument to backdrop_alter() was altered.');
-
-
-
-
- $array_copy = $array;
- $array_expected = array('foo' => 'Backdrop block theme');
- backdrop_alter(array('backdrop_alter', 'backdrop_alter_foo'), $array_copy);
- $this->assertEqual($array_copy, $array_expected, 'hook_TYPE_alter() implementations ran in correct order.');
- }
- }
-
- * Tests for URL generation functions.
- *
- * url() calls module_implements(), which may issue a db query, which requires
- * inheriting from a web test case rather than a unit test case.
- */
- class CommonURLWebTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
-
- * Confirm that invalid text given as $path is filtered.
- */
- function testLXSS() {
- $text = $this->randomName();
- $path = "<SCRIPT>alert('XSS')</SCRIPT>";
- $link = l($text, $path);
- $sanitized_path = check_url(url($path));
- $this->assertTrue(strpos($link, $sanitized_path) !== FALSE, format_string('XSS attack @path was filtered', array('@path' => $path)));
- }
-
-
- * Tests for active class in l() function.
- */
- function testLActiveClass() {
- $link = l($this->randomName(), $_GET['q']);
- $this->assertTrue($this->hasClass($link, 'active'), format_string('Class @class is present on link to the current page', array('@class' => 'active')));
- }
-
-
- * Tests for custom class in l() function.
- */
- function testLCustomClass() {
- $class = $this->randomName();
- $link = l($this->randomName(), $_GET['q'], array('attributes' => array('class' => array($class))));
- $this->assertTrue($this->hasClass($link, $class), format_string('Custom class @class is present on link when requested', array('@class' => $class)));
- $this->assertTrue($this->hasClass($link, 'active'), format_string('Class @class is present on link to the current page', array('@class' => 'active')));
- }
-
- private function hasClass($link, $class) {
- return preg_match('|class="([^\"\s]+\s+)*' . $class . '|', $link);
- }
-
-
- * Test url() with/without query, with/without fragment, absolute on/off and
- * assert all that works when clean URLs are on and off.
- */
- function testUrl() {
- global $base_url;
-
- foreach (array(FALSE, TRUE) as $absolute) {
-
- $base = $absolute ? $base_url . '/' : base_path();
- $absolute_string = $absolute ? 'absolute' : NULL;
-
-
- config_set('system.core', 'clean_url', 0);
- backdrop_static_reset('url');
-
- $url = $base . '?q=node/123';
- $result = url('node/123', array('absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . '?q=node/123#foo';
- $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . '?q=node/123&foo';
- $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . '?q=node/123&foo=bar&bar=baz';
- $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . '?q=node/123&foo#bar';
- $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . '?q=node/123&foo#0';
- $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => '0', 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . '?q=node/123&foo';
- $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => '', 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base;
- $result = url('<front>', array('absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
-
- config_set('system.core', 'clean_url', 1);
- backdrop_static_reset('url');
-
- $url = $base . 'node/123';
- $result = url('node/123', array('absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . 'node/123#foo';
- $result = url('node/123', array('fragment' => 'foo', 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . 'node/123?foo';
- $result = url('node/123', array('query' => array('foo' => NULL), 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . 'node/123?foo=bar&bar=baz';
- $result = url('node/123', array('query' => array('foo' => 'bar', 'bar' => 'baz'), 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base . 'node/123?foo#bar';
- $result = url('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
-
- $url = $base;
- $result = url('<front>', array('absolute' => $absolute));
- $this->assertEqual($url, $result, "$url == $result");
- }
- }
-
-
- * Test external URL handling.
- */
- function testExternalUrls() {
- $test_url = 'https://backdropcms.org/';
-
-
- $url = $test_url . '#backdrop';
- $result = url($url);
- $this->assertEqual($url, $result, 'External URL with fragment works without a fragment in $options.');
-
-
- $url = $test_url . '#backdrop';
- $fragment = $this->randomName(10);
- $result = url($url, array('fragment' => $fragment));
- $this->assertEqual($test_url . '#' . $fragment, $result, 'External URL fragment is overidden with a custom fragment in $options.');
-
-
- $url = $test_url . '?backdrop=awesome';
- $result = url($url);
- $this->assertEqual($url, $result, 'External URL with query string works without a query string in $options.');
-
-
- $url = $test_url;
- $query = array($this->randomName(5) => $this->randomName(5));
- $result = url($url, array('query' => $query));
- $this->assertEqual($url . '?' . http_build_query($query, '', '&'), $result, 'External URL can be extended with a query string in $options.');
-
-
- $url = $test_url . '?backdrop=awesome';
- $query = array($this->randomName(5) => $this->randomName(5));
- $result = url($url, array('query' => $query));
- $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result, 'External URL query string can be extended with a custom query string in $options.');
-
-
-
- $url = '/backdropcms.org';
- $result = url($url);
- $this->assertTrue(strpos($result, '//') === FALSE, 'Internal URL does not turn into an external URL.');
-
-
- $url = '//backdropcms.org';
- $result = url($url);
- $this->assertEqual($url, $result, 'External URL without protocol is not altered.');
- }
-
-
- * Tests the url() function on internal paths which mimic external URLs.
- */
- function testInternalPathMimicsExternal() {
- module_enable(array('common_test'));
-
-
-
-
- state_set('common_test_link_to_current_path', TRUE);
- $this->backdropGet('/http://example.com');
- $this->clickLink('link which should point to the current path');
- $this->assertUrl('/http://example.com');
- $this->assertText('link which should point to the current path');
- }
- }
-
- * All URL testing that does not require a Backdrop bootstrap.
- */
- class CommonURLUnitTestCase extends BackdropUnitTestCase {
-
- * Test backdrop_get_query_parameters().
- */
- function testBackdropGetQueryParameters() {
- $original = array(
- 'a' => 1,
- 'b' => array(
- 'd' => 4,
- 'e' => array(
- 'f' => 5,
- ),
- ),
- 'c' => 3,
- 'q' => 'foo/bar',
- );
-
-
- $result = $_GET;
- unset($result['q']);
- $this->assertEqual(backdrop_get_query_parameters(), $result, "\$_GET['q'] was removed.");
-
-
- $result = $original;
- unset($result['q']);
- $this->assertEqual(backdrop_get_query_parameters($original), $result, "'q' was removed.");
-
-
- $result = $original;
- unset($result['b']);
- $this->assertEqual(backdrop_get_query_parameters($original, array('b')), $result, "'b' was removed.");
-
-
- $result = $original;
- unset($result['b']['d']);
- $this->assertEqual(backdrop_get_query_parameters($original, array('b[d]')), $result, "'b[d]' was removed.");
-
-
- $result = $original;
- unset($result['b']['e']['f']);
- $this->assertEqual(backdrop_get_query_parameters($original, array('b[e][f]')), $result, "'b[e][f]' was removed.");
-
-
- $result = $original;
- unset($result['a'], $result['b']['e'], $result['c']);
- $this->assertEqual(backdrop_get_query_parameters($original, array('a', 'b[e]', 'c')), $result, "'a', 'b[e]', 'c' were removed.");
- }
-
-
- * Test backdrop_http_build_query().
- */
- function testBackdropHttpBuildQuery() {
- $this->assertEqual(backdrop_http_build_query(array('a' => ' &#//+%20@۞')), 'a=%20%26%23//%2B%2520%40%DB%9E', 'Value was properly encoded.');
- $this->assertEqual(backdrop_http_build_query(array(' &#//+%20@۞' => 'a')), '%20%26%23//%2B%2520%40%DB%9E=a', 'Key was properly encoded.');
- $this->assertEqual(backdrop_http_build_query(array('a' => '1', 'b' => '2', 'c' => '3')), 'a=1&b=2&c=3', 'Multiple values were properly concatenated.');
- $this->assertEqual(backdrop_http_build_query(array('a' => array('b' => '2', 'c' => '3'), 'd' => 'foo')), 'a%5Bb%5D=2&a%5Bc%5D=3&d=foo', 'Nested array was properly encoded.');
- }
-
-
- * Test backdrop_get_bare_domain().
- */
- function testBackdropGetBareDomain() {
-
- $tests = array(
- 'http://www.example.com/path-to-page' => 'example.com',
- 'http://example.com/path-to-page' => 'example.com',
- 'http://beta.example.com/path-to-page' => 'example.com',
- 'https://www.beta.example.co.uk/path-to-page' => 'example.co.uk',
- 'http://example.co.uk/path-to-page' => 'example.co.uk',
- 'http://beta.example.co.uk/path-to-page' => 'example.co.uk',
- '//example.co.uk/path-to-page' => 'example.co.uk',
-
- 'example.co.uk' => 'example.co.uk',
- 'example.com' => 'example.com',
- 'beta.example.com' => 'example.com',
- 'alpha.beta.example.com' => 'example.com',
- 'bbc.co.uk' => 'bbc.co.uk',
- 'foo.bbc.co.uk' => 'bbc.co.uk',
- 'bar.foo.bbc.co.uk' => 'bbc.co.uk',
- 'bar.foo.abc.com' => 'abc.com',
- 'lb.cm' => 'lb.cm',
- );
-
- foreach ($tests as $input => $expected_output) {
- $this->assertIdentical($expected_output, backdrop_get_bare_domain($input));
- }
- }
-
-
- * Test backdrop_parse_url().
- */
- function testBackdropParseUrl() {
-
- $url = 'foo/bar?foo=bar&bar=baz&baz#foo';
- $result = array(
- 'path' => 'foo/bar',
- 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
- 'fragment' => 'foo',
- );
- $this->assertEqual(backdrop_parse_url($url), $result, 'Relative URL parsed correctly.');
-
-
- $url = 'foo/bar:1';
- $result = array(
- 'path' => 'foo/bar:1',
- 'query' => array(),
- 'fragment' => '',
- );
- $this->assertEqual(backdrop_parse_url($url), $result, 'Relative URL parsed correctly.');
-
-
- $url = '/foo/bar?foo=bar&bar=baz&baz#foo';
- $result = array(
- 'path' => '/foo/bar',
- 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
- 'fragment' => 'foo',
- );
- $this->assertEqual(backdrop_parse_url($url), $result, 'Absolute URL parsed correctly.');
-
-
- $url = 'https://backdropcms.org/foo/bar?foo=bar&bar=baz&baz#foo';
-
-
-
- $this->assertTrue(url_is_external($url), 'Correctly identified an external URL.');
-
-
- $url = '//backdropcms.org/foo/bar?foo=bar&bar=baz&baz#foo';
- $this->assertTrue(url_is_external($url), 'Correctly identified an external URL without a protocol part.');
-
-
- $url = '/backdropcms.org';
- $this->assertFalse(url_is_external($url), 'Correctly identified an internal URL with a leading slash.');
-
-
- $url = 'https://backdropcms.org/foo/bar?foo=bar&bar=baz&baz#foo';
- $result = array(
- 'path' => 'https://backdropcms.org/foo/bar',
- 'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
- 'fragment' => 'foo',
- );
- $this->assertEqual(backdrop_parse_url($url), $result, 'External URL parsed correctly.');
-
-
- $result = array(
- 'path' => 'foo/bar',
- 'query' => array('bar' => 'baz'),
- 'fragment' => 'foo',
- );
-
- $url = $GLOBALS['base_url'] . '/?q=foo/bar&bar=baz#foo';
- $this->assertEqual(backdrop_parse_url($url), $result, 'Absolute URL with clean URLs disabled parsed correctly.');
-
-
- $url = '?q=foo/bar&bar=baz#foo';
- $this->assertEqual(backdrop_parse_url($url), $result, 'Relative URL with clean URLs disabled parsed correctly.');
-
-
- $url = 'index.php?q=foo/bar&bar=baz#foo';
- $this->assertEqual(backdrop_parse_url($url), $result, 'Relative URL on non-Apache webserver with clean URLs disabled parsed correctly.');
-
-
- $parts = backdrop_parse_url('forged:http://cwe.mitre.org/data/definitions/601.html');
- $this->assertFalse(valid_url($parts['path'], TRUE), 'backdrop_parse_url() correctly parsed a forged URL.');
- }
- }
-
- * Tests url_is_external().
- */
- class UrlIsExternalUnitTest extends BackdropUnitTestCase {
-
- * Tests if each URL is external or not.
- */
- function testUrlIsExternal() {
- foreach ($this->examples() as $path => $expected) {
- $this->assertIdentical(url_is_external($path), $expected, $path);
- }
- }
-
-
- * Provides data for testUrlIsExternal().
- *
- * @return array
- * An array of test data, keyed by a path, with the expected value where
- * TRUE is external, and FALSE is not external.
- */
- protected function examples() {
- return array(
-
- 'http://example.com' => TRUE,
- 'https://example.com' => TRUE,
- 'http://example.org/foo/bar?foo=bar&bar=baz&baz#foo' => TRUE,
- '//example.org' => TRUE,
-
- "\x00//www.example.com" => TRUE,
- "\x08//www.example.com" => TRUE,
- "\x1F//www.example.com" => TRUE,
- "\n//www.example.com" => TRUE,
-
- json_decode('"\u00AD"') . "//www.example.com" => TRUE,
- json_decode('"\u200E"') . "//www.example.com" => TRUE,
- json_decode('"\uE0020"') . "//www.example.com" => TRUE,
- json_decode('"\uE000"') . "//www.example.com" => TRUE,
-
- '\\\\example.com' => TRUE,
-
- 'node' => FALSE,
- '/system/ajax' => FALSE,
- '?q=foo:bar' => FALSE,
- 'node/edit:me' => FALSE,
- '/example.org' => FALSE,
- '<front>' => FALSE,
- );
- }
- }
-
- * Tests for check_plain(), filter_xss(), format_string(), and check_url().
- */
- class CommonXssUnitTestCase extends BackdropUnitTestCase {
-
- * Check that invalid multi-byte sequences are rejected.
- */
- function testInvalidMultiByte() {
-
- $text = @check_plain("Foo\xC0barbaz");
- $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "Foo\xC0barbaz"');
-
- $text = @check_plain("\xc2\"");
- $this->assertEqual($text, '', 'check_plain() rejects invalid sequence "\xc2\""');
- $text = check_plain("Fooÿñ");
- $this->assertEqual($text, "Fooÿñ", 'check_plain() accepts valid sequence "Fooÿñ"');
- $text = filter_xss("Foo\xC0barbaz");
- $this->assertEqual($text, '', 'filter_xss() rejects invalid sequence "Foo\xC0barbaz"');
- $text = filter_xss("Fooÿñ");
- $this->assertEqual($text, "Fooÿñ", 'filter_xss() accepts valid sequence Fooÿñ');
- }
-
-
- * Check that special characters are escaped.
- */
- function testEscaping() {
- $text = check_plain("<script>");
- $this->assertEqual($text, '<script>', 'check_plain() escapes <script>');
- $text = check_plain('<>&"\'');
- $this->assertEqual($text, '<>&"'', 'check_plain() escapes reserved HTML characters.');
- }
-
-
- * Test t() and format_string() replacement functionality.
- */
- function testFormatStringAndT() {
- foreach (array('format_string', 't') as $function) {
- $text = $function('Simple text');
- $this->assertEqual($text, 'Simple text', $function . ' leaves simple text alone.');
- $text = $function('Escaped text: @value', array('@value' => '<script>'));
- $this->assertEqual($text, 'Escaped text: <script>', $function . ' replaces and escapes string.');
- $text = $function('Placeholder text: %value', array('%value' => '<script>'));
- $this->assertEqual($text, 'Placeholder text: <em class="placeholder"><script></em>', $function . ' replaces, escapes and themes string.');
- $text = $function('Verbatim text: !value', array('!value' => '<script>'));
- $this->assertEqual($text, 'Verbatim text: <script>', $function . ' replaces verbatim string as-is.');
- }
- }
-
-
- * Check that harmful protocols are stripped.
- */
- function testBadProtocolStripping() {
-
-
-
- $url = 'javascript:http://www.example.com/?x=1&y=2';
- $expected_plain = 'http://www.example.com/?x=1&y=2';
- $expected_html = 'http://www.example.com/?x=1&y=2';
- $this->assertIdentical(check_url($url), $expected_html, 'check_url() filters a URL and encodes it for HTML.');
- $this->assertIdentical(backdrop_strip_dangerous_protocols($url), $expected_plain, 'backdrop_strip_dangerous_protocols() filters a URL and returns plain text.');
- }
- }
-
- * Tests file size parsing and formatting functions.
- */
- class CommonSizeUnitTestCase extends BackdropUnitTestCase {
- protected $exact_test_cases;
- protected $rounded_test_cases;
-
- function setUp() {
- $kb = BACKDROP_KILOBYTE;
- $this->exact_test_cases = array(
- '1 byte' => 1,
- '1 KB' => $kb,
- '1 MB' => $kb * $kb,
- '1 GB' => $kb * $kb * $kb,
- '1 TB' => $kb * $kb * $kb * $kb,
- '1 PB' => $kb * $kb * $kb * $kb * $kb,
- '1 EB' => $kb * $kb * $kb * $kb * $kb * $kb,
- '1 ZB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
- '1 YB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
- );
- $this->rounded_test_cases = array(
- '2 bytes' => 2,
- '1 MB' => ($kb * $kb) - 1,
- round(3623651 / ($this->exact_test_cases['1 MB']), 2) . ' MB' => 3623651,
- round(67234178751368124 / ($this->exact_test_cases['1 PB']), 2) . ' PB' => 67234178751368124,
- round(235346823821125814962843827 / ($this->exact_test_cases['1 YB']), 2) . ' YB' => 235346823821125814962843827,
- );
- parent::setUp();
- }
-
-
- * Check that format_size() returns the expected string.
- */
- function testCommonFormatSize() {
- foreach (array($this->exact_test_cases, $this->rounded_test_cases) as $test_cases) {
- foreach ($test_cases as $expected => $input) {
- $this->assertEqual(
- ($result = format_size($input, NULL)),
- $expected,
- $expected . ' == ' . $result . ' (' . $input . ' bytes)'
- );
- }
- }
- }
-
-
- * Check that parse_size() returns the proper byte sizes.
- */
- function testCommonParseSize() {
- foreach ($this->exact_test_cases as $string => $size) {
- $this->assertEqual(
- $parsed_size = parse_size($string),
- $size,
- $size . ' == ' . $parsed_size . ' (' . $string . ')'
- );
- }
-
-
- $string = '23476892 bytes';
- $this->assertEqual(
- ($parsed_size = parse_size($string)),
- $size = 23476892,
- $string . ' == ' . $parsed_size . ' bytes'
- );
- $string = '76MRandomStringThatShouldBeIgnoredByParseSize.';
- $this->assertEqual(
- $parsed_size = parse_size($string),
- $size = 79691776,
- $string . ' == ' . $parsed_size . ' bytes'
- );
- $string = '76.24 Giggabyte';
- $this->assertEqual(
- $parsed_size = parse_size($string),
- $size = 81862076662,
- $string . ' == ' . $parsed_size . ' bytes'
- );
- }
-
-
- * Cross-test parse_size() and format_size().
- */
- function testCommonParseSizeFormatSize() {
- foreach ($this->exact_test_cases as $size) {
- $this->assertEqual(
- $size,
- ($parsed_size = parse_size($string = format_size($size, NULL))),
- $size . ' == ' . $parsed_size . ' (' . $string . ')'
- );
- }
- }
- }
-
- * Test backdrop_explode_tags() and backdrop_implode_tags().
- */
- class CommonAutocompleteTagsTestCase extends BackdropUnitTestCase {
- var $validTags = array(
- 'Backdrop' => 'Backdrop',
- 'Backdrop with some spaces' => 'Backdrop with some spaces',
- '"Inside of quotes: ""Backdrop"""' => 'Inside of quotes: "Backdrop"',
- '"Remove quotes"' => 'Remove quotes',
- );
-
-
- * Explode a series of tags.
- */
- function testBackdropExplodeTags() {
- $string = implode(', ', array_keys($this->validTags));
- $tags = backdrop_explode_tags($string);
- $this->assertTags($tags);
- }
-
-
- * Implode a series of tags.
- */
- function testBackdropImplodeTags() {
- $tags = array_values($this->validTags);
-
- for ($i = 0; $i < 10; $i++) {
- $string = backdrop_implode_tags($tags);
- $tags = backdrop_explode_tags($string);
- }
- $this->assertTags($tags);
- }
-
-
- * Helper function: asserts that the ending array of tags is what we wanted.
- */
- function assertTags($tags) {
- $original = $this->validTags;
- foreach ($tags as $tag) {
- $key = array_search($tag, $original);
- $this->assertTrue($key, format_string('Make sure tag %tag shows up in the final tags array (originally %original)', array('%tag' => $tag, '%original' => $key)));
- unset($original[$key]);
- }
- foreach ($original as $leftover) {
- $this->fail(format_string('Leftover tag %leftover was left over.', array('%leftover' => $leftover)));
- }
- }
- }
-
- * Test the Backdrop CSS system.
- */
- class CommonCascadingStylesheetsTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('language', 'common_test');
-
- backdrop_static_reset('backdrop_add_css');
- }
-
-
- * Check default stylesheets as empty.
- */
- function testDefault() {
- $this->assertEqual(array(), backdrop_add_css(), 'Default CSS is empty.');
- }
-
-
- * Test that stylesheets in module .info files are loaded.
- */
- function testModuleInfo() {
- $this->backdropGet('');
-
-
- $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
- ':media' => 'all',
- ':filename' => 'tests/common_test.css',
- ));
- $this->assertTrue(count($elements), "Stylesheet with media 'all' in module .info file found.");
-
-
- $elements = $this->xpath('//style[@media=:media and contains(text(), :filename)]', array(
- ':media' => 'print',
- ':filename' => 'tests/common_test.print.css',
- ));
- $this->assertTrue(count($elements), "Stylesheet with media 'print' in module .info file found.");
- }
-
-
- * Tests adding a file stylesheet.
- */
- function testAddFile() {
- $path = backdrop_get_path('module', 'simpletest') . '/css/simpletest.css';
- $css = backdrop_add_css($path);
- $this->assertEqual($css[$path]['data'], $path, 'Adding a CSS file caches it properly.');
- }
-
-
- * Tests adding an external stylesheet.
- */
- function testAddExternal() {
- $path = 'http://example.com/style.css';
- $css = backdrop_add_css($path, 'external');
- $this->assertEqual($css[$path]['type'], 'external', 'Adding an external CSS file caches it properly.');
- }
-
-
- * Makes sure that reseting the CSS empties the cache.
- */
- function testReset() {
- backdrop_static_reset('backdrop_add_css');
- $this->assertEqual(array(), backdrop_add_css(), 'Resetting the CSS empties the cache.');
- }
-
-
- * Tests rendering the stylesheets.
- */
- function testRenderFile() {
- $css = backdrop_get_path('module', 'simpletest') . '/css/simpletest.css';
- backdrop_add_css($css);
- $styles = backdrop_get_css();
- $this->assertTrue(strpos($styles, $css) > 0, 'Rendered CSS includes the added stylesheet.');
-
- $query_string = state_get('css_js_query_string', '0');
- $css_processed = "<style media=\"all\">\n@import url(\"" . check_plain(file_create_url($css)) . "?" . $query_string ."\");\n</style>";
- $this->assertEqual(trim($styles), $css_processed, t('Rendered CSS includes newlines inside style tags for JavaScript use.'));
- }
-
-
- * Tests rendering an external stylesheet.
- */
- function testRenderExternal() {
- $css = 'http://example.com/style.css';
- backdrop_add_css($css, 'external');
- $styles = backdrop_get_css();
-
-
- $this->assertTrue(strpos($styles, 'href="' . $css) > 0 || strpos($styles, '@import url("' . $css . '")') > 0, 'Rendering an external CSS file.');
- }
-
-
- * Tests rendering inline stylesheets with preprocessing on.
- */
- function testRenderInlinePreprocess() {
- $css = 'body { padding: 0px; }';
- $css_preprocessed = '<style media="all">' . backdrop_load_stylesheet_content($css, TRUE) . '</style>';
- backdrop_add_css($css, array('type' => 'inline'));
- $styles = backdrop_get_css();
- $this->assertEqual(trim($styles), $css_preprocessed, 'Rendering preprocessed inline CSS adds it to the page.');
-
- }
-
-
- * Tests removing charset when rendering stylesheets with preprocessing on.
- */
- function testRenderRemoveCharsetPreprocess() {
- $cases = array(
- array(
- 'asset' => '@charset "UTF-8";html{font-family:"sans-serif";}',
- 'expected' => 'html{font-family:"sans-serif";}',
- ),
-
- array(
- 'asset' => "@charset 'UTF-8';\nhtml{font-family:'sans-serif';}",
- 'expected' => "\nhtml{font-family:'sans-serif';}",
- ),
- );
-
- foreach ($cases as $case) {
- $this->assertEqual(
- $case['expected'],
- backdrop_load_stylesheet_content($case['asset']),
- 'CSS optimizing correctly removes the charset declaration.'
- );
- }
- }
-
-
- * Tests rendering inline stylesheets with preprocessing off.
- */
- function testRenderInlineNoPreprocess() {
- $css = 'body { padding: 0px; }';
- backdrop_add_css($css, array('type' => 'inline', 'preprocess' => FALSE));
- $styles = backdrop_get_css();
- $this->assertTrue(strpos($styles, $css) > 0, 'Rendering non-preprocessed inline CSS adds it to the page.');
- }
-
-
- * Tests rendering inline stylesheets through a full page request.
- *
- * @see common_test_render_inline_full_page()
- */
- function testRenderInlineFullPage() {
-
-
- $expected = 'body{font-size:254px;}';
-
-
- $this->backdropGet('common-test/css-render-inline-full-page');
- $this->assertRaw($expected, 'Inline stylesheets appear in the full page rendering.');
- }
-
-
- * Test CSS ordering.
- */
- function testRenderOrder() {
-
- backdrop_add_css(backdrop_get_path('module', 'simpletest') . '/css/simpletest.css');
-
- $system_path = backdrop_get_path('module', 'system');
- backdrop_add_css($system_path . '/css/system.css', array('group' => CSS_SYSTEM, 'weight' => -10));
- backdrop_add_css($system_path . '/css/system.theme.css', array('group' => CSS_SYSTEM));
-
- $expected = array(
- $system_path . '/css/system.css',
- $system_path . '/css/system.theme.css',
- backdrop_get_path('module', 'simpletest') . '/css/simpletest.css',
- );
-
-
- $styles = backdrop_get_css();
-
-
- if (preg_match_all('/(href="|url\(")' . preg_quote($GLOBALS['base_url'] . '/', '/') . '([^?]+)\?/', $styles, $matches)) {
- $result = $matches[2];
- }
- else {
- $result = array();
- }
-
- $this->assertIdentical($result, $expected, 'The CSS files are in the expected order.');
- }
-
-
- * Test CSS override.
- */
- function testRenderOverride() {
- $system = backdrop_get_path('module', 'system');
- $simpletest = backdrop_get_path('module', 'simpletest');
-
- backdrop_add_css($system . '/css/system.css');
- backdrop_add_css($simpletest . '/tests/system.css');
-
-
- $styles = backdrop_get_css();
- $this->assert(strpos($styles, $simpletest . '/tests/system.css') !== FALSE, 'The overriding CSS file is output.');
- $this->assert(strpos($styles, $system . '/css/system.css') === FALSE, 'The overridden CSS file is not output.');
-
- backdrop_static_reset('backdrop_add_css');
- backdrop_add_css($simpletest . '/tests/system.css');
- backdrop_add_css($system . '/css/system.css');
-
-
- $styles = backdrop_get_css();
- $this->assert(strpos($styles, $system . '/css/system.css') !== FALSE, 'The overriding CSS file is output.');
- $this->assert(strpos($styles, $simpletest . '/tests/system.css') === FALSE, 'The overridden CSS file is not output.');
- }
-
-
- * Test CSS Styles with attributes rendering.
- */
- function testRenderStylesAttributes() {
-
- config_set('system.core', 'preprocess_css', 0);
-
-
-
- $css_internal = 'core/misc/print.css';
- $css_external = 'http://example.com/styles.css';
- backdrop_add_css($css_internal, array('attributes' => array('custom' => 'foo')));
- backdrop_add_css($css_external, array(
- 'attributes' => array(
- 'custom' => 'foo',
- ),
- 'type' => 'external',
- ));
- $css = backdrop_get_css();
- $this->backdropSetContent($css);
- $this->assertTrue($this->xpath('//link[starts-with(@href, "' . file_create_url($css_internal) . '") and @custom="foo"]'), 'Rendered internal CSS with correct custom attribute.');
- $this->assertTrue($this->xpath('//link[@href="' . $css_external . '" and @custom="foo"]'), 'Rendered external CSS with correct custom attribute.');
- }
-
-
- * Tests that the query string remains intact when adding CSS files that have
- * query string parameters.
- */
- function testAddCssFileWithQueryString() {
- $this->backdropGet('common-test/query-string');
- $query_string = state_get('css_js_query_string', '0');
- $this->assertRaw(backdrop_get_path('module', 'node') . '/css/node.admin.css?' . $query_string, 'Query string was appended correctly to css.');
- $this->assertRaw(backdrop_get_path('module', 'node') . '/node-fake.css?arg1=value1&arg2=value2', 'Query string not escaped on a URI.');
- }
- }
-
- * Test for cleaning HTML identifiers.
- */
- class CommonHTMLIdentifierTestCase extends BackdropUnitTestCase {
-
- * Tests that backdrop_clean_css_identifier() cleans the identifier properly.
- */
- function testBackdropCleanCSSIdentifier() {
-
- $identifier = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
- $this->assertIdentical(backdrop_clean_css_identifier($identifier, array()), $identifier, 'Verify valid ASCII characters pass through.');
-
-
- $identifier = '¡¢£¤¥';
- $this->assertIdentical(backdrop_clean_css_identifier($identifier, array()), $identifier, 'Verify valid UTF-8 characters pass through.');
-
-
- $this->assertIdentical(backdrop_clean_css_identifier('invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', array()), 'invalididentifier', 'Strip invalid characters.');
- }
-
-
- * Tests that backdrop_html_class() cleans the class name properly.
- */
- function testBackdropHTMLClass() {
-
- $this->assertIdentical(backdrop_html_class('CLASS NAME_[Ü]'), 'class-name--ü', 'Enforce Backdrop coding standards.');
- }
-
-
- * Tests that backdrop_html_id() cleans the ID properly.
- */
- function testBackdropHTMLId() {
-
- $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
- $this->assertIdentical(backdrop_html_id($id), $id, 'Verify valid characters pass through.');
-
-
- $this->assertIdentical(backdrop_html_id('invalid,./:@\\^`{Üidentifier'), 'invalididentifier', 'Strip invalid characters.');
-
-
- $this->assertIdentical(backdrop_html_id('ID NAME_[1]'), 'id-name-1', 'Enforce Backdrop coding standards.');
-
-
- backdrop_static_reset('backdrop_html_id');
-
-
- $this->assertIdentical(backdrop_html_id('test-unique-id'), 'test-unique-id', 'Test the uniqueness of IDs #1.');
- $this->assertIdentical(backdrop_html_id('test-unique-id'), 'test-unique-id--2', 'Test the uniqueness of IDs #2.');
- $this->assertIdentical(backdrop_html_id('test-unique-id'), 'test-unique-id--3', 'Test the uniqueness of IDs #3.');
- }
- }
-
- * CSS Unit Tests.
- */
- class CommonCascadingStylesheetsUnitTestCase extends BackdropUnitTestCase {
-
- * Tests basic CSS loading with and without optimization via backdrop_load_stylesheet().
- *
- * Known tests:
- * - Retain white-space in selectors. (https://drupal.org/node/472820)
- * - Proper URLs in imported files. (https://drupal.org/node/265719)
- * - Retain pseudo-selectors. (https://drupal.org/node/460448)
- * - Don't adjust data URIs. (https://drupal.org/node/2142441)
- */
- function testLoadCssBasic() {
-
-
-
-
- $testfiles = array(
- 'css_input_without_import.css',
- 'css_input_with_import.css',
- 'css_subfolder/css_input_with_import.css',
- 'comment_hacks.css'
- );
- $path = backdrop_get_path('module', 'simpletest') . '/files/css_test_files';
- foreach ($testfiles as $file) {
- $file_path = $path . '/' . $file;
- $file_url = $GLOBALS['base_url'] . '/' . $file_path;
-
- $expected = file_get_contents($file_path . '.unoptimized.css');
- $unoptimized_output = backdrop_load_stylesheet($file_path, FALSE);
- $this->assertEqual($unoptimized_output, $expected, format_string('Unoptimized CSS file has expected contents (@file)', array('@file' => $file)));
-
- $expected = file_get_contents($file_path . '.optimized.css');
- $optimized_output = backdrop_load_stylesheet($file_path, TRUE);
- $this->assertEqual($optimized_output, $expected, format_string('Optimized CSS file has expected contents (@file)', array('@file' => $file)));
-
-
- $expected = file_get_contents($file_path . '.unoptimized.css');
- $unoptimized_output_url = backdrop_load_stylesheet($file_url, FALSE);
- $this->assertEqual($unoptimized_output_url, $expected, format_string('Unoptimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
-
- $expected = file_get_contents($file_path . '.optimized.css');
- $optimized_output_url = backdrop_load_stylesheet($file_url, TRUE);
- $this->assertEqual($optimized_output_url, $expected, format_string('Optimized CSS file (loaded from an URL) has expected contents (@file)', array('@file' => $file)));
- }
- }
- }
-
- * Test backdrop_http_request().
- */
- class CommonBackdropHTTPRequestTestCase extends BackdropWebTestCase {
- function setUp() {
- parent::setUp('system_test', 'locale');
- }
-
- function testBackdropHTTPRequest() {
- global $is_https;
-
-
- $missing_scheme = backdrop_http_request('example.com/path');
- $this->assertEqual($missing_scheme->code, -1002, 'Returned with "-1002" error code.');
- $this->assertEqual($missing_scheme->error, 'missing schema', 'Returned with "missing schema" error message.');
-
- $unable_to_parse = backdrop_http_request('http:///path');
- $this->assertEqual($unable_to_parse->code, -1001, 'Returned with "-1001" error code.');
- $this->assertEqual($unable_to_parse->error, 'unable to parse URL', 'Returned with "unable to parse URL" error message.');
-
-
-
- $data_array = array($this->randomName() => $this->randomString() . ' "\'');
- $data_string = backdrop_http_build_query($data_array);
- $result = backdrop_http_request(url('node', array('absolute' => TRUE)), array('data' => $data_array));
- $this->assertEqual($result->code, 200, 'Fetched page successfully.');
- $this->assertTrue(substr($result->request, -strlen($data_string)) === $data_string, 'Request ends with URL-encoded data when drupal_http_request() is called using an array.');
- $result = backdrop_http_request(url('node', array('absolute' => TRUE)), array('data' => $data_string));
- $this->assertTrue(substr($result->request, -strlen($data_string)) === $data_string, 'Request ends with URL-encoded data when drupal_http_request() is called using a string.');
-
- $this->backdropSetContent($result->data);
- $this->assertTitle(t('Home | @site-name', array('@site-name' => config_get_translated('system.core', 'site_name'))), 'Site title matches.');
-
-
- $result = backdrop_http_request(url('pagedoesnotexist', array('absolute' => TRUE)));
- $this->assertTrue(!empty($result->protocol), 'Result protocol is returned.');
- $this->assertEqual($result->code, '404', 'Result code is 404');
- $this->assertEqual($result->status_message, 'Not Found', 'Result status message is "Not Found"');
-
-
-
-
- if (!$is_https) {
-
-
-
-
-
-
- timer_start(__METHOD__);
- $result = backdrop_http_request(url('system-test/sleep/10', array('absolute' => TRUE)), array('timeout' => 2));
- $time = timer_read(__METHOD__) / 1000;
- $this->assertTrue(1.8 < $time && $time < 5, format_string('Request timed out (%time seconds).', array('%time' => $time)));
- $this->assertTrue($result->error, 'An error message was returned.');
- $this->assertEqual($result->code, HTTP_REQUEST_TIMEOUT, 'Proper error code was returned.');
- }
- }
-
- function testBackdropHTTPRequestBasicAuth() {
- $username = $this->randomName();
- $password = $this->randomName();
- $url = url('system-test/auth', array('absolute' => TRUE));
-
- $auth = str_replace('://', '://' . $username . ':' . $password . '@', $url);
- $result = backdrop_http_request($auth);
-
- $this->backdropSetContent($result->data);
- $this->assertRaw($username, 'Username is passed correctly.');
- $this->assertRaw($password, 'Password is passed correctly.');
- }
-
- function testBackdropHTTPRequestRedirect() {
- $redirect_301 = backdrop_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($redirect_301->redirect_code, 301, 'backdrop_http_request follows the 301 redirect.');
-
- $redirect_301 = backdrop_http_request(url('system-test/redirect/301', array('absolute' => TRUE)), array('max_redirects' => 0));
- $this->assertFalse(isset($redirect_301->redirect_code), 'backdrop_http_request does not follow 301 redirect if max_redirects = 0.');
-
- $redirect_invalid = backdrop_http_request(url('system-test/redirect-noscheme', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($redirect_invalid->code, -1002, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
- $this->assertEqual($redirect_invalid->error, 'missing schema', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
-
- $redirect_invalid = backdrop_http_request(url('system-test/redirect-noparse', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($redirect_invalid->code, -1001, format_string('301 redirect to invalid URL returned with error message code "!error".', array('!error' => $redirect_invalid->error)));
- $this->assertEqual($redirect_invalid->error, 'unable to parse URL', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
-
- $redirect_invalid = backdrop_http_request(url('system-test/redirect-invalid-scheme', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($redirect_invalid->code, -1003, format_string('301 redirect to invalid URL returned with error code !error.', array('!error' => $redirect_invalid->error)));
- $this->assertEqual($redirect_invalid->error, 'invalid schema ftp', format_string('301 redirect to invalid URL returned with error message "!error".', array('!error' => $redirect_invalid->error)));
-
- $redirect_302 = backdrop_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($redirect_302->redirect_code, 302, 'backdrop_http_request follows the 302 redirect.');
-
- $redirect_302 = backdrop_http_request(url('system-test/redirect/302', array('absolute' => TRUE)), array('max_redirects' => 0));
- $this->assertFalse(isset($redirect_302->redirect_code), 'backdrop_http_request does not follow 302 redirect if $retry = 0.');
-
- $redirect_307 = backdrop_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($redirect_307->redirect_code, 307, 'backdrop_http_request follows the 307 redirect.');
-
- $redirect_307 = backdrop_http_request(url('system-test/redirect/307', array('absolute' => TRUE)), array('max_redirects' => 0));
- $this->assertFalse(isset($redirect_307->redirect_code), 'backdrop_http_request does not follow 307 redirect if max_redirects = 0.');
-
- $multiple_redirect_final_url = url('system-test/multiple-redirects/0', array('absolute' => TRUE));
- $multiple_redirect_1 = backdrop_http_request(url('system-test/multiple-redirects/1', array('absolute' => TRUE)), array('max_redirects' => 1));
- $this->assertEqual($multiple_redirect_1->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 1 redirect.');
-
- $multiple_redirect_3 = backdrop_http_request(url('system-test/multiple-redirects/3', array('absolute' => TRUE)), array('max_redirects' => 3));
- $this->assertEqual($multiple_redirect_3->redirect_url, $multiple_redirect_final_url, 'redirect_url contains the final redirection location after 3 redirects.');
- }
-
-
- * Tests Content-language headers generated by Backdrop.
- */
- function testBackdropHTTPRequestHeaders() {
-
- $request = backdrop_http_request(url('<front>', array('absolute' => TRUE)));
- $this->assertEqual($request->headers['content-language'], 'en', t('Content-Language HTTP header is English.'));
-
-
- $language = (object) array(
- 'langcode' => 'fr',
- 'name' => 'French',
- );
- language_save($language);
-
-
- $request = backdrop_http_request(url('<front>', array('absolute' => TRUE, 'language' => $language)));
- $this->assertEqual($request->headers['content-language'], 'fr', t('Content-Language HTTP header is French.'));
- }
- }
-
- * Tests parsing of the HTTP response status line.
- *
- * @see _backdrop_parse_response_status()
- */
- class CommonBackdropHTTPResponseStatusLineTest extends BackdropUnitTestCase {
-
- * Tests parsing HTTP response status line.
- */
- public function testStatusLine() {
-
- $data = $this->statusLineData();
- foreach($data as $test_case) {
- $test_data = array_shift($test_case);
- $expected = array_shift($test_case);
-
- $outcome = _backdrop_parse_response_status($test_data);
-
- foreach(array_keys($expected) as $key) {
- $this->assertIdentical($outcome[$key], $expected[$key]);
- }
- }
- }
-
-
- * Data provider for testStatusLine().
- *
- * @return array
- * Test data.
- */
- protected function statusLineData() {
- return array(
- array(
- 'HTTP/1.1 200 OK',
- array(
- 'http_version' => 'HTTP/1.1',
- 'response_code' => '200',
- 'reason_phrase' => 'OK',
- ),
- ),
-
- array(
- 'HTTP/1.1 200',
- array(
- 'http_version' => 'HTTP/1.1',
- 'response_code' => '200',
- 'reason_phrase' => '',
- ),
- ),
-
- array(
- 'version code multi word explanation',
- array(
- 'http_version' => 'version',
- 'response_code' => 'code',
- 'reason_phrase' => 'multi word explanation',
- ),
- ),
- );
- }
- }
-
-
- * Tests backdrop_goto() and hook_backdrop_goto_alter().
- */
- class CommonBackdropGotoTestCase extends BackdropWebTestCase {
- function setUp() {
- parent::setUp('common_test');
- }
-
-
- * Test backdrop_goto().
- */
- function testBackdropGoto() {
- $this->backdropGet('common-test/backdrop_goto/redirect');
- $headers = $this->backdropGetHeaders(TRUE);
- list(, $status) = explode(' ', $headers[0][':status'], 3);
- $this->assertEqual($status, 302, 'Expected response code was sent.');
- $this->assertText('backdrop_goto', 'Backdrop goto redirect succeeded.');
- $this->assertEqual($this->getUrl(), url('common-test/backdrop_goto', array('absolute' => TRUE)), 'Backdrop goto redirected to expected URL.');
-
-
- state_set('common_test_redirect_current_path', TRUE);
- $this->backdropGet('', array('query' => array('q' => 'http://www.example.com/')));
- $headers = $this->backdropGetHeaders(TRUE);
- list(, $status) = explode(' ', $headers[0][':status'], 3);
- $this->assertEqual($status, 302, 'Expected response code was sent.');
- $this->assertNotEqual($this->getUrl(), 'http://www.example.com/', 'Backdrop goto did not redirect to external URL.');
- $this->assertTrue(strpos($this->getUrl(), url('<front>', array('absolute' => TRUE))) === 0, 'Backdrop redirected to itself.');
- state_del('common_test_redirect_current_path');
-
- $this->backdropGet('common-test/backdrop_goto/redirect_advanced');
- $headers = $this->backdropGetHeaders(TRUE);
- list(, $status) = explode(' ', $headers[0][':status'], 3);
- $this->assertEqual($status, 301, 'Expected response code was sent.');
- $this->assertText('backdrop_goto', 'Backdrop goto redirect succeeded.');
- $this->assertEqual($this->getUrl(), url('common-test/backdrop_goto', array('query' => array('foo' => '123'), 'absolute' => TRUE)), 'Backdrop goto redirected to expected URL.');
-
-
-
- $destination = 'common-test/backdrop_goto/destination?foo=%2525&bar=123';
- $this->backdropGet('common-test/backdrop_goto/redirect', array('query' => array('destination' => $destination)));
- $this->assertText('backdrop_goto', 'Backdrop goto redirect with destination succeeded.');
- $this->assertEqual($this->getUrl(), url('common-test/backdrop_goto/destination', array('query' => array('foo' => '%25', 'bar' => '123'), 'absolute' => TRUE)), 'Backdrop goto redirected to given query string destination.');
- }
-
-
- * Test hook_backdrop_goto_alter().
- */
- function testBackdropGotoAlter() {
- $this->backdropGet('common-test/backdrop_goto/redirect_fail');
-
- $this->assertNoText(t("Backdrop goto failed to stop program"), 'Backdrop goto stopped program.');
- $this->assertNoText('backdrop_goto_fail', 'Backdrop goto redirect failed.');
- }
-
-
- * Test backdrop_get_destination().
- */
- function testBackdropGetDestination() {
- $query = $this->randomName(10);
-
-
- $this->backdropGet('common-test/destination', array('query' => array('destination' => $query)));
- $this->assertText('The destination: ' . $query, 'The given query string destination is determined as destination.');
-
-
- $this->backdropGet('common-test/destination', array('query' => array($query => NULL)));
- $url = 'common-test/destination?' . $query;
- $this->assertText('The destination: ' . $url, 'The current path is determined as destination.');
- }
- }
-
- * Tests for the JavaScript system.
- */
- class CommonJavaScriptTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- * Store configured value for JavaScript preprocessing.
- */
- protected $preprocess_js = NULL;
-
- function setUp() {
-
- parent::setUp('locale', 'simpletest', 'common_test');
-
-
- $this->preprocess_js = config_get('system.core', 'preprocess_js');
- config_set('system.core', 'preprocess_js', 0);
-
-
- backdrop_static_reset('backdrop_add_js');
- backdrop_static_reset('backdrop_add_library');
- }
-
- function tearDown() {
-
- config_set('system.core', 'preprocess_js', $this->preprocess_js);
- parent::tearDown();
- }
-
-
- * Test default JavaScript is empty.
- */
- function testDefault() {
- $this->assertEqual(array(), backdrop_add_js(), 'Default JavaScript is empty.');
- }
-
-
- * Test adding a JavaScript file.
- */
- function testAddFile() {
- $javascript = backdrop_add_js('core/misc/collapse.js');
- $this->assertTrue(array_key_exists('core/misc/jquery.js', $javascript), 'jQuery is added when a file is added.');
- $this->assertTrue(array_key_exists('core/misc/backdrop.js', $javascript), 'Backdrop.js is added when file is added.');
- $this->assertTrue(array_key_exists('core/misc/html5.js', $javascript), 'html5.js is added when file is added.');
- $this->assertTrue(array_key_exists('core/misc/collapse.js', $javascript), 'JavaScript files are correctly added.');
- $this->assertEqual(base_path(), $javascript['settings']['data'][0]['basePath'], 'Base path JavaScript setting is correctly set.');
- url('', array('prefix' => &$prefix));
- $this->assertEqual(empty($prefix) ? '' : $prefix, $javascript['settings']['data'][1]['pathPrefix'], 'Path prefix JavaScript setting is correctly set.');
- }
-
-
- * Test adding settings.
- */
- function testAddSetting() {
- $javascript = backdrop_add_js(array('backdrop' => 'rocks', 'v1.0.0' => 1421394600), 'setting');
- $this->assertEqual(1421394600, $javascript['settings']['data'][2]['v1.0.0'], 'JavaScript setting is set correctly.');
- $this->assertEqual('rocks', $javascript['settings']['data'][2]['backdrop'], 'The other JavaScript setting is set correctly.');
- }
-
-
- * Tests adding an external JavaScript File.
- */
- function testAddExternal() {
- $path = 'http://example.com/script.js';
- $javascript = backdrop_add_js($path, 'external');
- $this->assertTrue(array_key_exists('http://example.com/script.js', $javascript), 'Added an external JavaScript file.');
- }
-
-
- * Test backdrop_get_js() for JavaScript settings.
- */
- function testHeaderSetting() {
-
- backdrop_add_js(array('commonTest' => 'commonTestShouldNotAppear'), 'setting');
- backdrop_add_js(array('commonTest' => 'commonTestShouldAppear'), 'setting');
-
- backdrop_add_js(array('commonTestArray' => array('commonTestValue0')), 'setting');
- backdrop_add_js(array('commonTestArray' => array('commonTestValue1')), 'setting');
- backdrop_add_js(array('commonTestArray' => array('commonTestValue2')), 'setting');
-
- backdrop_add_js(array('commonTestArray' => array('key' => 'commonTestOldValue')), 'setting');
- backdrop_add_js(array('commonTestArray' => array('key' => 'commonTestNewValue')), 'setting');
-
- $javascript = backdrop_get_js('header');
- $this->assertTrue(strpos($javascript, 'basePath') > 0, 'Rendered JavaScript header returns basePath setting.');
- $this->assertTrue(strpos($javascript, 'core/misc/jquery.js') > 0, 'Rendered JavaScript header includes jQuery.');
- $this->assertTrue(strpos($javascript, 'pathPrefix') > 0, 'Rendered JavaScript header returns pathPrefix setting.');
-
-
- $this->assertTrue(strpos($javascript, 'commonTestShouldAppear') > 0, 'Rendered JavaScript header returns custom setting.');
- $this->assertTrue(strpos($javascript, 'commonTestShouldNotAppear') === FALSE, 'backdrop_add_js() correctly overrides a custom setting.');
-
-
-
- $array_values_appear = strpos($javascript, 'commonTestValue0') > 0 && strpos($javascript, 'commonTestValue1') > 0 && strpos($javascript, 'commonTestValue2') > 0;
- $this->assertTrue($array_values_appear, 'backdrop_add_js() correctly adds settings to the end of an indexed array.');
-
-
-
- $associative_array_override = strpos($javascript, 'commonTestNewValue') > 0 && strpos($javascript, 'commonTestOldValue') === FALSE;
- $this->assertTrue($associative_array_override, 'backdrop_add_js() correctly overrides settings within an associative array.');
- }
-
-
- * Test to see if resetting the JavaScript empties the cache.
- */
- function testReset() {
- backdrop_add_js('core/misc/collapse.js');
- backdrop_static_reset('backdrop_add_js');
- $this->assertEqual(array(), backdrop_add_js(), 'Resetting the JavaScript correctly empties the cache.');
- }
-
-
- * Test adding inline scripts.
- */
- function testAddInline() {
- $inline = 'jQuery(function () { });';
- $javascript = backdrop_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
- $this->assertTrue(array_key_exists('core/misc/jquery.js', $javascript), 'jQuery is added when inline scripts are added.');
- $data = end($javascript);
- $this->assertEqual($inline, $data['data'], 'Inline JavaScript is correctly added to the footer.');
- }
-
-
- * Test rendering an external JavaScript file.
- */
- function testRenderExternal() {
- $external = 'http://example.com/example.js';
- backdrop_add_js($external, 'external');
- $javascript = backdrop_get_js();
-
- $this->assertTrue(strpos($javascript, 'src="' . $external) > 0, 'Rendering an external JavaScript file.');
- }
-
-
- * Test backdrop_get_js() with a footer scope.
- */
- function testFooterHTML() {
- $inline = 'jQuery(function () { });';
- backdrop_add_js($inline, array('type' => 'inline', 'scope' => 'footer'));
- $javascript = backdrop_get_js('footer');
- $this->assertTrue(strpos($javascript, $inline) > 0, 'Rendered JavaScript footer returns the inline code.');
- }
-
-
- * Test backdrop_add_js() sets preproccess to false when cache is set to false.
- */
- function testNoCache() {
- $javascript = backdrop_add_js('core/misc/collapse.js', array('cache' => FALSE));
- $this->assertFalse($javascript['core/misc/collapse.js']['preprocess'], 'Setting cache to FALSE sets preprocess to FALSE when adding JavaScript.');
- }
-
-
- * Test adding a JavaScript file with a different group.
- */
- function testDifferentGroup() {
- $javascript = backdrop_add_js('core/misc/collapse.js', array('group' => JS_THEME));
- $this->assertEqual($javascript['core/misc/collapse.js']['group'], JS_THEME, 'Adding a JavaScript file with a different group caches the given group.');
- }
-
-
- * Test adding a JavaScript file with a different weight.
- */
- function testDifferentWeight() {
- $javascript = backdrop_add_js('core/misc/collapse.js', array('weight' => 2));
- $this->assertEqual($javascript['core/misc/collapse.js']['weight'], 2, 'Adding a JavaScript file with a different weight caches the given weight.');
- }
-
-
- * Test adding JavaScript within conditional comments.
- *
- * @see backdrop_pre_render_conditional_comments()
- */
- function testBrowserConditionalComments() {
- $default_query_string = state_get('css_js_query_string', '0');
-
- backdrop_add_js('core/misc/collapse.js', array('browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE)));
- backdrop_add_js('jQuery(function () { });', array('type' => 'inline', 'browsers' => array('IE' => FALSE)));
- $javascript = backdrop_get_js();
-
- $expected_1 = "<!--[if lte IE 8]>\n" . '<script src="' . file_create_url('core/misc/collapse.js') . '?' . $default_query_string . '"></script>' . "\n<![endif]-->";
- $expected_2 = "<!--[if !IE]><!-->\n" . '<script>jQuery(function () { });</script>' . "\n<!--<![endif]-->";
-
- $this->assertTrue(strpos($javascript, $expected_1) > 0, t('Rendered JavaScript within downlevel-hidden conditional comments.'));
- $this->assertTrue(strpos($javascript, $expected_2) > 0, t('Rendered JavaScript within downlevel-revealed conditional comments.'));
- }
-
-
- * Test JavaScript versioning.
- */
- function testVersionQueryString() {
- backdrop_add_js('core/misc/collapse.js', array('version' => 'foo'));
- backdrop_add_js('core/misc/ajax.js', array('version' => 'bar'));
- $javascript = backdrop_get_js();
- $this->assertTrue(strpos($javascript, 'core/misc/collapse.js?v=foo') > 0 && strpos($javascript, 'core/misc/ajax.js?v=bar') > 0 , t('JavaScript version identifiers correctly appended to URLs'));
- }
-
-
- * Test JavaScript grouping and aggregation.
- */
- function testAggregation() {
- $default_query_string = state_get('css_js_query_string', '0');
-
-
-
-
-
- backdrop_add_js('core/misc/ajax.js');
- backdrop_add_js('core/misc/collapse.js', array('every_page' => TRUE));
- backdrop_add_js('core/misc/autocomplete.js');
- backdrop_add_js('core/misc/batch.js', array('every_page' => TRUE));
- $javascript = backdrop_get_js();
- $expected = implode("\n", array(
- '<script src="' . file_create_url('core/misc/collapse.js') . '?' . $default_query_string . '"></script>',
- '<script src="' . file_create_url('core/misc/batch.js') . '?' . $default_query_string . '"></script>',
- '<script src="' . file_create_url('core/misc/ajax.js') . '?' . $default_query_string . '"></script>',
- '<script src="' . file_create_url('core/misc/autocomplete.js') . '?' . $default_query_string . '"></script>',
- ));
- $this->assertTrue(strpos($javascript, $expected) > 0, t('Unaggregated JavaScript is added in the expected group order.'));
-
-
-
- backdrop_static_reset('backdrop_add_js');
- config_set('system.core', 'preprocess_js', 1);
- backdrop_add_js('core/misc/ajax.js');
- backdrop_add_js('core/misc/collapse.js', array('every_page' => TRUE));
- backdrop_add_js('core/misc/autocomplete.js');
- backdrop_add_js('core/misc/batch.js', array('every_page' => TRUE));
- $js_items = backdrop_add_js();
- $javascript = backdrop_get_js();
- $expected = implode("\n", array(
- '<script src="' . file_create_url(backdrop_build_js_cache(array('core/misc/collapse.js' => $js_items['core/misc/collapse.js'], 'core/misc/batch.js' => $js_items['core/misc/batch.js']))) . '"></script>',
- '<script src="' . file_create_url(backdrop_build_js_cache(array('core/misc/ajax.js' => $js_items['core/misc/ajax.js'], 'core/misc/autocomplete.js' => $js_items['core/misc/autocomplete.js']))) . '"></script>',
- ));
- $this->assertTrue(strpos($javascript, $expected) > 0, t('JavaScript is aggregated in the expected groups and order.'));
- }
-
-
- * Tests JavaScript aggregation when files are added to a different scope.
- */
- function testAggregationOrder() {
-
- config_set('system.core', 'preprocess_js', 1);
- backdrop_static_reset('backdrop_add_js');
-
-
- backdrop_add_js('core/misc/ajax.js');
- backdrop_add_js('core/misc/autocomplete.js');
-
- $js_items = backdrop_add_js();
- backdrop_build_js_cache(array(
- 'core/misc/ajax.js' => $js_items['core/misc/ajax.js'],
- 'core/misc/autocomplete.js' => $js_items['core/misc/autocomplete.js']
- ));
-
-
- $cache = array_keys(state_get('js_cache_files', array()));
- $expected_key = $cache[0];
-
-
- state_set('js_cache_files', FALSE);
- backdrop_static_reset('backdrop_add_js');
- backdrop_add_js('some/custom/javascript_file.js', array('scope' => 'footer'));
- backdrop_add_js('core/misc/ajax.js');
- backdrop_add_js('core/misc/autocomplete.js');
-
-
- $js_items = backdrop_add_js();
- backdrop_build_js_cache(array(
- 'core/misc/ajax.js' => $js_items['core/misc/ajax.js'],
- 'core/misc/autocomplete.js' => $js_items['core/misc/autocomplete.js']
- ));
-
-
- $cache = array_keys(state_get('js_cache_files', array()));
- $key = $cache[0];
- $this->assertEqual($key, $expected_key, 'JavaScript aggregation is not affected by ordering in different scopes.');
- }
-
-
- * Test JavaScript ordering.
- */
- function testRenderOrder() {
-
- backdrop_add_js('(function($){alert("Weight 5 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
- backdrop_add_js('(function($){alert("Weight 0 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
- backdrop_add_js('(function($){alert("Weight 0 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
- backdrop_add_js('(function($){alert("Weight -8 #1");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
- backdrop_add_js('(function($){alert("Weight -8 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
- backdrop_add_js('(function($){alert("Weight -8 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
- backdrop_add_js('http://example.com/example.js?Weight -5 #1', array('type' => 'external', 'scope' => 'footer', 'weight' => -5));
- backdrop_add_js('(function($){alert("Weight -8 #4");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => -8));
- backdrop_add_js('(function($){alert("Weight 5 #2");})(jQuery);', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));
- backdrop_add_js('(function($){alert("Weight 0 #3");})(jQuery);', array('type' => 'inline', 'scope' => 'footer'));
-
-
- $expected = array(
- "-8 #1",
- "-8 #2",
- "-8 #3",
- "-8 #4",
- "-5 #1",
- "0 #1",
- "0 #2",
- "0 #3",
- "5 #1",
- "5 #2",
- );
-
-
- $js = backdrop_get_js('footer');
- $matches = array();
- if (preg_match_all('/Weight\s([-0-9]+\s[#0-9]+)/', $js, $matches)) {
- $result = $matches[1];
- }
- else {
- $result = array();
- }
- $this->assertIdentical($result, $expected, 'JavaScript is added in the expected weight order.');
- }
-
-
- * Test rendering the JavaScript with a file's weight above jQuery's.
- */
- function testRenderDifferentWeight() {
-
-
-
- backdrop_add_js('core/misc/collapse.js', array('group' => JS_LIBRARY, 'every_page' => TRUE, 'weight' => -21));
- $javascript = backdrop_get_js();
- $this->assertTrue(strpos($javascript, 'core/misc/collapse.js') < strpos($javascript, 'core/misc/jquery.js'), 'Rendering a JavaScript file above jQuery.');
- }
-
-
- * Tests adding JavaScript files with additional attributes.
- */
- public function testAttributes() {
-
- config_set('system.core', 'preprocess_js', 0);
-
-
-
- $js_internal = 'core/misc/collapse.js';
- $js_external = 'http://example.com/script.js';
- backdrop_add_js($js_internal, array('attributes' => array('async' => 'async'), 'defer' => 'defer'));
- backdrop_add_js($js_external, array(
- 'attributes' => array(
- 'async' => 'async',
- ),
- 'defer' => 'defer',
- 'type' => 'external',
- ));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @async="async" and @defer="defer"]'), 'Rendered internal JavaScript with correct defer and async attributes.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @async="async" and @defer="defer"]'), 'Rendered external JavaScript with correct defer and async attributes.');
-
-
- backdrop_add_js($js_internal, array('defer' => 'defer'));
- backdrop_add_js($js_external, array('defer' => 'defer', 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @defer="defer"]'), 'Rendered internal JavaScript with correct defer attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @defer="defer"]'), 'Rendered external JavaScript with correct defer attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('async' => 'async')));
- backdrop_add_js($js_external, array('attributes' => array('async' => 'async'), 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @async="async"]'), 'Rendered internal JavaScript with correct async attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @async="async"]'), 'Rendered external JavaScript with correct async attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('custom' => 'foo')));
- backdrop_add_js($js_external, array('attributes' => array('custom' => 'foo'), 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @custom="foo"]'), 'Rendered internal JavaScript with correct custom attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @custom="foo"]'), 'Rendered external JavaScript with correct custom attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('custom' => 'foo'), 'defer' => 'defer'));
- backdrop_add_js($js_external, array(
- 'attributes' => array(
- 'custom' => 'foo',
- ),
- 'defer' => 'defer',
- 'type' => 'external',
- ));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @custom="foo" and @defer="defer"]'), 'Rendered internal JavaScript with correct custom attribute and defer attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @custom="foo" and @defer="defer"]'), 'Rendered external JavaScript with correct custom attribute and defer attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('custom' => 'foo', 'async' => 'async')));
- backdrop_add_js($js_external, array(
- 'attributes' => array(
- 'custom' => 'foo',
- 'async' => 'async',
- ),
- 'type' => 'external',
- ));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @custom="foo" and @async="async"]'), 'Rendered internal JavaScript with custom attribute and async attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @custom="foo" and @async="async"]'), 'Rendered external JavaScript with correct custom attribute and async attribute.');
- }
-
-
- * Tests that attributes are maintained when JS aggregation is enabled.
- */
- public function testAggregatedAttributes() {
-
- config_set('system.core', 'preprocess_js', TRUE);
-
-
-
- $js_internal = 'core/misc/collapse.js';
- $js_external = 'http://example.com/script.js';
- backdrop_add_js($js_internal, array('attributes' => array('async' => 'async'), 'defer' => 'defer'));
- backdrop_add_js($js_external, array('attributes' => array('async' => 'async'), 'defer' => 'defer', 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @async="async" and @defer="defer"]'), 'Rendered internal JavaScript with correct defer and async attributes.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @async="async" and @defer="defer"]'), 'Rendered external JavaScript with correct defer and async attributes.');
-
-
- backdrop_add_js($js_internal, array('defer' => 'defer'));
- backdrop_add_js($js_external, array('defer' => 'defer', 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @defer="defer"]'), 'Rendered internal JavaScript with correct defer attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @defer="defer"]'), 'Rendered external JavaScript with correct defer attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('async' => 'async')));
- backdrop_add_js($js_external, array('attributes' => array('async' => 'async'), 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @async="async"]'), 'Rendered internal JavaScript with correct async attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @async="async"]'), 'Rendered external JavaScript with correct async attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('custom' => 'foo')));
- backdrop_add_js($js_external, array('attributes' => array('custom' => 'foo'), 'type' => 'external'));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @custom="foo"]'), 'Rendered internal JavaScript with correct custom attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @custom="foo"]'), 'Rendered external JavaScript with correct custom attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('custom' => 'foo'), 'defer' => 'defer'));
- backdrop_add_js($js_external, array(
- 'attributes' => array(
- 'custom' => 'foo',
- ),
- 'defer' => 'defer',
- 'type' => 'external',
- ));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @custom="foo" and @defer="defer"]'), 'Rendered internal JavaScript with custom attribute and defer attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @custom="foo" and @defer="defer"]'), 'Rendered external JavaScript with correct custom attribute and defer attribute.');
-
-
- backdrop_add_js($js_internal, array('attributes' => array('custom' => 'foo', 'async' => 'async')));
- backdrop_add_js($js_external, array(
- 'attributes' => array(
- 'custom' => 'foo',
- 'async' => 'async',
- ),
- 'type' => 'external',
- ));
- $javascript = backdrop_get_js();
- $this->backdropSetContent($javascript);
- $this->assertTrue($this->xpath('//script[starts-with(@src, "' . file_create_url($js_internal) . '") and @custom="foo" and @async="async"]'), 'Rendered internal JavaScript with custom attribute and async attribute.');
- $this->assertTrue($this->xpath('//script[@src="' . $js_external . '" and @custom="foo" and @async="async"]'), 'Rendered external JavaScript with correct custom attribute and async attribute.');
- }
-
-
- * Test altering a JavaScript's weight via hook_js_alter().
- *
- * @see simpletest_js_alter()
- */
- function testAlter() {
-
- backdrop_add_js('core/misc/tableselect.js');
- backdrop_add_js(backdrop_get_path('module', 'simpletest') . '/js/simpletest.js', array('weight' => 9999));
-
-
-
-
- $javascript = backdrop_get_js();
- $this->assertTrue(strpos($javascript, 'simpletest.js') < strpos($javascript, 'core/misc/tableselect.js'), 'Altering JavaScript weight through the alter hook.');
- }
-
-
- * Adds a library to the page and tests for both its JavaScript and its CSS.
- */
- function testLibraryRender() {
- $result = backdrop_add_library('system', 'farbtastic');
- $this->assertTrue($result !== FALSE, t('Library was added without errors.'));
- $scripts = backdrop_get_js();
- $styles = backdrop_get_css();
- $this->assertTrue(strpos($scripts, 'core/misc/farbtastic/farbtastic.js'), 'JavaScript for library was added to the page.');
- $this->assertTrue(strpos($styles, 'core/misc/farbtastic/farbtastic.css'), 'Stylesheet for library was added to the page.');
- }
-
-
- * Adds a JavaScript library to the page and alters it.
- *
- * @see common_test_library_info_alter()
- */
- function testLibraryAlter() {
-
- $library = backdrop_get_library('system', 'farbtastic');
- $this->assertEqual($library['title'], 'Farbtastic: Altered Library', 'Registered libraries were altered.');
-
-
- backdrop_add_library('system', 'farbtastic');
- $scripts = backdrop_get_js();
- $this->assertTrue(strpos($scripts, 'core/misc/jquery.form.js'), 'Altered library dependencies are added to the page.');
- }
-
-
- * Tests that multiple modules can implement the same library.
- *
- * @see common_test_library_info()
- */
- function testLibraryNameConflicts() {
- $farbtastic = backdrop_get_library('common_test', 'farbtastic');
- $this->assertEqual($farbtastic['title'], 'Custom Farbtastic Library', 'Alternative libraries can be added to the page.');
- }
-
-
- * Tests non-existing libraries.
- */
- function testLibraryUnknown() {
- $result = backdrop_get_library('unknown', 'unknown');
- $this->assertFalse($result, 'Unknown library returned FALSE.');
- backdrop_static_reset('backdrop_get_library');
-
- $result = backdrop_add_library('unknown', 'unknown');
- $this->assertFalse($result, 'Unknown library returned FALSE.');
- $scripts = backdrop_get_js();
- $this->assertTrue(strpos($scripts, 'unknown') === FALSE, 'Unknown library was not added to the page.');
- }
-
-
- * Tests the addition of libraries through the #attached['library'] property.
- */
- function testAttachedLibrary() {
- $element['#attached']['library'][] = array('system', 'farbtastic');
- backdrop_render($element);
- $scripts = backdrop_get_js();
- $this->assertTrue(strpos($scripts, 'core/misc/farbtastic/farbtastic.js'), 'The attached_library property adds the additional libraries.');
- }
-
-
- * Tests retrieval of libraries via backdrop_get_library().
- */
- function testGetLibrary() {
-
- $libraries = backdrop_get_library('common_test');
- $this->assertTrue(isset($libraries['farbtastic']), 'Retrieved all module libraries.');
-
-
- $libraries = backdrop_get_library('locale');
- $this->assertEqual($libraries, array(), 'Retrieving libraries from a module not implementing hook_library_info() returns an emtpy array.');
-
-
- $farbtastic = backdrop_get_library('common_test', 'farbtastic');
- $this->assertEqual($farbtastic['version'], '5.3', 'Retrieved a single library.');
-
- $farbtastic = backdrop_get_library('common_test', 'foo');
- $this->assertIdentical($farbtastic, FALSE, 'Retrieving a non-existing library returns FALSE.');
- }
-
-
- * Tests that the query string remains intact when adding JavaScript files
- * that have query string parameters.
- */
- function testAddJsFileWithQueryString() {
- $this->backdropGet('common-test/query-string');
- $query_string = state_get('css_js_query_string', '0');
- $this->assertRaw(backdrop_get_path('module', 'node') . '/js/node.js?' . $query_string, 'Query string was appended correctly to js.');
- }
- }
-
- * Tests for backdrop_render().
- */
- class CommonBackdropRenderTestCase extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('common_test');
- }
-
-
- * Tests the output backdrop_render() for some elementary input values.
- */
- function testBackdropRenderBasics() {
- $types = array(
- array(
- 'name' => 'null',
- 'value' => NULL,
- 'expected' => '',
- ),
- array(
- 'name' => 'no value',
- 'expected' => '',
- ),
- array(
- 'name' => 'empty string',
- 'value' => '',
- 'expected' => '',
- ),
- array(
- 'name' => 'no access',
- 'value' => array(
- '#markup' => 'foo',
- '#access' => FALSE,
- ),
- 'expected' => '',
- ),
- array(
- 'name' => 'previously printed',
- 'value' => array(
- '#markup' => 'foo',
- '#printed' => TRUE,
- ),
- 'expected' => '',
- ),
- array(
- 'name' => 'printed in prerender',
- 'value' => array(
- '#markup' => 'foo',
- '#pre_render' => array('common_test_backdrop_render_printing_pre_render'),
- ),
- 'expected' => '',
- ),
- array(
- 'name' => 'basic renderable array',
- 'value' => array('#markup' => 'foo'),
- 'expected' => 'foo',
- ),
- );
- foreach($types as $type) {
- $this->assertIdentical(backdrop_render($type['value']), $type['expected'], '"' . $type['name'] . '" input rendered correctly by backdrop_render().');
- }
- }
-
-
- * Test sorting by weight.
- */
- function testBackdropRenderSorting() {
- $first = $this->randomName();
- $second = $this->randomName();
-
- $elements = array(
- 'second' => array(
- '#weight' => 10,
- '#markup' => $second,
- ),
- 'first' => array(
- '#weight' => 0,
- '#markup' => $first,
- ),
- );
- $output = backdrop_render($elements);
-
-
- $this->assertTrue(strpos($output, $second) > strpos($output, $first), 'Elements were sorted correctly by weight.');
-
-
- $this->assertTrue($elements['#sorted'], "'#sorted' => TRUE was added to the array");
-
-
-
-
- $children = element_children($elements);
- $this->assertTrue(array_shift($children) == 'first', 'Child found in the correct order.');
- $this->assertTrue(array_shift($children) == 'second', 'Child found in the correct order.');
-
-
-
- $elements = array(
- 'second' => array(
- '#weight' => 10,
- '#markup' => $second,
- ),
- 'first' => array(
- '#weight' => 0,
- '#markup' => $first,
- ),
- '#sorted' => TRUE,
- );
- $output = backdrop_render($elements);
-
-
- $this->assertTrue(strpos($output, $second) < strpos($output, $first), 'Elements were not sorted.');
- }
-
-
- * Test #attached functionality in children elements.
- */
- function testBackdropRenderChildrenAttached() {
-
- $request_method = $_SERVER['REQUEST_METHOD'];
- $_SERVER['REQUEST_METHOD'] = 'GET';
-
-
-
- $parent_js = backdrop_get_path('module', 'user') . '/js/user.js';
- $child_js = backdrop_get_path('module', 'node') . '/js/node.js';
- $subchild_js = backdrop_get_path('module', 'book') . '/js/book.js';
-
- $element = array(
- '#type' => 'fieldset',
- '#cache' => array(
- 'keys' => array('simpletest', 'backdrop_render', 'children_attached'),
- ),
- '#attached' => array('js' => array($parent_js)),
- '#title' => 'Parent',
- );
- $element['child'] = array(
- '#type' => 'fieldset',
- '#attached' => array('js' => array($child_js)),
- '#title' => 'Child',
- );
- $element['child']['subchild'] = array(
- '#attached' => array('js' => array($subchild_js)),
- '#markup' => 'Subchild',
- );
-
-
- backdrop_render($element);
- $scripts = backdrop_get_js();
- $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included.');
- $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included.');
- $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included.');
-
-
-
- backdrop_static_reset('backdrop_add_js');
- $this->assertTrue(backdrop_render_cache_get($element), 'The element was retrieved from cache.');
- $scripts = backdrop_get_js();
- $this->assertTrue(strpos($scripts, $parent_js), 'The element #attached JavaScript was included when loading from cache.');
- $this->assertTrue(strpos($scripts, $child_js), 'The child #attached JavaScript was included when loading from cache.');
- $this->assertTrue(strpos($scripts, $subchild_js), 'The subchild #attached JavaScript was included when loading from cache.');
-
- $_SERVER['REQUEST_METHOD'] = $request_method;
- }
-
-
- * Test passing arguments to the theme function.
- */
- function testBackdropRenderThemeArguments() {
- $element = array(
- '#theme' => 'common_test_foo',
- );
-
- $this->assertEqual(backdrop_render($element), 'foobar', 'Defaults work');
- $element = array(
- '#theme' => 'common_test_foo',
- '#foo' => $this->randomName(),
- '#bar' => $this->randomName(),
- );
-
- $this->assertEqual(backdrop_render($element), $element['#foo'] . $element['#bar'], 'Passing arguments to theme functions works');
- }
-
-
- * Test rendering form elements without passing through form_builder().
- */
- function testBackdropRenderFormElements() {
-
- $element = array(
- '#type' => 'button',
- '#value' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
-
- $element = array(
- '#type' => 'textfield',
- '#title' => $this->randomName(),
- '#value' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
-
- $element = array(
- '#type' => 'password',
- '#title' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
-
- $element = array(
- '#type' => 'textarea',
- '#title' => $this->randomName(),
- '#value' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//textarea');
-
- $element = array(
- '#type' => 'radio',
- '#title' => $this->randomName(),
- '#value' => FALSE,
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
-
- $element = array(
- '#type' => 'checkbox',
- '#title' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
-
- $element = array(
- '#type' => 'select',
- '#title' => $this->randomName(),
- '#options' => array(
- 0 => $this->randomName(),
- 1 => $this->randomName(),
- ),
- );
- $this->assertRenderedElement($element, '//select');
-
- $element = array(
- '#type' => 'file',
- '#title' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
-
- $element = array(
- '#type' => 'item',
- '#title' => $this->randomName(),
- '#markup' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(
- ':class' => 'form-type-item',
- ':markup' => $element['#markup'],
- ':label' => $element['#title'],
- ));
-
- $element = array(
- '#type' => 'hidden',
- '#title' => $this->randomName(),
- '#value' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
-
- $element = array(
- '#type' => 'link',
- '#title' => $this->randomName(),
- '#href' => $this->randomName(),
- '#options' => array(
- 'absolute' => TRUE,
- ),
- );
- $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(
- ':href' => url($element['#href'], array('absolute' => TRUE)),
- ':title' => $element['#title'],
- ));
-
- $element = array(
- '#type' => 'fieldset',
- '#title' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//fieldset/legend[contains(., :title)]', array(
- ':title' => $element['#title'],
- ));
-
- $element['item'] = array(
- '#type' => 'item',
- '#title' => $this->randomName(),
- '#markup' => $this->randomName(),
- );
- $this->assertRenderedElement($element, '//fieldset/div/div[contains(@class, :class) and contains(., :markup)]', array(
- ':class' => 'form-type-item',
- ':markup' => $element['item']['#markup'],
- ));
- }
-
-
- * Test rendering elements with invalid keys.
- */
- function testBackdropRenderInvalidKeys() {
- $error = array(
- '%type' => 'User error',
- '!message' => '"child" is an invalid render array key',
- '%function' => 'element_children()',
- );
- $message = t('%type: !message in %function (line ', $error);
-
- config_set('system.core', 'error_level', ERROR_REPORTING_DISPLAY_ALL);
- $this->backdropGet('common-test/backdrop-render-invalid-keys');
- $this->assertResponse(200, t('Received expected HTTP status code.'));
- $this->assertRaw($message, t('Found error message: !message.', array('!message' => $message)));
- }
-
- protected function assertRenderedElement(array $element, $xpath, array $xpath_args = array()) {
- $original_element = $element;
- $this->backdropSetContent(backdrop_render($element));
- $this->verbose('<pre>' . check_plain(var_export($original_element, TRUE)) . '</pre>'
- . '<pre>' . check_plain(var_export($element, TRUE)) . '</pre>'
- . '<hr />' . $this->backdropGetContent()
- );
-
-
- $xpath = $this->buildXPathQuery($xpath, $xpath_args);
- $element += array('#value' => NULL);
- $this->assertFieldByXPath($xpath, $element['#value'], format_string('#type @type was properly rendered.', array(
- '@type' => var_export($element['#type'], TRUE),
- )));
- }
-
-
- * Tests caching of render items.
- */
- function testBackdropRenderCache() {
-
- $request_method = $_SERVER['REQUEST_METHOD'];
- $_SERVER['REQUEST_METHOD'] = 'GET';
-
- $test_element = array(
- '#cache' => array(
- 'cid' => 'render_cache_test',
- ),
- '#markup' => '',
- );
-
-
-
- $element = $test_element;
- backdrop_render($element);
- $this->assertTrue(isset($element['#printed']), 'No cache hit');
-
-
-
- $element = $test_element;
- backdrop_render($element);
- $this->assertFalse(isset($element['#printed']), 'Cache hit');
-
-
-
- $user1 = user_load(1);
- $first_authenticated_user = $this->backdropCreateUser();
- $second_authenticated_user = $this->backdropCreateUser();
- $user1->roles = array_intersect($user1->roles, array(BACKDROP_AUTHENTICATED_ROLE));
- user_save($user1);
-
-
- $user1 = user_load(1);
- $first_authenticated_user = user_load($first_authenticated_user->uid);
- $second_authenticated_user = user_load($second_authenticated_user->uid);
- $this->assertEqual($user1->roles, $first_authenticated_user->roles, 'User 1 has the same roles as an authenticated user.');
-
-
- $original_user = $GLOBALS['user'];
- $original_session_state = backdrop_save_session();
- backdrop_save_session(FALSE);
- $GLOBALS['user'] = $user1;
- $test_element = array(
- '#cache' => array(
- 'keys' => array('test'),
- 'granularity' => BACKDROP_CACHE_PER_ROLE,
- ),
- );
- $element = $test_element;
- $element['#markup'] = 'content for user 1';
- $output = backdrop_render($element);
- $this->assertEqual($output, 'content for user 1');
-
-
- $element = $test_element;
- $element['#markup'] = 'should not be used';
- $output = backdrop_render($element);
- $this->assertEqual($output, 'content for user 1');
-
-
- $GLOBALS['user'] = $first_authenticated_user;
- $element = $test_element;
- $element['#markup'] = 'content for authenticated users';
- $output = backdrop_render($element);
- $this->assertEqual($output, 'content for authenticated users');
-
-
- $GLOBALS['user'] = $second_authenticated_user;
- $element = $test_element;
- $element['#markup'] = 'should not be used';
- $output = backdrop_render($element);
- $this->assertEqual($output, 'content for authenticated users');
-
- $GLOBALS['user'] = $original_user;
- backdrop_save_session($original_session_state);
-
-
- $_SERVER['REQUEST_METHOD'] = $request_method;
- }
- }
-
- * Tests URL validation by valid_url().
- */
- class CommonValidUrlUnitTestCase extends BackdropUnitTestCase {
-
- * Test valid absolute URLs.
- */
- function testValidAbsolute() {
- $url_schemes = array('http', 'https', 'ftp');
- $valid_absolute_urls = array(
- 'example.com',
- 'www.example.com',
- 'ex-ample.com',
- '3xampl3.com',
- 'example.com/paren(the)sis',
- 'example.com/index.html#pagetop',
- 'example.com:8080',
- 'subdomain.example.com',
- 'example.com/index.php?q=node',
- 'example.com/index.php?q=node¶m=false',
- 'user@www.example.com',
- 'user:pass@www.example.com:8080/login.php?do=login&style=%23#pagetop',
- '127.0.0.1',
- 'example.org?',
- 'john%20doe:secret:foo@example.org/',
- 'example.org/~,$\'*;',
- 'caf%C3%A9.example.org',
- '[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
- );
-
- foreach ($url_schemes as $scheme) {
- foreach ($valid_absolute_urls as $url) {
- $test_url = $scheme . '://' . $url;
- $valid_url = valid_url($test_url, TRUE);
- $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
- }
- }
- }
-
-
- * Test invalid absolute URLs.
- */
- function testInvalidAbsolute() {
- $url_schemes = array('http', 'https', 'ftp');
- $invalid_ablosule_urls = array(
- '',
- 'ex!ample.com',
- 'ex%ample.com',
- );
-
- foreach ($url_schemes as $scheme) {
- foreach ($invalid_ablosule_urls as $url) {
- $test_url = $scheme . '://' . $url;
- $valid_url = valid_url($test_url, TRUE);
- $this->assertFalse($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
- }
- }
- }
-
-
- * Test valid relative URLs.
- */
- function testValidRelative() {
- $valid_relative_urls = array(
- 'paren(the)sis',
- 'index.html#pagetop',
- 'index.php?q=node',
- 'index.php?q=node¶m=false',
- 'login.php?do=login&style=%23#pagetop',
- );
-
- foreach (array('', '/') as $front) {
- foreach ($valid_relative_urls as $url) {
- $test_url = $front . $url;
- $valid_url = valid_url($test_url);
- $this->assertTrue($valid_url, format_string('@url is a valid url.', array('@url' => $test_url)));
- }
- }
- }
-
-
- * Test invalid relative URLs.
- */
- function testInvalidRelative() {
- $invalid_relative_urls = array(
- 'ex^mple',
- 'example<>',
- 'ex%ample',
- );
-
- foreach (array('', '/') as $front) {
- foreach ($invalid_relative_urls as $url) {
- $test_url = $front . $url;
- $valid_url = valid_url($test_url);
- $this->assertFALSE($valid_url, format_string('@url is NOT a valid url.', array('@url' => $test_url)));
- }
- }
- }
- }
-
- * Tests number step validation by valid_number_step().
- */
- class CommonValidNumberStepUnitTestCase extends BackdropUnitTestCase {
-
- * Tests valid_number_step() without offset.
- */
- function testNumberStep() {
-
- $this->assertTrue(valid_number_step(10.3, 10.3));
-
-
- $this->assertTrue(valid_number_step(42, 21));
- $this->assertTrue(valid_number_step(42, 3));
-
-
- $this->assertTrue(valid_number_step(42, 10.5));
- $this->assertTrue(valid_number_step(1000, -10));
-
-
- $this->assertTrue(valid_number_step(1000.12345, 1e-10));
- $this->assertTrue(valid_number_step(1936.5, 3e-8));
- $this->assertTrue(valid_number_step(3.9999999999999, 1e-13));
-
-
- $this->assertTrue(valid_number_step(20.123456789, 1.0E-10));
- $this->assertTrue(valid_number_step(9999.1933172003, 1.0E-10));
- $this->assertTrue(valid_number_step(199.200001, 1.0E-10));
- $this->assertTrue(valid_number_step(1109.87, 1.0E-10));
- $this->assertTrue(valid_number_step(41239412.55, 1.0E-2));
- $this->assertTrue(valid_number_step(13517282.20, 1.0E-2));
- $this->assertTrue(valid_number_step(12345678.12, 1.0E-2));
-
-
- $this->assertFalse(valid_number_step(100, 30));
- $this->assertFalse(valid_number_step(-10, 4));
-
-
- $this->assertFalse(valid_number_step(6, 5/7));
- $this->assertFalse(valid_number_step(10.3, 10.25));
- $this->assertFalse(valid_number_step(1, 1/3));
- $this->assertFalse(valid_number_step(-100, 100/7));
-
-
- $this->assertFalse(valid_number_step(70 + 9e-7, 10 + 9e-7));
- $this->assertFalse(valid_number_step(1109.87, 0.07));
- $this->assertFalse(valid_number_step(41239412.11, 2));
- $this->assertFalse(valid_number_step(13517283.0001, 3));
- }
-
-
- * Tests valid_number_step() with offset.
- */
- function testNumberStepOffset() {
-
- $this->assertTrue(valid_number_step(11.3, 10.3, 1));
- $this->assertTrue(valid_number_step(100, 10, 50));
-
-
- $this->assertFalse(valid_number_step(10.3, 10.3, 0.0001));
- $this->assertFalse(valid_number_step(1/5, 1/7, 1/11));
-
-
- $this->assertFalse(valid_number_step(-100, 90/7, -10));
- $this->assertFalse(valid_number_step(1000, 10, -5));
- $this->assertFalse(valid_number_step(-10, 4, 0));
- $this->assertFalse(valid_number_step(-10, 4, -4));
- }
- }
-
- * Tests writing of data records with backdrop_write_record().
- */
- class CommonBackdropWriteRecordTestCase extends BackdropWebTestCase {
- function setUp() {
- parent::setUp('database_test');
- }
-
-
- * Test the backdrop_write_record() API function.
- */
- function testBackdropWriteRecord() {
-
- $record = array();
- $insert_result = backdrop_write_record('test', $record);
- $this->assertTrue($insert_result == SAVED_NEW, t('Correct value returned when an empty record is inserted with backdrop_write_record().'));
-
-
- $person = new stdClass();
- $person->name = 'John';
- $person->unknown_column = 123;
- $insert_result = backdrop_write_record('test', $person);
- $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with backdrop_write_record() for a table with a single-field primary key.');
- $this->assertTrue(isset($person->id), 'Primary key is set on record created with backdrop_write_record().');
- $this->assertIdentical($person->age, 0, 'Age field set to default value.');
- $this->assertIdentical($person->job, 'Undefined', 'Job field set to default value.');
-
-
- $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'John', 'Name field set.');
- $this->assertIdentical($result->age, '0', 'Age field set to default value.');
- $this->assertIdentical($result->job, 'Undefined', 'Job field set to default value.');
- $this->assertFalse(isset($result->unknown_column), 'Unknown column was ignored.');
-
-
- $person->name = 'Peter';
- $person->age = 27;
- $person->job = NULL;
- $update_result = backdrop_write_record('test', $person, array('id'));
- $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record updated with backdrop_write_record() for table with single-field primary key.');
-
-
- $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'Peter', 'Name field set.');
- $this->assertIdentical($result->age, '27', 'Age field set.');
- $this->assertIdentical($result->job, '', 'Job field set and cast to string.');
-
-
- $person = new stdClass();
- $person->name = 'Ringo';
- $person->age = NULL;
- $person->job = NULL;
- $insert_result = backdrop_write_record('test', $person);
- $this->assertTrue(isset($person->id), 'Primary key is set on record created with backdrop_write_record().');
- $result = db_query("SELECT * FROM {test} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'Ringo', 'Name field set.');
- $this->assertIdentical($result->age, '0', 'Age field set.');
- $this->assertIdentical($result->job, '', 'Job field set.');
-
-
- $person = new stdClass();
- $person->name = 'Paul';
- $person->age = NULL;
- $insert_result = backdrop_write_record('test_null', $person);
- $this->assertTrue(isset($person->id), 'Primary key is set on record created with backdrop_write_record().');
- $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'Paul', 'Name field set.');
- $this->assertIdentical($result->age, NULL, 'Age field set.');
-
-
- $person = new stdClass();
- $person->name = 'Meredith';
- $insert_result = backdrop_write_record('test_null', $person);
- $this->assertTrue(isset($person->id), 'Primary key is set on record created with backdrop_write_record().');
- $this->assertIdentical($person->age, 0, 'Age field set to default value.');
- $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'Meredith', 'Name field set.');
- $this->assertIdentical($result->age, '0', 'Age field set to default value.');
-
-
- $person->name = 'Mary';
- $person->age = NULL;
- $update_result = backdrop_write_record('test_null', $person, array('id'));
- $result = db_query("SELECT * FROM {test_null} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'Mary', 'Name field set.');
- $this->assertIdentical($result->age, NULL, 'Age field set.');
-
-
- $person = new stdClass();
- $person->name = 'Dave';
- $update_result = backdrop_write_record('test_serialized', $person);
- $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical($result->name, 'Dave', 'Name field set.');
- $this->assertIdentical($result->info, NULL, 'Info field set.');
-
- $person->info = array();
- $update_result = backdrop_write_record('test_serialized', $person, array('id'));
- $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical(unserialize($result->info), array(), 'Info field updated.');
-
-
- $data = array('foo' => 'bar', 1 => 2, 'empty' => '', 'null' => NULL);
- $person->info = $data;
- $update_result = backdrop_write_record('test_serialized', $person, array('id'));
- $result = db_query("SELECT * FROM {test_serialized} WHERE id = :id", array(':id' => $person->id))->fetchObject();
- $this->assertIdentical(unserialize($result->info), $data, 'Info field updated.');
-
-
-
-
- $update_result = backdrop_write_record('test_null', $person, array('id'));
- $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a valid update is run without changing any values.');
-
-
- $node_access = new stdClass();
- $node_access->nid = mt_rand();
- $node_access->gid = mt_rand();
- $node_access->realm = $this->randomName();
- $insert_result = backdrop_write_record('node_access', $node_access);
- $this->assertTrue($insert_result == SAVED_NEW, 'Correct value returned when a record is inserted with backdrop_write_record() for a table with a multi-field primary key.');
-
-
- $update_result = backdrop_write_record('node_access', $node_access, array('nid', 'gid', 'realm'));
- $this->assertTrue($update_result == SAVED_UPDATED, 'Correct value returned when a record is updated with backdrop_write_record() for a table with a multi-field primary key.');
- }
-
- }
-
- * Tests SimpleTest error and exception collector.
- */
- class CommonSimpleTestErrorCollectorTestCase extends BackdropWebTestCase {
-
-
- * Errors triggered during the test.
- *
- * Errors are intercepted by the overriden implementation
- * of BackdropWebTestCase::error below.
- *
- * @var Array
- */
- protected $collectedErrors = array();
-
- function setUp() {
- parent::setUp('system_test', 'error_test');
- }
-
-
- * Test that simpletest collects errors from the tested site.
- */
- function testErrorCollect() {
- $this->collectedErrors = array();
- $this->backdropGet('error-test/generate-warnings-with-report');
- $this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
-
- if (count($this->collectedErrors) == 3) {
- $this->assertError($this->collectedErrors[0], 'Notice', 'error_test_generate_warnings()', 'error_test.module', 'Object of class stdClass could not be converted to int');
- $this->assertError($this->collectedErrors[1], 'Warning', 'error_test_generate_warnings()', 'error_test.module', \PHP_VERSION_ID < 80000 ? 'Invalid argument supplied for foreach()' : 'foreach() argument must be of type array|object, string given');
- $this->assertError($this->collectedErrors[2], 'User warning', 'error_test_generate_warnings()', 'error_test.module', 'Backdrop is awesome');
- }
- else {
-
- foreach ($this->collectedErrors as $error) {
- parent::error($error['message'], $error['group'], $error['caller']);
- }
- }
- }
-
-
- * Error handler that collects errors in an array.
- *
- * This test class is trying to verify that simpletest correctly sees errors
- * and warnings. However, it can't generate errors and warnings that
- * propagate up to the testing framework itself, or these tests would always
- * fail. So, this special copy of error() doesn't propagate the errors up
- * the class hierarchy. It just stuffs them into a protected collectedErrors
- * array for various assertions to inspect.
- */
- protected function error($message = '', $group = 'Other', array $caller = NULL) {
-
-
-
-
-
-
- if ($group == 'User notice') {
- parent::error($message, $group, $caller);
- }
-
- else {
- $this->collectedErrors[] = array(
- 'message' => $message,
- 'group' => $group,
- 'caller' => $caller
- );
- }
- }
-
-
- * Assert that a collected error matches what we are expecting.
- */
- function assertError($error, $group, $function, $file, $message = NULL) {
- $this->assertEqual($error['group'], $group, format_string("Group was %group", array('%group' => $group)));
- $this->assertEqual($error['caller']['function'], $function, format_string("Function was %function", array('%function' => $function)));
- $this->assertEqual(backdrop_basename($error['caller']['file']), $file, format_string("File was %file", array('%file' => $file)));
- if (isset($message)) {
- $this->assertEqual($error['message'], $message, t("Message was %message", array('%message' => $message)));
- }
- }
- }
-
- * Tests the backdrop_parse_info_file() API function.
- */
- class CommonBackdropParseInfoFileTestCase extends BackdropUnitTestCase {
-
- * Parse an example .info file an verify the results.
- */
- function testParseInfoFile() {
- $info_values = backdrop_parse_info_file(backdrop_get_path('module', 'simpletest') . '/tests/common_test_info.txt');
- $this->assertEqual($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.', 'System');
- $this->assertEqual($info_values['simple_constant'], WATCHDOG_INFO, 'Constant value was parsed correctly.', 'System');
- $this->assertEqual($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.', 'System');
- }
- }
-
- * Tests scanning system directories in backdrop_system_listing().
- */
- class CommonBackdropSystemListingTestCase extends BackdropWebTestCase {
-
- * Use the testing profile; this is needed for testDirectoryPrecedence().
- */
- protected $profile = 'testing';
-
-
- * Test that files in different directories take precedence as expected.
- */
- function testDirectoryPrecedence() {
-
-
- $expected_directories = array(
-
-
-
- 'backdrop_system_listing_incompatible_test' => array(
- 'core/modules/simpletest/tests',
- 'core/profiles/testing/modules',
- ),
-
-
- 'backdrop_system_listing_compatible_test' => array(
- 'core/profiles/testing/modules',
- 'core/modules/simpletest/tests',
- ),
- );
-
-
-
-
- foreach ($expected_directories as $module => $directories) {
- foreach ($directories as $directory) {
- $filename = "$directory/$module/$module.module";
- $this->assertTrue(file_exists(BACKDROP_ROOT . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
- }
- }
-
-
-
- $files = backdrop_system_listing('/\.module$/', 'modules', 'name', 1);
- foreach ($expected_directories as $module => $directories) {
- $expected_directory = array_shift($directories);
- $expected_filename = "$expected_directory/$module/$module.module";
- $this->assertEqual($files[$module]->uri, $expected_filename, format_string('Module @module was found at @filename.', array('@module' => $module, '@filename' => $expected_filename)));
- }
- }
- }
-
- * Tests the format_date() function.
- */
- class CommonFormatDateTestCase extends BackdropWebTestCase {
-
-
- * Arbitrary langcode for a custom language.
- */
- const LANGCODE = 'xx';
-
- function setUp() {
- parent::setUp('locale');
-
- config('system.date')
- ->set('user_configurable_timezones', 1)
- ->set('formats.long.pattern', 'l, j. F Y - G:i')
- ->set('formats.medium.pattern', 'j. F Y - G:i')
- ->set('formats.short.pattern', 'Y M j - g:ia')
- ->save();
- backdrop_static_reset('system_get_date_formats');
-
- $GLOBALS['settings']['locale_custom_strings_' . self::LANGCODE] = array(
- '' => array('Sunday' => 'domingo'),
- 'Long month name' => array('March' => 'marzo'),
- );
-
- $this->refreshVariables();
- }
-
-
- * Test admin-defined formats in format_date().
- */
- function testAdminDefinedFormatDate() {
-
- $this->admin_user = $this->backdropCreateUser(array('administer site configuration'));
- $this->backdropLogin($this->admin_user);
-
-
- $edit = array(
- 'label' => 'Example Style',
- 'name' => 'example_style',
- 'pattern' => 'j M y',
- );
- $this->backdropPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
-
-
- $edit = array(
- 'label' => 'Example Style Uppercase',
- 'name' => 'example_style_uppercase',
- 'pattern' => 'j M Y',
- );
- $this->backdropPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
- $this->assertText(t('Date format updated.'));
-
-
-
- backdrop_static_reset('system_get_date_formats');
-
- $timestamp = strtotime('2007-03-10T00:00:00+00:00');
- $this->assertIdentical(format_date($timestamp, 'example_style', '', 'America/Los_Angeles'), '9 Mar 07', 'Test format_date() using an admin-defined date type.');
- $this->assertIdentical(format_date($timestamp, 'example_style_uppercase', '', 'America/Los_Angeles'), '9 Mar 2007', 'Test format_date() using an admin-defined date type with different case.');
- $this->assertIdentical(format_date($timestamp, 'undefined_style'), format_date($timestamp, 'medium'), 'Test format_date() defaulting to medium when $type not found.');
- }
-
-
- * Tests for the format_date() function.
- */
- function testFormatDate() {
- global $user, $language;
-
- $timestamp = strtotime('2007-03-26T00:00:00+00:00');
- $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', 'Test all parameters.');
- $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test translated format.');
- $this->assertIdentical(format_date($timestamp, 'custom', '\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'l, 25-Mar-07 17:00:00 PDT', 'Test an escaped format string.');
- $this->assertIdentical(format_date($timestamp, 'custom', '\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\domingo, 25-Mar-07 17:00:00 PDT', 'Test format containing backslash character.');
- $this->assertIdentical(format_date($timestamp, 'custom', '\\\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\l, 25-Mar-07 17:00:00 PDT', 'Test format containing backslash followed by escaped format string.');
- $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
-
-
- $admin_user = $this->backdropCreateUser(array('administer languages'));
- $this->backdropLogin($admin_user);
- $edit = array(
- 'predefined_langcode' => 'custom',
- 'langcode' => self::LANGCODE,
- 'name' => self::LANGCODE,
- 'native' => self::LANGCODE,
- 'direction' => LANGUAGE_LTR,
- );
- $this->backdropPost('admin/config/regional/language/add', $edit, t('Add custom language'));
-
-
- $edit = array('prefix[' . self::LANGCODE . ']' => self::LANGCODE);
- $this->backdropPost('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
-
-
- $test_user = $this->backdropCreateUser();
- $this->backdropLogin($test_user);
- $edit = array('language' => self::LANGCODE, 'mail' => $test_user->mail, 'timezone' => 'America/Los_Angeles');
- $this->backdropPost('user/' . $test_user->uid . '/edit', $edit, t('Save'));
-
-
- backdrop_save_session(FALSE);
-
- $real_user = $user;
- $user = user_load($test_user->uid, TRUE);
- $real_language = $language->langcode;
- $language->langcode = $user->language;
-
- date_default_timezone_set(backdrop_get_user_timezone());
-
- $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', 'Test a different language.');
- $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
- $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T'), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test custom date format.');
- $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
- $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
- $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
- $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
-
- $this->assertIdentical(format_date($timestamp, 'html_datetime'), '2007-03-25T17:00:00-0700', 'Test html_datetime date format.');
- $this->assertIdentical(format_date($timestamp, 'html_date'), '2007-03-25', 'Test html_date date format.');
- $this->assertIdentical(format_date($timestamp, 'html_time'), '17:00:00', 'Test html_time date format.');
- $this->assertIdentical(format_date($timestamp, 'html_yearless_date'), '03-25', 'Test html_yearless_date date format.');
- $this->assertIdentical(format_date($timestamp, 'html_week'), '2007-W12', 'Test html_week date format.');
- $this->assertIdentical(format_date($timestamp, 'html_month'), '2007-03', 'Test html_month date format.');
- $this->assertIdentical(format_date($timestamp, 'html_year'), '2007', 'Test html_year date format.');
-
-
- $user = $real_user;
- $language->langcode = $real_language;
-
- date_default_timezone_set(backdrop_get_user_timezone());
- backdrop_save_session(TRUE);
- }
- }
-
- * Tests the format_xml_elements() API function.
- */
- class CommonBackdropFormatXmlElementsUnitTestCase extends BackdropUnitTestCase {
-
- * Provide a sample data structure and verify the XML results.
- */
- function testParseFormatXmlElements() {
- $structure = array(
-
- 'key-value-pairs' => array(
- 'second-1' => 'foo',
- 'second-2' => 'bar',
- ),
-
- 'attributes' => array(
- array(
- 'key' => 'second',
- 'value' => 'baz',
- 'attributes' => array(
- 'attr-1' => 'foo',
- 'attr-2' => 'bar',
- ),
- ),
- ),
-
- 'encoding' => array(
- array(
- 'key' => 'second',
- 'value' => '<foo>',
- ),
- array(
- 'key' => 'second',
- 'value' => check_plain('<bar>'),
- 'encoded' => TRUE,
- ),
- ),
-
- 'nested' => array(
- array(
- 'key' => 'second',
- 'value' => array(
- 'third' => 'foo'
- ),
- ),
- ),
- );
- $expected_output = <<<EOF
- <key-value-pairs>
- <second-1>foo</second-1>
- <second-2>bar</second-2>
- </key-value-pairs>
- <attributes>
- <second attr-1="foo" attr-2="bar">baz</second>
- </attributes>
- <encoding>
- <second><foo></second>
- <second><bar></second>
- </encoding>
- <nested>
- <second>
- <third>foo</third>
- </second>
- </nested>
-
- EOF;
- $this->assertIdentical($expected_output, format_xml_elements($structure));
- }
- }
-
- * Tests the backdrop_attributes() functionality.
- */
- class CommonBackdropAttributesUnitTestCase extends BackdropUnitTestCase {
-
- * Tests that backdrop_html_class() cleans the class name properly.
- */
- function testBackdropAttributes() {
-
- $this->assertIdentical(backdrop_attributes(array('title' => '&"\'<>')), ' title="&"'<>"', 'HTML encode attribute values.');
-
-
- $attributes = array('class' => array('first', 'last'));
- $this->assertIdentical(backdrop_attributes(array('class' => array('first', 'last'))), ' class="first last"', 'Concatenate multi-value attributes.');
-
-
- $this->assertIdentical(backdrop_attributes(array('alt' => '')), ' alt=""', 'Empty attribute value #1.');
- $this->assertIdentical(backdrop_attributes(array('alt' => NULL)), ' alt=""', 'Empty attribute value #2.');
-
-
- $attributes = array(
- 'id' => 'id-test',
- 'class' => array('first', 'last'),
- 'alt' => 'Alternate',
- );
- $this->assertIdentical(backdrop_attributes($attributes), ' id="id-test" class="first last" alt="Alternate"', 'Multiple attributes.');
-
-
- $this->assertIdentical(backdrop_attributes(array()), '', 'Empty attributes array.');
- }
- }
-
- * Tests the various backdrop_array_* helper functions.
- */
- class CommonBackdropArrayUnitTest extends BackdropUnitTestCase {
-
-
- * Form array to check.
- */
- protected $form;
-
-
- * Array of parents for the nested element.
- */
- protected $parents;
-
- function setUp() {
- parent::setUp();
-
-
- $this->form['fieldset']['element'] = array(
- '#value' => 'Nested element',
- );
-
-
- $this->parents = array('fieldset', 'element');
- }
-
-
- * Tests getting nested array values.
- */
- function testGet() {
-
- $value = backdrop_array_get_nested_value($this->form, $this->parents);
- $this->assertEqual($value['#value'], 'Nested element', 'Nested element value found.');
-
-
- $value = &backdrop_array_get_nested_value($this->form, $this->parents);
- $value['#value'] = 'New value';
- $value = backdrop_array_get_nested_value($this->form, $this->parents);
- $this->assertEqual($value['#value'], 'New value', 'Nested element value was changed by reference.');
- $this->assertEqual($this->form['fieldset']['element']['#value'], 'New value', 'Nested element value was changed by reference.');
-
-
- $key_exists = NULL;
- backdrop_array_get_nested_value($this->form, $this->parents, $key_exists);
- $this->assertIdentical($key_exists, TRUE, 'Existing key found.');
-
-
- $key_exists = NULL;
- $parents = $this->parents;
- $parents[] = 'foo';
- backdrop_array_get_nested_value($this->form, $parents, $key_exists);
- $this->assertIdentical($key_exists, FALSE, 'Non-existing key not found.');
- }
-
-
- * Tests setting nested array values.
- */
- function testSet() {
- $new_value = array(
- '#value' => 'New value',
- '#required' => TRUE,
- );
-
-
- backdrop_array_set_nested_value($this->form, $this->parents, $new_value);
- $this->assertEqual($this->form['fieldset']['element']['#value'], 'New value', 'Changed nested element value found.');
- $this->assertIdentical($this->form['fieldset']['element']['#required'], TRUE, 'New nested element value found.');
- }
-
-
- * Tests unsetting nested array values.
- */
- function testUnset() {
-
-
- $key_existed = NULL;
- $parents = $this->parents;
- $parents[] = 'foo';
- backdrop_array_unset_nested_value($this->form, $parents, $key_existed);
- $this->assertTrue(isset($this->form['fieldset']['element']['#value']), 'Outermost nested element key still exists.');
- $this->assertIdentical($key_existed, FALSE, 'Non-existing key not found.');
-
-
- $key_existed = NULL;
- backdrop_array_unset_nested_value($this->form, $this->parents, $key_existed);
- $this->assertFalse(isset($this->form['fieldset']['element']), 'Removed nested element not found.');
- $this->assertIdentical($key_existed, TRUE, 'Existing key was found.');
- }
-
-
- * Tests existence of array key.
- */
- function testKeyExists() {
-
- $this->assertIdentical(backdrop_array_nested_key_exists($this->form, $this->parents), TRUE, 'Nested key found.');
-
-
- $parents = $this->parents;
- $parents[] = 'foo';
- $this->assertIdentical(backdrop_array_nested_key_exists($this->form, $parents), FALSE, 'Non-existing nested key not found.');
- }
- }
-
- * Tests the backdrop_json_encode() and backdrop_json_decode() functions.
- */
- class CommonJSONUnitTestCase extends BackdropUnitTestCase {
-
- * Tests converting PHP variables to JSON strings and back.
- */
- function testJSON() {
-
- $str = '';
- for ($i=0; $i < 128; $i++) {
- $str .= chr($i);
- }
-
-
- $html_unsafe = array('<', '>', '\'', '&');
-
- $html_unsafe_escaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
-
-
- $this->assertIdentical(strlen($str), 128, 'A string with the full ASCII table has the correct length.');
- foreach ($html_unsafe as $char) {
- $this->assertTrue(strpos($str, $char) > 0, format_string('A string with the full ASCII table includes @s.', array('@s' => $char)));
- }
-
-
- $json = backdrop_json_encode($str);
- $this->assertTrue(strlen($json) > strlen($str), 'A JSON encoded string is larger than the source string.');
-
-
- $this->assertTrue($json[0] == '"', 'A JSON encoded string begins with ".');
- $this->assertTrue($json[strlen($json) - 1] == '"', 'A JSON encoded string ends with ".');
- $this->assertTrue(substr_count($json, '"') == 2, 'A JSON encoded string contains exactly two ".');
-
-
- $json_decoded = backdrop_json_decode($json);
- $this->assertIdentical($str, $json_decoded, 'Encoding a string to JSON and decoding back results in the original string.');
-
-
-
- $source = array(TRUE, FALSE, 0, 1, '0', '1', '[ ]', '\'', "\"", '\\', $str, array('key1' => $str, 'key2' => array('nested' => TRUE)));
- $json = backdrop_json_encode($source);
- foreach ($html_unsafe as $char) {
- $this->assertTrue(strpos($json, $char) === FALSE, format_string('A JSON encoded string does not contain @s.', array('@s' => $char)));
- }
-
- foreach ($html_unsafe_escaped as $char) {
- $this->assertTrue(strpos($json, $char) > 0, format_string('A JSON encoded string contains @s.', array('@s' => $char)));
- }
- $json_decoded = backdrop_json_decode($json);
- $this->assertNotIdentical($source, $json, 'An array encoded in JSON is not identical to the source.');
- $this->assertIdentical($source, $json_decoded, 'Encoding structured data to JSON and decoding back results in the original data.');
-
-
- $json = backdrop_json_encode($source, TRUE);
- $json_decoded = backdrop_json_decode($json);
- $this->assertIdentical($source, $json_decoded, 'Encoding structured data to pretty-printed JSON and decoding back results in the original data.');
-
-
- $unicode_decoded = 'üéåâ';
- $unicode_encoded = '\u00fc\u00e9\u00e5\u00e2';
- $unicode_encoded_escaped = '\\\\u00fc\\\\u00e9\\\\u00e5\\\\u00e2';
-
-
- $this->assertIdentical('"' . $unicode_decoded . '"', backdrop_json_encode($unicode_decoded, TRUE), 'UTF-8 characters are not encoded in pretty print JSON.');
- $this->assertIdentical('"' . $unicode_encoded_escaped . '"', backdrop_json_encode($unicode_encoded, TRUE), 'Escaped Unicode characters are double-escaped in pretty print JSON.');
-
-
- $this->assertIdentical('"' . $unicode_encoded . '"', backdrop_json_encode($unicode_decoded), 'UTF-8 characters are Unicode encoded in non-pretty JSON.');
- $this->assertIdentical('"' . $unicode_encoded_escaped . '"', backdrop_json_encode($unicode_encoded), 'Escaped Unicode characters are double-escaped in non-pretty JSON.');
-
-
- $this->assertIdentical($unicode_decoded, backdrop_json_decode(backdrop_json_encode($unicode_decoded, TRUE)), 'UTF-8 characters escaped and then unescaped matches original.');
- $this->assertIdentical($unicode_encoded, backdrop_json_decode(backdrop_json_encode($unicode_encoded, TRUE)), 'Unicode characters escaped and then unescaped matches original.');
- $this->assertIdentical($unicode_encoded_escaped, backdrop_json_decode(backdrop_json_encode($unicode_encoded_escaped, TRUE)), 'Escaped Unicode characters escaped and then unescaped matches original.');
-
-
- $this->assertIdentical($unicode_decoded, backdrop_json_decode(backdrop_json_encode($unicode_decoded)), 'UTF-8 characters escaped and then unescaped matches original.');
- $this->assertIdentical($unicode_encoded, backdrop_json_decode(backdrop_json_encode($unicode_encoded)), 'Unicode characters escaped and then unescaped matches original.');
- $this->assertIdentical($unicode_encoded_escaped, backdrop_json_decode(backdrop_json_encode($unicode_encoded_escaped)), 'Escaped Unicode characters escaped and then unescaped matches original.');
- }
- }
-
- * Basic tests for backdrop_add_feed().
- */
- class CommonBackdropAddFeedTestCase extends BackdropWebTestCase {
-
- * Test backdrop_add_feed() with paths, URLs, and titles.
- */
- function testBasicFeedAddNoTitle() {
- $path = $this->randomName(12);
- $external_url = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
- $fully_qualified_local_url = url($this->randomName(12), array('absolute' => TRUE));
-
- $path_for_title = $this->randomName(12);
- $external_for_title = 'http://' . $this->randomName(12) . '/' . $this->randomName(12);
- $fully_qualified_for_title = url($this->randomName(12), array('absolute' => TRUE));
-
-
-
-
-
- $urls = array(
- 'path without title' => array(
- 'input_url' => $path,
- 'output_url' => url($path, array('absolute' => TRUE)),
- 'title' => '',
- ),
- 'external URL without title' => array(
- 'input_url' => $external_url,
- 'output_url' => $external_url,
- 'title' => '',
- ),
- 'local URL without title' => array(
- 'input_url' => $fully_qualified_local_url,
- 'output_url' => $fully_qualified_local_url,
- 'title' => '',
- ),
- 'path with title' => array(
- 'input_url' => $path_for_title,
- 'output_url' => url($path_for_title, array('absolute' => TRUE)),
- 'title' => $this->randomName(12),
- ),
- 'external URL with title' => array(
- 'input_url' => $external_for_title,
- 'output_url' => $external_for_title,
- 'title' => $this->randomName(12),
- ),
- 'local URL with title' => array(
- 'input_url' => $fully_qualified_for_title,
- 'output_url' => $fully_qualified_for_title,
- 'title' => $this->randomName(12),
- ),
- );
-
- foreach ($urls as $description => $feed_info) {
- backdrop_add_feed($feed_info['input_url'], $feed_info['title']);
- }
-
- $this->backdropSetContent(backdrop_get_html_head());
- foreach ($urls as $description => $feed_info) {
- $this->assertPattern($this->urlToRSSLinkPattern($feed_info['output_url'], $feed_info['title']), format_string('Found correct feed header for %description', array('%description' => $description)));
- }
- }
-
-
- * Create a pattern representing the RSS feed in the page.
- */
- function urlToRSSLinkPattern($url, $title = '') {
-
- $url = preg_replace('/([+?.*])/', '[$0]', $url);
- $generated_pattern = '%<link +rel="alternate" +type="application/rss.xml" +title="' . $title . '" +href="' . $url . '" */>%';
- return $generated_pattern;
- }
- }
-
- * Test that backdrop_sort() works correctly.
- */
- class CommonBackdropSortUnitTest extends BackdropUnitTestCase {
-
-
- * Array to use for testing.
- *
- * @var array
- */
- protected $test_array;
-
- function setUp() {
- parent::setUp();
-
- $this->test_array = array(
- 'breadcrumb' => array(
- 'info' => 'Breadcrumb',
- 'weight' => 4,
- 'description' => 'A trail of links from the homepage to the current page.',
- 'render last' => TRUE,
- ),
- 'main-menu' => array(
- 'info' => 'Primary navigation',
- 'weight' => 2,
- 'description' => 'A hierarchical list of links for the Primary navigation.',
- ),
- 'recent' => array(
- 'info' => 'Recent content',
- 'weight' => 3,
- 'description' => 'A list of recently published content.',
- ),
- 'content' => array(
- 'info' => 'Content block',
- 'weight' => 1,
- 'description' => 'Displays a node in a block.',
- 'class' => 'NodeBlock',
- ),
- 'form' => array(
- 'info' => 'Search form',
- 'weight' => -2,
- 'description' => 'The search form for searching site content.',
- ),
- 'custom_block' => array(
- 'info' => 'Add a custom block',
- 'weight' => -1,
- 'description' => 'A basic block for adding custom text.',
- 'class' => 'BlockText',
- ),
- );
- }
-
-
- * Tests backdrop_sort().
- */
- public function testBackdropSort() {
- $expected = array(
- 'form',
- 'custom_block',
- 'content',
- 'main-menu',
- 'recent',
- 'breadcrumb',
- );
-
-
- backdrop_sort($this->test_array, array('weight' => SORT_NUMERIC));
- $this->assertIdentical(array_keys($this->test_array), $expected);
-
-
- backdrop_sort($this->test_array, array('weight' => SORT_NUMERIC), SORT_DESC);
- $this->assertIdentical(array_keys($this->test_array), array_reverse($expected));
-
- $expected = array(
- 'custom_block',
- 'main-menu',
- 'recent',
- 'breadcrumb',
- 'content',
- 'form',
- );
-
-
- backdrop_sort($this->test_array, array('description' => SORT_STRING));
- $this->assertIdentical(array_keys($this->test_array), $expected);
-
-
- backdrop_sort($this->test_array, array('description' => SORT_STRING), SORT_DESC);
- $this->assertIdentical(array_keys($this->test_array), array_reverse($expected));
-
- $expected = array(
- 'form',
- 'custom_block',
- 'content',
- 'main-menu',
- 'recent',
- 'breadcrumb',
- );
-
-
- backdrop_sort($this->test_array, array('weight' => SORT_NUMERIC, 'info' => SORT_STRING));
- $this->assertIdentical(array_keys($this->test_array), $expected);
-
-
- backdrop_sort($this->test_array, array('weight' => SORT_NUMERIC, 'info' => SORT_STRING), SORT_DESC);
- $this->assertIdentical(array_keys($this->test_array), array_reverse($expected));
-
- }
-
- }
-
- * Test array diff functions.
- */
- class ArrayDiffUnitTest extends BackdropUnitTestCase {
-
-
- * Array to use for testing.
- *
- * @var array
- */
- protected $array1;
-
-
- * Array to use for testing.
- *
- * @var array
- */
- protected $array2;
-
- function setUp() {
- parent::setUp();
-
- $this->array1 = array(
- 'same' => 'yes',
- 'different' => 'no',
- 'array_empty_diff' => array(),
- 'null' => NULL,
- 'int_diff' => 1,
- 'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
- 'array_compared_to_string' => array('value'),
- 'string_compared_to_array' => 'value',
- 'new' => 'new',
- );
- $this->array2 = array(
- 'same' => 'yes',
- 'different' => 'yes',
- 'array_empty_diff' => array(),
- 'null' => NULL,
- 'int_diff' => '1',
- 'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
- 'array_compared_to_string' => 'value',
- 'string_compared_to_array' => array('value'),
- );
- }
-
-
-
- * Tests backdrop_array_diff_assoc_recursive().
- */
- public function testArrayDiffAssocRecursive() {
- $expected = array(
- 'different' => 'no',
- 'int_diff' => 1,
-
- 'array_diff' => array('same' => 'same'),
- 'array_compared_to_string' => array('value'),
- 'string_compared_to_array' => 'value',
- 'new' => 'new',
- );
-
- $this->assertIdentical(backdrop_array_diff_assoc_recursive($this->array1, $this->array2), $expected);
- }
- }
-
- * Tests the functionality of backdrop_get_query_array().
- */
- class BackdropGetQueryArrayTestCase extends BackdropWebTestCase {
-
- * Tests that backdrop_get_query_array() correctly explodes query parameters.
- */
- public function testBackdropGetQueryArray() {
- $url = "http://my.site.com/somepath?foo=/content/folder[@name='foo']/folder[@name='bar']";
- $parsed = parse_url($url);
- $result = backdrop_get_query_array($parsed['query']);
- $this->assertEqual($result['foo'], "/content/folder[@name='foo']/folder[@name='bar']", 'backdrop_get_query_array() should only explode parameters on the first equals sign.');
- }
-
- }
-
- * Test for block_interest_cohort.
- */
- class BlockInterestCohortTest extends BackdropWebTestCase {
- protected $profile = 'testing';
-
- function setUp() {
- parent::setUp('common_test');
- }
-
-
- * Tests that FLoC is blocked by default.
- */
- function testDefaultBlocking() {
- $this->backdropGet('node');
- $this->assertEqual($this->backdropGetHeader('Permissions-Policy'), 'interest-cohort=()', 'FLoC is blocked by default.');
- }
-
-
- * Tests that an existing interest-cohort policy is not overwritten.
- */
- function testExistingInterestCohortPolicy() {
- $this->backdropGet('common-test/existing_interest_cohort_policy');
- $this->assertEqual($this->backdropGetHeader('Permissions-Policy'), 'interest-cohort=*', 'Existing interest-cohort policy is not overwritten.');
- }
-
-
- * Tests that an existing header is appended to correctly.
- */
- function testExistingPolicyHeader() {
- $this->backdropGet('common-test/existing_permissions_policy_header');
- $this->assertTrue((strpos($this->backdropGetHeader('Permissions-Policy'), 'geolocation=(),interest-cohort=()') !== FALSE), 'The interest-cohort policy is appended to existing header.');
- }
-
-
- * Tests that FLoC blocking can be disabled.
- */
- function testDisableBlocking() {
- config_set('system.core', 'block_interest_cohort', FALSE);
- $this->backdropGet('node');
- $this->assertFalse($this->backdropGetHeader('Permissions-Policy'), 'FLoC blocking can be disabled.');
- }
- }
-
- * Test for theme_feed_icon().
- */
- class FeedIconTest extends BackdropWebTestCase {
-
- * Check that special characters are correctly escaped. Test for issue #1211668.
- */
- function testFeedIconEscaping() {
- $variables = array();
- $variables['url'] = 'node';
- $variables['title'] = '<>&"\'';
- $text = theme_feed_icon($variables);
- preg_match('/title="(.*?)"/', $text, $matches);
- $this->assertEqual($matches[1], 'Subscribe to &"'', 'theme_feed_icon() escapes reserved HTML characters.');
- }
-
- }