class LanguageUILanguageNegotiationTest

Same name and namespace in other branches
  1. 8.9.x core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php \Drupal\Tests\language\Functional\LanguageUILanguageNegotiationTest
  2. 10 core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php \Drupal\Tests\language\Functional\LanguageUILanguageNegotiationTest
  3. 11.x core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php \Drupal\Tests\language\Functional\LanguageUILanguageNegotiationTest

Tests the language UI for language switching.

The uses cases that get tested, are:

  • URL (path) > default: Test that the URL prefix setting gets precedence over the default language. The browser language preference does not have any influence.
  • URL (path) > browser > default: Test that the URL prefix setting gets precedence over the browser language preference, which in turn gets precedence over the default language.
  • URL (domain) > default: Tests that the URL domain setting gets precedence over the default language.

The paths that are used for each of these, are:

  • admin/config: Tests the UI using the precedence rules.
  • zh-hans/admin/config: Tests the UI in Chinese.
  • blah-blah/admin/config: Tests the 404 page.

@group language

Hierarchy

Expanded class hierarchy of LanguageUILanguageNegotiationTest

File

core/modules/language/tests/src/Functional/LanguageUILanguageNegotiationTest.php, line 43

Namespace

Drupal\Tests\language\Functional
View source
class LanguageUILanguageNegotiationTest extends BrowserTestBase {
    
    /**
     * The admin user for testing.
     *
     * @var \Drupal\user\Entity\User
     */
    protected $adminUser;
    
    /**
     * Modules to enable.
     *
     * We marginally use interface translation functionality here, so need to use
     * the locale module instead of language only, but the 90% of the test is
     * about the negotiation process which is solely in language module.
     *
     * @var array
     */
    protected static $modules = [
        'locale',
        'language_test',
        'block',
        'user',
        'content_translation',
    ];
    
    /**
     * {@inheritdoc}
     */
    protected $defaultTheme = 'stark';
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $this->adminUser = $this->drupalCreateUser([
            'administer languages',
            'translate interface',
            'access administration pages',
            'administer blocks',
        ]);
        $this->drupalLogin($this->adminUser);
    }
    
    /**
     * Tests for language switching by URL path.
     */
    public function testUILanguageNegotiation() {
        // A few languages to switch to.
        // This one is unknown, should get the default lang version.
        $langcode_unknown = 'blah-blah';
        // For testing browser lang preference.
        $langcode_browser_fallback = 'vi';
        // For testing path prefix.
        $langcode = 'zh-hans';
        // For setting browser language preference to 'vi'.
        $http_header_browser_fallback = [
            "Accept-Language" => "{$langcode_browser_fallback};q=1",
        ];
        // For setting browser language preference to some unknown.
        $http_header_blah = [
            "Accept-Language" => "blah;q=1",
        ];
        // Create a private file for testing accessible by the admin user.
        \Drupal::service('file_system')->mkdir($this->privateFilesDirectory . '/test');
        $filepath = 'private://test/private-file-test.txt';
        $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
        file_put_contents($filepath, $contents);
        $file = File::create([
            'uri' => $filepath,
            'uid' => $this->adminUser
                ->id(),
        ]);
        $file->save();
        // Setup the site languages by installing two languages.
        // Set the default language in order for the translated string to be registered
        // into database when seen by t(). Without doing this, our target string
        // is for some reason not found when doing translate search. This might
        // be some bug.
        $default_language = \Drupal::languageManager()->getDefaultLanguage();
        ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)->save();
        $this->config('system.site')
            ->set('default_langcode', $langcode_browser_fallback)
            ->save();
        ConfigurableLanguage::createFromLangcode($langcode)->save();
        // We will look for this string in the admin/config screen to see if the
        // corresponding translated string is shown.
        $default_string = 'Hide descriptions';
        // First visit this page to make sure our target string is searchable.
        $this->drupalGet('admin/config');
        // Now the t()'ed string is in db so switch the language back to default.
        // This will rebuild the container so we need to rebuild the container in
        // the test environment.
        $this->config('system.site')
            ->set('default_langcode', $default_language->getId())
            ->save();
        $this->config('language.negotiation')
            ->set('url.prefixes.en', '')
            ->save();
        $this->rebuildContainer();
        // Translate the string.
        $language_browser_fallback_string = "In {$langcode_browser_fallback} In {$langcode_browser_fallback} In {$langcode_browser_fallback}";
        $language_string = "In {$langcode} In {$langcode} In {$langcode}";
        // Do a translate search of our target string.
        $search = [
            'string' => $default_string,
            'langcode' => $langcode_browser_fallback,
        ];
        $this->drupalGet('admin/config/regional/translate');
        $this->submitForm($search, 'Filter');
        $textarea = $this->assertSession()
            ->elementExists('xpath', '//textarea');
        $lid = $textarea->getAttribute('name');
        $edit = [
            $lid => $language_browser_fallback_string,
        ];
        $this->drupalGet('admin/config/regional/translate');
        $this->submitForm($edit, 'Save translations');
        $search = [
            'string' => $default_string,
            'langcode' => $langcode,
        ];
        $this->drupalGet('admin/config/regional/translate');
        $this->submitForm($search, 'Filter');
        $textarea = $this->assertSession()
            ->elementExists('xpath', '//textarea');
        $lid = $textarea->getAttribute('name');
        $edit = [
            $lid => $language_string,
        ];
        $this->drupalGet('admin/config/regional/translate');
        $this->submitForm($edit, 'Save translations');
        // Configure selected language negotiation to use zh-hans.
        $edit = [
            'selected_langcode' => $langcode,
        ];
        $this->drupalGet('admin/config/regional/language/detection/selected');
        $this->submitForm($edit, 'Save configuration');
        $test = [
            'language_negotiation' => [
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $language_string,
            'expected_method_id' => LanguageNegotiationSelected::METHOD_ID,
            'http_header' => $http_header_browser_fallback,
            'message' => 'SELECTED: UI language is switched based on selected language.',
        ];
        $this->doRunTest($test);
        // An invalid language is selected.
        $this->config('language.negotiation')
            ->set('selected_langcode', NULL)
            ->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
            'http_header' => $http_header_browser_fallback,
            'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
        ];
        $this->doRunTest($test);
        // No selected language is available.
        $this->config('language.negotiation')
            ->set('selected_langcode', $langcode_unknown)
            ->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
            'http_header' => $http_header_browser_fallback,
            'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
        ];
        $this->doRunTest($test);
        $tests = [
            // Default, browser preference should have no influence.
[
                'language_negotiation' => [
                    LanguageNegotiationUrl::METHOD_ID,
                    LanguageNegotiationSelected::METHOD_ID,
                ],
                'path' => 'admin/config',
                'expect' => $default_string,
                'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
                'http_header' => $http_header_browser_fallback,
                'message' => 'URL (PATH) > DEFAULT: no language prefix, UI language is default and the browser language preference setting is not used.',
            ],
            // Language prefix.
[
                'language_negotiation' => [
                    LanguageNegotiationUrl::METHOD_ID,
                    LanguageNegotiationSelected::METHOD_ID,
                ],
                'path' => "{$langcode}/admin/config",
                'expect' => $language_string,
                'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
                'http_header' => $http_header_browser_fallback,
                'message' => 'URL (PATH) > DEFAULT: with language prefix, UI language is switched based on path prefix',
            ],
            // Default, go by browser preference.
[
                'language_negotiation' => [
                    LanguageNegotiationUrl::METHOD_ID,
                    LanguageNegotiationBrowser::METHOD_ID,
                ],
                'path' => 'admin/config',
                'expect' => $language_browser_fallback_string,
                'expected_method_id' => LanguageNegotiationBrowser::METHOD_ID,
                'http_header' => $http_header_browser_fallback,
                'message' => 'URL (PATH) > BROWSER: no language prefix, UI language is determined by browser language preference',
            ],
            // Prefix, switch to the language.
[
                'language_negotiation' => [
                    LanguageNegotiationUrl::METHOD_ID,
                    LanguageNegotiationBrowser::METHOD_ID,
                ],
                'path' => "{$langcode}/admin/config",
                'expect' => $language_string,
                'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
                'http_header' => $http_header_browser_fallback,
                'message' => 'URL (PATH) > BROWSER: with language prefix, UI language is based on path prefix',
            ],
            // Default, browser language preference is not one of site's lang.
[
                'language_negotiation' => [
                    LanguageNegotiationUrl::METHOD_ID,
                    LanguageNegotiationBrowser::METHOD_ID,
                    LanguageNegotiationSelected::METHOD_ID,
                ],
                'path' => 'admin/config',
                'expect' => $default_string,
                'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
                'http_header' => $http_header_blah,
                'message' => 'URL (PATH) > BROWSER > DEFAULT: no language prefix and browser language preference set to unknown language should use default language',
            ],
        ];
        foreach ($tests as $test) {
            $this->doRunTest($test);
        }
        // Unknown language prefix should return 404.
        $definitions = \Drupal::languageManager()->getNegotiator()
            ->getNegotiationMethods();
        // Enable only methods, which are either not limited to a specific language
        // type or are supporting the interface language type.
        $language_interface_method_definitions = array_filter($definitions, function ($method_definition) {
            return !isset($method_definition['types']) || isset($method_definition['types']) && in_array(LanguageInterface::TYPE_INTERFACE, $method_definition['types']);
        });
        $this->config('language.types')
            ->set('negotiation.' . LanguageInterface::TYPE_INTERFACE . '.enabled', array_flip(array_keys($language_interface_method_definitions)))
            ->save();
        $this->drupalGet("{$langcode_unknown}/admin/config", [], $http_header_browser_fallback);
        $this->assertSession()
            ->statusCodeEquals(404);
        // Set preferred langcode for user to NULL.
        $account = $this->loggedInUser;
        $account->preferred_langcode = NULL;
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUser::METHOD_ID,
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
            'http_header' => [],
            'message' => 'USER > DEFAULT: no preferred user language setting, the UI language is default',
        ];
        $this->doRunTest($test);
        // Set preferred langcode for user to default langcode.
        $account = $this->loggedInUser;
        $account->preferred_langcode = $default_language->getId();
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUser::METHOD_ID,
                LanguageNegotiationUrl::METHOD_ID,
            ],
            'path' => "{$langcode}/admin/config",
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiationUser::METHOD_ID,
            'http_header' => [],
            'message' => 'USER > URL: User has default language as preferred user language setting, the UI language is default',
        ];
        $this->doRunTest($test);
        // Set preferred langcode for user to unknown language.
        $account = $this->loggedInUser;
        $account->preferred_langcode = $langcode_unknown;
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUser::METHOD_ID,
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
            'http_header' => [],
            'message' => 'USER > DEFAULT: invalid preferred user language setting, the UI language is default',
        ];
        $this->doRunTest($test);
        // Set preferred langcode for user to non default.
        $account->preferred_langcode = $langcode;
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUser::METHOD_ID,
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $language_string,
            'expected_method_id' => LanguageNegotiationUser::METHOD_ID,
            'http_header' => [],
            'message' => 'USER > DEFAULT: defined preferred user language setting, the UI language is based on user setting',
        ];
        $this->doRunTest($test);
        // Set preferred admin langcode for user to NULL.
        $account->preferred_admin_langcode = NULL;
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUserAdmin::METHOD_ID,
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
            'http_header' => [],
            'message' => 'USER ADMIN > DEFAULT: no preferred user admin language setting, the UI language is default',
        ];
        $this->doRunTest($test);
        // Set preferred admin langcode for user to unknown language.
        $account->preferred_admin_langcode = $langcode_unknown;
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUserAdmin::METHOD_ID,
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $default_string,
            'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
            'http_header' => [],
            'message' => 'USER ADMIN > DEFAULT: invalid preferred user admin language setting, the UI language is default',
        ];
        $this->doRunTest($test);
        // Set preferred admin langcode for user to non default.
        $account->preferred_admin_langcode = $langcode;
        $account->save();
        $test = [
            'language_negotiation' => [
                LanguageNegotiationUserAdmin::METHOD_ID,
                LanguageNegotiationSelected::METHOD_ID,
            ],
            'path' => 'admin/config',
            'expect' => $language_string,
            'expected_method_id' => LanguageNegotiationUserAdmin::METHOD_ID,
            'http_header' => [],
            'message' => 'USER ADMIN > DEFAULT: defined preferred user admin language setting, the UI language is based on user setting',
        ];
        $this->doRunTest($test);
        // Go by session preference.
        $language_negotiation_session_param = $this->randomMachineName();
        $edit = [
            'language_negotiation_session_param' => $language_negotiation_session_param,
        ];
        $this->drupalGet('admin/config/regional/language/detection/session');
        $this->submitForm($edit, 'Save configuration');
        $tests = [
            [
                'language_negotiation' => [
                    LanguageNegotiationSession::METHOD_ID,
                ],
                'path' => "admin/config",
                'expect' => $default_string,
                'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
                'http_header' => $http_header_browser_fallback,
                'message' => 'SESSION > DEFAULT: no language given, the UI language is default',
            ],
            [
                'language_negotiation' => [
                    LanguageNegotiationSession::METHOD_ID,
                ],
                'path' => 'admin/config',
                'path_options' => [
                    'query' => [
                        $language_negotiation_session_param => $langcode,
                    ],
                ],
                'expect' => $language_string,
                'expected_method_id' => LanguageNegotiationSession::METHOD_ID,
                'http_header' => $http_header_browser_fallback,
                'message' => 'SESSION > DEFAULT: language given, UI language is determined by session language preference',
            ],
        ];
        foreach ($tests as $test) {
            $this->doRunTest($test);
        }
    }
    protected function doRunTest($test) {
        $test += [
            'path_options' => [],
        ];
        if (!empty($test['language_negotiation'])) {
            $method_weights = array_flip($test['language_negotiation']);
            $this->container
                ->get('language_negotiator')
                ->saveConfiguration(LanguageInterface::TYPE_INTERFACE, $method_weights);
        }
        if (!empty($test['language_negotiation_url_part'])) {
            $this->config('language.negotiation')
                ->set('url.source', $test['language_negotiation_url_part'])
                ->save();
        }
        if (!empty($test['language_test_domain'])) {
            \Drupal::state()->set('language_test.domain', $test['language_test_domain']);
        }
        $this->container
            ->get('language_manager')
            ->reset();
        $this->drupalGet($test['path'], $test['path_options'], $test['http_header']);
        $this->assertSession()
            ->pageTextContains($test['expect']);
        $this->assertSession()
            ->statusMessageContains('Language negotiation method: ' . $test['expected_method_id'], 'status');
        // Get the private file and ensure it is a 200. It is important to
        // invalidate the router cache to ensure the routing system runs a full
        // match.
        Cache::invalidateTags([
            'route_match',
        ]);
        $this->drupalGet('system/files/test/private-file-test.txt');
        $this->assertSession()
            ->statusCodeEquals(200);
    }
    
    /**
     * Tests URL language detection when the requested URL has no language.
     */
    public function testUrlLanguageFallback() {
        // Add the Italian language.
        $langcode_browser_fallback = 'it';
        ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)->save();
        $languages = $this->container
            ->get('language_manager')
            ->getLanguages();
        // Enable the path prefix for the default language: this way any unprefixed
        // URL must have a valid fallback value.
        $edit = [
            'prefix[en]' => 'en',
        ];
        $this->drupalGet('admin/config/regional/language/detection/url');
        $this->submitForm($edit, 'Save configuration');
        // Enable browser and URL language detection.
        $edit = [
            'language_interface[enabled][language-browser]' => TRUE,
            'language_interface[enabled][language-url]' => TRUE,
            'language_interface[weight][language-browser]' => -8,
            'language_interface[weight][language-url]' => -10,
        ];
        $this->drupalGet('admin/config/regional/language/detection');
        $this->submitForm($edit, 'Save settings');
        $this->drupalGet('admin/config/regional/language/detection');
        // Enable the language switcher block.
        $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, [
            'id' => 'test_language_block',
        ]);
        // Log out, because for anonymous users, the "active" class is set by PHP
        // (which means we can easily test it here), whereas for authenticated users
        // it is set by JavaScript.
        $this->drupalLogout();
        // Place a site branding block in the header region.
        $this->drupalPlaceBlock('system_branding_block', [
            'region' => 'header',
            'id' => 'site-branding',
        ]);
        // Access the front page without specifying any valid URL language prefix
        // and having as browser language preference a non-default language.
        $http_header = [
            "Accept-Language" => "{$langcode_browser_fallback};q=1",
        ];
        $language = new Language([
            'id' => '',
        ]);
        $this->drupalGet('', [
            'language' => $language,
        ], $http_header);
        // Check that the language switcher active link matches the given browser
        // language.
        $href = Url::fromRoute('<front>')->toString() . $langcode_browser_fallback;
        $this->assertSession()
            ->elementTextEquals('xpath', "//div[@id='block-test-language-block']//a[@class='language-link is-active' and starts-with(@href, '{$href}')]", $languages[$langcode_browser_fallback]->getName());
        // Check that URLs are rewritten using the given browser language.
        $this->assertSession()
            ->elementTextEquals('xpath', "//div[@id='block-site-branding']/a[@rel='home' and @href='{$href}'][2]", 'Drupal');
    }
    
    /**
     * Tests URL handling when separate domains are used for multiple languages.
     */
    public function testLanguageDomain() {
        global $base_url;
        // Get the current host URI we're running on.
        $base_url_host = parse_url($base_url, PHP_URL_HOST);
        // Add the Italian language.
        ConfigurableLanguage::createFromLangcode('it')->save();
        $languages = $this->container
            ->get('language_manager')
            ->getLanguages();
        // Enable browser and URL language detection.
        $edit = [
            'language_interface[enabled][language-url]' => TRUE,
            'language_interface[weight][language-url]' => -10,
        ];
        $this->drupalGet('admin/config/regional/language/detection');
        $this->submitForm($edit, 'Save settings');
        // Do not allow blank domain.
        $edit = [
            'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
            'domain[en]' => '',
        ];
        $this->drupalGet('admin/config/regional/language/detection/url');
        $this->submitForm($edit, 'Save configuration');
        $this->assertSession()
            ->statusMessageContains('The domain may not be left blank for English', 'error');
        $this->rebuildContainer();
        // Change the domain for the Italian language.
        $edit = [
            'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
            'domain[en]' => $base_url_host,
            'domain[it]' => 'it.example.com',
        ];
        $this->drupalGet('admin/config/regional/language/detection/url');
        $this->submitForm($edit, 'Save configuration');
        $this->assertSession()
            ->statusMessageContains('The configuration options have been saved', 'status');
        $this->rebuildContainer();
        // Try to use an invalid domain.
        $edit = [
            'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
            'domain[en]' => $base_url_host,
            'domain[it]' => 'it.example.com/',
        ];
        $this->drupalGet('admin/config/regional/language/detection/url');
        $this->submitForm($edit, 'Save configuration');
        $this->assertSession()
            ->statusMessageContains("The domain for Italian may only contain the domain name, not a trailing slash, protocol and/or port.", 'error');
        // Build the link we're going to test.
        $link = 'it.example.com' . rtrim(base_path(), '/') . '/admin';
        // Test URL in another language: http://it.example.com/admin.
        // Base path gives problems on the testbot, so $correct_link is hard-coded.
        // @see UrlAlterFunctionalTest::assertUrlOutboundAlter (path.test).
        $italian_url = Url::fromRoute('system.admin', [], [
            'language' => $languages['it'],
        ])->toString();
        $url_scheme = \Drupal::request()->isSecure() ? 'https://' : 'http://';
        $correct_link = $url_scheme . $link;
        $this->assertEquals($correct_link, $italian_url, new FormattableMarkup('The right URL (@url) in accordance with the chosen language', [
            '@url' => $italian_url,
        ]));
        // Test HTTPS via options.
        $italian_url = Url::fromRoute('system.admin', [], [
            'https' => TRUE,
            'language' => $languages['it'],
        ])->toString();
        $correct_link = 'https://' . $link;
        $this->assertSame($correct_link, $italian_url, new FormattableMarkup('The right HTTPS URL (via options) (@url) in accordance with the chosen language', [
            '@url' => $italian_url,
        ]));
        // Test HTTPS via current URL scheme.
        $request = Request::create('', 'GET', [], [], [], [
            'HTTPS' => 'on',
        ]);
        $this->container
            ->get('request_stack')
            ->push($request);
        $italian_url = Url::fromRoute('system.admin', [], [
            'language' => $languages['it'],
        ])->toString();
        $correct_link = 'https://' . $link;
        $this->assertSame($correct_link, $italian_url, new FormattableMarkup('The right URL (via current URL scheme) (@url) in accordance with the chosen language', [
            '@url' => $italian_url,
        ]));
    }
    
    /**
     * Tests persistence of negotiation settings for the content language type.
     */
    public function testContentCustomization() {
        // Customize content language settings from their defaults.
        $edit = [
            'language_content[configurable]' => TRUE,
            'language_content[enabled][language-url]' => FALSE,
            'language_content[enabled][language-session]' => TRUE,
        ];
        $this->drupalGet('admin/config/regional/language/detection');
        $this->submitForm($edit, 'Save settings');
        // Check if configurability persisted.
        $config = $this->config('language.types');
        $this->assertContains('language_interface', $config->get('configurable'), 'Interface language is configurable.');
        $this->assertContains('language_content', $config->get('configurable'), 'Content language is configurable.');
        // Ensure configuration was saved.
        $this->assertArrayNotHasKey('language-url', $config->get('negotiation.language_content.enabled'));
        $this->assertArrayHasKey('language-session', $config->get('negotiation.language_content.enabled'));
    }
    
    /**
     * Tests if the language switcher block gets deleted when a language type has been made not configurable.
     */
    public function testDisableLanguageSwitcher() {
        $block_id = 'test_language_block';
        // Enable the language switcher block.
        $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_CONTENT, [
            'id' => $block_id,
        ]);
        // Check if the language switcher block has been created.
        $block = Block::load($block_id);
        $this->assertNotEmpty($block, 'Language switcher block was created.');
        // Make sure language_content is not configurable.
        $edit = [
            'language_content[configurable]' => FALSE,
        ];
        $this->drupalGet('admin/config/regional/language/detection');
        $this->submitForm($edit, 'Save settings');
        $this->assertSession()
            ->statusCodeEquals(200);
        // Check if the language switcher block has been removed.
        $block = Block::load($block_id);
        $this->assertNull($block, 'Language switcher block was removed.');
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Member alias Overriden Title Overrides
AssertLegacyTrait::assert Deprecated protected function
AssertLegacyTrait::assertCacheTag Deprecated protected function Asserts whether an expected cache tag was present in the last response.
AssertLegacyTrait::assertElementNotPresent Deprecated protected function Asserts that the element with the given CSS selector is not present.
AssertLegacyTrait::assertElementPresent Deprecated protected function Asserts that the element with the given CSS selector is present.
AssertLegacyTrait::assertEqual Deprecated protected function
AssertLegacyTrait::assertEscaped Deprecated protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertLegacyTrait::assertField Deprecated protected function Asserts that a field exists with the given name or ID.
AssertLegacyTrait::assertFieldById Deprecated protected function Asserts that a field exists with the given ID and value.
AssertLegacyTrait::assertFieldByName Deprecated protected function Asserts that a field exists with the given name and value.
AssertLegacyTrait::assertFieldByXPath Deprecated protected function Asserts that a field exists in the current page by the given XPath.
AssertLegacyTrait::assertFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is checked.
AssertLegacyTrait::assertFieldsByValue Deprecated protected function Asserts that a field exists in the current page with a given Xpath result.
AssertLegacyTrait::assertHeader Deprecated protected function Checks that current response header equals value.
AssertLegacyTrait::assertIdentical Deprecated protected function
AssertLegacyTrait::assertIdenticalObject Deprecated protected function
AssertLegacyTrait::assertLink Deprecated protected function Passes if a link with the specified label is found.
AssertLegacyTrait::assertLinkByHref Deprecated protected function Passes if a link containing a given href (part) is found.
AssertLegacyTrait::assertNoCacheTag Deprecated protected function Asserts whether an expected cache tag was absent in the last response.
AssertLegacyTrait::assertNoEscaped Deprecated protected function Passes if the raw text is not found escaped on the loaded page.
AssertLegacyTrait::assertNoField Deprecated protected function Asserts that a field does NOT exist with the given name or ID.
AssertLegacyTrait::assertNoFieldById Deprecated protected function Asserts that a field does not exist with the given ID and value.
AssertLegacyTrait::assertNoFieldByName Deprecated protected function Asserts that a field does not exist with the given name and value.
AssertLegacyTrait::assertNoFieldByXPath Deprecated protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertLegacyTrait::assertNoFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is not checked.
AssertLegacyTrait::assertNoLink Deprecated protected function Passes if a link with the specified label is not found.
AssertLegacyTrait::assertNoLinkByHref Deprecated protected function Passes if a link containing a given href (part) is not found.
AssertLegacyTrait::assertNoOption Deprecated protected function Asserts that a select option does NOT exist in the current page.
AssertLegacyTrait::assertNoPattern Deprecated protected function Triggers a pass if the Perl regex pattern is not found in the raw content.
AssertLegacyTrait::assertNoRaw Deprecated protected function Passes if the raw text IS not found on the loaded page, fail otherwise.
AssertLegacyTrait::assertNotEqual Deprecated protected function
AssertLegacyTrait::assertNoText Deprecated protected function Passes if the page (with HTML stripped) does not contains the text.
AssertLegacyTrait::assertNotIdentical Deprecated protected function
AssertLegacyTrait::assertNoUniqueText Deprecated protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertLegacyTrait::assertOption Deprecated protected function Asserts that a select option in the current page exists.
AssertLegacyTrait::assertOptionByText Deprecated protected function Asserts that a select option with the visible text exists.
AssertLegacyTrait::assertOptionSelected Deprecated protected function Asserts that a select option in the current page is checked.
AssertLegacyTrait::assertPattern Deprecated protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertLegacyTrait::assertRaw Deprecated protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertLegacyTrait::assertResponse Deprecated protected function Asserts the page responds with the specified response code.
AssertLegacyTrait::assertText Deprecated protected function Passes if the page (with HTML stripped) contains the text.
AssertLegacyTrait::assertTextHelper Deprecated protected function Helper for assertText and assertNoText.
AssertLegacyTrait::assertTitle Deprecated protected function Pass if the page title is the given string.
AssertLegacyTrait::assertUniqueText Deprecated protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertLegacyTrait::assertUrl Deprecated protected function Passes if the internal browser&#039;s URL matches the given path.
AssertLegacyTrait::buildXPathQuery Deprecated protected function Builds an XPath query.
AssertLegacyTrait::constructFieldXpath Deprecated protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertLegacyTrait::getAllOptions Deprecated protected function Get all option elements, including nested options, in a select.
AssertLegacyTrait::getRawContent Deprecated protected function Gets the current raw content.
AssertLegacyTrait::pass Deprecated protected function
AssertLegacyTrait::verbose Deprecated protected function
BlockCreationTrait::placeBlock protected function Creates a block instance based on default settings. Aliased as: drupalPlaceBlock
BrowserHtmlDebugTrait::$htmlOutputBaseUrl protected property The Base URI to use for links to the output files.
BrowserHtmlDebugTrait::$htmlOutputClassName protected property Class name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounter protected property Counter for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounterStorage protected property Counter storage for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputDirectory protected property Directory name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputEnabled protected property HTML output enabled.
BrowserHtmlDebugTrait::$htmlOutputFile protected property The file name to write the list of URLs to.
BrowserHtmlDebugTrait::$htmlOutputTestId protected property HTML output test ID.
BrowserHtmlDebugTrait::formatHtmlOutputHeaders protected function Formats HTTP headers as string for HTML output logging.
BrowserHtmlDebugTrait::getHtmlOutputHeaders protected function Returns headers in HTML output format. 1
BrowserHtmlDebugTrait::getResponseLogHandler protected function Provides a Guzzle middleware handler to log every response received.
BrowserHtmlDebugTrait::htmlOutput protected function Logs a HTML output message in a text file.
BrowserHtmlDebugTrait::initBrowserOutputFile protected function Creates the directory to store browser output.
BrowserTestBase::$baseUrl protected property The base URL.
BrowserTestBase::$configImporter protected property The config importer that can be used in a test.
BrowserTestBase::$customTranslations protected property An array of custom translations suitable for drupal_rewrite_settings().
BrowserTestBase::$mink protected property Mink session manager.
BrowserTestBase::$minkDefaultDriverArgs protected property Mink default driver params.
BrowserTestBase::$minkDefaultDriverClass protected property Mink class for the default driver to use. 1
BrowserTestBase::$originalContainer protected property The original container.
BrowserTestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks.
BrowserTestBase::$preserveGlobalState protected property
BrowserTestBase::$profile protected property The profile to install as a basis for testing. 37
BrowserTestBase::$runTestInSeparateProcess protected property Browser tests are run in separate processes to prevent collisions between
code that may be loaded by tests.
BrowserTestBase::$timeLimit protected property Time limit in seconds for the test.
BrowserTestBase::$translationFilesDirectory protected property The translation file directory for the test environment.
BrowserTestBase::cleanupEnvironment protected function Clean up the Simpletest environment.
BrowserTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
BrowserTestBase::drupalGetHeader Deprecated protected function Gets the value of an HTTP response header.
BrowserTestBase::filePreDeleteCallback public static function Ensures test files are deletable.
BrowserTestBase::getDefaultDriverInstance protected function Gets an instance of the default Mink driver.
BrowserTestBase::getDrupalSettings protected function Gets the JavaScript drupalSettings variable for the currently-loaded page. 1
BrowserTestBase::getHttpClient protected function Obtain the HTTP client for the system under test.
BrowserTestBase::getMinkDriverArgs protected function Gets the Mink driver args from an environment variable. 1
BrowserTestBase::getOptions protected function Helper function to get the options of select field.
BrowserTestBase::getSession public function Returns Mink session.
BrowserTestBase::getSessionCookies protected function Get session cookies from current session.
BrowserTestBase::getTestMethodCaller protected function Retrieves the current calling line in the class under test. Overrides BrowserHtmlDebugTrait::getTestMethodCaller
BrowserTestBase::initFrontPage protected function Visits the front page when initializing Mink. 3
BrowserTestBase::initMink protected function Initializes Mink sessions. 1
BrowserTestBase::installDrupal public function Installs Drupal into the Simpletest site. 1
BrowserTestBase::registerSessions protected function Registers additional Mink sessions.
BrowserTestBase::setUpAppRoot protected function Sets up the root application path.
BrowserTestBase::setUpBeforeClass public static function 1
BrowserTestBase::tearDown protected function 3
BrowserTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for submitForm().
BrowserTestBase::xpath protected function Performs an xpath search on the contents of the internal browser.
BrowserTestBase::__sleep public function Prevents serializing any properties.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
ContentTypeCreationTrait::createContentType protected function Creates a custom content type based on default settings. Aliased as: drupalCreateContentType 1
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
FunctionalTestSetupTrait::$apcuEnsureUniquePrefix protected property The flag to set &#039;apcu_ensure_unique_prefix&#039; setting. 1
FunctionalTestSetupTrait::$classLoader protected property The class loader to use for installation and initialization of setup.
FunctionalTestSetupTrait::$rootUser protected property The &quot;#1&quot; admin user.
FunctionalTestSetupTrait::doInstall protected function Execute the non-interactive installer. 1
FunctionalTestSetupTrait::getDatabaseTypes protected function Returns all supported database driver installer objects.
FunctionalTestSetupTrait::initConfig protected function Initialize various configurations post-installation. 1
FunctionalTestSetupTrait::initKernel protected function Initializes the kernel after installation.
FunctionalTestSetupTrait::initSettings protected function Initialize settings created during install.
FunctionalTestSetupTrait::initUserSession protected function Initializes user 1 for the site to be installed.
FunctionalTestSetupTrait::installDefaultThemeFromClassProperty protected function Installs the default theme defined by `static::$defaultTheme` when needed.
FunctionalTestSetupTrait::installModulesFromClassProperty protected function Install modules defined by `static::$modules`. 1
FunctionalTestSetupTrait::installParameters protected function Returns the parameters that will be used when Simpletest installs Drupal. 8
FunctionalTestSetupTrait::prepareEnvironment protected function Prepares the current environment for running the test. 22
FunctionalTestSetupTrait::prepareRequestForGenerator protected function Creates a mock request and sets it on the generator.
FunctionalTestSetupTrait::prepareSettings protected function Prepares site settings and services before installation. 3
FunctionalTestSetupTrait::rebuildAll protected function Resets and rebuilds the environment after setup.
FunctionalTestSetupTrait::rebuildContainer protected function Rebuilds \Drupal::getContainer().
FunctionalTestSetupTrait::resetAll protected function Resets all data structures after having enabled new modules.
FunctionalTestSetupTrait::setContainerParameter protected function Changes parameters in the services.yml file.
FunctionalTestSetupTrait::setupBaseUrl protected function Sets up the base URL based upon the environment variable.
FunctionalTestSetupTrait::writeSettings protected function Rewrites the settings.php file of the test site. 1
LanguageUILanguageNegotiationTest::$adminUser protected property The admin user for testing.
LanguageUILanguageNegotiationTest::$defaultTheme protected property The theme to install as the default for testing. Overrides BrowserTestBase::$defaultTheme
LanguageUILanguageNegotiationTest::$modules protected static property Modules to enable. Overrides BrowserTestBase::$modules
LanguageUILanguageNegotiationTest::doRunTest protected function
LanguageUILanguageNegotiationTest::setUp protected function Overrides BrowserTestBase::setUp
LanguageUILanguageNegotiationTest::testContentCustomization public function Tests persistence of negotiation settings for the content language type.
LanguageUILanguageNegotiationTest::testDisableLanguageSwitcher public function Tests if the language switcher block gets deleted when a language type has been made not configurable.
LanguageUILanguageNegotiationTest::testLanguageDomain public function Tests URL handling when separate domains are used for multiple languages.
LanguageUILanguageNegotiationTest::testUILanguageNegotiation public function Tests for language switching by URL path.
LanguageUILanguageNegotiationTest::testUrlLanguageFallback public function Tests URL language detection when the requested URL has no language.
NodeCreationTrait::createNode protected function Creates a node based on default settings. Aliased as: drupalCreateNode
NodeCreationTrait::getNodeByTitle public function Get a node from the database based on its title. Aliased as: drupalGetNodeByTitle
PhpUnitWarnings::$deprecationWarnings private static property Deprecation warnings from PHPUnit to raise with @trigger_error().
PhpUnitWarnings::addWarning public function Converts PHPUnit deprecation warnings to E_USER_DEPRECATED.
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers. 1
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
RefreshVariablesTrait::refreshVariables protected function Refreshes in-memory configuration and state information. 1
SessionTestTrait::$sessionName protected property The name of the session cookie.
SessionTestTrait::generateSessionName protected function Generates a session cookie name.
SessionTestTrait::getSessionName protected function Returns the session name in use on the child site.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestRequirementsTrait::checkModuleRequirements private function Checks missing module requirements.
TestRequirementsTrait::checkRequirements protected function Check module requirements for the Drupal use case.
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.
TestSetupTrait::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking. 1
TestSetupTrait::$container protected property The dependency injection container used in the test.
TestSetupTrait::$databasePrefix protected property The database prefix of this test run.
TestSetupTrait::$kernel protected property The DrupalKernel instance used in the test.
TestSetupTrait::$originalSite protected property The site directory of the original parent site.
TestSetupTrait::$privateFilesDirectory protected property The private file directory for the test environment.
TestSetupTrait::$publicFilesDirectory protected property The public file directory for the test environment.
TestSetupTrait::$root protected property The app root.
TestSetupTrait::$siteDirectory protected property The site directory of this test run.
TestSetupTrait::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 1
TestSetupTrait::$tempFilesDirectory protected property The temporary file directory for the test environment.
TestSetupTrait::$testId protected property The test run ID.
TestSetupTrait::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
TestSetupTrait::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
TestSetupTrait::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestSetupTrait::prepareDatabasePrefix protected function Generates a database prefix for running tests. 1
UiHelperTrait::$loggedInUser protected property The current user logged in using the Mink controlled browser.
UiHelperTrait::$maximumMetaRefreshCount protected property The number of meta refresh redirects to follow, or NULL if unlimited.
UiHelperTrait::$metaRefreshCount protected property The number of meta refresh redirects followed during ::drupalGet().
UiHelperTrait::assertSession public function Returns WebAssert object. 1
UiHelperTrait::buildUrl protected function Builds an absolute URL from a system path or a URL object.
UiHelperTrait::checkForMetaRefresh protected function Checks for meta refresh tag and if found call drupalGet() recursively.
UiHelperTrait::click protected function Clicks the element with the given CSS selector.
UiHelperTrait::clickLink protected function Follows a link by complete name.
UiHelperTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
UiHelperTrait::cssSelectToXpath protected function Translates a CSS expression to its XPath equivalent.
UiHelperTrait::drupalGet protected function Retrieves a Drupal path or an absolute path. 2
UiHelperTrait::drupalLogin protected function Logs in a user using the Mink controlled browser.
UiHelperTrait::drupalLogout protected function Logs a user out of the Mink controlled browser and confirms.
UiHelperTrait::drupalPostForm Deprecated protected function Executes a form submission.
UiHelperTrait::drupalUserIsLoggedIn protected function Returns whether a given user account is logged in.
UiHelperTrait::getAbsoluteUrl protected function Takes a path and returns an absolute path.
UiHelperTrait::getTextContent protected function Retrieves the plain-text content from the current page.
UiHelperTrait::getUrl protected function Get the current URL from the browser.
UiHelperTrait::isTestUsingGuzzleClient protected function Determines if test is using DrupalTestBrowser.
UiHelperTrait::prepareRequest protected function Prepare for a request to testing site. 1
UiHelperTrait::submitForm protected function Fills and submits a form.
UserCreationTrait::checkPermissions protected function Checks whether a given list of permission names is valid.
UserCreationTrait::createAdminRole protected function Creates an administrative role.
UserCreationTrait::createRole protected function Creates a role with specified permissions. Aliased as: drupalCreateRole
UserCreationTrait::createUser protected function Create a user with a given set of permissions. Aliased as: drupalCreateUser
UserCreationTrait::grantPermissions protected function Grant permissions to a user role.
UserCreationTrait::setCurrentUser protected function Switch the current logged in user.
UserCreationTrait::setUpCurrentUser protected function Creates a random user account and sets it as current user.
XdebugRequestTrait::extractCookiesFromRequest protected function Adds xdebug cookies, from request setup.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.