From 415924ec98c5e73b7d1600e98e51da10e645a531 Mon Sep 17 00:00:00 2001 From: nsubbot Date: Tue, 3 Feb 2026 10:03:28 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=B2=D0=BA=D0=BB=D0=B0=D0=B4=D0=BA=D0=B8=20'=D0=9D?= =?UTF-8?q?=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B8/=D0=90=D1=83?= =?UTF-8?q?=D1=82=D0=B5=D0=BD=D1=82=D0=B8=D1=84=D0=B8=D0=BA=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- locators/settings_form_locators.py | 2 + pages/keycloak_settings_tab.py | 211 +++++++++++ pages/ldap_settings_tab.py | 333 ++++++++++++++++++ .../test_keycloack_settings_tab.py | 115 ++++++ .../authentication/test_ldap_settings_tab.py | 143 ++++++++ 5 files changed, 804 insertions(+) create mode 100644 pages/keycloak_settings_tab.py create mode 100644 pages/ldap_settings_tab.py create mode 100644 tests/e2e/authentication/test_keycloack_settings_tab.py create mode 100644 tests/e2e/authentication/test_ldap_settings_tab.py diff --git a/locators/settings_form_locators.py b/locators/settings_form_locators.py index 83bd744..eebee6a 100644 --- a/locators/settings_form_locators.py +++ b/locators/settings_form_locators.py @@ -20,6 +20,8 @@ class SettingsFormLocators: SETTINGS_FORM_INPUT_FORM_CONTAINER = "//nav[contains(@class, 'active v-toolbar')]/following-sibling::div" SETTINGS_FORM_SMS_INPUT_FORM_CONTAINER = "//nav[contains(@class, 'active v-toolbar')]/../following-sibling::div" + SETTINGS_FORM_LDAP_INPUT_FORM_CONTAINER = "//nav[contains(@class, 'active v-toolbar')]/../following-sibling::div" + SETTINGS_FORM_KEYCLOAK_INPUT_FORM_CONTAINER = "//nav[contains(@class, 'active v-toolbar')]/../following-sibling::div" SETTINGS_FORM_INPUT_FIELD = "div.v-text-field__slot > input" SETTINGS_FORM_INPUT_VALUE_SUFFIX = ".v-text-field__suffix" diff --git a/pages/keycloak_settings_tab.py b/pages/keycloak_settings_tab.py new file mode 100644 index 0000000..8529e6a --- /dev/null +++ b/pages/keycloak_settings_tab.py @@ -0,0 +1,211 @@ +"""Модуль вкладки настройки Keycloak Аутентификации. + +Содержит класс KeycloakAuthSettings для работы с вкладкой настройки Keycloak Аутентификации. +Позволяет проверять состояние и взаимодействовать с элементами вкладки. +""" + +import re +from playwright.sync_api import Page +from locators.settings_form_locators import SettingsFormLocators +from elements.text_input_element import TextInput +from components.toolbar_component import ToolbarComponent +from components.alert_component import AlertComponent +from components_derived.settings_form_component import SettingsFormComponent +from pages.base_page import BasePage + +class KeycloakAuthSettingsTab(BasePage): + """Класс для работы с вкладкой настройки Keycloak Аутентификации. + + Предоставляет методы для взаимодействия с вкладкой настройки Keycloak Аутентификации. + + Args: + page: Экземпляр страницы Playwright. + """ + + def __init__(self, page: Page) -> None: + """Инициализирует компоненты вкладки настройки Keycloak Аутентификации.""" + + super().__init__(page) + + self.toolbar = ToolbarComponent(page, "KEYCLOAK") + + toolbar_button_edit = self.page.get_by_role("navigation"). \ + locator("//button[@data-testid='KEYCLOAK__btn__edit']") + self.toolbar.add_tooltip_button(toolbar_button_edit, "edit") + + toolbar_button_save = self.page.get_by_role("navigation"). \ + locator("//button[@data-testid='KEYCLOAK__btn__done']") + self.toolbar.add_tooltip_button(toolbar_button_save, "save") + + toolbar_button_cancel = self.page.get_by_role("navigation"). \ + locator("//button[@data-testid='KEYCLOAK__btn__close']") + self.toolbar.add_tooltip_button(toolbar_button_cancel, "cancel") + + # Форма для отображения/редактирования полей настроек KEYCLOAK Аутентификации + self.settings_form = SettingsFormComponent(page) + + container_locator = self.page.locator(SettingsFormLocators.SETTINGS_FORM_KEYCLOAK_INPUT_FORM_CONTAINER) + + self.input_fields_locators = self.settings_form.get_input_fields_locators(container_locator) + + loc = self.input_fields_locators.get("url") + loc_url_input = loc.locator("//input[@data-testid='KEYCLOAK__text-field__url']") + url_setting_input = TextInput(page, loc_url_input, "url_setting_input") + self.settings_form.add_content_item("url_setting_input", url_setting_input) + + loc = self.input_fields_locators.get("url_token") + loc_url_token_input = loc.locator("//input[@data-testid='KEYCLOAK__text-field__url_token']") + url_token_setting_input = TextInput(page, loc_url_token_input, "url_token_setting_input") + self.settings_form.add_content_item("url_token_setting_input", url_token_setting_input) + + loc = self.input_fields_locators.get("clientid") + loc_clientid_input = loc.locator("//input[@data-testid='KEYCLOAK__text-field__clientid']") + clientid_setting_input = TextInput(page, loc_clientid_input, "clientid_setting_input") + self.settings_form.add_content_item("clientid_setting_input", clientid_setting_input) + + loc = self.input_fields_locators.get("clientsecret") + loc_clientsecret_input = loc.locator("//input[@data-testid='KEYCLOAK__text-field__clientsecret']") + clientsecret_setting_input = TextInput(page, loc_clientsecret_input, "clientsecret_setting_input") + self.settings_form.add_content_item("clientsecret_setting_input", clientsecret_setting_input) + + loc = self.input_fields_locators.get("redirect_uri") + loc_redirect_uri_input = loc.locator("//input[@data-testid='KEYCLOAK__text-field__redirect_uri']") + redirect_uri_setting_input = TextInput(page, loc_redirect_uri_input, "redirect_uri_setting_input") + self.settings_form.add_content_item("redirect_uri_setting_input", redirect_uri_setting_input) + + self.alert = AlertComponent(page) + + # Действия: + def click_cancel_button(self) -> None: + """Нажатие кнопки 'Отменить' на тулбаре.""" + + self.toolbar.check_button_visibility("cancel") + self.toolbar.get_button_by_name("cancel").click() + + def click_edit_button(self) -> None: + """Нажатие кнопки 'Редактировать' на тулбаре.""" + + self.toolbar.check_button_visibility("edit") + self.toolbar.get_button_by_name("edit").click() + + def click_save_button(self) -> None: + """Нажатие кнопки 'Сохранить' на тулбаре.""" + + self.toolbar.check_button_visibility("save") + self.toolbar.get_button_by_name("save").click() + + def get_current_setting_values(self) -> dict: + """Возвращает текущее значение полей настроек. + + Returns: + str : Текущее значение полей настроек. + """ + + values = {} + field = self.settings_form.get_content_item("url_setting_input") + values.update({"url": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("url_token_setting_input") + values.update({"url_token": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("clientid_setting_input") + values.update({"clientid": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("clientsecret_setting_input") + values.update({"clientsecret": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("redirect_uri_setting_input") + values.update({"redirect_uri": field.get_input_value().strip()}) + + return values + + def input_url(self, text: str) -> None: + """Заполнение поля 'URL'.""" + + message_input = self.settings_form.get_content_item("url_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_url_token(self, text: str) -> None: + """Заполнение поля 'URL_TOKEN'.""" + + message_input = self.settings_form.get_content_item("url_token_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_clientid(self, text: str) -> None: + """Заполнение поля 'CLIENTID'.""" + + message_input = self.settings_form.get_content_item("clientid_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_clientsecret(self, text: str) -> None: + """Заполнение поля 'CLIENTSECRET'.""" + + message_input = self.settings_form.get_content_item("clientsecret_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_redirect_uri(self, text: str) -> None: + """Заполнение поля 'REDIRECT_URI'.""" + + message_input = self.settings_form.get_content_item("redirect_uri_setting_input") + message_input.clear() + message_input.input_value(text) + + # Проверки: + def check_content(self): + """Проверяет наличие и корректность всех элементов страницы.""" + + expected_input_field_names = ["url", "url_token", "clientid", + "clientsecret", "redirect_uri"] + + self.should_be_toolbar() + + actual_input_field_names = self.input_fields_locators.keys() + + for name in expected_input_field_names: + assert name in actual_input_field_names, \ + f"Expected input field name {name} is missing in actual input field names" + + for name in self.settings_form.content_items.keys(): + item = self.settings_form.get_content_item(name) + item.check_visibility( + f"KEYCLOAK settings input form item with name '{name}' is missing" + ) + + def should_be_toolbar(self) -> None: + """Проверяет наличие тулбара страницы, наличие и функциональность кнопок тулбара. + + Raises: + AssertionError: Если тулбар или кнопка тулбара отсутствуют. + """ + loc = self.page.get_by_role("navigation").filter( + has_text=re.compile("KEYCLOAK")).locator("div").nth(1) + self.toolbar.check_toolbar_presence_by_locator(loc, "Toolbar with title 'KEYCLOAK' is missing") + + self.toolbar.check_button_visibility("edit") + self.toolbar.check_button_tooltip("edit", "Редактировать") + + self.toolbar.get_button_by_name("edit").click() + self.toolbar.check_button_visibility("save") + self.toolbar.check_button_visibility("cancel") + self.toolbar.check_button_tooltip("save", "Сохранить") + self.toolbar.check_button_tooltip("cancel", "Отменить") + + self.toolbar.get_button_by_name("cancel").click() + self.toolbar.check_button_visibility("edit") + + def should_be_success_alert(self) -> None: + """Проверяет наличие сообщения об успешном сохранении заданных параметров. + + Raises: + AssertionError: Если тулбар отсутствует. + """ + + alert_type = self.alert.get_alert_type() + assert alert_type == "success", f"Expected success alert, but got {alert_type} alert" + + self.alert.check_alert_presence('\nПараметры успешно\n обновлены\n') + self.alert.check_alert_absence('\nПараметры успешно\n обновлены\n') diff --git a/pages/ldap_settings_tab.py b/pages/ldap_settings_tab.py new file mode 100644 index 0000000..e048c29 --- /dev/null +++ b/pages/ldap_settings_tab.py @@ -0,0 +1,333 @@ +"""Модуль вкладки настройки LDAP Аутентификации. + +Содержит класс LDAPAuthSettings для работы с вкладкой настройки LDAP Аутентификации. +Позволяет проверять состояние и взаимодействовать с элементами вкладки. +""" + +import re +from playwright.sync_api import Page +from locators.text_input_locators import TextInputLocators +from locators.settings_form_locators import SettingsFormLocators +from elements.text_input_element import TextInput +from elements.text_element import Text +from elements.icon_element import Icon +from elements.checkbox_element import Checkbox +from components.toolbar_component import ToolbarComponent +from components.alert_component import AlertComponent +from components_derived.settings_form_component import SettingsFormComponent +from pages.base_page import BasePage + +class LDAPAuthSettingsTab(BasePage): + """Класс для работы с вкладкой настройки LDAP Аутентификации. + + Предоставляет методы для взаимодействия с вкладкой настройки LDAP Аутентификации. + + Args: + page: Экземпляр страницы Playwright. + """ + + def __init__(self, page: Page) -> None: + """Инициализирует компоненты вкладки настройки LDAP Аутентификации.""" + + super().__init__(page) + + self.toolbar = ToolbarComponent(page, "LDAP") + + toolbar_button_edit = self.page.get_by_role("navigation").locator("//button[@data-testid='LDAP__btn__edit']") + self.toolbar.add_tooltip_button(toolbar_button_edit, "edit") + + toolbar_button_save = self.page.get_by_role("navigation").locator("//button[@data-testid='LDAP__btn__submit']") + self.toolbar.add_tooltip_button(toolbar_button_save, "save") + + toolbar_button_cancel = self.page.get_by_role("navigation"). \ + locator("//button[@data-testid='LDAP__btn__cancelEdit']") + self.toolbar.add_tooltip_button(toolbar_button_cancel, "cancel") + + # Форма для отображения/редактирования полей настроек LDAP Аутентификации + self.settings_form = SettingsFormComponent(page) + + container_locator = self.page.locator(SettingsFormLocators.SETTINGS_FORM_LDAP_INPUT_FORM_CONTAINER) + + # Метка "tls" + label_tls_locator = container_locator.get_by_text("tls") + label_tls = Text( + page, + label_tls_locator, + "tls_checkbox_label" + ) + self.settings_form.add_content_item("tls_checkbox_label", label_tls) + + # Чекбокс "tls" + checkbox_tls = Checkbox( + page, + container_locator.locator("//input[@data-testid='LDAP__checkbox__tls']"), + "tls_checkbox" + ) + self.settings_form.add_content_item("tls_checkbox", checkbox_tls) + + self.input_fields_locators = self.settings_form.get_input_fields_locators(container_locator) + + loc = self.input_fields_locators.get("ip") + loc_ip_input = loc.locator("//input[@data-testid='LDAP__text-field__ip']") + ip_setting_input = TextInput(page, loc_ip_input, "ip_setting_input") + self.settings_form.add_content_item("ip_setting_input", ip_setting_input) + + loc = self.input_fields_locators.get("Порт") + loc_port_input = loc.locator("//input[@data-testid='LDAP__text-field__port']") + port_setting_input = TextInput(page, loc_port_input, "port_setting_input") + self.settings_form.add_content_item("port_setting_input", port_setting_input) + + loc = self.input_fields_locators.get("Имя пользователя") + loc_user_input = loc.locator("//input[@data-testid='LDAP__text-field__login']") + user_setting_input = TextInput(page, loc_user_input, "user_setting_input") + self.settings_form.add_content_item("user_setting_input", user_setting_input) + + loc = self.input_fields_locators.get("Пароль") + loc_password_input = loc.locator("//input[@data-testid='LDAP__text-field__password']") + password_setting_input = TextInput(page, loc_password_input, "password_setting_input") + self.settings_form.add_content_item("password_setting_input", password_setting_input) + + loc = self.input_fields_locators.get("Домен") + loc_domain_input = loc.locator("//input[@data-testid='LDAP__text-field__domain']") + domain_setting_input = TextInput(page, loc_domain_input, "domain_setting_input") + self.settings_form.add_content_item("domain_setting_input", domain_setting_input) + + loc = self.input_fields_locators.get("DN каталог пользователей") + loc_dn_catalog_input = loc.locator("//input[@data-testid='LDAP__text-field__base_dn']") + dn_catalog_setting_input = TextInput(page, loc_dn_catalog_input, "dn_catalog_setting_input") + self.settings_form.add_content_item("dn_catalog_setting_input", dn_catalog_setting_input) + + loc = self.input_fields_locators.get("Атрибут авторизации") + loc_login_attr_input = loc.locator("//input[@data-testid='LDAP__text-field__login_attribute']") + login_attr_setting_input = TextInput(page, loc_login_attr_input, "login_attr_setting_input") + self.settings_form.add_content_item("login_attr_setting_input", login_attr_setting_input) + + loc = self.input_fields_locators.get("Атрибут email") + loc_email_attr_input = loc.locator("//input[@data-testid='LDAP__text-field__email_attribute']") + email_attr_setting_input = TextInput(page, loc_email_attr_input, "email_attr_setting_input") + self.settings_form.add_content_item("email_attr_setting_input", email_attr_setting_input) + + loc = self.input_fields_locators.get("Атрибут sms") + loc_sms_attr_input = loc.locator("//input[@data-testid='LDAP__text-field__sms_attribute']") + sms_attr_setting_input = TextInput(page, loc_sms_attr_input, "sms_attr_setting_input") + self.settings_form.add_content_item("sms_attr_setting_input", sms_attr_setting_input) + + icon_locator = loc_password_input.locator("../..").locator(TextInputLocators.ICON_PASSWORD_HIDING) + password_hidden_icon = Icon(page, icon_locator, + "password hidden icon") + self.settings_form.add_content_item("password_hidden_icon", password_hidden_icon) + + self.alert = AlertComponent(page) + + # Действия: + def click_cancel_button(self) -> None: + """Нажатие кнопки 'Отменить' на тулбаре.""" + + self.toolbar.check_button_visibility("cancel") + self.toolbar.get_button_by_name("cancel").click() + + def click_edit_button(self) -> None: + """Нажатие кнопки 'Редактировать' на тулбаре.""" + + self.toolbar.check_button_visibility("edit") + self.toolbar.get_button_by_name("edit").click() + + def click_save_button(self) -> None: + """Нажатие кнопки 'Сохранить' на тулбаре.""" + + self.toolbar.check_button_visibility("save") + self.toolbar.get_button_by_name("save").click() + + def click_password_hidden_icon(self) -> None: + """Нажатие на иконку скрытия пароля.""" + + self.settings_form.get_content_item("password_hidden_icon").click() + + def check_checkbox_tls(self): + """Включает чек-бокс tls.""" + + self.settings_form.get_content_item("tls_checkbox").check(force=True) + + def uncheck_checkbox_tls(self): + """Выключает чек-бокс tls.""" + + self.settings_form.get_content_item("tls_checkbox").uncheck(force=True) + + def get_current_setting_values(self) -> dict: + """Возвращает текущее значение полей настроек. + + Returns: + str : Текущее значение полей настроек. + """ + + values = {} + tls_checkbox = self.settings_form.get_content_item("tls_checkbox") + values.update({"tls checked": tls_checkbox.is_checked()}) + + field = self.settings_form.get_content_item("ip_setting_input") + values.update({"ip": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("port_setting_input") + values.update({"Порт": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("user_setting_input") + values.update({"Имя пользователя": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("password_setting_input") + values.update({"Пароль": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("domain_setting_input") + values.update({"Домен": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("dn_catalog_setting_input") + values.update({"DN каталог пользователей": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("login_attr_setting_input") + values.update({"Атрибут авторизации": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("email_attr_setting_input") + values.update({"Атрибут email": field.get_input_value().strip()}) + + field = self.settings_form.get_content_item("sms_attr_setting_input") + values.update({"Атрибут sms": field.get_input_value().strip()}) + + return values + + def get_password_setting_value(self) -> str: + """Возвращает текущее значение поля настроек 'Пароль'. + + Returns: + str : Текущее отображение значения поля настроек 'Пароль'. + """ + + input_field = self.settings_form.get_content_item("password_setting_input") + is_hidden_state = self.settings_form.get_content_item("password_hidden_icon").is_password_hidden() + + password_value = input_field.get_input_value().strip() + if is_hidden_state: + password_value = "." * len(password_value) + return password_value + + def input_ip(self, text: str) -> None: + """Заполнение поля 'IP'.""" + + message_input = self.settings_form.get_content_item("ip_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_port(self, text: str) -> None: + """Заполнение поля 'Порт'.""" + + message_input = self.settings_form.get_content_item("port_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_user(self, text: str) -> None: + """Заполнение поля 'Имя пользователя'.""" + + message_input = self.settings_form.get_content_item("user_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_password(self, text: str) -> None: + """Заполнение поля 'Пароль'.""" + + message_input = self.settings_form.get_content_item("password_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_domain(self, text: str) -> None: + """Заполнение поля 'Домен'.""" + + message_input = self.settings_form.get_content_item("domain_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_dn_catalog(self, text: str) -> None: + """Заполнение поля 'DN каталог пользователей'.""" + + message_input = self.settings_form.get_content_item("dn_catalog_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_login_attribute(self, text: str) -> None: + """Заполнение поля 'Атрибут авторизации'.""" + + message_input = self.settings_form.get_content_item("login_attr_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_email_attribute(self, text: str) -> None: + """Заполнение поля 'Атрибут email'.""" + + message_input = self.settings_form.get_content_item("email_attr_setting_input") + message_input.clear() + message_input.input_value(text) + + def input_sms_attribute(self, text: str) -> None: + """Заполнение поля 'Атрибут sms'.""" + + message_input = self.settings_form.get_content_item("sms_attr_setting_input") + message_input.clear() + message_input.input_value(text) + + # Проверки: + def check_content(self): + """Проверяет наличие и корректность всех элементов страницы.""" + + expected_input_field_names = ["ip", "Порт", "Имя пользователя", "Пароль", + "Домен", "DN каталог пользователей", + "Атрибут авторизации", "Атрибут email", "Атрибут sms"] + + self.should_be_toolbar() + + actual_input_field_names = self.input_fields_locators.keys() + + for name in expected_input_field_names: + assert name in actual_input_field_names, \ + f"Expected input field name {name} is missing in actual input field names" + + for name in self.settings_form.content_items.keys(): + item = self.settings_form.get_content_item(name) + item.check_visibility( + f"LDAP settings input form item with name '{name}' is missing" + ) + + if name == "password_hidden_icon": + is_hidden_state = item.is_password_hidden() + assert is_hidden_state, "Password hidden icon should be in hidden state" + + def should_be_toolbar(self) -> None: + """Проверяет наличие тулбара страницы, наличие и функциональность кнопок тулбара. + + Raises: + AssertionError: Если тулбар или кнопка тулбара отсутствуют. + """ + loc = self.page.get_by_role("navigation").filter( + has_text=re.compile("LDAP")).locator("div").nth(1) + self.toolbar.check_toolbar_presence_by_locator(loc, "Toolbar with title 'LDAP' is missing") + + self.toolbar.check_button_visibility("edit") + self.toolbar.check_button_tooltip("edit", "Редактировать") + + self.toolbar.get_button_by_name("edit").click() + self.toolbar.check_button_visibility("save") + self.toolbar.check_button_visibility("cancel") + self.toolbar.check_button_tooltip("save", "Сохранить") + self.toolbar.check_button_tooltip("cancel", "Отменить") + + self.toolbar.get_button_by_name("cancel").click() + self.toolbar.check_button_visibility("edit") + + def should_be_success_alert(self) -> None: + """Проверяет наличие сообщения об успешном сохранении заданных параметров. + + Raises: + AssertionError: Если тулбар отсутствует. + """ + + alert_type = self.alert.get_alert_type() + assert alert_type == "success", f"Expected success alert, but got {alert_type} alert" + + self.alert.check_alert_presence('\nПараметры успешно\n обновлены\n') + self.alert.check_alert_absence('\nПараметры успешно\n обновлены\n') diff --git a/tests/e2e/authentication/test_keycloack_settings_tab.py b/tests/e2e/authentication/test_keycloack_settings_tab.py new file mode 100644 index 0000000..dcc86f7 --- /dev/null +++ b/tests/e2e/authentication/test_keycloack_settings_tab.py @@ -0,0 +1,115 @@ +"""Модуль тестов вкладки настройки Keycloak Аутентификации. + +Содержит тесты для проверки корректности отображения +и функциональности элементов страницы настройки Keycloak Аутентификации. +""" + +import pytest +from playwright.sync_api import Page +from pages.login_page import LoginPage +from pages.main_page import MainPage +from pages.keycloak_settings_tab import KeycloakAuthSettingsTab + + +# @pytest.mark.smoke +class TestKeycloakAuthSettingsTab: + """Набор тестов для вкладки настройки Keycloak Аутентификации. + + Проверяет корректность отображения и функциональность элементов вкладки настройки LDAP Аутентификации. + """ + + @pytest.fixture(scope="function", autouse=True) + def setup(self, browser: Page) -> None: + """Фикстура для подготовки тестового окружения. + + Выполняет: + 1. Авторизацию в системе + 2. Переход на вкладку настройки Keycloak Аутентификации через панель навигации + """ + # Авторизация в системе + login_page = LoginPage(browser) + login_page.do_login() + + # Инициализация главной страницы + main_page = MainPage(browser) + + # Проверка и взаимодействие с элементами навигации + main_page.should_be_navigation_panel() + main_page.click_main_navigation_panel_item("Настройки") + main_page.click_subpanel_item("Аутентификация") + main_page.click_subpanel_item("KEYCLOAK") + + # @pytest.mark.develop + def test_keycloak_auth_settings_tab_content(self, browser: Page) -> None: + """Тест содержимого вкладки настройки Keycloak Аутентификации. + + Проверяет: + Наличие и корректность элементов интерфейса + """ + + current_settings = {} + default_settings = {} + + # Инициализация вкладки + keycloak_auth_settings_tab = KeycloakAuthSettingsTab(browser) + + # запрос текущих установок + cur_settings_response = keycloak_auth_settings_tab.send_get_api_request("e-cmdb/api/keycloack") + if cur_settings_response.status == 200: + response_body = keycloak_auth_settings_tab.get_response_body(cur_settings_response) + + if response_body: + current_settings = response_body[0].copy() + + # запрос дефолтных значений + default_settings_response = keycloak_auth_settings_tab.send_get_api_request("e-cmdb/api/keycloack/meta") + if default_settings_response.status == 200: + response_body = keycloak_auth_settings_tab.get_response_body(default_settings_response) + + if response_body: + default_settings = response_body["fields"].copy() + + # Проверка элементов интерфейса + keycloak_auth_settings_tab.check_content() + + # Получение и проверка отображаемых входных значений формы настроек + settings = keycloak_auth_settings_tab.get_current_setting_values() + + value = settings["url"] + expected = current_settings["url"] + if expected is None: + expected = self._get_default_value("url", default_settings) + assert value == expected, f"Actual value {value} is not equal expected {expected} for field 'URL'" + + value = settings["url_token"] + expected = current_settings["url_token"] + if expected is None: + expected = self._get_default_value("url_token", default_settings) + assert value == expected, f"Actual value {value} is not equal expected {expected} for field 'URL_TOKEN'" + + value = settings["clientid"] + expected = current_settings["clientid"] + if expected is None: + expected = self._get_default_value("clientid", default_settings) + assert value == expected, f"Actual value {value} is not equal expected {expected} for field 'CLIENTID'" + + value = settings["clientsecret"] + expected = current_settings["clientsecret"] + if expected is None: + expected = self._get_default_value("clientsecret", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'CLIENTSECRET'" + + value = settings["redirect_uri"] + expected = current_settings["redirect_uri"] + if expected is None: + expected = self._get_default_value("redirect_uri", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'REDIRECT_URI'" + + + def _get_default_value(self, setting_name: str, default_settings: dict) -> str| None: + for setting in default_settings: + if setting["name"] == setting_name: + return setting["default"] + return None diff --git a/tests/e2e/authentication/test_ldap_settings_tab.py b/tests/e2e/authentication/test_ldap_settings_tab.py new file mode 100644 index 0000000..532c1cf --- /dev/null +++ b/tests/e2e/authentication/test_ldap_settings_tab.py @@ -0,0 +1,143 @@ +"""Модуль тестов вкладки настройки LDAP Аутентификации. + +Содержит тесты для проверки корректности отображения +и функциональности элементов страницы настройки LDAP Аутентификации. +""" + +import pytest +from playwright.sync_api import Page +from pages.login_page import LoginPage +from pages.main_page import MainPage +from pages.ldap_settings_tab import LDAPAuthSettingsTab + + +# @pytest.mark.smoke +class TestLDAPAuthSettingsTab: + """Набор тестов для вкладки настройки LDAP Аутентификации. + + Проверяет корректность отображения и функциональность элементов вкладки настройки LDAP Аутентификации. + """ + + @pytest.fixture(scope="function", autouse=True) + def setup(self, browser: Page) -> None: + """Фикстура для подготовки тестового окружения. + + Выполняет: + 1. Авторизацию в системе + 2. Переход на вкладку настройки LDAP Аутентификации через панель навигации + """ + # Авторизация в системе + login_page = LoginPage(browser) + login_page.do_login() + + # Инициализация главной страницы + main_page = MainPage(browser) + + # Проверка и взаимодействие с элементами навигации + main_page.should_be_navigation_panel() + main_page.click_main_navigation_panel_item("Настройки") + main_page.click_subpanel_item("Аутентификация") + main_page.click_subpanel_item("LDAP") + + # @pytest.mark.develop + def test_ldap_auth_settings_tab_content(self, browser: Page) -> None: + """Тест содержимого вкладки настройки LDAP Аутентификации. + + Проверяет: + Наличие и корректность элементов интерфейса + """ + + current_settings = {} + default_settings = {} + + # Инициализация вкладки + ldap_auth_settings_tab = LDAPAuthSettingsTab(browser) + + # запрос текущих установок + cur_settings_response = ldap_auth_settings_tab.send_get_api_request("e-cmdb/api/ldap") + if cur_settings_response.status == 200: + response_body = ldap_auth_settings_tab.get_response_body(cur_settings_response) + + if response_body: + current_settings = response_body[0].copy() + + # запрос дефолтных значений + default_settings_response = ldap_auth_settings_tab.send_get_api_request("e-cmdb/api/ldap/meta") + if default_settings_response.status == 200: + response_body = ldap_auth_settings_tab.get_response_body(default_settings_response) + + if response_body: + default_settings = response_body["fields"].copy() + + # Проверка элементов интерфейса + ldap_auth_settings_tab.check_content() + + # Получение и проверка отображаемых входных значений формы настроек + settings = ldap_auth_settings_tab.get_current_setting_values() + + value = settings["ip"] + expected = current_settings["ip"] + if expected is None: + expected = self._get_default_value("ip", default_settings) + assert value == expected, f"Actual value {value} is not equal expected {expected} for field 'IP'" + + value = settings["Порт"] + expected = current_settings["port"] + if expected is None: + expected = self._get_default_value("port", default_settings) + assert value == expected, f"Actual value {value} is not equal expected {expected} for field 'Порт'" + + value = settings["Имя пользователя"] + expected = current_settings["login"] + if expected is None: + expected = self._get_default_value("login", default_settings) + assert value == expected, f"Actual value {value} is not equal expected {expected} for field 'Имя пользователя'" + + value = settings["Пароль"] + expected = current_settings["password"] + if expected is None: + expected = self._get_default_value("password", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'Пароль'" + + value = settings["Домен"] + expected = current_settings["domain"] + if expected is None: + expected = self._get_default_value("domain", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'Домен'" + + value = settings["DN каталог пользователей"] + expected = current_settings["base_dn"] + if expected is None: + expected = self._get_default_value("base_dn", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'DN каталог пользователей'" + + value = settings["Атрибут авторизации"] + expected = current_settings["login_attribute"] + if expected is None: + expected = self._get_default_value("login_attribute", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'Атрибут авторизации'" + + value = settings["Атрибут email"] + expected = current_settings["email_attribute"] + if expected is None: + expected = self._get_default_value("email_attribute", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'Атрибут email'" + + value = settings["Атрибут sms"] + expected = current_settings["sms_attribute"] + if expected is None: + expected = self._get_default_value("sms_attribute", default_settings) + assert value == expected, \ + f"Actual value {value} is not equal expected {expected} for field 'Атрибут sms'" + + + def _get_default_value(self, setting_name: str, default_settings: dict) -> str| None: + for setting in default_settings: + if setting["name"] == setting_name: + return setting["default"] + return None