3 namespace Drupal\system\Tests\Routing;
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
7 use Drupal\Core\Language\LanguageInterface;
8 use Drupal\simpletest\WebTestBase;
9 use Symfony\Component\Routing\Exception\RouteNotFoundException;
13 * Functional class for the full integrated routing system.
17 class RouterTest extends WebTestBase {
24 public static $modules = ['router_test'];
27 * Confirms that our FinishResponseSubscriber logic works properly.
29 public function testFinishResponseSubscriber() {
30 $renderer_required_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
31 $expected_cache_contexts = Cache::mergeContexts($renderer_required_cache_contexts, ['url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT]);
33 // Confirm that the router can get to a controller.
34 $this->drupalGet('router_test/test1');
35 $this->assertRaw('test1', 'The correct string was returned because the route was successful.');
36 // Check expected headers from FinishResponseSubscriber.
37 $headers = $this->drupalGetHeaders();
38 $this->assertEqual($headers['x-ua-compatible'], 'IE=edge');
39 $this->assertEqual($headers['content-language'], 'en');
40 $this->assertEqual($headers['x-content-type-options'], 'nosniff');
41 $this->assertEqual($headers['x-frame-options'], 'SAMEORIGIN');
43 $this->drupalGet('router_test/test2');
44 $this->assertRaw('test2', 'The correct string was returned because the route was successful.');
45 // Check expected headers from FinishResponseSubscriber.
46 $headers = $this->drupalGetHeaders();
47 $this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', $expected_cache_contexts));
48 $this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous http_response rendered');
49 // Confirm that the page wrapping is being added, so we're not getting a
51 $this->assertRaw('</html>', 'Page markup was found.');
52 // In some instances, the subrequest handling may get confused and render
53 // a page inception style. This test verifies that is not happening.
54 $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
57 // Confirm that route-level access check's cacheability is applied to the
58 // X-Drupal-Cache-Contexts and X-Drupal-Cache-Tags headers.
59 // 1. controller result: render array, globally cacheable route access.
60 $this->drupalGet('router_test/test18');
61 $headers = $this->drupalGetHeaders();
62 $this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', Cache::mergeContexts($renderer_required_cache_contexts, ['url'])));
63 $this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous foo http_response rendered');
64 // 2. controller result: render array, per-role cacheable route access.
65 $this->drupalGet('router_test/test19');
66 $headers = $this->drupalGetHeaders();
67 $this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', Cache::mergeContexts($renderer_required_cache_contexts, ['url', 'user.roles'])));
68 $this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous foo http_response rendered');
69 // 3. controller result: Response object, globally cacheable route access.
70 $this->drupalGet('router_test/test1');
71 $headers = $this->drupalGetHeaders();
72 $this->assertFalse(isset($headers['x-drupal-cache-contexts']));
73 $this->assertFalse(isset($headers['x-drupal-cache-tags']));
74 // 4. controller result: Response object, per-role cacheable route access.
75 $this->drupalGet('router_test/test20');
76 $headers = $this->drupalGetHeaders();
77 $this->assertFalse(isset($headers['x-drupal-cache-contexts']));
78 $this->assertFalse(isset($headers['x-drupal-cache-tags']));
79 // 5. controller result: CacheableResponse object, globally cacheable route access.
80 $this->drupalGet('router_test/test21');
81 $headers = $this->drupalGetHeaders();
82 $this->assertEqual($headers['x-drupal-cache-contexts'], '');
83 $this->assertEqual($headers['x-drupal-cache-tags'], 'http_response');
84 // 6. controller result: CacheableResponse object, per-role cacheable route access.
85 $this->drupalGet('router_test/test22');
86 $headers = $this->drupalGetHeaders();
87 $this->assertEqual($headers['x-drupal-cache-contexts'], 'user.roles');
88 $this->assertEqual($headers['x-drupal-cache-tags'], 'http_response');
90 // Finally, verify that the X-Drupal-Cache-Contexts and X-Drupal-Cache-Tags
91 // headers are not sent when their container parameter is set to FALSE.
92 $this->drupalGet('router_test/test18');
93 $headers = $this->drupalGetHeaders();
94 $this->assertTrue(isset($headers['x-drupal-cache-contexts']));
95 $this->assertTrue(isset($headers['x-drupal-cache-tags']));
96 $this->setHttpResponseDebugCacheabilityHeaders(FALSE);
97 $this->drupalGet('router_test/test18');
98 $headers = $this->drupalGetHeaders();
99 $this->assertFalse(isset($headers['x-drupal-cache-contexts']));
100 $this->assertFalse(isset($headers['x-drupal-cache-tags']));
104 * Confirms that multiple routes with the same path do not cause an error.
106 public function testDuplicateRoutePaths() {
107 // Tests two routes with exactly the same path. The route with the maximum
108 // fit and lowest sorting route name will match, regardless of the order the
109 // routes are declared.
110 // @see \Drupal\Core\Routing\RouteProvider::getRoutesByPath()
111 $this->drupalGet('router-test/duplicate-path2');
112 $this->assertResponse(200);
113 $this->assertRaw('router_test.two_duplicate1');
115 // Tests three routes with same the path. One of the routes the path has a
117 $this->drupalGet('router-test/case-sensitive-duplicate-path3');
118 $this->assertResponse(200);
119 $this->assertRaw('router_test.case_sensitive_duplicate1');
120 // While case-insensitive matching works, exact matches are preferred.
121 $this->drupalGet('router-test/case-sensitive-Duplicate-PATH3');
122 $this->assertResponse(200);
123 $this->assertRaw('router_test.case_sensitive_duplicate2');
124 // Test that case-insensitive matching works, falling back to the first
126 $this->drupalGet('router-test/case-sensitive-Duplicate-Path3');
127 $this->assertResponse(200);
128 $this->assertRaw('router_test.case_sensitive_duplicate1');
132 * Confirms that placeholders in paths work correctly.
134 public function testControllerPlaceholders() {
135 // Test with 0 and a random value.
136 $values = ["0", $this->randomMachineName()];
137 foreach ($values as $value) {
138 $this->drupalGet('router_test/test3/' . $value);
139 $this->assertResponse(200);
140 $this->assertRaw($value, 'The correct string was returned because the route was successful.');
143 // Confirm that the page wrapping is being added, so we're not getting a
144 // raw body returned.
145 $this->assertRaw('</html>', 'Page markup was found.');
147 // In some instances, the subrequest handling may get confused and render
148 // a page inception style. This test verifies that is not happening.
149 $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
153 * Confirms that default placeholders in paths work correctly.
155 public function testControllerPlaceholdersDefaultValues() {
156 $this->drupalGet('router_test/test4');
157 $this->assertResponse(200);
158 $this->assertRaw('narf', 'The correct string was returned because the route was successful.');
160 // Confirm that the page wrapping is being added, so we're not getting a
161 // raw body returned.
162 $this->assertRaw('</html>', 'Page markup was found.');
164 // In some instances, the subrequest handling may get confused and render
165 // a page inception style. This test verifies that is not happening.
166 $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
170 * Confirms that default placeholders in paths work correctly.
172 public function testControllerPlaceholdersDefaultValuesProvided() {
173 $this->drupalGet('router_test/test4/barf');
174 $this->assertResponse(200);
175 $this->assertRaw('barf', 'The correct string was returned because the route was successful.');
177 // Confirm that the page wrapping is being added, so we're not getting a
178 // raw body returned.
179 $this->assertRaw('</html>', 'Page markup was found.');
181 // In some instances, the subrequest handling may get confused and render
182 // a page inception style. This test verifies that is not happening.
183 $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
187 * Checks that dynamically defined and altered routes work correctly.
189 * @see \Drupal\router_test\RouteSubscriber
191 public function testDynamicRoutes() {
192 // Test the altered route.
193 $this->drupalGet('router_test/test6');
194 $this->assertResponse(200);
195 $this->assertRaw('test5', 'The correct string was returned because the route was successful.');
199 * Checks that a request with text/html response gets rendered as a page.
201 public function testControllerResolutionPage() {
202 $this->drupalGet('/router_test/test10');
204 $this->assertRaw('abcde', 'Correct body was found.');
206 // Confirm that the page wrapping is being added, so we're not getting a
207 // raw body returned.
208 $this->assertRaw('</html>', 'Page markup was found.');
210 // In some instances, the subrequest handling may get confused and render
211 // a page inception style. This test verifies that is not happening.
212 $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
216 * Checks the generate method on the url generator using the front router.
218 public function testUrlGeneratorFront() {
219 $front_url = Url::fromRoute('<front>', [], ['absolute' => TRUE]);
220 // Compare to the site base URL.
221 $base_url = Url::fromUri('base:/', ['absolute' => TRUE]);
222 $this->assertIdentical($base_url->toString(), $front_url->toString());
226 * Tests that a page trying to match a path will succeed.
228 public function testRouterMatching() {
229 $this->drupalGet('router_test/test14/1');
230 $this->assertResponse(200);
231 $this->assertText('User route "entity.user.canonical" was matched.');
233 // Try to match a route for a non-existent user.
234 $this->drupalGet('router_test/test14/2');
235 $this->assertResponse(200);
236 $this->assertText('Route not matched.');
238 // Check that very long paths don't cause an error.
239 $path = 'router_test/test1';
240 $suffix = '/d/r/u/p/a/l';
241 for ($i = 0; $i < 10; $i++) {
243 $this->drupalGet($path);
244 $this->assertResponse(404);
249 * Tests that a PSR-7 response works.
251 public function testRouterResponsePsr7() {
252 $this->drupalGet('/router_test/test23');
253 $this->assertResponse(200);
254 $this->assertText('test23');
258 * Tests the user account on the DIC.
260 public function testUserAccount() {
261 $account = $this->drupalCreateUser();
262 $this->drupalLogin($account);
264 $second_account = $this->drupalCreateUser();
266 $this->drupalGet('router_test/test12/' . $second_account->id());
267 $this->assertText($account->getUsername() . ':' . $second_account->getUsername());
268 $this->assertEqual($account->id(), $this->loggedInUser->id(), 'Ensure that the user was not changed.');
270 $this->drupalGet('router_test/test13/' . $second_account->id());
271 $this->assertText($account->getUsername() . ':' . $second_account->getUsername());
272 $this->assertEqual($account->id(), $this->loggedInUser->id(), 'Ensure that the user was not changed.');
276 * Checks that an ajax request gets rendered as an Ajax response, by mime.
278 public function testControllerResolutionAjax() {
279 // This will fail with a JSON parse error if the request is not routed to
280 // The correct controller.
281 $this->drupalGetAjax('/router_test/test10');
283 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/json', 'Correct mime content type was returned');
285 $this->assertRaw('abcde', 'Correct body was found.');
289 * Tests that routes no longer exist for a module that has been uninstalled.
291 public function testRouterUninstallInstall() {
292 \Drupal::service('module_installer')->uninstall(['router_test']);
293 \Drupal::service('router.builder')->rebuild();
295 \Drupal::service('router.route_provider')->getRouteByName('router_test.1');
296 $this->fail('Route was delete on uninstall.');
298 catch (RouteNotFoundException $e) {
299 $this->pass('Route was delete on uninstall.');
301 // Install the module again.
302 \Drupal::service('module_installer')->install(['router_test']);
303 \Drupal::service('router.builder')->rebuild();
304 $route = \Drupal::service('router.route_provider')->getRouteByName('router_test.1');
305 $this->assertNotNull($route, 'Route exists after module installation');
309 * Ensure that multiple leading slashes are redirected.
311 public function testLeadingSlashes() {
312 $request = $this->container->get('request_stack')->getCurrentRequest();
313 $url = $request->getUriForPath('//router_test/test1');
314 $this->drupalGet($url);
315 $this->assertEqual(1, $this->redirectCount, $url . " redirected to " . $this->url);
316 $this->assertUrl($request->getUriForPath('/router_test/test1'));
318 // It should not matter how many leading slashes are used and query strings
319 // should be preserved.
320 $url = $request->getUriForPath('/////////////////////////////////////////////////router_test/test1') . '?qs=test';
321 $this->drupalGet($url);
322 $this->assertEqual(1, $this->redirectCount, $url . " redirected to " . $this->url);
323 $this->assertUrl($request->getUriForPath('/router_test/test1') . '?qs=test');