Skip to content
theme.test 17.8 KiB
Newer Older
class ThemeTestCase extends DrupalWebTestCase {
      'description' => 'Test low-level theme functions.',
  function setUp() {
    parent::setUp('theme_test');
    theme_enable(array('test_theme'));
  }

   * Test function theme_get_suggestions() for SA-CORE-2009-003.
    // Set the front page as something random otherwise the CLI
    // test runner fails.
    variable_set('site_frontpage', 'nobody-home');
    $args = array('node', '1', 'edit');
    $suggestions = theme_get_suggestions($args, 'page');
    $this->assertEqual($suggestions, array('page__node', 'page__node__%', 'page__node__1', 'page__node__edit'), t('Found expected node edit page suggestions'));
    // Check attack vectors.
    $args = array('node', '\\1');
    $suggestions = theme_get_suggestions($args, 'page');
    $this->assertEqual($suggestions, array('page__node', 'page__node__%', 'page__node__1'), t('Removed invalid \\ from suggestions'));
    $suggestions = theme_get_suggestions($args, 'page');
    $this->assertEqual($suggestions, array('page__node', 'page__node__%', 'page__node__1'), t('Removed invalid / from suggestions'));
    $suggestions = theme_get_suggestions($args, 'page');
    $this->assertEqual($suggestions, array('page__node', 'page__node__%', 'page__node__1'), t('Removed invalid \\0 from suggestions'));
    // Define path with hyphens to be used to generate suggestions.
    $args = array('node', '1', 'hyphen-path');
    $result = array('page__node', 'page__node__%', 'page__node__1', 'page__node__hyphen_path');
    $suggestions = theme_get_suggestions($args, 'page');
    $this->assertEqual($suggestions, $result, t('Found expected page suggestions for paths containing hyphens.'));
   * Ensures preprocess functions run even for suggestion implementations.
   *
   * The theme hook used by this test has its base preprocess function in a
   * separate file, so this test also ensures that that file is correctly loaded
   * when needed.
   */
  function testPreprocessForSuggestions() {
    // Test with both an unprimed and primed theme registry.
    drupal_theme_rebuild();
    for ($i = 0; $i < 2; $i++) {
      $this->drupalGet('theme-test/suggestion');
      $this->assertText('Theme hook implementor=test_theme_theme_test__suggestion(). Foo=template_preprocess_theme_test', 'Theme hook suggestion ran with data available from a preprocess function for the base hook.');
    }

  /**
   * Ensure page-front template suggestion is added when on front page.
   */
  function testFrontPageThemeSuggestion() {
    $q = $_GET['q'];
    // Set $_GET['q'] to node because theme_get_suggestions() will query it to
    // see if we are on the front page.
    $_GET['q'] = variable_get('site_frontpage', 'node');
    $suggestions = theme_get_suggestions(explode('/', $_GET['q']), 'page');
    // Set it back to not annoy the batch runner.
    $_GET['q'] = $q;
    $this->assertTrue(in_array('page__front', $suggestions), t('Front page template was suggested.'));

  /**
   * Ensures theme hook_*_alter() implementations can run before anything is rendered.
   */
  function testAlter() {
    $this->drupalGet('theme-test/alter');
    $this->assertText('The altered data is test_theme_theme_test_alter_alter was invoked.', t('The theme was able to implement an alter hook during page building before anything was rendered.'));
  }

  /**
   * Ensures a theme's .info file is able to override a module CSS file from being added to the page.
   *
   * @see test_theme.info
   */
  function testCSSOverride() {
    // Reuse the same page as in testPreprocessForSuggestions(). We're testing
    // what is output to the HTML HEAD based on what is in a theme's .info file,
    // so it doesn't matter what page we get, as long as it is themed with the
    // test theme. First we test with CSS aggregation disabled.
    variable_set('preprocess_css', 0);
    $this->drupalGet('theme-test/suggestion');
    $this->assertNoText('system.base.css', t('The theme\'s .info file is able to override a module CSS file from being added to the page.'));

    // Also test with aggregation enabled, simply ensuring no PHP errors are
    // triggered during drupal_build_css_cache() when a source file doesn't
    // exist. Then allow remaining tests to continue with aggregation disabled
    // by default.
    variable_set('preprocess_css', 1);
    $this->drupalGet('theme-test/suggestion');
    variable_set('preprocess_css', 0);
  }

  /**
   * Ensures the theme registry is rebuilt when modules are disabled/enabled.
   */
  function testRegistryRebuild() {
    $this->assertIdentical(theme('theme_test_foo', array('foo' => 'a')), 'a', 'The theme registry contains theme_test_foo.');

    module_disable(array('theme_test'), FALSE);
    $this->assertIdentical(theme('theme_test_foo', array('foo' => 'b')), '', 'The theme registry does not contain theme_test_foo, because the module is disabled.');

    module_enable(array('theme_test'), FALSE);
    $this->assertIdentical(theme('theme_test_foo', array('foo' => 'c')), 'c', 'The theme registry contains theme_test_foo again after re-enabling the module.');
  }
class ThemeTableTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme Table',
      'description' => 'Tests built-in theme functions.',
      'group' => 'Theme',
  /**
   * Tableheader.js provides 'sticky' table headers, and is included by default.
   */
  function testThemeTableStickyHeaders() {
    $header = array('one', 'two', 'three');
    $rows = array(array(1,2,3), array(4,5,6), array(7,8,9));
    $this->content = theme('table', array('header' => $header, 'rows' => $rows));
    $this->assertTrue(isset($js['misc/tableheader.js']), t('tableheader.js was included when $sticky = TRUE.'));
    $this->assertRaw('sticky-enabled',  t('Table has a class of sticky-enabled when $sticky = TRUE.'));
    drupal_static_reset('drupal_add_js');
  }

  /**
   * If $sticky is FALSE, no tableheader.js should be included.
   */
  function testThemeTableNoStickyHeaders() {
    $header = array('one', 'two', 'three');
    $rows = array(array(1,2,3), array(4,5,6), array(7,8,9));
    $attributes = array();
    $caption = NULL;
    $colgroups = array();
    $this->content = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => $attributes, 'caption' => $caption, 'colgroups' => $colgroups, 'sticky' => FALSE));
    $this->assertFalse(isset($js['misc/tableheader.js']), t('tableheader.js was not included because $sticky = FALSE.'));
    $this->assertNoRaw('sticky-enabled',  t('Table does not have a class of sticky-enabled because $sticky = FALSE.'));
    drupal_static_reset('drupal_add_js');
  }
   * Tests that the table header is printed correctly even if there are no rows,
   * and that the empty text is displayed correctly.
    $header = array(
      t('Header 1'),
      array(
        'data' => t('Header 2'),
        'colspan' => 2,
      ),
    );
    $this->content = theme('table', array('header' => $header, 'rows' => array(), 'empty' => t('No strings available.')));
    $this->assertRaw('<tr class="odd"><td colspan="3" class="empty message">No strings available.</td>', t('Correct colspan was set on empty message.'));
    $this->assertRaw('<thead><tr><th>Header 1</th>', t('Table header was printed.'));

/**
 * Unit tests for theme_item_list().
 */
class ThemeItemListUnitTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme item list',
      'description' => 'Test the theme_item_list() function.',
      'group' => 'Theme',
    );
  }

  /**
   * Test nested list rendering.
   */
  function testNestedList() {
    $items = array('a', array('data' => 'b', 'children' => array('c', 'd')), 'e');
    $expected = '<div class="item-list"><ul><li class="first">a</li>
<li>b<div class="item-list"><ul><li class="first">c</li>
<li class="last">d</li>
</ul></div></li>
<li class="last">e</li>
</ul></div>';
    $output = theme('item_list', array('items' => $items));
    $this->assertIdentical($expected, $output, 'Nested list is rendered correctly.');
  }
}
class ThemeLinksTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Links',
      'description' => 'Test the theme_links() function and rendering groups of links.',
      'group' => 'Theme',
    );
  }

  /**
   * Test the use of drupal_pre_render_links() on a nested array of links.
   */
  function testDrupalPreRenderLinks() {
    // Define the base array to be rendered, containing a variety of different
    // kinds of links.
    $base_array = array(
      '#theme' => 'links',
      '#pre_render' => array('drupal_pre_render_links'),
      '#links' => array(
        'parent_link' => array(
          'title' => 'Parent link original',
          'href' => 'parent-link-original',
        ),
      ),
      'first_child' => array(
        '#theme' => 'links',
        '#links' => array(
          // This should be rendered if 'first_child' is rendered separately,
          // but ignored if the parent is being rendered (since it duplicates
          // one of the parent's links).
          'parent_link' => array(
            'title' => 'Parent link copy',
            'href' => 'parent-link-copy',
          ),
          // This should always be rendered.
          'first_child_link' => array(
            'title' => 'First child link',
            'href' => 'first-child-link',
          ),
        ),
      ),
      // This should always be rendered as part of the parent.
      'second_child' => array(
        '#theme' => 'links',
        '#links' => array(
          'second_child_link' => array(
            'title' => 'Second child link',
            'href' => 'second-child-link',
          ),
        ),
      ),
      // This should never be rendered, since the user does not have access to
      // it.
      'third_child' => array(
        '#theme' => 'links',
        '#links' => array(
          'third_child_link' => array(
            'title' => 'Third child link',
            'href' => 'third-child-link',
          ),
        ),
        '#access' => FALSE,
      ),
    );

    // Start with a fresh copy of the base array, and try rendering the entire
    // thing. We expect a single <ul> with appropriate links contained within
    // it.
    $render_array = $base_array;
    $html = drupal_render($render_array);
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $this->assertEqual($dom->getElementsByTagName('ul')->length, 1, t('One "ul" tag found in the rendered HTML.'));
    $list_elements = $dom->getElementsByTagName('li');
    $this->assertEqual($list_elements->length, 3, t('Three "li" tags found in the rendered HTML.'));
    $this->assertEqual($list_elements->item(0)->nodeValue, 'Parent link original', t('First expected link found.'));
    $this->assertEqual($list_elements->item(1)->nodeValue, 'First child link', t('Second expected link found.'));
    $this->assertEqual($list_elements->item(2)->nodeValue, 'Second child link', t('Third expected link found.'));
    $this->assertIdentical(strpos($html, 'Parent link copy'), FALSE, t('"Parent link copy" link not found.'));
    $this->assertIdentical(strpos($html, 'Third child link'), FALSE, t('"Third child link" link not found.'));

    // Now render 'first_child', followed by the rest of the links, and make
    // sure we get two separate <ul>'s with the appropriate links contained
    // within each.
    $render_array = $base_array;
    $child_html = drupal_render($render_array['first_child']);
    $parent_html = drupal_render($render_array);
    // First check the child HTML.
    $dom = new DOMDocument();
    $dom->loadHTML($child_html);
    $this->assertEqual($dom->getElementsByTagName('ul')->length, 1, t('One "ul" tag found in the rendered child HTML.'));
    $list_elements = $dom->getElementsByTagName('li');
    $this->assertEqual($list_elements->length, 2, t('Two "li" tags found in the rendered child HTML.'));
    $this->assertEqual($list_elements->item(0)->nodeValue, 'Parent link copy', t('First expected link found.'));
    $this->assertEqual($list_elements->item(1)->nodeValue, 'First child link', t('Second expected link found.'));
    // Then check the parent HTML.
    $dom = new DOMDocument();
    $dom->loadHTML($parent_html);
    $this->assertEqual($dom->getElementsByTagName('ul')->length, 1, t('One "ul" tag found in the rendered parent HTML.'));
    $list_elements = $dom->getElementsByTagName('li');
    $this->assertEqual($list_elements->length, 2, t('Two "li" tags found in the rendered parent HTML.'));
    $this->assertEqual($list_elements->item(0)->nodeValue, 'Parent link original', t('First expected link found.'));
    $this->assertEqual($list_elements->item(1)->nodeValue, 'Second child link', t('Second expected link found.'));
    $this->assertIdentical(strpos($parent_html, 'First child link'), FALSE, t('"First child link" link not found.'));
    $this->assertIdentical(strpos($parent_html, 'Third child link'), FALSE, t('"Third child link" link not found.'));
  }
}

/**
 * Functional test for initialization of the theme system in hook_init().
 */
class ThemeHookInitTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme initialization in hook_init()',
      'description' => 'Tests that the theme system can be correctly initialized in hook_init().',
      'group' => 'Theme',
    );
  }

  function setUp() {
    parent::setUp('theme_test');
  }

  /**
   * Test that the theme system can generate output when called by hook_init().
   */
  function testThemeInitializationHookInit() {
    $this->drupalGet('theme-test/hook-init');
    $this->assertRaw('Themed output generated in hook_init()', t('Themed output generated in hook_init() correctly appears on the page.'));
    $this->assertRaw('bartik/css/style.css', t("The default theme's CSS appears on the page when the theme system is initialized in hook_init()."));

/**
 * Tests autocompletion not loading registry.
 */
class ThemeFastTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme fast initialization',
      'description' => 'Test that autocompletion does not load the registry.',
      'group' => 'Theme'
    );
  }

  function setUp() {
    parent::setUp('theme_test');
    $this->account = $this->drupalCreateUser(array('access user profiles'));
  }

  /**
   * Tests access to user autocompletion and verify the correct results.
   */
  function testUserAutocomplete() {
    $this->drupalLogin($this->account);
    $this->drupalGet('user/autocomplete/' . $this->account->name);
    $this->assertText('registry not initialized', t('The registry was not initialized'));
  }
}

/**
 * Unit tests for theme_html_tag().
 */
class ThemeHtmlTag extends DrupalUnitTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme HTML Tag',
      'description' => 'Tests theme_html_tag() built-in theme functions.',
      'group' => 'Theme',
    );
  }

  /**
   * Test function theme_html_tag()
   */
  function testThemeHtmlTag() {
    // Test auto-closure meta tag generation
    $tag['element'] = array('#tag' => 'meta', '#attributes' => array('name' => 'description', 'content' => 'Drupal test'));
    $this->assertEqual('<meta name="description" content="Drupal test" />'."\n", theme_html_tag($tag), t('Test auto-closure meta tag generation.'));

    // Test title tag generation
    $tag['element'] = array('#tag' => 'title', '#value' => 'title test');
    $this->assertEqual('<title>title test</title>'."\n", theme_html_tag($tag), t('Test title tag generation.'));
  }
}

/**
 * Tests for the ThemeRegistry class.
 */
class ThemeRegistryTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'ThemeRegistry',
      'description' => 'Tests the behavior of the ThemeRegistry class',
      'group' => 'Theme',
    );
  }
  function setUp() {
    parent::setUp('theme_test');
  }

  /**
   * Tests the behavior of the theme registry class.
   */
  function testRaceCondition() {
    $_SERVER['REQUEST_METHOD'] = 'GET';
    $cid = 'test_theme_registry';

    // Directly instantiate the theme registry, this will cause a base cache
    // entry to be written in __construct().
    $registry = new ThemeRegistry($cid, 'cache');

    $this->assertTrue(cache_get($cid), 'Cache entry was created.');

    // Trigger a cache miss for an offset.
    $this->assertTrue($registry['theme_test_template_test'], 'Offset was returned correctly from the theme registry.');
    // This will cause the ThemeRegistry class to write an updated version of
    // the cache entry when it is destroyed, usually at the end of the request.
    // Before that happens, manually delete the cache entry we created earlier
    // so that the new entry is written from scratch.
    cache_clear_all($cid, 'cache');

    // Destroy the class so that it triggers a cache write for the offset.
    unset($registry);

    $this->assertTrue(cache_get($cid), 'Cache entry was created.');

    // Create a new instance of the class. Confirm that both the offset
    // requested previously, and one that has not yet been requested are both
    // available.
    $registry = new ThemeRegistry($cid, 'cache');

    $this->assertTrue($registry['theme_test_template_test'], 'Offset was returned correctly from the theme registry');
    $this->assertTrue($registry['theme_test_template_test_2'], 'Offset was returned correctly from the theme registry');
  }
}