3 namespace Drupal\system\Tests\System;
5 use Drupal\Component\Utility\SafeMarkup;
6 use Drupal\simpletest\WebTestBase;
7 use Drupal\user\RoleInterface;
10 * Tests page not found functionality, including custom 404 pages.
14 class PageNotFoundTest extends WebTestBase {
21 public static $modules = ['system_test'];
25 protected function setUp() {
28 // Create an administrative user.
29 $this->adminUser = $this->drupalCreateUser(['administer site configuration', 'link to any page']);
30 $this->adminUser->roles[] = 'administrator';
31 $this->adminUser->save();
33 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access user profiles']);
34 user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access user profiles']);
37 public function testPageNotFound() {
38 $this->drupalLogin($this->adminUser);
39 $this->drupalGet($this->randomMachineName(10));
40 $this->assertText(t('Page not found'), 'Found the default 404 page');
42 // Set a custom 404 page without a starting slash.
44 'site_404' => 'user/' . $this->adminUser->id(),
46 $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
47 $this->assertRaw(SafeMarkup::format("The path '%path' has to start with a slash.", ['%path' => $edit['site_404']]));
49 // Use a custom 404 page.
51 'site_404' => '/user/' . $this->adminUser->id(),
53 $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
55 $this->drupalGet($this->randomMachineName(10));
56 $this->assertText($this->adminUser->getUsername(), 'Found the custom 404 page');
60 * Tests that an inaccessible custom 404 page falls back to the default.
62 public function testPageNotFoundCustomPageWithAccessDenied() {
63 // Sets up a 404 page not accessible by the anonymous user.
64 $this->config('system.site')->set('page.404', '/system-test/custom-4xx')->save();
66 $this->drupalGet('/this-path-does-not-exist');
67 $this->assertNoText('Admin-only 4xx response');
68 $this->assertText('The requested page could not be found.');
69 $this->assertResponse(404);
70 // Verify the access cacheability metadata for custom 404 is bubbled.
71 $this->assertCacheContext('user.roles');
73 $this->drupalLogin($this->adminUser);
74 $this->drupalGet('/this-path-does-not-exist');
75 $this->assertText('Admin-only 4xx response');
76 $this->assertNoText('The requested page could not be found.');
77 $this->assertResponse(404);
78 // Verify the access cacheability metadata for custom 404 is bubbled.
79 $this->assertCacheContext('user.roles');