3 namespace Drupal\system\Tests\Theme;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\simpletest\WebTestBase;
7 use Drupal\test_theme\ThemeClass;
8 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\Routing\Route;
11 use Drupal\Component\Render\MarkupInterface;
14 * Tests low-level theme functions.
18 class ThemeTest extends WebTestBase {
25 public static $modules = ['theme_test', 'node'];
27 protected function setUp() {
29 \Drupal::service('theme_handler')->install(['test_theme']);
33 * Test attribute merging.
35 * Render arrays that use a render element and templates (and hence call
36 * template_preprocess()) must ensure the attributes at different occasions
37 * are all merged correctly:
38 * - $variables['attributes'] as passed in to the theme hook implementation.
39 * - the render element's #attributes
40 * - any attributes set in the template's preprocessing function
42 public function testAttributeMerging() {
43 $theme_test_render_element = [
45 '#attributes' => ['data-foo' => 'bar'],
51 $this->assertThemeOutput('theme_test_render_element', $theme_test_render_element, '<div id="bazinga" data-foo="bar" data-variables-are-preprocessed></div>' . "\n");
55 * Test that ThemeManager renders the expected data types.
57 public function testThemeDataTypes() {
58 // theme_test_false is an implemented theme hook so \Drupal::theme() service
59 // should return a string or an object that implements MarkupInterface,
60 // even though the theme function itself can return anything.
61 $foos = ['null' => NULL, 'false' => FALSE, 'integer' => 1, 'string' => 'foo', 'empty_string' => ''];
62 foreach ($foos as $type => $example) {
63 $output = \Drupal::theme()->render('theme_test_foo', ['foo' => $example]);
64 $this->assertTrue($output instanceof MarkupInterface || is_string($output), format_string('\Drupal::theme() returns an object that implements MarkupInterface or a string for data type @type.', ['@type' => $type]));
65 if ($output instanceof MarkupInterface) {
66 $this->assertIdentical((string) $example, $output->__toString());
68 elseif (is_string($output)) {
69 $this->assertIdentical($output, '', 'A string will be return when the theme returns an empty string.');
73 // suggestionnotimplemented is not an implemented theme hook so \Drupal::theme() service
74 // should return FALSE instead of a string.
75 $output = \Drupal::theme()->render(['suggestionnotimplemented'], []);
76 $this->assertIdentical($output, FALSE, '\Drupal::theme() returns FALSE when a hook suggestion is not implemented.');
80 * Test function theme_get_suggestions() for SA-CORE-2009-003.
82 public function testThemeSuggestions() {
83 // Set the front page as something random otherwise the CLI
85 $this->config('system.site')->set('page.front', '/nobody-home')->save();
86 $args = ['node', '1', 'edit'];
87 $suggestions = theme_get_suggestions($args, 'page');
88 $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1', 'page__node__edit'], 'Found expected node edit page suggestions');
89 // Check attack vectors.
90 $args = ['node', '\\1'];
91 $suggestions = theme_get_suggestions($args, 'page');
92 $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1'], 'Removed invalid \\ from suggestions');
93 $args = ['node', '1/'];
94 $suggestions = theme_get_suggestions($args, 'page');
95 $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1'], 'Removed invalid / from suggestions');
96 $args = ['node', "1\0"];
97 $suggestions = theme_get_suggestions($args, 'page');
98 $this->assertEqual($suggestions, ['page__node', 'page__node__%', 'page__node__1'], 'Removed invalid \\0 from suggestions');
99 // Define path with hyphens to be used to generate suggestions.
100 $args = ['node', '1', 'hyphen-path'];
101 $result = ['page__node', 'page__node__%', 'page__node__1', 'page__node__hyphen_path'];
102 $suggestions = theme_get_suggestions($args, 'page');
103 $this->assertEqual($suggestions, $result, 'Found expected page suggestions for paths containing hyphens.');
107 * Ensures preprocess functions run even for suggestion implementations.
109 * The theme hook used by this test has its base preprocess function in a
110 * separate file, so this test also ensures that that file is correctly loaded
113 public function testPreprocessForSuggestions() {
114 // Test with both an unprimed and primed theme registry.
115 drupal_theme_rebuild();
116 for ($i = 0; $i < 2; $i++) {
117 $this->drupalGet('theme-test/suggestion');
118 $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.');
123 * Tests the priority of some theme negotiators.
125 public function testNegotiatorPriorities() {
126 $this->drupalGet('theme-test/priority');
128 // Ensure that the custom theme negotiator was not able to set the theme.
130 $this->assertNoText('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.');
134 * Ensures that non-HTML requests never initialize themes.
136 public function testThemeOnNonHtmlRequest() {
137 $this->drupalGet('theme-test/non-html');
138 $json = Json::decode($this->getRawContent());
139 $this->assertFalse($json['theme_initialized']);
143 * Ensure page-front template suggestion is added when on front page.
145 public function testFrontPageThemeSuggestion() {
146 // Set the current route to user.login because theme_get_suggestions() will
147 // query it to see if we are on the front page.
148 $request = Request::create('/user/login');
149 $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'user.login');
150 $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/user/login'));
151 \Drupal::requestStack()->push($request);
152 $this->config('system.site')->set('page.front', '/user/login')->save();
153 $suggestions = theme_get_suggestions(['user', 'login'], 'page');
154 // Set it back to not annoy the batch runner.
155 \Drupal::requestStack()->pop();
156 $this->assertTrue(in_array('page__front', $suggestions), 'Front page template was suggested.');
160 * Ensures a theme's .info.yml file is able to override a module CSS file from being added to the page.
162 * @see test_theme.info.yml
164 public function testCSSOverride() {
165 // Reuse the same page as in testPreprocessForSuggestions(). We're testing
166 // what is output to the HTML HEAD based on what is in a theme's .info.yml
167 // file, so it doesn't matter what page we get, as long as it is themed with
168 // the test theme. First we test with CSS aggregation disabled.
169 $config = $this->config('system.performance');
170 $config->set('css.preprocess', 0);
172 $this->drupalGet('theme-test/suggestion');
173 $this->assertNoText('js.module.css', 'The theme\'s .info.yml file is able to override a module CSS file from being added to the page.');
175 // Also test with aggregation enabled, simply ensuring no PHP errors are
176 // triggered during drupal_build_css_cache() when a source file doesn't
177 // exist. Then allow remaining tests to continue with aggregation disabled
179 $config->set('css.preprocess', 1);
181 $this->drupalGet('theme-test/suggestion');
182 $config->set('css.preprocess', 0);
187 * Ensures a themes template is overridable based on the 'template' filename.
189 public function testTemplateOverride() {
190 $this->config('system.theme')
191 ->set('default', 'test_theme')
193 $this->drupalGet('theme-test/template-test');
194 $this->assertText('Success: Template overridden.', 'Template overridden by defined \'template\' filename.');
198 * Ensures a theme template can override a theme function.
200 public function testFunctionOverride() {
201 $this->drupalGet('theme-test/function-template-overridden');
202 $this->assertText('Success: Template overrides theme function.', 'Theme function overridden by test_theme template.');
206 * Test the listInfo() function.
208 public function testListThemes() {
209 $theme_handler = $this->container->get('theme_handler');
210 $theme_handler->install(['test_subtheme']);
211 $themes = $theme_handler->listInfo();
213 // Check if ThemeHandlerInterface::listInfo() retrieves enabled themes.
214 $this->assertIdentical(1, $themes['test_theme']->status, 'Installed theme detected');
216 // Check if ThemeHandlerInterface::listInfo() returns disabled themes.
217 // Check for base theme and subtheme lists.
218 $base_theme_list = ['test_basetheme' => 'Theme test base theme'];
219 $sub_theme_list = ['test_subsubtheme' => 'Theme test subsubtheme', 'test_subtheme' => 'Theme test subtheme'];
221 $this->assertIdentical($themes['test_basetheme']->sub_themes, $sub_theme_list, 'Base theme\'s object includes list of subthemes.');
222 $this->assertIdentical($themes['test_subtheme']->base_themes, $base_theme_list, 'Subtheme\'s object includes list of base themes.');
223 // Check for theme engine in subtheme.
224 $this->assertIdentical($themes['test_subtheme']->engine, 'twig', 'Subtheme\'s object includes the theme engine.');
225 // Check for theme engine prefix.
226 $this->assertIdentical($themes['test_basetheme']->prefix, 'twig', 'Base theme\'s object includes the theme engine prefix.');
227 $this->assertIdentical($themes['test_subtheme']->prefix, 'twig', 'Subtheme\'s object includes the theme engine prefix.');
231 * Tests child element rendering for 'render element' theme hooks.
233 public function testDrupalRenderChildren() {
235 '#theme' => 'theme_test_render_element_children',
240 $this->assertThemeOutput('theme_test_render_element_children', $element, 'Foo', 'drupal_render() avoids #theme recursion loop when rendering a render element.');
243 '#theme_wrappers' => ['theme_test_render_element_children'],
248 $this->assertThemeOutput('theme_test_render_element_children', $element, 'Foo', 'drupal_render() avoids #theme_wrappers recursion loop when rendering a render element.');
252 * Tests theme can provide classes.
254 public function testClassLoading() {
259 * Tests drupal_find_theme_templates().
261 public function testFindThemeTemplates() {
262 $registry = $this->container->get('theme.registry')->get();
263 $templates = drupal_find_theme_templates($registry, '.html.twig', drupal_get_path('theme', 'test_theme'));
264 $this->assertEqual($templates['node__1']['template'], 'node--1', 'Template node--1.tpl.twig was found in test_theme.');
268 * Tests that the page variable is not prematurely flattened.
270 * Some modules check the page array in template_preprocess_html(), so we
271 * ensure that it has not been rendered prematurely.
273 public function testPreprocessHtml() {
274 $this->drupalGet('');
275 $attributes = $this->xpath('/html/body[@theme_test_page_variable="Page variable is an array."]');
276 $this->assertTrue(count($attributes) == 1, 'In template_preprocess_html(), the page variable is still an array (not rendered yet).');
277 $this->assertText('theme test page bottom markup', 'Modules are able to set the page bottom region.');
281 * Tests that region attributes can be manipulated via preprocess functions.
283 public function testRegionClass() {
284 \Drupal::service('module_installer')->install(['block', 'theme_region_test']);
287 $this->drupalPlaceBlock('system_main_block');
288 $this->drupalGet('');
289 $elements = $this->cssSelect(".region-sidebar-first.new_class");
290 $this->assertEqual(count($elements), 1, 'New class found.');
294 * Ensures suggestion preprocess functions run for default implementations.
296 * The theme hook used by this test has its base preprocess function in a
297 * separate file, so this test also ensures that that file is correctly loaded
300 public function testSuggestionPreprocessForDefaults() {
301 $this->config('system.theme')->set('default', 'test_theme')->save();
302 // Test with both an unprimed and primed theme registry.
303 drupal_theme_rebuild();
304 for ($i = 0; $i < 2; $i++) {
305 $this->drupalGet('theme-test/preprocess-suggestions');
306 $items = $this->cssSelect('.suggestion');
314 foreach ($expected_values as $key => $value) {
315 $this->assertEqual((string) $value, $items[$key]);