Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[yaffs-website] / web / core / modules / system / src / Tests / Routing / RouterTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Routing;
4
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;
10 use Drupal\Core\Url;
11
12 /**
13  * Functional class for the full integrated routing system.
14  *
15  * @group Routing
16  */
17 class RouterTest extends WebTestBase {
18
19   /**
20    * Modules to enable.
21    *
22    * @var array
23    */
24   public static $modules = ['router_test'];
25
26   /**
27    * Confirms that our FinishResponseSubscriber logic works properly.
28    */
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]);
32
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');
42
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
50     // raw body returned.
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.');
55
56     // Confirm that route-level access check's cacheability is applied to the
57     // X-Drupal-Cache-Contexts and X-Drupal-Cache-Tags headers.
58     // 1. controller result: render array, globally cacheable route access.
59     $this->drupalGet('router_test/test18');
60     $headers = $this->drupalGetHeaders();
61     $this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', Cache::mergeContexts($renderer_required_cache_contexts, ['url'])));
62     $this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous foo http_response rendered');
63     // 2. controller result: render array, per-role cacheable route access.
64     $this->drupalGet('router_test/test19');
65     $headers = $this->drupalGetHeaders();
66     $this->assertEqual($headers['x-drupal-cache-contexts'], implode(' ', Cache::mergeContexts($renderer_required_cache_contexts, ['url', 'user.roles'])));
67     $this->assertEqual($headers['x-drupal-cache-tags'], 'config:user.role.anonymous foo http_response rendered');
68     // 3. controller result: Response object, globally cacheable route access.
69     $this->drupalGet('router_test/test1');
70     $headers = $this->drupalGetHeaders();
71     $this->assertFalse(isset($headers['x-drupal-cache-contexts']));
72     $this->assertFalse(isset($headers['x-drupal-cache-tags']));
73     // 4. controller result: Response object, per-role cacheable route access.
74     $this->drupalGet('router_test/test20');
75     $headers = $this->drupalGetHeaders();
76     $this->assertFalse(isset($headers['x-drupal-cache-contexts']));
77     $this->assertFalse(isset($headers['x-drupal-cache-tags']));
78     // 5. controller result: CacheableResponse object, globally cacheable route access.
79     $this->drupalGet('router_test/test21');
80     $headers = $this->drupalGetHeaders();
81     $this->assertEqual($headers['x-drupal-cache-contexts'], '');
82     $this->assertEqual($headers['x-drupal-cache-tags'], 'http_response');
83     // 6. controller result: CacheableResponse object, per-role cacheable route access.
84     $this->drupalGet('router_test/test22');
85     $headers = $this->drupalGetHeaders();
86     $this->assertEqual($headers['x-drupal-cache-contexts'], 'user.roles');
87     $this->assertEqual($headers['x-drupal-cache-tags'], 'http_response');
88
89     // Finally, verify that the X-Drupal-Cache-Contexts and X-Drupal-Cache-Tags
90     // headers are not sent when their container parameter is set to FALSE.
91     $this->drupalGet('router_test/test18');
92     $headers = $this->drupalGetHeaders();
93     $this->assertTrue(isset($headers['x-drupal-cache-contexts']));
94     $this->assertTrue(isset($headers['x-drupal-cache-tags']));
95     $this->setHttpResponseDebugCacheabilityHeaders(FALSE);
96     $this->drupalGet('router_test/test18');
97     $headers = $this->drupalGetHeaders();
98     $this->assertFalse(isset($headers['x-drupal-cache-contexts']));
99     $this->assertFalse(isset($headers['x-drupal-cache-tags']));
100   }
101
102   /**
103    * Confirms that multiple routes with the same path do not cause an error.
104    */
105   public function testDuplicateRoutePaths() {
106     // Tests two routes with exactly the same path. The route with the maximum
107     // fit and lowest sorting route name will match, regardless of the order the
108     // routes are declared.
109     // @see \Drupal\Core\Routing\RouteProvider::getRoutesByPath()
110     $this->drupalGet('router-test/duplicate-path2');
111     $this->assertResponse(200);
112     $this->assertRaw('router_test.two_duplicate1');
113
114     // Tests three routes with same the path. One of the routes the path has a
115     // different case.
116     $this->drupalGet('router-test/case-sensitive-duplicate-path3');
117     $this->assertResponse(200);
118     $this->assertRaw('router_test.case_sensitive_duplicate1');
119     // While case-insensitive matching works, exact matches are preferred.
120     $this->drupalGet('router-test/case-sensitive-Duplicate-PATH3');
121     $this->assertResponse(200);
122     $this->assertRaw('router_test.case_sensitive_duplicate2');
123     // Test that case-insensitive matching works, falling back to the first
124     // route defined.
125     $this->drupalGet('router-test/case-sensitive-Duplicate-Path3');
126     $this->assertResponse(200);
127     $this->assertRaw('router_test.case_sensitive_duplicate1');
128   }
129
130   /**
131    * Confirms that placeholders in paths work correctly.
132    */
133   public function testControllerPlaceholders() {
134     // Test with 0 and a random value.
135     $values = ["0", $this->randomMachineName()];
136     foreach ($values as $value) {
137       $this->drupalGet('router_test/test3/' . $value);
138       $this->assertResponse(200);
139       $this->assertRaw($value, 'The correct string was returned because the route was successful.');
140     }
141
142     // Confirm that the page wrapping is being added, so we're not getting a
143     // raw body returned.
144     $this->assertRaw('</html>', 'Page markup was found.');
145
146     // In some instances, the subrequest handling may get confused and render
147     // a page inception style.  This test verifies that is not happening.
148     $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
149   }
150
151   /**
152    * Confirms that default placeholders in paths work correctly.
153    */
154   public function testControllerPlaceholdersDefaultValues() {
155     $this->drupalGet('router_test/test4');
156     $this->assertResponse(200);
157     $this->assertRaw('narf', 'The correct string was returned because the route was successful.');
158
159     // Confirm that the page wrapping is being added, so we're not getting a
160     // raw body returned.
161     $this->assertRaw('</html>', 'Page markup was found.');
162
163     // In some instances, the subrequest handling may get confused and render
164     // a page inception style.  This test verifies that is not happening.
165     $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
166   }
167
168   /**
169    * Confirms that default placeholders in paths work correctly.
170    */
171   public function testControllerPlaceholdersDefaultValuesProvided() {
172     $this->drupalGet('router_test/test4/barf');
173     $this->assertResponse(200);
174     $this->assertRaw('barf', 'The correct string was returned because the route was successful.');
175
176     // Confirm that the page wrapping is being added, so we're not getting a
177     // raw body returned.
178     $this->assertRaw('</html>', 'Page markup was found.');
179
180     // In some instances, the subrequest handling may get confused and render
181     // a page inception style.  This test verifies that is not happening.
182     $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
183   }
184
185   /**
186    * Checks that dynamically defined and altered routes work correctly.
187    *
188    * @see \Drupal\router_test\RouteSubscriber
189    */
190   public function testDynamicRoutes() {
191     // Test the altered route.
192     $this->drupalGet('router_test/test6');
193     $this->assertResponse(200);
194     $this->assertRaw('test5', 'The correct string was returned because the route was successful.');
195   }
196
197   /**
198    * Checks that a request with text/html response gets rendered as a page.
199    */
200   public function testControllerResolutionPage() {
201     $this->drupalGet('/router_test/test10');
202
203     $this->assertRaw('abcde', 'Correct body was found.');
204
205     // Confirm that the page wrapping is being added, so we're not getting a
206     // raw body returned.
207     $this->assertRaw('</html>', 'Page markup was found.');
208
209     // In some instances, the subrequest handling may get confused and render
210     // a page inception style. This test verifies that is not happening.
211     $this->assertNoPattern('#</body>.*</body>#s', 'There was no double-page effect from a misrendered subrequest.');
212   }
213
214   /**
215    * Checks the generate method on the url generator using the front router.
216    */
217   public function testUrlGeneratorFront() {
218     $front_url = Url::fromRoute('<front>', [], ['absolute' => TRUE]);
219     // Compare to the site base URL.
220     $base_url = Url::fromUri('base:/', ['absolute' => TRUE]);
221     $this->assertIdentical($base_url->toString(), $front_url->toString());
222   }
223
224   /**
225    * Tests that a page trying to match a path will succeed.
226    */
227   public function testRouterMatching() {
228     $this->drupalGet('router_test/test14/1');
229     $this->assertResponse(200);
230     $this->assertText('User route "entity.user.canonical" was matched.');
231
232     // Try to match a route for a non-existent user.
233     $this->drupalGet('router_test/test14/2');
234     $this->assertResponse(200);
235     $this->assertText('Route not matched.');
236
237     // Check that very long paths don't cause an error.
238     $path = 'router_test/test1';
239     $suffix = '/d/r/u/p/a/l';
240     for ($i = 0; $i < 10; $i++) {
241       $path .= $suffix;
242       $this->drupalGet($path);
243       $this->assertResponse(404);
244     }
245   }
246
247   /**
248    * Tests that a PSR-7 response works.
249    */
250   public function testRouterResponsePsr7() {
251     $this->drupalGet('/router_test/test23');
252     $this->assertResponse(200);
253     $this->assertText('test23');
254   }
255
256   /**
257    * Tests the user account on the DIC.
258    */
259   public function testUserAccount() {
260     $account = $this->drupalCreateUser();
261     $this->drupalLogin($account);
262
263     $second_account = $this->drupalCreateUser();
264
265     $this->drupalGet('router_test/test12/' . $second_account->id());
266     $this->assertText($account->getUsername() . ':' . $second_account->getUsername());
267     $this->assertEqual($account->id(), $this->loggedInUser->id(), 'Ensure that the user was not changed.');
268
269     $this->drupalGet('router_test/test13/' . $second_account->id());
270     $this->assertText($account->getUsername() . ':' . $second_account->getUsername());
271     $this->assertEqual($account->id(), $this->loggedInUser->id(), 'Ensure that the user was not changed.');
272   }
273
274   /**
275    * Checks that an ajax request gets rendered as an Ajax response, by mime.
276    */
277   public function testControllerResolutionAjax() {
278     // This will fail with a JSON parse error if the request is not routed to
279     // The correct controller.
280     $this->drupalGetAjax('/router_test/test10');
281
282     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/json', 'Correct mime content type was returned');
283
284     $this->assertRaw('abcde', 'Correct body was found.');
285   }
286
287   /**
288    * Tests that routes no longer exist for a module that has been uninstalled.
289    */
290   public function testRouterUninstallInstall() {
291     \Drupal::service('module_installer')->uninstall(['router_test']);
292     \Drupal::service('router.builder')->rebuild();
293     try {
294       \Drupal::service('router.route_provider')->getRouteByName('router_test.1');
295       $this->fail('Route was delete on uninstall.');
296     }
297     catch (RouteNotFoundException $e) {
298       $this->pass('Route was delete on uninstall.');
299     }
300     // Install the module again.
301     \Drupal::service('module_installer')->install(['router_test']);
302     \Drupal::service('router.builder')->rebuild();
303     $route = \Drupal::service('router.route_provider')->getRouteByName('router_test.1');
304     $this->assertNotNull($route, 'Route exists after module installation');
305   }
306
307   /**
308    * Ensure that multiple leading slashes are redirected.
309    */
310   public function testLeadingSlashes() {
311     $request = $this->container->get('request_stack')->getCurrentRequest();
312     $url = $request->getUriForPath('//router_test/test1');
313     $this->drupalGet($url);
314     $this->assertEqual(1, $this->redirectCount, $url . " redirected to " . $this->url);
315     $this->assertUrl($request->getUriForPath('/router_test/test1'));
316
317     // It should not matter how many leading slashes are used and query strings
318     // should be preserved.
319     $url = $request->getUriForPath('/////////////////////////////////////////////////router_test/test1') . '?qs=test';
320     $this->drupalGet($url);
321     $this->assertEqual(1, $this->redirectCount, $url . " redirected to " . $this->url);
322     $this->assertUrl($request->getUriForPath('/router_test/test1') . '?qs=test');
323
324     // Ensure that external URLs in destination query params are not redirected
325     // to.
326     $url = $request->getUriForPath('/////////////////////////////////////////////////router_test/test1') . '?qs=test&destination=http://www.example.com%5c@drupal8alt.test';
327     $this->drupalGet($url);
328     $this->assertEqual(1, $this->redirectCount, $url . " redirected to " . $this->url);
329     $this->assertUrl($request->getUriForPath('/router_test/test1') . '?qs=test');
330   }
331
332 }