3 namespace Drupal\Tests\system\Functional\System;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Tests\BrowserTestBase;
7 use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
8 use Drupal\user\RoleInterface;
11 * Tests page not found functionality, including custom 404 pages.
15 class PageNotFoundTest extends BrowserTestBase {
17 use AssertPageCacheContextsAndTagsTrait;
24 public static $modules = ['system_test'];
28 protected function setUp() {
31 // Create an administrative user.
32 $this->adminUser = $this->drupalCreateUser(['administer site configuration', 'link to any page']);
33 $this->adminUser->roles[] = 'administrator';
34 $this->adminUser->save();
36 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access user profiles']);
37 user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access user profiles']);
40 public function testPageNotFound() {
41 $this->drupalLogin($this->adminUser);
42 $this->drupalGet($this->randomMachineName(10));
43 $this->assertText(t('Page not found'), 'Found the default 404 page');
45 // Set a custom 404 page without a starting slash.
47 'site_404' => 'user/' . $this->adminUser->id(),
49 $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
50 $this->assertRaw(new FormattableMarkup("The path '%path' has to start with a slash.", ['%path' => $edit['site_404']]));
52 // Use a custom 404 page.
54 'site_404' => '/user/' . $this->adminUser->id(),
56 $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
58 $this->drupalGet($this->randomMachineName(10));
59 $this->assertText($this->adminUser->getUsername(), 'Found the custom 404 page');
63 * Tests that an inaccessible custom 404 page falls back to the default.
65 public function testPageNotFoundCustomPageWithAccessDenied() {
66 // Sets up a 404 page not accessible by the anonymous user.
67 $this->config('system.site')->set('page.404', '/system-test/custom-4xx')->save();
69 $this->drupalGet('/this-path-does-not-exist');
70 $this->assertNoText('Admin-only 4xx response');
71 $this->assertText('The requested page could not be found.');
72 $this->assertResponse(404);
73 // Verify the access cacheability metadata for custom 404 is bubbled.
74 $this->assertCacheContext('user.roles');
76 $this->drupalLogin($this->adminUser);
77 $this->drupalGet('/this-path-does-not-exist');
78 $this->assertText('Admin-only 4xx response');
79 $this->assertNoText('The requested page could not be found.');
80 $this->assertResponse(404);
81 // Verify the access cacheability metadata for custom 404 is bubbled.
82 $this->assertCacheContext('user.roles');