"""Модуль modal_add_local_user содержит класс для работы
с модальным окном добавления локального пользователя.
Класс AddLocalUserModalWindow наследует базовый функционал ModalWindowComponent
и реализует специфичные методы для работы с формами добавления пользователей.
"""
import re
from playwright.sync_api import Page
from tools.logger import get_logger
from locators.modal_window_locators import ModalWindowLocators
from elements.text_input_element import TextInput
from elements.text_element import Text
from elements.checkbox_element import Checkbox
from data.roles_dict import roles_dict
from components.modal_window_component import ModalWindowComponent
from components.dropdown_list_component import DropdownList
from components.confirm_component import ConfirmComponent
logger = get_logger("ADD_LOCAL_USER_MODAL_WINDOW")
[документация]
class AddLocalUserModalWindow(ModalWindowComponent):
"""Модальное окно добавления нового пользователя.
Наследует ModalWindowComponent и добавляет элементы формы:
- Поля ввода (имя, пароль, email и др.)
- Чекбоксы (Active Directory, Блокировка, Push-уведомления)
- Выпадающий список ролей
- Кнопки действий
"""
[документация]
def __init__(self, page: Page):
"""Инициализирует элементы формы добавления пользователя."""
super().__init__(page)
# Локаторы элементов формы
text_field_locator = ModalWindowLocators.TEXT_FIELD_INPUT_FORM_USER_DATA
input_form_locator = ModalWindowLocators.INPUT_FORM_USER_DATA
label_locator = ModalWindowLocators.LABEL_INPUT_FORM_USER_DATA
# Настройка заголовка и кнопки закрытия тулбара
self.window_title = "Добавить нового пользователя"
locator_button_toolbar_close = (
self.page.get_by_role("navigation")
.filter(has_text=re.compile(self.window_title))
.get_by_role("button")
)
self.add_toolbar_title(self.window_title)
self.add_toolbar_button(locator_button_toolbar_close, "close")
# Добавление элементов формы по порядку расположения в окне
checkbox_1 = Checkbox(
page,
self.page.locator(input_form_locator).get_by_role("checkbox").nth(0),
"active_directory"
)
self.add_content_item("active_directory_checkbox", checkbox_1)
label_1 = Text(
page,
self.page.locator(label_locator).nth(0),
"active_directory_checkbox_label"
)
self.add_content_item("active_directory_checkbox_label", label_1)
# Поле Имя
loc = f"{input_form_locator}/div[2]/{text_field_locator}"
name_input = TextInput(page, self.page.locator(loc), "name_input")
self.add_content_item("name_input", name_input)
# Чекбокс "Блокировка" - индекс 1
checkbox_2 = Checkbox(
page,
self.page.locator(input_form_locator).get_by_role("checkbox").nth(1),
"blocking"
)
self.add_content_item("blocking_checkbox", checkbox_2)
# Метка "Блокировка" - индекс 1
label_2 = Text(
page,
self.page.locator(label_locator).nth(1),
"blocking_checkbox_label"
)
self.add_content_item("blocking_checkbox_label", label_2)
# Поле Роль
role_loc = self.page.locator(input_form_locator).get_by_role("combobox").nth(0)
role_input = TextInput(page, role_loc, "role_input")
self.add_content_item("role_input", role_input)
self.add_content_item("roles_list", DropdownList(page))
# Поле Пароль
loc = f"{input_form_locator}/div[5]/{text_field_locator}"
password_input = TextInput(page, self.page.locator(loc), "password_input")
self.add_content_item("password_input", password_input)
# Поле Комментарий
loc = f"{input_form_locator}/div[6]/{text_field_locator}"
commentary_input = TextInput(page, self.page.locator(loc), "commentary_input")
self.add_content_item("commentary_input", commentary_input)
# Поле E-mail
loc = f"{input_form_locator}/div[7]/{text_field_locator}"
email_input = TextInput(page, self.page.locator(loc), "email_input")
self.add_content_item("email_input", email_input)
# Поле Номер для СМС
loc = f"{input_form_locator}/div[8]/{text_field_locator}"
phone_input = TextInput(page, self.page.locator(loc), "phone_input")
self.add_content_item("phone_input", phone_input)
# Чекбокс "Подписка на Push-уведомления" - индекс 2
checkbox_3 = Checkbox(
page,
self.page.locator(ModalWindowLocators.INPUT_FORM_USER_DATA)
.get_by_role("checkbox").nth(2),
"push_notification"
)
self.add_content_item("push_notification_checkbox", checkbox_3)
# Метка "Подписка на Push-уведомления" - индекс 2
label_3 = Text(
page,
self.page.locator(label_locator).nth(2),
"push_notification_checkbox_label"
)
self.add_content_item("push_notification_checkbox_label", label_3)
# Добавление кнопок действий
locator_button_add = self.page.get_by_role("button", name="Добавить")
self.add_button(locator_button_add, "add")
locator_button_close = self.page.get_by_role("button", name="Закрыть")
self.add_button(locator_button_close, "close")
# Добавление компонента подтверждения/отмены заведения пользователя
self.new_user_confirm = ConfirmComponent(page, " Отмена ", " Добавить ")
# Действия:
[документация]
def check_active_directory_checkbox(self):
"""Включает чек-бокс Active Directory."""
self.get_content_item("active_directory_checkbox").check(force=True)
[документация]
def uncheck_active_directory_checkbox(self):
"""Выключает чек-бокс Active Directory."""
self.get_content_item("active_directory_checkbox").uncheck(force=True)
[документация]
def check_blocking_checkbox(self):
"""Включает чек-бокс Блокировка."""
self.get_content_item("blocking_checkbox").check(force=True)
[документация]
def uncheck_blocking_checkbox(self):
"""Выключает чек-бокс Блокировка."""
self.get_content_item("blocking_checkbox").uncheck(force=True)
[документация]
def check_push_notification_checkbox(self):
"""Включает чек-бокс Push-уведомления."""
self.get_content_item("push_notification_checkbox").check(force=True)
[документация]
def uncheck_push_notification_checkbox(self):
"""Выключает чек-бокс Push-уведомления."""
self.get_content_item("push_notification_checkbox").uncheck(force=True)
[документация]
def new_user(self, user_data):
"""Заполняет форму и добавляет нового пользователя.
Args:
user_data (dict): Данные пользователя (имя, роль, пароль и др.)
"""
fields = user_data.keys()
if "name" in fields:
input_field = self.get_content_item("name_input")
input_field.input_value(user_data["name"])
if "role" in fields:
role_field = self.get_content_item("role_input")
role_field.click()
roles_list = self.get_content_item("roles_list")
roles_list.check_item_with_text(user_data["role"])
roles_list.click_item_with_text(user_data["role"])
if "password" in fields:
input_field = self.get_content_item("password_input")
input_field.input_value(user_data["password"])
if "commentary" in fields:
input_field = self.get_content_item("commentary_input")
input_field.input_value(user_data["commentary"])
if "email" in fields:
input_field = self.get_content_item("email_input")
input_field.input_value(user_data["email"])
if "phone_number" in fields:
input_field = self.get_content_item("phone_input")
input_field.input_value(user_data["phone_number"])
if "blocking_checked" in fields:
checkbox = self.get_content_item("blocking_checkbox")
if user_data["blocking_checked"]:
checkbox.check()
else:
checkbox.uncheck()
if "push_notification_checked" in fields:
checkbox = self.get_content_item("push_notification_checkbox")
if user_data["push_notification_checked"]:
checkbox.check()
else:
checkbox.uncheck()
# Отправка формы
add_button = self.get_button_by_name("add")
add_button.click()
# Подтверждение действия
title = "Добавить нового пользователя"
self.new_user_confirm.check_title(
title,
f"Confirmation dialog window with title '{title}' is missing"
)
self.new_user_confirm.click_allow_button()
[документация]
def close_window(self):
"""Закрывает модальное окно через кнопку 'Закрыть'."""
close_button = self.get_button_by_name("close")
close_button.click()
# Проверки:
[документация]
def check_content(self):
"""Проверяет наличие и корректность всех элементов формы."""
menu_locator = self.page.locator(ModalWindowLocators.MENU_INPUT_FORM_USER_DATA)
self.check_by_window_title()
is_checked = self.get_content_item("active_directory_checkbox").is_checked()
if is_checked:
assert False, (
"The checkbox 'Active Directory' should not be checked for "
"the add local user window"
)
self.check_toolbar_button_visibility("close")
self.check_toolbar_button_tooltip("close", "Закрыть")
input_fields = ["name_input", "password_input",
"commentary_input", "email_input", "phone_input"]
for name in self.content_items:
item = self.get_content_item(name)
if name == "active_directory_checkbox_label":
item.check_have_text(
"Active Directory",
"Label 'Active Directory' is missing"
)
elif name == "blocking_checkbox_label":
item.check_have_text(
"Блокировка",
"Label 'Блокировка' is missing"
)
elif name == "push_notification_checkbox_label":
item.check_have_text(
"Подписка на Push-уведомления",
"Label 'Подписка на Push-уведомления' is missing"
)
elif name == "role_input":
item.click()
roles_list = self.get_content_item("roles_list")
roles_list.check_visibility(menu_locator, "Roles list is missing")
is_scrollable_vertically = roles_list.check_vertical_scrolling(menu_locator)
assert not is_scrollable_vertically, (
"Roles list should not be scrollable_vertically"
)
for role in roles_dict.values():
# временно, пока есть несоответствие со списком ролей в вкладке Сессии
if role == "Пользователь":
continue
roles_list.check_item_with_text(role)
elif name in input_fields:
item.check_editable_input(
f"Input field with name '{name}' should be editable"
)
elif name == "roles_list":
continue
else:
print(f"check item: {name}")
print(item)
item.check_visibility(
f"Modal window content item with name '{name}' is missing"
)
# Дополнительная проверка состояния чекбоксов
blocking_checkbox = self.get_content_item("blocking_checkbox")
is_blocking_checked = blocking_checkbox.is_checked()
assert not is_blocking_checked, (
"Checkbox 'Блокировка' should not be checked by default"
)
push_checkbox = self.get_content_item("push_notification_checkbox")
is_push_checked = push_checkbox.is_checked()
assert not is_push_checked, (
"Checkbox 'Подписка на Push-уведомления' should not be checked by default"
)
self.check_button_visibility("add")
self.check_button_visibility("close")