e-nms_qa_automation/modal_windows/modal_add_user.py

236 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from playwright.sync_api import Page
from components.confirm_component import ConfirmComponent
from components.modal_window_component import ModalWindowComponent
from elements.checkbox_element import Checkbox
from elements.dropdown_list_element import DropdownList
from elements.text_element import Text
from elements.text_input_element import TextInput
from locators.modal_window_locators import ModalWindowLocators
from data.roles_dict import roles_dict
import re
from tools.logger import get_logger
logger = get_logger("ADD_USER_MODAL_WINDOW")
class AddUserModalWindow(ModalWindowComponent):
"""Класс модального окна добавления нового пользователя.
Наследует функциональность базового модального окна и добавляет специфичные элементы:
- Поля ввода данных пользователя
- Чекбоксы
- Выпадающий список ролей
- Кнопки действий
Args:
page (Page): Экземпляр страницы Playwright
"""
def __init__(self, page: Page):
"""Инициализация компонентов модального окна добавления пользователя."""
super().__init__(page)
# Локаторы элементов формы
text_field_locator = ModalWindowLocators.TEXT_FIELD_INPUT_FORM_USER_DATA
roles_field_locator = ModalWindowLocators.ROLES_FIELD_INPUT_FORM_USER_DATA
input_form_locator = ModalWindowLocators.INPUT_FORM_USER_DATA
label_locator = ModalWindowLocators.LABEL_INPUT_FORM_USER_DATA
roles_menu_locator = ModalWindowLocators.ROLES_MENU_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.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 = self.page.locator(input_form_locator).locator("xpath=div[2]").locator(text_field_locator)
type_auth_input = TextInput(page, loc, "type_auth_input")
self.add_content_item("type_auth_input", type_auth_input)
loc = self.page.locator(input_form_locator).locator("xpath=div[3]").locator(text_field_locator)
name_input = TextInput(page, loc, "name_input")
self.add_content_item("name_input", name_input)
role_loc = self.page.locator(input_form_locator).locator("xpath=div[4]").locator(roles_field_locator)
role_input = TextInput(page, role_loc, "role_input")
self.add_content_item("role_input", role_input)
self.add_content_item(
"roles_list",
DropdownList(page, roles_menu_locator, "roles_list")
)
loc = self.page.locator(input_form_locator).locator("xpath=div[5]").locator(text_field_locator)
commentary_input = TextInput(page, loc, "commentary_input")
self.add_content_item("commentary_input", commentary_input)
loc = self.page.locator(input_form_locator).locator("xpath=div[6]").locator(text_field_locator)
email_input = TextInput(page, loc, "email_input")
self.add_content_item("email_input", email_input)
loc = self.page.locator(input_form_locator).locator("xpath=div[7]").locator(text_field_locator)
phone_input = TextInput(page, loc, "phone_input")
self.add_content_item("phone_input", phone_input)
checkbox_2 = Checkbox(
page,
page.get_by_role("checkbox").nth(1),
"push_notification"
)
self.add_content_item("push_notification_checkbox", checkbox_2)
label_2 = Text(
page,
self.page.locator(label_locator).nth(1),
"push_notification_checkbox_label"
)
self.add_content_item("push_notification_checkbox_label", label_2)
# Добавление кнопок действий
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 new_user(self, user_data):
"""Заполняет форму и добавляет нового пользователя.
Args:
user_data (dict): Словарь с данными пользователя. Может содержать ключи:
- active_directory_checked (bool): Состояние чекбокса Active Directory
- type_auth (str): Тип авторизации
- name (str): Имя пользователя
- role (str): Роль пользователя
- commentary (str): Комментарий
- email (str): Email
- phone_number (str): Номер телефона
- push_notification_checked (bool): Состояние чекбокса Push-уведомлений
Raises:
AssertionError: Если подтверждающее окно не отображается
"""
fields = user_data.keys()
if "active_directory_checked" in fields:
checkbox = self.get_content_item("active_directory_checkbox")
if user_data["active_directory_checked"]:
checkbox.check()
else:
checkbox.uncheck()
if "type_auth" in fields:
input_field = self.get_content_item("type_auth_input")
input_field.input_value(user_data["type_auth"])
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 "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 "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 close_window_by_toolbar_button(self):
"""Закрывает модальное окно с помощью кнопки закрытия в тулбаре."""
self.click_toolbar_close_button()
def check_content(self):
"""Проверяет наличие и корректность всех элементов модального окна.
Raises:
AssertionError: Если какой-либо элемент отсутствует или содержит некорректные данные
"""
self.check_by_window_title()
self.check_toolbar_button_presence("close")
self.check_toolbar_button_tooltip("close", "Закрыть")
for name in self.content_items.keys():
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 == "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_presence("Roles list is missing")
for role in roles_dict.values():
roles_list.check_item_with_text(role)
elif name == "roles_list":
continue
else:
item.check_presence(
f"Modal window content item with name '{name}' is missing"
)
self.check_button_presence("add")
self.check_button_presence("close")