From 900be573902c7ad041e05e094a8b20555532906e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Wed, 4 Dec 2024 07:58:28 +0200 Subject: [PATCH 01/14] UHF-10908: Use variable for the spacerParentSelector, if it is set. --- modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js index 296861a70..ec42eb645 100644 --- a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js +++ b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js @@ -36,7 +36,7 @@ language: drupalSettings.hdbt_cookie_banner.langcode, theme: drupalSettings.hdbt_cookie_banner.theme, settingsPageSelector: drupalSettings.hdbt_cookie_banner.settingsPageSelector, - spacerParentSelector: '.footer', + spacerParentSelector: drupalSettings.hdbt_cookie_banner.spacerParentSelector || '.footer', }; window.hds.CookieConsentCore.create(apiUrl, options); } From 870a12e005cd5b000525b22203f2198d130b462f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Wed, 4 Dec 2024 08:49:28 +0200 Subject: [PATCH 02/14] UHF-10908: Added hdbt_cookie_banner_test module to alter settings in tests. --- .../hdbt_cookie_banner_test.info.yml | 4 +++ .../hdbt_cookie_banner_test.module | 18 +++++++++++++ .../hdbt_cookie_banner_test.routing.yml | 7 ++++++ .../src/Controller/TestController.php | 25 +++++++++++++++++++ 4 files changed, 54 insertions(+) create mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml create mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module create mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.routing.yml create mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/src/Controller/TestController.php diff --git a/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml b/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml new file mode 100644 index 000000000..7fd1aa085 --- /dev/null +++ b/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml @@ -0,0 +1,4 @@ +name: 'HDBT cookie banner test module' +type: module +package: Custom +core_version_requirement: ^10 || ^11 diff --git a/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module b/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module new file mode 100644 index 000000000..18b44ab4a --- /dev/null +++ b/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module @@ -0,0 +1,18 @@ + 'inline_template', + '#template' => '

Test Content

', + ]; + } + +} From bc452d52dc2b7f0d52828dba906d323bd13454eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Wed, 4 Dec 2024 09:09:23 +0200 Subject: [PATCH 03/14] UHF-10908: Added test for the cookie banner functionality. --- .../FunctionalJavascript/CookieBannerTest.php | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php diff --git a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php new file mode 100644 index 000000000..f37a6ba6d --- /dev/null +++ b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php @@ -0,0 +1,112 @@ +getPath('hdbt_cookie_banner'); + $json_file_path = $module_path . '/assets/json/siteSettingsTemplate.json'; + + // Assert the file exists. + $this->assertTrue(file_exists($json_file_path)); + + // Load and decode the JSON. + $json_content = file_get_contents($json_file_path); + $this->assertNotEmpty($json_content, 'Decoded JSON data is not empty.'); + + // Get the public base URL (in a FunctionalJavascript test). + // Construct a URL for the hds-cookie-consent.min.js file. + $cookie_js_url = "/$module_path/assets/js/hds-cookie-consent.min.js"; + + // Change configuration value before the test runs. + $config = $this->config('hdbt_cookie_banner.settings'); + $config + ->set('use_custom_settings', TRUE) + ->set('site_settings', $json_content) + ->set('use_internal_hds_cookie_js', FALSE) + ->set('hds_cookie_js_override', $cookie_js_url) + ->save(); + + \Drupal::service('cache.default')->deleteAll(); + } + + /** + * Tests the cookie banner visibility and interaction. + */ + public function testCookieBanner() { + + $this->drupalGet('/test-page'); + $this->assertSession()->pageTextContains('Test Content'); + $this->assertSession()->elementExists('css', '.test-footer'); + + // phpcs:disable + // Take a screenshot. + // $this->createScreenshot(\Drupal::root() .'/sites/default/files/simpletest/test.png'); + + // Get browser logs (console output). + // $logs = $this->getSession()->getDriver()->getWebDriverSession()->log('browser'); + // foreach ($logs as $log) { + // var_dump( "JavaScript Log: " . $log['message']); + // } + + // Debug the page html. + // $page = $this->getSession()->getPage(); + // $this->htmlOutput($page->getHtml()); + // phpcs:enable + + // Get the Shadow DOM host and button selectors. + $shadowHostSelector = '.hds-cc__target'; + $buttonSelector = '.hds-cc__all-cookies-button'; + + // JavaScript to locate the button inside the Shadow DOM and click it. + $js = <<getSession()->executeScript($js); + } + +} From 3a7ce0387f6aba0fd5d2997321316790b6f88e10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Wed, 4 Dec 2024 10:11:16 +0200 Subject: [PATCH 04/14] UHF-10908: Fixed phpstan error. --- .../tests/src/FunctionalJavascript/CookieBannerTest.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php index f37a6ba6d..95f1d6398 100644 --- a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php +++ b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php @@ -12,9 +12,7 @@ class CookieBannerTest extends WebDriverTestBase { /** - * Modules to enable. - * - * @var array + * {@inheritdoc} */ protected static $modules = [ 'hdbt_cookie_banner', From dc45cd1f41f9d56a6b836e4b984a2a973f67b760 Mon Sep 17 00:00:00 2001 From: tuutti Date: Thu, 5 Dec 2024 11:23:33 +0200 Subject: [PATCH 05/14] UHF-10908: Testing fixes --- .../assets/js/hdbt-cookie-banner.js | 52 +++++++++---------- .../hdbt_cookie_banner.module | 17 +----- .../src/Services/CookieSettings.php | 15 ------ .../FunctionalJavascript/CookieBannerTest.php | 9 +--- 4 files changed, 28 insertions(+), 65 deletions(-) diff --git a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js index ec42eb645..8471ad61b 100644 --- a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js +++ b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js @@ -67,41 +67,39 @@ window.addEventListener( 'hds-cookie-consent-unapproved-item-found', (e) => { + if (typeof window.Sentry === 'undefined') { + return; + } const { storageType, keys, acceptedGroups } = e.detail // Alphabetize the keys array const sortedKeys = keys.sort(); - if (window.Sentry) { - // Sentry requires a unique name for each error in order to record - // each found unapproved item per type. - const name = `Unapproved ${storageType}` - const message = `Found: ${sortedKeys.join(', ')}` + // Sentry requires a unique name for each error in order to record + // each found unapproved item per type. + const name = `Unapproved ${storageType}` + const message = `Found: ${sortedKeys.join(', ')}` - class UnapprovedItemError extends Error { - constructor(message) { - super(message) - this.name = name - } + class UnapprovedItemError extends Error { + constructor(message) { + super(message) + this.name = name } - - // Capture the error with Sentry and send a message with the - // unapproved items so that they can be searched in Sentry. - window.Sentry.captureException(new UnapprovedItemError(message), { - level: 'warning', - tags: { - approvedCategories: acceptedGroups.join(', '), - }, - extra: { - storageType, - cookieNames: sortedKeys, - approvedCategories: acceptedGroups, - }, - }) - } else { - // If Sentry is not defined, throw an error. - throw new Error('Sentry is not defined') } + + // Capture the error with Sentry and send a message with the + // unapproved items so that they can be searched in Sentry. + window.Sentry.captureException(new UnapprovedItemError(message), { + level: 'warning', + tags: { + approvedCategories: acceptedGroups.join(', '), + }, + extra: { + storageType, + cookieNames: sortedKeys, + approvedCategories: acceptedGroups, + }, + }) } ) }, diff --git a/modules/hdbt_cookie_banner/hdbt_cookie_banner.module b/modules/hdbt_cookie_banner/hdbt_cookie_banner.module index 4874869b8..86c347891 100644 --- a/modules/hdbt_cookie_banner/hdbt_cookie_banner.module +++ b/modules/hdbt_cookie_banner/hdbt_cookie_banner.module @@ -65,22 +65,7 @@ function hdbt_cookie_banner_page_attachments(array &$attachments) : void { /** @var \Drupal\hdbt_cookie_banner\Services\CookieSettings $cookie_settings_service */ $cookie_settings_service = \Drupal::service('hdbt_cookie_banner.cookie_settings'); - // By default, we use the hel.fi etusivu instance HDS cookie consent JS file. - if (empty($config->get('use_custom_settings'))) { - $cookie_settings_service->injectBannerJavaScript($attachments); - } - // We can also use the current instance HDS cookie consent JS file. - elseif (empty($config->get('use_internal_hds_cookie_js'))) { - $attachments['#attached']['library'][] = 'hdbt_cookie_banner/hds_cookie_consent'; - } - // Or the custom HDS cookie consent JS file can be used. - else { - $cookie_settings_service->injectBannerJavaScript( - $attachments, - $config->get('hds_cookie_js_override') - ); - } - + $attachments['#attached']['library'][] = 'hdbt_cookie_banner/hds_cookie_consent'; // Attach HDBT cookie banner initialization JS file. $attachments['#attached']['library'][] = 'hdbt_cookie_banner/hdbt_cookie_banner'; diff --git a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php index c6a43e3c1..11f90f1f5 100644 --- a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php +++ b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php @@ -61,21 +61,6 @@ public function getCookieBannerApiUrl(): string { $config = $this->configFactory->get(HdbtCookieBannerForm::SETTINGS); $language = $this->languageManager->getDefaultLanguage(); - // Default to Etusivu API URL. - if (!$config->get('use_custom_settings')) { - try { - $environment = $this->environmentResolver->getEnvironment( - Project::ETUSIVU, - $this->environmentResolver->getActiveEnvironmentName() - ); - - return vsprintf("%s/api/cookie-banner", [ - $environment->getUrl($language->getId()), - ]); - } - catch (\InvalidArgumentException) { - } - } return $this->urlGenerator->generateFromRoute( 'hdbt_cookie_banner.site_settings', options: ['language' => $language], diff --git a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php index 95f1d6398..251c5ccc3 100644 --- a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php +++ b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php @@ -42,17 +42,12 @@ protected function setUp(): void { $json_content = file_get_contents($json_file_path); $this->assertNotEmpty($json_content, 'Decoded JSON data is not empty.'); - // Get the public base URL (in a FunctionalJavascript test). - // Construct a URL for the hds-cookie-consent.min.js file. - $cookie_js_url = "/$module_path/assets/js/hds-cookie-consent.min.js"; - // Change configuration value before the test runs. $config = $this->config('hdbt_cookie_banner.settings'); $config - ->set('use_custom_settings', TRUE) ->set('site_settings', $json_content) - ->set('use_internal_hds_cookie_js', FALSE) - ->set('hds_cookie_js_override', $cookie_js_url) + ->set('use_custom_settings', TRUE) + ->set('use_internal_hds_cookie_js', TRUE) ->save(); \Drupal::service('cache.default')->deleteAll(); From af42bf7208648a13d9a430b9974041a9cd51220f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Mon, 9 Dec 2024 21:53:24 +0200 Subject: [PATCH 06/14] UHF-10908: Get cookie settings page URL with a langcode. --- .../src/Services/CookieSettings.php | 97 ++++++++++++++++--- 1 file changed, 82 insertions(+), 15 deletions(-) diff --git a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php index 11f90f1f5..ac89141a0 100644 --- a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php +++ b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php @@ -4,6 +4,7 @@ namespace Drupal\hdbt_cookie_banner\Services; +use Drupal\helfi_api_base\Environment\Environment; use Drupal\Core\Asset\LibraryDiscoveryInterface; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Language\LanguageManagerInterface; @@ -37,7 +38,30 @@ public function __construct( * @return \Drupal\Core\Url|null * The URL of the cookie settings page. */ - public function getCookieSettingsPageUrl(): ?Url { + public function getCookieSettingsPageUrl(?string $langcode = ''): ?Url { + if (!$langcode) { + $langcode = $this->languageManager->getDefaultLanguage()->getId(); + } + + // Default to Etusivu cookie settings page. + if (!$this->useCustomSettings()) { + $environment = $this->getActiveEtusivuEnvironment(); + + if ($environment instanceof Environment) { + $path = match($langcode) { + 'fi' => "evasteasetukset", + 'sv' => "cookie-installningar", + default => "cookie-settings", + }; + + $url = vsprintf("%s/%s", [ + $environment->getUrl($langcode), + $path, + ]); + return Url::fromUri($url); + } + } + $route_name = 'hdbt_cookie_banner.cookie_settings_page'; try { // Check if the cookie settings page route exists. @@ -58,9 +82,19 @@ public function getCookieSettingsPageUrl(): ?Url { * Cookie banner API URL as a string. */ public function getCookieBannerApiUrl(): string { - $config = $this->configFactory->get(HdbtCookieBannerForm::SETTINGS); $language = $this->languageManager->getDefaultLanguage(); + // Default to Etusivu API URL. + if (!$this->useCustomSettings()) { + $environment = $this->getActiveEtusivuEnvironment(); + + if ($environment instanceof Environment) { + return vsprintf("%s/api/cookie-banner", [ + $environment->getUrl($language->getId()), + ]); + } + } + return $this->urlGenerator->generateFromRoute( 'hdbt_cookie_banner.site_settings', options: ['language' => $language], @@ -79,19 +113,8 @@ public function injectBannerJavaScript(array &$attachments, ?string $library = N // Load HDS cookie consent JavaScript file from Etusivu instance. if (!$library) { - // Get active Etusivu environment. - try { - $environment = $this->environmentResolver->getEnvironment( - Project::ETUSIVU, - $this->environmentResolver->getActiveEnvironmentName() - ); - } - catch (\InvalidArgumentException) { - $environment = $this->environmentResolver->getEnvironment( - Project::ETUSIVU, - EnvironmentEnum::Prod->value - ); - } + // Get the active Etusivu environment, default to production. + $environment = $this->getActiveEtusivuEnvironment(TRUE); // Construct the URL to the HDS cookie consent JS file. $library = vsprintf("%s/etusivu-assets/%s/assets/js/hds-cookie-consent.min.js%s", [ @@ -137,4 +160,48 @@ protected function getCookieLibraryVersion(): string { return ''; } + /** + * Checks if current drupal instance uses custom settings. + * + * If not, the default settings are used and all information is retrieved + * from "hel.fi" drupal instance. + * + * @return bool + * Returns true if custom settings are used. + */ + protected function useCustomSettings(): bool { + $config = $this->configFactory->get(HdbtCookieBannerForm::SETTINGS); + return (bool) $config->get('use_custom_settings'); + } + + /** + * Get the active Etusivu environment if available. + * + * @param bool $default_to_production + * Should the Etusivu production be used? + * + * @return \Drupal\helfi_api_base\Environment\Environment|null + * Returns the active Etusivu environment or NULL. + */ + protected function getActiveEtusivuEnvironment(?bool $default_to_production = FALSE): Environment|NULL { + $environment = 'NULL'; + + // Get active Etusivu environment. + try { + $environment = $this->environmentResolver->getEnvironment( + Project::ETUSIVU, + $this->environmentResolver->getActiveEnvironmentName() + ); + } + catch (\InvalidArgumentException) { + if ($default_to_production) { + $environment = $this->environmentResolver->getEnvironment( + Project::ETUSIVU, + EnvironmentEnum::Prod->value + ); + } + } + return $environment; + } + } From ed62b5fb3d6ba87080ace83cf4ea308ee70db205 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Mon, 9 Dec 2024 21:54:56 +0200 Subject: [PATCH 07/14] UHF-10908: Reverted the custom cookie consent JS injection, until it's properly removed. --- .../hdbt_cookie_banner.module | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/modules/hdbt_cookie_banner/hdbt_cookie_banner.module b/modules/hdbt_cookie_banner/hdbt_cookie_banner.module index 86c347891..4874869b8 100644 --- a/modules/hdbt_cookie_banner/hdbt_cookie_banner.module +++ b/modules/hdbt_cookie_banner/hdbt_cookie_banner.module @@ -65,7 +65,22 @@ function hdbt_cookie_banner_page_attachments(array &$attachments) : void { /** @var \Drupal\hdbt_cookie_banner\Services\CookieSettings $cookie_settings_service */ $cookie_settings_service = \Drupal::service('hdbt_cookie_banner.cookie_settings'); - $attachments['#attached']['library'][] = 'hdbt_cookie_banner/hds_cookie_consent'; + // By default, we use the hel.fi etusivu instance HDS cookie consent JS file. + if (empty($config->get('use_custom_settings'))) { + $cookie_settings_service->injectBannerJavaScript($attachments); + } + // We can also use the current instance HDS cookie consent JS file. + elseif (empty($config->get('use_internal_hds_cookie_js'))) { + $attachments['#attached']['library'][] = 'hdbt_cookie_banner/hds_cookie_consent'; + } + // Or the custom HDS cookie consent JS file can be used. + else { + $cookie_settings_service->injectBannerJavaScript( + $attachments, + $config->get('hds_cookie_js_override') + ); + } + // Attach HDBT cookie banner initialization JS file. $attachments['#attached']['library'][] = 'hdbt_cookie_banner/hdbt_cookie_banner'; From ea093bbfd1f045c8b3f05e45bb8be1e691e3b46b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Mon, 9 Dec 2024 21:56:17 +0200 Subject: [PATCH 08/14] UHF-10908: Test the cookie banner settings page url with languages. --- .../tests/src/Kernel/KernelTestBase.php | 4 +- .../Kernel/Services/CookieSettingsTest.php | 104 ++++++++++++++---- 2 files changed, 87 insertions(+), 21 deletions(-) diff --git a/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php b/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php index 44e5ca8a9..9db9e40a0 100644 --- a/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php +++ b/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php @@ -101,7 +101,7 @@ protected function setUp(): void { $mockEnvironment = new Environment( new Address('www.test.hel.ninja'), new Address('internal-address.local', 'http', 8080), - ['en' => '/en'], + ['en' => '/en', 'fi' => '/fi', 'sv' => '/sv'], EnvironmentEnum::Test, [], ); @@ -142,7 +142,7 @@ protected function setUpTheConfigurations(array $configuration): void { $immutableConfig->method('get')->willReturnMap($configuration); // Only mock the 'HdbtCookieBannerForm::SETTINGS' configuration. - $this->configFactory->expects($this->once()) + $this->configFactory->expects($this->atLeastOnce()) ->method('get') ->with(HdbtCookieBannerForm::SETTINGS) ->willReturn($immutableConfig); diff --git a/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php b/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php index 92a055d45..0df1e4932 100644 --- a/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php +++ b/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php @@ -10,7 +10,6 @@ use Drupal\hdbt_cookie_banner\Services\CookieSettings; use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Routing\Exception\RouteNotFoundException; -use Symfony\Component\Routing\Route; /** * Tests the CookieSettings service. @@ -33,6 +32,13 @@ class CookieSettingsTest extends KernelTestBase { */ protected LanguageInterface|MockObject $language; + /** + * An array of mock LanguageInterface objects. + * + * @var array + */ + protected array $languages; + /** * {@inheritdoc} */ @@ -49,14 +55,42 @@ protected function setUp(): void { $this->container->get('library.discovery'), ); - $this->language = $this->createMock(LanguageInterface::class); - $this->language->expects($this->any()) - ->method('getId') - ->willReturn('en'); + $this->languages = $this->setUpLanguages(); $this->languageManager->expects($this->any()) ->method('getDefaultLanguage') - ->willReturn($this->language); + ->willReturn($this->languages['en']); + } + + /** + * Sets up mock LanguageInterface objects. + * + * @return array + * An array of mock LanguageInterface objects. + */ + protected function setUpLanguages(): array { + $language_fi = $this->createMock(LanguageInterface::class); + $language_fi->expects($this->any()) + ->method('getId') + ->willReturn('fi'); + $language_sv = $this->createMock(LanguageInterface::class); + $language_sv->expects($this->any()) + ->method('getId') + ->willReturn('sv'); + $language_en = $this->createMock(LanguageInterface::class); + $language_en->expects($this->any()) + ->method('getId') + ->willReturn('en'); + $language_it = $this->createMock(LanguageInterface::class); + $language_it->expects($this->any()) + ->method('getId') + ->willReturn('it'); + return [ + 'fi' => $language_fi, + 'sv' => $language_sv, + 'en' => $language_en, + 'it' => $language_it, + ]; } /** @@ -96,7 +130,7 @@ public function testGetCookieBannerApiUrlWithCustomSettings(): void { ->with( 'hdbt_cookie_banner.site_settings', [], - ['language' => $this->language], + ['language' => $this->languages['en']], ) ->willReturn('/en/api/cookie-banner'); @@ -140,27 +174,59 @@ public function testInjectBannerJavaScriptWithLibrary(): void { } /** - * Tests getCookieSettingsPageUrl when the route exists. + * Tests getCookieBannerApiUrl with custom settings. */ - public function testGetCookieSettingsPageUrlRouteExists(): void { - $route_name = 'hdbt_cookie_banner.cookie_settings_page'; + public function testGetCookieSettingsPage(): void { + // Expected settings for external (hel.fi) setup. + $expected = [ + ['site_settings', '{"test": "true"}'], + ['use_custom_settings', FALSE], + ]; - // Simulate that the route exists by not throwing an exception. - $this->routeProvider->expects($this->once()) - ->method('getRouteByName') - ->with($route_name) - ->willReturn($this->createMock(Route::class)); + // Set up the configurations with specified settings. + $this->setUpTheConfigurations($expected); - // Test that the URL is returned correctly. - $url = $this->cookieSettings->getCookieSettingsPageUrl(); - $this->assertInstanceOf(Url::class, $url); - $this->assertEquals($route_name, $url->getRouteName()); + $language_map = [ + 'en' => 'https://www.test.hel.ninja/en/cookie-settings', + 'fi' => 'https://www.test.hel.ninja/fi/evasteasetukset', + 'sv' => 'https://www.test.hel.ninja/sv/cookie-installningar', + 'it' => 'https://www.test.hel.ninja/en/cookie-settings', + ]; + + foreach ($language_map as $langcode => $mock_url) { + $return_value = match($langcode) { + 'fi' => 'fi', + 'sv' => 'sv', + default => 'en', + }; + + $this->languages[$langcode]->expects($this->any())->method('getId')->willReturn($return_value); + + if ($langcode === 'it') { + $this->expectExceptionMessage('Path not found for "it" language.'); + $url = $this->cookieSettings->getCookieSettingsPageUrl((string) $langcode); + } + else { + // Test that the URL is returned correctly. + $url = $this->cookieSettings->getCookieSettingsPageUrl((string) $langcode); + $this->assertInstanceOf(Url::class, $url); + $this->assertEquals($mock_url, $url->toString()); + } + } } /** * Tests getCookieSettingsPageUrl when the route does not exist. */ public function testGetCookieSettingsPageUrlRouteNotExists(): void { + // Expected settings for external (hel.fi) setup. + $expected = [ + ['use_custom_settings', TRUE], + ]; + + // Set up the configurations with specified settings. + $this->setUpTheConfigurations($expected); + $route_name = 'hdbt_cookie_banner.cookie_settings_page'; // Simulate that the route does not exist by throwing an exception. From 740876bd0868df316811e4d28000f66eeea3c487 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Mon, 9 Dec 2024 22:55:19 +0200 Subject: [PATCH 09/14] UHF-10908: Updated the siteSettingsTemplate.json. --- .../assets/json/siteSettingsTemplate.json | 253 +++++++++--------- 1 file changed, 127 insertions(+), 126 deletions(-) diff --git a/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json b/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json index 4484457f1..7d2ed97e3 100644 --- a/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json +++ b/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json @@ -29,9 +29,9 @@ "en": "Essential cookies" }, "description": { - "fi": "Välttämättömät evästeet auttavat tekemään verkkosivustosta käyttökelpoisen sallimalla perustoimintoja, kuten sivulla siirtymisen ja sivuston suojattujen alueiden käytön. Verkkosivusto ei toimi kunnolla ilman näitä evästeitä eikä niihin tarvita suostumusta.", - "sv": "Nödvändiga cookies hjälper till att göra webbplatsen användbar genom att tillåta grundläggande funktioner som att navigera på sidan och använda de skyddade områdena på webbplatsen. Webbplatsen fungerar inte korrekt utan dessa cookies och kräver inte samtycke.", - "en": "Essential cookies help to make the website usable by allowing basic functions, navigating the page and using the protected areas of the site. The website will not work properly without these cookies and their consent is not required." + "fi": "Välttämättömät evästeet varmistavat, että sivusto toimii kunnolla. Välttämättömiin evästeisiin ei tarvita suostumusta. Nämä evästeet mahdollistavat perustoimintoja, kuten sivulla siirtymisen ja sivuston suojattujen alueiden käytön.", + "sv": "Nödvändiga kakor säkerställer att webbplatsen fungerar ordentligt. För nödvändiga kakor behövs inte samtycke. Dessa kakor möjliggör grundläggande funktioner såsom sidnavigering och åtkomst till skyddade områden på webbplatsen.", + "en": "Essential cookies ensure that the website functions correctly. Essential cookies do not require consent. These cookies enable basic functions, such as site navigation and access to protected areas of the website." }, "cookies": [ { @@ -41,88 +41,14 @@ "description": { "fi": "Sivusto käyttää tätä evästettä tietojen tallentamiseen siitä, ovatko kävijät antaneet hyväksyntänsä tai kieltäytyneet evästeiden käytöstä.", "sv": "Cookie möjliggör hantering av cookies på webbplatsen.", - "en": "Used by www.hel.fi Drupal to store information about whether visitors have given or declined the use of cookie categories used on the www.hel.fi site." + "en": "Used by change-me.hel.fi Drupal to store information about whether visitors have given or declined the use of cookie categories used on the change-me.hel.fi site." }, "expiration": { "fi": "100 päivää", "sv": "100 dagar", "en": "100 days" - } - }, - { - "name": "SSESS*", - "host": "change-me.hel.fi", - "storageType": 1, - "description": { - "fi": "Sisällönhallintajärjestelmän toimintaan liittyvä eväste.", - "sv": "En cookie relaterad till driften av innehållshanteringssystemet.", - "en": "A cookie related to the operation of the content management system." - }, - "expiration": { - "fi": "23 päivää", - "sv": "23 dagar", - "en": "23 days" - } - }, - { - "name": "mtm_cookie_consent", - "host": "kartta.hel.fi", - "storageType": 1, - "description": { - "fi": "Tekninen eväste johon talletetaan tieto valinnastasi evästeiden käytöstä kertovan bannerin kohdalla", - "sv": "A technical cookie that stores information about how you responded to the notice in the cookie banner about the use of cookies.", - "en": "A technical cookie that stores information about how you responded to the notice in the cookie banner about the use of cookies." - }, - "expiration": { - "fi": "10950 päivää", - "sv": "10950 dagar", - "en": "10950 days" - } - }, - { - "name": "JSESSIONID", - "host": "helsinkikanava.fi", - "storageType": 1, - "description": { - "fi": "Sivuston pakollinen eväste mahdollistaa kävijän vierailun sivustolla.", - "sv": "Kakan är en obligatorisk kaka som gör det möjligt för besökaren att besöka webbplatsen.", - "en": "The cookie is an obligatory cookie that facilitates visiting the website." }, - "expiration": { - "fi": "Istunto", - "sv": "Session", - "en": "Session" - } - }, - { - "name": "COOKIE_SUPPORT", - "host": "helsinkikanava.fi", - "storageType": 1, - "description": { - "fi": "Mahdollistaa evästeiden hallinnan sivustolla.", - "sv": "Kakan möjliggör hanteringen av kakor på webbplatsen.", - "en": "The cookie facilitates managing cookies on the website." - }, - "expiration": { - "fi": "365 päivää", - "sv": "365 dagar", - "en": "365 days" - } - }, - { - "name": "GUEST_LANGUAGE_ID", - "host": "helsinkikanava.fi", - "storageType": 1, - "description": { - "fi": "Tämän evästeen on luonut Liferay, se tallentaa kieliasetukset.", - "sv": "Denna cookie genereras av Liferay, dess funktion är att lagra språkinställningarna.", - "en": "This cookie is generated by the Liferay, its function is to store the language preferences." - }, - "expiration": { - "fi": "365 päivää", - "sv": "365 dagar", - "en": "365 days" - } + "ype": 1 }, { "name": "helfi-settings", @@ -130,8 +56,8 @@ "storageType": 2, "description": { "fi": "Sivusto käyttää tätä tietuetta tietojen tallentamiseen siitä, mitä poikkeusilmoituksia on suljettu ja mikä on avattavien sisältöalueiden tila.", - "sv": "Används av hel.fi Drupal för att lagra information om stängda meddelanden och accordions' tillstånd.", - "en": "Used by hel.fi Drupal to store information about closed announcements and accordions' state." + "sv": "Används av change-me.hel.fi Drupal för att lagra information om stängda meddelanden och accordions' tillstånd.", + "en": "Used by change-me.hel.fi Drupal to store information about closed announcements and accordions' state." }, "expiration": "-" } @@ -145,21 +71,25 @@ "en": "Editors' functional cookies" }, "description": { - "fi": "Sisäänkirjautuneiden sisällöntuottajien välttämättömät toiminnalliset evästeet mahdollistavat editointityökalujen käytön niitä käyttäville. Näitä evästeitä ei aseteta kirjautumattomille käyttäjille.", - "sv": "Nödvändiga funktionella cookies för inloggade redaktörer möjliggör användning av redigeringsverktyg för dem som använder dem. Dessa cookies är inte inställda för icke-inloggade användare.", - "en": "Necessary functional cookies for logged-in editors enable the use of editing tools for those who use them. These cookies are not set for non-logged in users." + "fi": "Sisällöntuottajien välttämättömät toiminnalliset evästeet tallennetaan ainoastaan kirjautuneille sisällöntuottajille. Ne mahdollistavat sivuston muokkaustoiminnot.", + "sv": "Nödvändiga funktionella kakor för innehållsproducenter sparas endast hos inloggade innehållsproducenter. De möjliggör funktioner för redigering av webbplatsen.", + "en": "The essential functional cookies for content providers are only saved for content providers who are signed in. They enable the editing of the website." }, "cookies": [ { - "name": "editoria11yResultCount", + "name": "SSESS*", "host": "change-me.hel.fi", - "storageType": 2, + "storageType": 1, "description": { - "fi": "Tallentaa sisällöntuottajan näkemien saavutettavuusongelmien lukumäärän nykyisellä sivulla.", - "sv": "Spårar tillgänglighetsproblem för den aktuella sidan när du är inloggad som redaktör på hel.fi.", - "en": "Tracks accessibility issues for the current page when logged in as an editor on hel.fi." + "fi": "Sisällönhallintajärjestelmän toimintaan liittyvä eväste.", + "sv": "En cookie relaterad till driften av innehållshanteringssystemet.", + "en": "A cookie related to the operation of the content management system." }, - "expiration": "-" + "expiration": { + "fi": "23 päivää", + "sv": "23 dagar", + "en": "23 days" + } }, { "name": "Drupal.gin.sidebarExpanded.desktop", @@ -167,8 +97,8 @@ "storageType": 2, "description": { "fi": "Tallentaa tiedon sisällöntuottajan käyttöliittymän sivupalkin näkyvyydestä työpöytänäkymässä.", - "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på skrivbordet när du är inloggad som redaktör på hel.fi.", - "en": "Stores whether the admin sidebar is expanded or collapsed on desktop when logged in as an editor on hel.fi." + "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på skrivbordet när du är inloggad som redaktör på change-me.hel.fi.", + "en": "Stores whether the admin sidebar is expanded or collapsed on desktop when logged in as an editor on change-me.hel.fi." }, "expiration": "-" }, @@ -178,8 +108,8 @@ "storageType": 2, "description": { "fi": "Tallentaa tiedon sisällöntuottajan käyttöliittymän sivupalkin näkyvyydestä mobiilinäkymässä.", - "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på mobil när du är inloggad som redaktör på hel.fi.", - "en": "Stores whether the admin sidebar is expanded or collapsed on mobile when logged in as an editor on hel.fi." + "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på mobil när du är inloggad som redaktör på change-me.hel.fi.", + "en": "Stores whether the admin sidebar is expanded or collapsed on mobile when logged in as an editor on change-me.hel.fi." }, "expiration": "-" }, @@ -189,8 +119,8 @@ "storageType": 2, "description": { "fi": "Tallentaa tiedon sisällöntuottajan valitsemasta \"tumma tila\"-asetuksesta.", - "sv": "Lagrar användarens mörkt läge-inställning i admin-temat när du är inloggad som redaktör på hel.fi.", - "en": "Stores the user's dark mode preference in the admin theme when logged in as an editor on hel.fi." + "sv": "Lagrar användarens mörkt läge-inställning i admin-temat när du är inloggad som redaktör på change-me.hel.fi.", + "en": "Stores the user's dark mode preference in the admin theme when logged in as an editor on change-me.hel.fi." }, "expiration": "-" }, @@ -216,17 +146,6 @@ }, "expiration": "-" }, - { - "name": "ed11ySeen", - "host": "change-me.hel.fi", - "storageType": 2, - "description": { - "fi": "Tallentaa sisällöntuottajan näkemät saavutettavuusongelmat, jotta vältetään ongelmien kaksoisilmoitukset.", - "sv": "Spårar vilka tillgänglighetsproblem en inloggad redaktör redan har sett för att undvika dubbla aviseringar.", - "en": "Tracks which accessibility issues a logged-in editor has already seen to avoid duplicate notifications." - }, - "expiration": "-" - }, { "name": "Drupal.toolbar.toolbarState", "host": "change-me.hel.fi", @@ -256,6 +175,28 @@ "sv": "Session", "en": "Session" } + }, + { + "name": "editoria11yResultCount", + "host": "change-me.hel.fi", + "storageType": 2, + "description": { + "fi": "Tallentaa löydettyjen saavutettavuusongelmien määrän sisällöntuottajalle, auttaen seuraamaan ja korjaamaan ne.", + "sv": "Spårar antalet tillgänglighetsproblem som hittats på specifika sidor för en inloggad redaktör, vilket hjälper till att övervaka och åtgärda dem.", + "en": "Tracks the number of accessibility issues found on specific pages for a logged-in editor, helping monitor and address them." + }, + "expiration": "-" + }, + { + "name": "ed11ySeen", + "host": "change-me.hel.fi", + "storageType": 2, + "description": { + "fi": "Tallentaa sisällöntuottajan näkemät saavutettavuusongelmat, jotta vältetään ongelmien kaksoisilmoitukset.", + "sv": "Spårar vilka tillgänglighetsproblem en inloggad redaktör redan har sett för att undvika dubbla aviseringar.", + "en": "Tracks which accessibility issues a logged-in editor has already seen to avoid duplicate notifications." + }, + "expiration": "-" } ] } @@ -275,28 +216,43 @@ }, "cookies": [ { - "name": "httpskartta.hel.fi.SWCulture", - "host": "kartta.hel.fi", + "name": "COOKIE_SUPPORT", + "host": "helsinkikanava.fi", "storageType": 1, "description": { - "fi": "Kaupungin karttapalvelun evästeeseen tallennetaan kieli, jolla palvelua käytetään.", - "sv": "I kakan på stadens kaktjänst sparas det språk som användaren använder i tjänsten.", - "en": "The City's map service cookie saves the language in which the service is used." + "fi": "Mahdollistaa evästeiden hallinnan sivustolla.", + "sv": "Kakan möjliggör hanteringen av kakor på webbplatsen.", + "en": "The cookie facilitates managing cookies on the website." }, "expiration": { - "fi": "1826 päivää", - "sv": "1826 dagar", - "en": "1826 days" + "fi": "365 päivää", + "sv": "365 dagar", + "en": "365 days" } }, { - "name": "icareus-device", + "name": "JSESSIONID", "host": "helsinkikanava.fi", "storageType": 1, "description": { - "fi": "Helsinki-kanavan videopalvelimen eväste.", - "sv": "Helsinki-kanavas kaka gör det möjligt att göra videor till en del av innehållet på webbplatsen.", - "en": "The Helsinki Channel video server cookie facilitates including videos as part of the website's content." + "fi": "Sivuston pakollinen eväste mahdollistaa kävijän vierailun sivustolla.", + "sv": "Kakan är en obligatorisk kaka som gör det möjligt för besökaren att besöka webbplatsen.", + "en": "The cookie is an obligatory cookie that facilitates visiting the website." + }, + "expiration": { + "fi": "Istunto", + "sv": "Session", + "en": "Session" + } + }, + { + "name": "GUEST_LANGUAGE_ID", + "host": "helsinkikanava.fi", + "storageType": 1, + "description": { + "fi": "Tämän evästeen on luonut Liferay, se tallentaa kieliasetukset.", + "sv": "Denna cookie genereras av Liferay, dess funktion är att lagra språkinställningarna.", + "en": "This cookie is generated by the Liferay, its function is to store the language preferences." }, "expiration": { "fi": "365 päivää", @@ -304,6 +260,32 @@ "en": "365 days" } }, + { + "name": "icareusDevice", + "host": "helsinkikanava.fi", + "storageType": 2, + "description": { + "fi": "Helsinki-kanavan videopalvelimen eväste.", + "sv": "Helsinki-kanavas kaka gör det möjligt att göra videor till en del av innehållet på webbplatsen.", + "en": "The Helsinki Channel video server cookie facilitates including videos as part of the website's content." + }, + "expiration": "-" + }, + { + "name": "httpskartta.hel.fi.SWCulture", + "host": "kartta.hel.fi", + "storageType": 1, + "description": { + "fi": "Kaupungin karttapalvelun evästeeseen tallennetaan kieli, jolla palvelua käytetään.", + "sv": "I kakan på stadens kaktjänst sparas det språk som användaren använder i tjänsten.", + "en": "The City's map service cookie saves the language in which the service is used." + }, + "expiration": { + "fi": "1826 päivää", + "sv": "1826 dagar", + "en": "1826 days" + } + }, { "name": "VISITOR_INFO1_LIVE", "host": "youtube.com", @@ -325,8 +307,8 @@ "storageType": 1, "description": { "fi": "Googlen eväste tallentaa kävijän evästehyväskynnän.", - "sv": "Används av Google för att lagra inställningar för användarens samtycke", - "en": "Used by Google to store user consent preferences" + "sv": "Används av Google för att lagra inställningar för användarens samtycke.", + "en": "Used by Google to store user consent preferences." }, "expiration": { "fi": "5947 päivää, 15 tuntia", @@ -386,7 +368,7 @@ "description": { "fi": "Matomo-tilastointijärjestelmän eväste.", "sv": "Matomo-statistiksystemets kaka samlar information om hur webbplatsen används.", - "en": "Matomo Analytics - used to store a few details about the user such as the unique visitor ID" + "en": "Matomo Analytics - short lived cookies used to temporarily store data for the visit" }, "expiration": { "fi": "1 tunti", @@ -416,7 +398,7 @@ "description": { "fi": "Matomo-tilastointijärjestelmän eväste.", "sv": "Matomo-statistiksystemets kaka samlar information om hur webbplatsen används.", - "en": "Matomo Analytics - used to store a few details about the user such as the unique visitor ID" + "en": "Matomo Analytics - short lived cookies used to temporarily store data for the visit" }, "expiration": { "fi": "1 tunti", @@ -446,8 +428,27 @@ { "name": "helfi_accordions_open", "storageType": 1 + }, + { + "name": "cookiehub", + "storageType": 1 + }, + { + "name": "cookie-agreed-version", + "storageType": 1 + }, + { + "name": "cookie-agreed-categories", + "storageType": 1 + }, + { + "name": "cookie-agreed", + "storageType": 1 } ], + "groupsWhitelistedForApi": [ + "chat" + ], "translations": { "bannerAriaLabel": { "fi": "Evästeasetukset", @@ -455,9 +456,9 @@ "en": "Cookie settings" }, "heading": { - "fi": "{{siteName}} käyttää evästeitä", - "sv": "{{siteName}} använder kakor", - "en": "{{siteName}} uses cookies" + "fi": "Evästeet {{siteName}}-sivustolla", + "sv": "Kakor på webbplatsen {{siteName}}", + "en": "Cookies on {{siteName}}" }, "description": { "fi": "Tämä sivusto käyttää välttämättömiä evästeitä sivun perustoimintojen ja suorituskyvyn varmistamiseksi. Lisäksi käytämme kohdennusevästeitä käyttäjäkokemuksen parantamiseksi, analytiikkaan ja yksilöidyn sisällön näyttämiseen.", From 32eb0da02e9f58abadbf8f48a47313ff5dde73be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Mon, 9 Dec 2024 22:55:40 +0200 Subject: [PATCH 10/14] UHF-10908: Updated the cookie banner functional test. --- .../FunctionalJavascript/CookieBannerTest.php | 88 +++++++++++++++---- 1 file changed, 71 insertions(+), 17 deletions(-) diff --git a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php index 251c5ccc3..39c449ec5 100644 --- a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php +++ b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\hdbt_cookie_banner\FunctionalJavascript; +use Behat\Mink\Driver\Selenium2Driver; use Drupal\FunctionalJavascriptTests\WebDriverTestBase; /** @@ -42,12 +43,18 @@ protected function setUp(): void { $json_content = file_get_contents($json_file_path); $this->assertNotEmpty($json_content, 'Decoded JSON data is not empty.'); + // Get the public base URL (in a FunctionalJavascript test). + // Construct a URL for the hds-cookie-consent.min.js file. + $cookie_js_url = "/$module_path/assets/js/hds-cookie-consent.min.js"; + // Change configuration value before the test runs. $config = $this->config('hdbt_cookie_banner.settings'); $config + ->set('use_custom_settings', TRUE) ->set('site_settings', $json_content) ->set('use_custom_settings', TRUE) - ->set('use_internal_hds_cookie_js', TRUE) + ->set('use_internal_hds_cookie_js', FALSE) + ->set('hds_cookie_js_override', $cookie_js_url) ->save(); \Drupal::service('cache.default')->deleteAll(); @@ -57,31 +64,60 @@ protected function setUp(): void { * Tests the cookie banner visibility and interaction. */ public function testCookieBanner() { - $this->drupalGet('/test-page'); $this->assertSession()->pageTextContains('Test Content'); $this->assertSession()->elementExists('css', '.test-footer'); - // phpcs:disable - // Take a screenshot. - // $this->createScreenshot(\Drupal::root() .'/sites/default/files/simpletest/test.png'); - - // Get browser logs (console output). - // $logs = $this->getSession()->getDriver()->getWebDriverSession()->log('browser'); - // foreach ($logs as $log) { - // var_dump( "JavaScript Log: " . $log['message']); - // } - - // Debug the page html. - // $page = $this->getSession()->getPage(); - // $this->htmlOutput($page->getHtml()); - // phpcs:enable + // Get the web driver. + $driver = $this->getSession()->getDriver(); + + // Check if the driver is an instance of DrupalSelenium2Driver. + if ($driver instanceof Selenium2Driver) { + // Get all cookies from the browser. + $cookies = $driver->getWebDriverSession()->getCookie(); + + // Extract only the 'name' keys from all the cookies, as we want to check + // if a specific cookie "change-me" exists. + $cookieNames = array_column($cookies, 'name'); + $this->assertNotContains( + 'change-me', + $cookieNames, + 'The cookie "change-me" was found, but it should not exist.', + ); + } + else { + $this->fail('The driver is not an instance of Selenium2Driver.'); + } + + // Assert that the cookie banner is visible and click the accept button. + $this->assertCookieBannerIsVisible(); + + // Get the new cookies from the browser. + $new_cookies = $driver->getWebDriverSession()->getCookie(); + + // There should be a new cookie called "change-me". + $cookieNames = array_column($new_cookies, 'name'); + $this->assertContains( + 'change-me', + $cookieNames, + 'The cookie "change-me" was not found after clicking the button.', + ); + + // Reload the page and assert that the cookie banner is not visible. + $this->drupalGet('/test-page'); + $this->assertSession()->pageTextContains('Test Content'); + $this->assertCookieBannerNotVisible(); + } + /** + * Asserts that the cookie banner is visible. + */ + protected function assertCookieBannerIsVisible() { // Get the Shadow DOM host and button selectors. $shadowHostSelector = '.hds-cc__target'; $buttonSelector = '.hds-cc__all-cookies-button'; - // JavaScript to locate the button inside the Shadow DOM and click it. + // Verify that the cookie banner is visible and click the accept button. $js = <<getSession()->executeScript($js); } + /** + * Asserts that the cookie banner is not visible. + */ + protected function assertCookieBannerNotVisible() { + // Get the Shadow DOM host and button selectors. + $shadowHostSelector = '.hds-cc__target'; + + // Verify that the cookie banner is not visible. + $js = <<getSession()->executeScript($js); + } + } From 411fc8b95dec577f943a562bcf7c584b586c431c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Mon, 9 Dec 2024 23:44:29 +0200 Subject: [PATCH 11/14] UHF-10908: Use current language if getCookieSettingsPageUrl is called without the language parameter. --- .../src/Services/CookieSettings.php | 28 ++++++++++++------- .../Kernel/Services/CookieSettingsTest.php | 17 +++++------ 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php index ac89141a0..f50430ff1 100644 --- a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php +++ b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php @@ -4,6 +4,7 @@ namespace Drupal\hdbt_cookie_banner\Services; +use Drupal\Core\Language\LanguageInterface; use Drupal\helfi_api_base\Environment\Environment; use Drupal\Core\Asset\LibraryDiscoveryInterface; use Drupal\Core\Config\ConfigFactoryInterface; @@ -38,9 +39,11 @@ public function __construct( * @return \Drupal\Core\Url|null * The URL of the cookie settings page. */ - public function getCookieSettingsPageUrl(?string $langcode = ''): ?Url { + public function getCookieSettingsPageUrl(?string $langcode = NULL): ?Url { if (!$langcode) { - $langcode = $this->languageManager->getDefaultLanguage()->getId(); + $langcode = $this->languageManager + ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT) + ->getId(); } // Default to Etusivu cookie settings page. @@ -48,17 +51,22 @@ public function getCookieSettingsPageUrl(?string $langcode = ''): ?Url { $environment = $this->getActiveEtusivuEnvironment(); if ($environment instanceof Environment) { + try { + $url = $environment->getUrl($langcode); + } + catch (\InvalidArgumentException) { + // Fallback to default language. + $langcode = $this->languageManager->getDefaultLanguage()->getId(); + $url = $environment->getUrl($langcode); + } + $path = match($langcode) { - 'fi' => "evasteasetukset", - 'sv' => "cookie-installningar", - default => "cookie-settings", + 'fi' => 'evasteasetukset', + 'sv' => 'cookie-installningar', + default => 'cookie-settings', }; - $url = vsprintf("%s/%s", [ - $environment->getUrl($langcode), - $path, - ]); - return Url::fromUri($url); + return Url::fromUri(vsprintf("%s/%s", [ $url, $path ])); } } diff --git a/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php b/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php index 0df1e4932..b5e527c57 100644 --- a/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php +++ b/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php @@ -60,6 +60,10 @@ protected function setUp(): void { $this->languageManager->expects($this->any()) ->method('getDefaultLanguage') ->willReturn($this->languages['en']); + $this->languageManager->expects($this->any()) + ->method('getCurrentLanguage') + ->withAnyParameters() + ->willReturn($this->languages['en']); } /** @@ -202,16 +206,9 @@ public function testGetCookieSettingsPage(): void { $this->languages[$langcode]->expects($this->any())->method('getId')->willReturn($return_value); - if ($langcode === 'it') { - $this->expectExceptionMessage('Path not found for "it" language.'); - $url = $this->cookieSettings->getCookieSettingsPageUrl((string) $langcode); - } - else { - // Test that the URL is returned correctly. - $url = $this->cookieSettings->getCookieSettingsPageUrl((string) $langcode); - $this->assertInstanceOf(Url::class, $url); - $this->assertEquals($mock_url, $url->toString()); - } + // Test that the URL is returned correctly. + $url = $this->cookieSettings->getCookieSettingsPageUrl($langcode); + $this->assertInstanceOf(Url::class, $url); } } From 8bc67e7212af7b2c1cd2c1d87b4210793e114a9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Tue, 10 Dec 2024 08:18:23 +0200 Subject: [PATCH 12/14] UHF-10908: Fixed PHPCS. --- modules/hdbt_cookie_banner/src/Services/CookieSettings.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php index f50430ff1..7cdb927b0 100644 --- a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php +++ b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php @@ -66,7 +66,7 @@ public function getCookieSettingsPageUrl(?string $langcode = NULL): ?Url { default => 'cookie-settings', }; - return Url::fromUri(vsprintf("%s/%s", [ $url, $path ])); + return Url::fromUri(vsprintf("%s/%s", [$url, $path])); } } From 983959a15ff7d160258b365ddb59f665bae2ccac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Tue, 10 Dec 2024 08:28:45 +0200 Subject: [PATCH 13/14] UHF-10908: Reverted the changes for functional cookie banner tests until the CI pipeline is updated. --- .../hdbt_cookie_banner_test.info.yml | 4 - .../hdbt_cookie_banner_test.module | 18 -- .../hdbt_cookie_banner_test.routing.yml | 7 - .../src/Controller/TestController.php | 25 --- .../FunctionalJavascript/CookieBannerTest.php | 159 ------------------ 5 files changed, 213 deletions(-) delete mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml delete mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module delete mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.routing.yml delete mode 100644 modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/src/Controller/TestController.php delete mode 100644 modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php diff --git a/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml b/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml deleted file mode 100644 index 7fd1aa085..000000000 --- a/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.info.yml +++ /dev/null @@ -1,4 +0,0 @@ -name: 'HDBT cookie banner test module' -type: module -package: Custom -core_version_requirement: ^10 || ^11 diff --git a/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module b/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module deleted file mode 100644 index 18b44ab4a..000000000 --- a/modules/hdbt_cookie_banner/tests/modules/hdbt_cookie_banner_test/hdbt_cookie_banner_test.module +++ /dev/null @@ -1,18 +0,0 @@ - 'inline_template', - '#template' => '

Test Content

', - ]; - } - -} diff --git a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php b/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php deleted file mode 100644 index 39c449ec5..000000000 --- a/modules/hdbt_cookie_banner/tests/src/FunctionalJavascript/CookieBannerTest.php +++ /dev/null @@ -1,159 +0,0 @@ -getPath('hdbt_cookie_banner'); - $json_file_path = $module_path . '/assets/json/siteSettingsTemplate.json'; - - // Assert the file exists. - $this->assertTrue(file_exists($json_file_path)); - - // Load and decode the JSON. - $json_content = file_get_contents($json_file_path); - $this->assertNotEmpty($json_content, 'Decoded JSON data is not empty.'); - - // Get the public base URL (in a FunctionalJavascript test). - // Construct a URL for the hds-cookie-consent.min.js file. - $cookie_js_url = "/$module_path/assets/js/hds-cookie-consent.min.js"; - - // Change configuration value before the test runs. - $config = $this->config('hdbt_cookie_banner.settings'); - $config - ->set('use_custom_settings', TRUE) - ->set('site_settings', $json_content) - ->set('use_custom_settings', TRUE) - ->set('use_internal_hds_cookie_js', FALSE) - ->set('hds_cookie_js_override', $cookie_js_url) - ->save(); - - \Drupal::service('cache.default')->deleteAll(); - } - - /** - * Tests the cookie banner visibility and interaction. - */ - public function testCookieBanner() { - $this->drupalGet('/test-page'); - $this->assertSession()->pageTextContains('Test Content'); - $this->assertSession()->elementExists('css', '.test-footer'); - - // Get the web driver. - $driver = $this->getSession()->getDriver(); - - // Check if the driver is an instance of DrupalSelenium2Driver. - if ($driver instanceof Selenium2Driver) { - // Get all cookies from the browser. - $cookies = $driver->getWebDriverSession()->getCookie(); - - // Extract only the 'name' keys from all the cookies, as we want to check - // if a specific cookie "change-me" exists. - $cookieNames = array_column($cookies, 'name'); - $this->assertNotContains( - 'change-me', - $cookieNames, - 'The cookie "change-me" was found, but it should not exist.', - ); - } - else { - $this->fail('The driver is not an instance of Selenium2Driver.'); - } - - // Assert that the cookie banner is visible and click the accept button. - $this->assertCookieBannerIsVisible(); - - // Get the new cookies from the browser. - $new_cookies = $driver->getWebDriverSession()->getCookie(); - - // There should be a new cookie called "change-me". - $cookieNames = array_column($new_cookies, 'name'); - $this->assertContains( - 'change-me', - $cookieNames, - 'The cookie "change-me" was not found after clicking the button.', - ); - - // Reload the page and assert that the cookie banner is not visible. - $this->drupalGet('/test-page'); - $this->assertSession()->pageTextContains('Test Content'); - $this->assertCookieBannerNotVisible(); - } - - /** - * Asserts that the cookie banner is visible. - */ - protected function assertCookieBannerIsVisible() { - // Get the Shadow DOM host and button selectors. - $shadowHostSelector = '.hds-cc__target'; - $buttonSelector = '.hds-cc__all-cookies-button'; - - // Verify that the cookie banner is visible and click the accept button. - $js = <<getSession()->executeScript($js); - } - - /** - * Asserts that the cookie banner is not visible. - */ - protected function assertCookieBannerNotVisible() { - // Get the Shadow DOM host and button selectors. - $shadowHostSelector = '.hds-cc__target'; - - // Verify that the cookie banner is not visible. - $js = <<getSession()->executeScript($js); - } - -} From 8b3db161e6b89fe8bd649a9cd45ef74938bafbe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Kalij=C3=A4rvi?= Date: Tue, 10 Dec 2024 08:59:46 +0200 Subject: [PATCH 14/14] UHF-10908: Moved the UnapprovedItemError class outside of the eventlistener. --- .../assets/js/hdbt-cookie-banner.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js index 8471ad61b..2422200f8 100644 --- a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js +++ b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js @@ -1,5 +1,12 @@ 'use strict'; +class UnapprovedItemError extends Error { + constructor(message, name) { + super(message) + this.name = name + } +} + ((Drupal, drupalSettings) => { // Global cookie consent status object. @@ -80,16 +87,9 @@ const name = `Unapproved ${storageType}` const message = `Found: ${sortedKeys.join(', ')}` - class UnapprovedItemError extends Error { - constructor(message) { - super(message) - this.name = name - } - } - // Capture the error with Sentry and send a message with the // unapproved items so that they can be searched in Sentry. - window.Sentry.captureException(new UnapprovedItemError(message), { + window.Sentry.captureException(new UnapprovedItemError(message, name), { level: 'warning', tags: { approvedCategories: acceptedGroups.join(', '),