Актуализация функционала пользователей, добавлена проверка чекбокса 'Блокировка'

pull/1/head
Radislav 2025-10-08 14:47:42 +03:00
parent fb5d9ed899
commit 1572c37d5f
6 changed files with 252 additions and 109 deletions

View File

@ -1,4 +1,5 @@
"""Модуль modal_add_local_user содержит класс для работы с модальным окном добавления локального пользователя. """Модуль modal_add_local_user содержит класс для работы
с модальным окном добавления локального пользователя.
Класс AddLocalUserModalWindow наследует базовый функционал ModalWindowComponent Класс AddLocalUserModalWindow наследует базовый функционал ModalWindowComponent
и реализует специфичные методы для работы с формами добавления пользователей. и реализует специфичные методы для работы с формами добавления пользователей.
@ -25,7 +26,7 @@ class AddLocalUserModalWindow(ModalWindowComponent):
Наследует ModalWindowComponent и добавляет элементы формы: Наследует ModalWindowComponent и добавляет элементы формы:
- Поля ввода (имя, пароль, email и др.) - Поля ввода (имя, пароль, email и др.)
- Чекбоксы (Active Directory, Push-уведомления) - Чекбоксы (Active Directory, Блокировка, Push-уведомления)
- Выпадающий список ролей - Выпадающий список ролей
- Кнопки действий - Кнопки действий
""" """
@ -42,9 +43,11 @@ class AddLocalUserModalWindow(ModalWindowComponent):
# Настройка заголовка и кнопки закрытия тулбара # Настройка заголовка и кнопки закрытия тулбара
self.window_title = "Добавить нового пользователя" self.window_title = "Добавить нового пользователя"
locator_button_toolbar_close = self.page.get_by_role("navigation").filter( locator_button_toolbar_close = (
has_text=re.compile(self.window_title) self.page.get_by_role("navigation")
).get_by_role("button") .filter(has_text=re.compile(self.window_title))
.get_by_role("button")
)
self.add_toolbar_title(self.window_title) self.add_toolbar_title(self.window_title)
self.add_toolbar_button(locator_button_toolbar_close, "close") self.add_toolbar_button(locator_button_toolbar_close, "close")
@ -65,47 +68,84 @@ class AddLocalUserModalWindow(ModalWindowComponent):
) )
self.add_content_item("active_directory_checkbox_label", label_1) 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) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[2]")
.locator(text_field_locator)
)
name_input = TextInput(page, loc, "name_input") name_input = TextInput(page, loc, "name_input")
self.add_content_item("name_input", name_input) self.add_content_item("name_input", name_input)
role_loc = self.page.locator(input_form_locator).get_by_role("combobox").nth(0) role_loc = self.page.locator(input_form_locator).get_by_role("combobox").nth(0)
role_input = TextInput(page, role_loc, "role_input") role_input = TextInput(page, role_loc, "role_input")
self.add_content_item("role_input", role_input) self.add_content_item("role_input", role_input)
self.add_content_item( self.add_content_item("roles_list", DropdownList(page))
"roles_list",
DropdownList(page)
)
loc = self.page.locator(input_form_locator).locator("xpath=div[4]").locator(text_field_locator) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[5]")
.locator(text_field_locator)
)
password_input = TextInput(page, loc, "password_input") password_input = TextInput(page, loc, "password_input")
self.add_content_item("password_input", password_input) self.add_content_item("password_input", password_input)
loc = self.page.locator(input_form_locator).locator("xpath=div[5]").locator(text_field_locator) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[6]")
.locator(text_field_locator)
)
commentary_input = TextInput(page, loc, "commentary_input") commentary_input = TextInput(page, loc, "commentary_input")
self.add_content_item("commentary_input", 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) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[7]")
.locator(text_field_locator)
)
email_input = TextInput(page, loc, "email_input") email_input = TextInput(page, loc, "email_input")
self.add_content_item("email_input", 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) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[8]")
.locator(text_field_locator)
)
phone_input = TextInput(page, loc, "phone_input") phone_input = TextInput(page, loc, "phone_input")
self.add_content_item("phone_input", phone_input) self.add_content_item("phone_input", phone_input)
# Чекбокс "Блокировка" - индекс 1
checkbox_2 = Checkbox( checkbox_2 = Checkbox(
page, page,
self.page.locator(input_form_locator).get_by_role("checkbox").nth(1), self.page.locator(ModalWindowLocators.INPUT_FORM_USER_DATA)
"push_notification" .get_by_role("checkbox").nth(1),
"blocking"
) )
self.add_content_item("push_notification_checkbox", checkbox_2) self.add_content_item("blocking_checkbox", checkbox_2)
# Метка "Блокировка" - индекс 1
label_2 = Text( label_2 = Text(
page, page,
self.page.locator(label_locator).nth(1), self.page.locator(label_locator).nth(1),
"blocking_checkbox_label"
)
self.add_content_item("blocking_checkbox_label", label_2)
# Чекбокс "Подписка на 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" "push_notification_checkbox_label"
) )
self.add_content_item("push_notification_checkbox_label", label_2) self.add_content_item("push_notification_checkbox_label", label_3)
# Добавление кнопок действий # Добавление кнопок действий
locator_button_add = self.page.get_by_role("button", name="Добавить") locator_button_add = self.page.get_by_role("button", name="Добавить")
@ -118,12 +158,12 @@ class AddLocalUserModalWindow(ModalWindowComponent):
# Действия: # Действия:
def check_active_directory_checkbox(self): def check_active_directory_checkbox(self):
"""Включает чек-бокс Active Directory. """ """Включает чек-бокс Active Directory."""
self.get_content_item("active_directory_checkbox").check(force=True) self.get_content_item("active_directory_checkbox").check(force=True)
def uncheck_active_directory_checkbox(self): def uncheck_active_directory_checkbox(self):
"""Выключает чек-бокс Active Directory. """ """Выключает чек-бокс Active Directory."""
self.get_content_item("active_directory_checkbox").uncheck(force=True) self.get_content_item("active_directory_checkbox").uncheck(force=True)
@ -164,6 +204,13 @@ class AddLocalUserModalWindow(ModalWindowComponent):
input_field = self.get_content_item("phone_input") input_field = self.get_content_item("phone_input")
input_field.input_value(user_data["phone_number"]) 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: if "push_notification_checked" in fields:
checkbox = self.get_content_item("push_notification_checkbox") checkbox = self.get_content_item("push_notification_checkbox")
if user_data["push_notification_checked"]: if user_data["push_notification_checked"]:
@ -204,13 +251,15 @@ class AddLocalUserModalWindow(ModalWindowComponent):
is_checked = self.get_content_item("active_directory_checkbox").is_checked() is_checked = self.get_content_item("active_directory_checkbox").is_checked()
if is_checked: if is_checked:
assert False, \ assert False, (
"The checkbox 'Active Directory'should not be checked for the add local user window" "The checkbox 'Active Directory' should not be checked for "
"the add local user window"
)
self.check_toolbar_button_visibility("close") self.check_toolbar_button_visibility("close")
self.check_toolbar_button_tooltip("close", "Закрыть") self.check_toolbar_button_tooltip("close", "Закрыть")
for name in self.content_items.keys(): for name in self.content_items:
item = self.get_content_item(name) item = self.get_content_item(name)
if name == "active_directory_checkbox_label": if name == "active_directory_checkbox_label":
@ -218,6 +267,11 @@ class AddLocalUserModalWindow(ModalWindowComponent):
"Active Directory", "Active Directory",
"Label 'Active Directory' is missing" "Label 'Active Directory' is missing"
) )
elif name == "blocking_checkbox_label":
item.check_have_text(
"Блокировка",
"Label 'Блокировка' is missing"
)
elif name == "push_notification_checkbox_label": elif name == "push_notification_checkbox_label":
item.check_have_text( item.check_have_text(
"Подписка на Push-уведомления", "Подписка на Push-уведомления",
@ -226,12 +280,12 @@ class AddLocalUserModalWindow(ModalWindowComponent):
elif name == "role_input": elif name == "role_input":
item.click() item.click()
roles_list = self.get_content_item("roles_list") roles_list = self.get_content_item("roles_list")
roles_list.check_visibility(menu_locator, roles_list.check_visibility(menu_locator, "Roles list is missing")
"Roles list is missing")
is_scrollable_vertically = roles_list.check_vertical_scrolling(menu_locator) is_scrollable_vertically = roles_list.check_vertical_scrolling(menu_locator)
assert not is_scrollable_vertically, \ assert not is_scrollable_vertically, (
"Roles list should not be scrollable_vertically" "Roles list should not be scrollable_vertically"
)
for role in roles_dict.values(): for role in roles_dict.values():
# временно, пока есть несоответствие со списком ролей в вкладке Сессии # временно, пока есть несоответствие со списком ролей в вкладке Сессии
@ -245,6 +299,18 @@ class AddLocalUserModalWindow(ModalWindowComponent):
f"Modal window content item with name '{name}' is missing" 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("add")
self.check_button_visibility("close") self.check_button_visibility("close")

View File

@ -40,49 +40,85 @@ class EditUserModalWindow(ModalWindowComponent):
# Настройка заголовка и кнопки закрытия # Настройка заголовка и кнопки закрытия
self.window_title = user_name self.window_title = user_name
locator_button_toolbar_close = self.page.get_by_role("navigation").filter( locator_button_toolbar_close = (
has_text=re.compile(self.window_title) self.page.get_by_role("navigation")
).get_by_role("button") .filter(has_text=re.compile(self.window_title))
.get_by_role("button")
)
self.add_toolbar_title(self.window_title) self.add_toolbar_title(self.window_title)
self.add_toolbar_button(locator_button_toolbar_close, "close") self.add_toolbar_button(locator_button_toolbar_close, "close")
# Добавление полей формы # Добавление полей формы
loc = self.page.locator(input_form_locator).locator("xpath=div[1]").locator(text_field_locator) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[1]")
.locator(text_field_locator)
)
name_input = TextInput(page, loc, "name_input") name_input = TextInput(page, loc, "name_input")
self.add_content_item("name_input", name_input) self.add_content_item("name_input", name_input)
role_loc = self.page.locator(input_form_locator).get_by_role("combobox").nth(0) role_loc = self.page.locator(input_form_locator).get_by_role("combobox").nth(0)
role_input = TextInput(page, role_loc, "role_input") role_input = TextInput(page, role_loc, "role_input")
self.add_content_item("role_input", role_input) self.add_content_item("role_input", role_input)
self.add_content_item( self.add_content_item("roles_list", DropdownList(page))
"roles_list",
DropdownList(page)
)
loc = self.page.locator(input_form_locator).locator("xpath=div[3]").locator(text_field_locator) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[4]")
.locator(text_field_locator)
)
commentary_input = TextInput(page, loc, "commentary_input") commentary_input = TextInput(page, loc, "commentary_input")
self.add_content_item("commentary_input", commentary_input) self.add_content_item("commentary_input", commentary_input)
loc = self.page.locator(input_form_locator).locator("xpath=div[4]").locator(text_field_locator) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[5]")
.locator(text_field_locator)
)
email_input = TextInput(page, loc, "email_input") email_input = TextInput(page, loc, "email_input")
self.add_content_item("email_input", email_input) self.add_content_item("email_input", email_input)
loc = self.page.locator(input_form_locator).locator("xpath=div[5]").locator(text_field_locator) loc = (
self.page.locator(input_form_locator)
.locator("xpath=div[6]")
.locator(text_field_locator)
)
phone_input = TextInput(page, loc, "phone_input") phone_input = TextInput(page, loc, "phone_input")
self.add_content_item("phone_input", phone_input) self.add_content_item("phone_input", phone_input)
# Добавление чекбоксов и их меток # Добавление чекбоксов и их меток
# Чекбокс "Блокировка" - теперь индекс 0 (т.к. нет Active Directory)
checkbox_1 = Checkbox(
page,
self.page.locator(ModalWindowLocators.INPUT_FORM_USER_DATA)
.get_by_role("checkbox").nth(0),
"blocking"
)
self.add_content_item("blocking_checkbox", checkbox_1)
# Метка "Блокировка" - индекс 0
label_1 = Text(
page,
self.page.locator(label_locator).nth(0),
"blocking_checkbox_label"
)
self.add_content_item("blocking_checkbox_label", label_1)
# Чекбокс "Подписка на Push-уведомления" - индекс 1
checkbox_2 = Checkbox( checkbox_2 = Checkbox(
page, page,
page.get_by_role("checkbox").nth(0), self.page.locator(ModalWindowLocators.INPUT_FORM_USER_DATA)
.get_by_role("checkbox").nth(1),
"push_notification" "push_notification"
) )
self.add_content_item("push_notification_checkbox", checkbox_2) self.add_content_item("push_notification_checkbox", checkbox_2)
# Метка "Подписка на Push-уведомления" - индекс 1
label_2 = Text( label_2 = Text(
page, page,
self.page.locator(label_locator).nth(0), self.page.locator(label_locator).nth(1),
"push_notification_checkbox_label" "push_notification_checkbox_label"
) )
self.add_content_item("push_notification_checkbox_label", label_2) self.add_content_item("push_notification_checkbox_label", label_2)
@ -161,6 +197,13 @@ class EditUserModalWindow(ModalWindowComponent):
input_field = self.get_content_item("phone_input") input_field = self.get_content_item("phone_input")
input_field.input_value(user_data["phone_number"]) 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: if "push_notification_checked" in fields:
checkbox = self.get_content_item("push_notification_checkbox") checkbox = self.get_content_item("push_notification_checkbox")
if user_data["push_notification_checked"]: if user_data["push_notification_checked"]:
@ -198,7 +241,7 @@ class EditUserModalWindow(ModalWindowComponent):
self.check_toolbar_button_visibility("close") self.check_toolbar_button_visibility("close")
self.check_toolbar_button_tooltip("close", "Закрыть") self.check_toolbar_button_tooltip("close", "Закрыть")
for name in self.content_items.keys(): for name in self.content_items:
item = self.get_content_item(name) item = self.get_content_item(name)
if name == "push_notification_checkbox_label": if name == "push_notification_checkbox_label":
@ -206,17 +249,22 @@ class EditUserModalWindow(ModalWindowComponent):
"Подписка на Push-уведомления", "Подписка на Push-уведомления",
"Label 'Подписка на Push-уведомления' is missing" "Label 'Подписка на Push-уведомления' is missing"
) )
elif name == "blocking_checkbox_label":
item.check_have_text(
"Блокировка",
"Label 'Блокировка' is missing"
)
elif name == "name_input": elif name == "name_input":
name = self.get_content_item("name_input") name_field = self.get_content_item("name_input")
text_value = name.get_input_value() text_value = name_field.get_input_value()
assert text_value == user_name, ( assert text_value == user_name, (
f"Expected user name '{user_name}' is not equal real user name '{text_value}'" f"Expected user name '{user_name}' is not equal "
f"real user name '{text_value}'"
) )
elif name == "role_input": elif name == "role_input":
item.click() item.click()
roles_list = self.get_content_item("roles_list") roles_list = self.get_content_item("roles_list")
roles_list.check_visibility(menu_locator, roles_list.check_visibility(menu_locator, "Roles list is missing")
"Roles list is missing")
roles_list.check_item_with_text(role) roles_list.check_item_with_text(role)
elif name == "roles_list": elif name == "roles_list":
continue continue
@ -225,6 +273,19 @@ class EditUserModalWindow(ModalWindowComponent):
f"Modal window content item with name '{name}' is missing" 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 be checked by default"
)
self.check_button_visibility("save") self.check_button_visibility("save")
self.check_button_visibility("delete") self.check_button_visibility("delete")
self.check_button_visibility("reset_password") self.check_button_visibility("reset_password")

View File

@ -34,18 +34,27 @@ class UserCard(BaseComponent):
card_locator = page.locator(UserCardLocators.CARD_USER) card_locator = page.locator(UserCardLocators.CARD_USER)
self.current_user_name = Text(page, # Обновленные локаторы согласно новой структуре карточки
card_locator.locator("xpath=/div/div[2]"), self.current_user_name = Text(
"current user name") page,
self.current_user_role = Text(page, card_locator.locator("xpath=/div/div[1]"), # Изменено с div[2] на div[1]
card_locator.locator("xpath=/div/div[3]"), "current user name"
"current user role") )
self.login_time = Text(page, self.current_user_role = Text(
card_locator.locator("xpath=/div/div[4]"), page,
"login time") card_locator.locator("xpath=/div/div[2]"), # Изменено с div[3] на div[2]
self.session_time = Text(page, "current user role"
card_locator.locator("xpath=/div/div[5]"), )
"current user name") self.login_time = Text(
page,
card_locator.locator("xpath=/div/div[3]"), # Изменено с div[4] на div[3]
"login time"
)
self.session_time = Text(
page,
card_locator.locator("xpath=/div/div[4]"), # Изменено с div[5] на div[4]
"session time" # Исправлено имя с "current user name" на "session time"
)
self.logout_button = Button( self.logout_button = Button(
page, page,
page.get_by_role("button", name="Выйти"), page.get_by_role("button", name="Выйти"),
@ -62,25 +71,11 @@ class UserCard(BaseComponent):
"settings button" "settings button"
) )
# self.close_button = Button(
# page,
# page.get_by_role("button", name="Закрыть"),
# "close button"
# )
# окна, отрываемые после нажатия кнопок # окна, отрываемые после нажатия кнопок
self.user_settings_dialog_window = UserSettingsDialogWindow(page) self.user_settings_dialog_window = UserSettingsDialogWindow(page)
self.change_password_modal_window = ChangePasswordModalWindow(page) self.change_password_modal_window = ChangePasswordModalWindow(page)
# Действия: # Действия:
# def click_close_button(self):
# """Нажимает кнопку выхода из карточки пользователя.
# Выполняет клик по кнопке 'Закрыть' в карточке пользователя.
# """
# self.close_button.click()
def click_change_password_button(self) -> ChangePasswordModalWindow: def click_change_password_button(self) -> ChangePasswordModalWindow:
"""Нажимает кнопку открытия окна изменения пароля. """Нажимает кнопку открытия окна изменения пароля.
@ -116,28 +111,38 @@ class UserCard(BaseComponent):
name = current_user_credential["login"] name = current_user_credential["login"]
text_to_check = f"Имя пользователя: {name}" text_to_check = f"Имя пользователя: {name}"
self.current_user_name.check_have_text(text_to_check, self.current_user_name.check_have_text(
f"Expected text {text_to_check} is missing in user card") text_to_check,
f"Expected text {text_to_check} is missing in user card"
)
role = roles_dict.get(current_user_credential["role"]) role = roles_dict.get(current_user_credential["role"])
if role is None: if role is None:
assert False, "Unknown user role in current user credential" assert False, "Unknown user role in current user credential"
text_to_check = f"Роль: {role}" text_to_check = f"Роль: {role}"
self.current_user_role.check_have_text(text_to_check, self.current_user_role.check_have_text(
f"Expected text {text_to_check} is missing in user card") text_to_check,
f"Expected text {text_to_check} is missing in user card"
)
login_time_str = self.login_time.get_text(0) login_time_str = self.login_time.get_text(0)
assert login_time_str.find("Время входа:")!= -1, \ assert login_time_str.find("Время входа:") != -1, (
"Expected text 'Время входа:' is missing in user card" "Expected text 'Время входа:' is missing in user card"
)
session_time_str = self.session_time.get_text(0) session_time_str = self.session_time.get_text(0)
assert session_time_str.find("Время сессии:")!= -1, \ assert session_time_str.find("Время сессии:") != -1, (
"Expected text 'Время сессии:' is missing in user card" "Expected text 'Время сессии:' is missing in user card"
)
self.logout_button.check_visibility("Logout button is missing on user card") self.logout_button.check_visibility(
self.change_password_button.check_visibility("Change password button is missing on user card") "Logout button is missing on user card"
# self.close_button.check_visibility("Close button is missing on user card") )
self.change_password_button.check_visibility(
"Change password button is missing on user card"
)
admin_roles = ["Администратор", admin_roles = ["Администратор", "Специалист информационной безопасности"]
"Специалист информационной безопасности"]
if role in admin_roles: if role in admin_roles:
self.settings_button.check_visibility("Settings button is missing on user card") self.settings_button.check_visibility(
"Settings button is missing on user card"
)

View File

@ -17,6 +17,7 @@ from components.modal_window_component import ModalWindowComponent
from components.alert_component import AlertComponent from components.alert_component import AlertComponent
from pages.base_page import BasePage from pages.base_page import BasePage
class UsersTab(BasePage): class UsersTab(BasePage):
"""Класс для работы с вкладкой 'Пользователи'. """Класс для работы с вкладкой 'Пользователи'.
@ -161,7 +162,6 @@ class UsersTab(BasePage):
self.close_modal_window(title) self.close_modal_window(title)
def add_new_user(self, user_data: dict) -> bool: def add_new_user(self, user_data: dict) -> bool:
"""Добавляет нового пользователя или обрабатывает ошибку при дубликате. """Добавляет нового пользователя или обрабатывает ошибку при дубликате.
@ -215,7 +215,7 @@ class UsersTab(BasePage):
self.get_modal_window(user_name).delete_user() self.get_modal_window(user_name).delete_user()
alert_type = self.alert.get_alert_type() alert_type = self.alert.get_alert_type()
assert alert_type=="success", f"Expected success alert, but got {alert_type} alert" assert alert_type == "success", f"Expected success alert, but got {alert_type} alert"
self.alert.check_alert_presence('\nПользователь удалён\n') self.alert.check_alert_presence('\nПользователь удалён\n')
self.alert.check_alert_absence('\nПользователь удалён\n') self.alert.check_alert_absence('\nПользователь удалён\n')
@ -234,7 +234,7 @@ class UsersTab(BasePage):
self.get_modal_window(user_name).edit_user(user_data) self.get_modal_window(user_name).edit_user(user_data)
alert_type = self.alert.get_alert_type() alert_type = self.alert.get_alert_type()
assert alert_type=="success", f"Expected success alert, but got {alert_type} alert" assert alert_type == "success", f"Expected success alert, but got {alert_type} alert"
self.alert.check_alert_presence('\nОбновление успешно\n') self.alert.check_alert_presence('\nОбновление успешно\n')
self.alert.check_alert_absence('\nОбновление успешно\n') self.alert.check_alert_absence('\nОбновление успешно\n')
@ -317,7 +317,8 @@ class UsersTab(BasePage):
self.page.wait_for_timeout(2000) self.page.wait_for_timeout(2000)
tmp_dict = {"admin": "Администратор", "manager": "Контактное лицо", "operator": "Оператор"} tmp_dict = {"admin": "Администратор", "manager": "Контактное лицо",
"operator": "Оператор"}
table_content = self.users_table.read(TableLocators.TABLE_WORK_AREA) table_content = self.users_table.read(TableLocators.TABLE_WORK_AREA)
if len(table_content) == 0: if len(table_content) == 0:
@ -335,7 +336,8 @@ class UsersTab(BasePage):
role = table_content[row_index][2] role = table_content[row_index][2]
self.page.locator(TableLocators.TABLE_WORK_AREA).locator("//tbody/tr").nth(row_index).click() self.page.locator(TableLocators.TABLE_WORK_AREA).locator(
"//tbody/tr").nth(row_index).click()
self.add_modal_window("edit_user", user_name) self.add_modal_window("edit_user", user_name)
self.get_modal_window(user_name).check_by_window_title() self.get_modal_window(user_name).check_by_window_title()
@ -356,12 +358,13 @@ class UsersTab(BasePage):
if row_index == -1: if row_index == -1:
assert False, f"User with name {user_name} and role {role} has not been found" assert False, f"User with name {user_name} and role {role} has not been found"
self.page.locator(TableLocators.TABLE_WORK_AREA).locator("//tbody/tr").nth(row_index).click() self.page.locator(TableLocators.TABLE_WORK_AREA).locator(
"//tbody/tr").nth(row_index).click()
self.add_modal_window("edit_user", user_name) self.add_modal_window("edit_user", user_name)
self.get_modal_window(user_name).check_by_window_title() self.get_modal_window(user_name).check_by_window_title()
def transform_to_add_AD_user_window(self): def transform_to_add_AD_user_window(self):
"""Трансформирует модальное окно добавления локального пользователя """Трансформирует модальное окно добавления локального пользователя
в окно добавления пользователя Active Directory с помощью нажатия в окно добавления пользователя Active Directory с помощью нажатия
чек-бокса Active Directory. чек-бокса Active Directory.
""" """
@ -372,7 +375,7 @@ class UsersTab(BasePage):
self.add_modal_window("add_AD_user", "") self.add_modal_window("add_AD_user", "")
def transform_to_add_user_window(self): def transform_to_add_user_window(self):
"""Трансформирует модальное окно добавления пользователя Active Directory """Трансформирует модальное окно добавления пользователя Active Directory
в окно добавления локального пользователя с помощью снятия отметки с в окно добавления локального пользователя с помощью снятия отметки с
чек-бокса Active Directory. чек-бокса Active Directory.
""" """
@ -394,7 +397,8 @@ class UsersTab(BasePage):
""" """
self.page.wait_for_timeout(2000) self.page.wait_for_timeout(2000)
expected_headers = ['Имя пользователя', 'Тип авторизации', 'Роль', 'E-mail', 'Номер для СМС'] expected_headers = ['Имя пользователя', 'Тип авторизации', 'Роль',
'E-mail', 'Номер для СМС']
table_content = self.users_table.read(TableLocators.TABLE_WORK_AREA) table_content = self.users_table.read(TableLocators.TABLE_WORK_AREA)
if len(table_content) == 0: if len(table_content) == 0:
@ -516,7 +520,6 @@ class UsersTab(BasePage):
""" """
expected_users_list = [] expected_users_list = []
tmp_dict = {"admin": "Администратор", "manager": "Контактное лицо", "operator": "Оператор"}
query = { query = {
"id": ["/catalogs/user"], "id": ["/catalogs/user"],
@ -533,9 +536,8 @@ class UsersTab(BasePage):
user_info = [] user_info = []
user_name = item["name"] user_name = item["name"]
if user_name in tmp_dict.keys(): # НЕ преобразуем имя пользователя - оставляем как есть из БД
item["name"] = tmp_dict[user_name] user_info.append(user_name)
user_info.append(item["name"])
if item["type_auth"] is not None: if item["type_auth"] is not None:
user_info.append(item["type_auth"]) user_info.append(item["type_auth"])
@ -544,7 +546,7 @@ class UsersTab(BasePage):
if item["role"] is not None: if item["role"] is not None:
role = item["role"] role = item["role"]
if role in roles_dict.keys(): if role in roles_dict: # Убрали вызов .keys()
item["role"] = roles_dict[role] item["role"] = roles_dict[role]
user_info.append(item["role"]) user_info.append(item["role"])
else: else:

View File

@ -4,13 +4,13 @@
карточки пользователя в приложении. карточки пользователя в приложении.
""" """
# import pytest import pytest
from playwright.sync_api import Page from playwright.sync_api import Page
from pages.users_tab import UsersTab from pages.users_tab import UsersTab
from pages.main_page import MainPage from pages.main_page import MainPage
from pages.login_page import LoginPage from pages.login_page import LoginPage
user_data = {"name": "TestUserForChangePwd", "role": "Администратор", "password": "qwerty", "new_password": "ytrewq"} user_data = {"name": "TestUserForChangePwd", "role": "Администратор", "password": "qwerty1234567", "new_password": "ytrewq7654321"}
# @pytest.mark.smoke # @pytest.mark.smoke
class TestUserCard: class TestUserCard:
@ -96,7 +96,7 @@ class TestUserCard:
# @pytest.mark.develop # @pytest.mark.develop
def test_open_close_user_settings_window(self, browser: Page) -> None: def test_open_close_user_settings_window(self, browser: Page) -> None:
"""Проверяет возможность открытия и закрытия диалогового окна просмотра сессионных данных пользователя. """Проверяет возможность открытия и закрытия диалогового окна просмотра сеанса данных пользователя.
Args: Args:
browser: Экземпляр страницы Playwright. browser: Экземпляр страницы Playwright.
@ -116,7 +116,7 @@ class TestUserCard:
# @pytest.mark.develop # @pytest.mark.develop
def test_user_settings_window_content(self, browser: Page) -> None: def test_user_settings_window_content(self, browser: Page) -> None:
"""Проверяет наличие и корректность элементов диалогового окна просмотра сессионных данных пользователя. """Проверяет наличие и корректность элементов диалогового окна просмотра сеанса данных пользователя.
Args: Args:
browser: Экземпляр страницы Playwright. browser: Экземпляр страницы Playwright.
@ -204,7 +204,7 @@ class TestUserCard:
# Используется неправильный старый пароль # Используется неправильный старый пароль
user_card = mp.click_user_button() user_card = mp.click_user_button()
change_password_window = user_card.click_change_password_button() change_password_window = user_card.click_change_password_button()
is_changed, _ = change_password_window.change_password("123456789", user_data["new_password"]) is_changed, _ = change_password_window.change_password("123456789123", user_data["new_password"])
assert not is_changed, "Sucessful attempt to change password for incorrect old password" assert not is_changed, "Sucessful attempt to change password for incorrect old password"
change_password_window.click_cancel_button() change_password_window.click_cancel_button()

View File

@ -76,7 +76,7 @@ class TestUsersTab:
ut.open_edit_user_page_by_user(user_name, "Администратор") ut.open_edit_user_page_by_user(user_name, "Администратор")
ut.delete_user(user_name) ut.delete_user(user_name)
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_users_tab_content(self, browser: Page) -> None: def test_users_tab_content(self, browser: Page) -> None:
"""Проверяет содержимое вкладки 'Пользователи'. """Проверяет содержимое вкладки 'Пользователи'.
@ -89,6 +89,7 @@ class TestUsersTab:
ut.should_be_users_table() ut.should_be_users_table()
ut.check_users_table_content(True) ut.check_users_table_content(True)
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_users_tab_toolbar_buttons(self, browser: Page) -> None: def test_users_tab_toolbar_buttons(self, browser: Page) -> None:
"""Проверяет кнопки на панели инструментов. """Проверяет кнопки на панели инструментов.
@ -100,6 +101,7 @@ class TestUsersTab:
ut.should_be_toolbar_buttons() ut.should_be_toolbar_buttons()
# @pytest.mark.develop # @pytest.mark.develop
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_add_user_window_content(self, browser: Page) -> None: def test_add_user_window_content(self, browser: Page) -> None:
"""Проверяет содержимое окна добавления пользователя. """Проверяет содержимое окна добавления пользователя.
@ -113,6 +115,7 @@ class TestUsersTab:
ut.transform_to_add_AD_user_window() ut.transform_to_add_AD_user_window()
ut.check_add_AD_user_window_content() ut.check_add_AD_user_window_content()
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_add_user_window_close_buttons(self, browser: Page) -> None: def test_add_user_window_close_buttons(self, browser: Page) -> None:
"""Проверяет кнопки закрытия окна добавления. """Проверяет кнопки закрытия окна добавления.
@ -135,6 +138,7 @@ class TestUsersTab:
ut.transform_to_add_AD_user_window() ut.transform_to_add_AD_user_window()
ut.close_add_AD_user_window() ut.close_add_AD_user_window()
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_edit_user_window_content(self, browser: Page) -> None: def test_edit_user_window_content(self, browser: Page) -> None:
"""Проверяет содержимое окна редактирования. """Проверяет содержимое окна редактирования.
@ -146,6 +150,7 @@ class TestUsersTab:
user_name, role = ut.open_edit_user_page_by_index(0) user_name, role = ut.open_edit_user_page_by_index(0)
ut.check_edit_user_window_content(user_name, role) ut.check_edit_user_window_content(user_name, role)
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_edit_user_window_close_buttons(self, browser: Page) -> None: def test_edit_user_window_close_buttons(self, browser: Page) -> None:
"""Проверяет кнопки закрытия окна редактирования. """Проверяет кнопки закрытия окна редактирования.
@ -160,6 +165,7 @@ class TestUsersTab:
ut.close_edit_user_window(user_name) ut.close_edit_user_window(user_name)
# @pytest.mark.develop # @pytest.mark.develop
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_add_and_delete_user(self, browser: Page, cleanup_users: None) -> None: def test_add_and_delete_user(self, browser: Page, cleanup_users: None) -> None:
"""Проверяет добавление и удаление пользователя. """Проверяет добавление и удаление пользователя.
@ -168,7 +174,7 @@ class TestUsersTab:
cleanup_users: Фикстура для автоматического удаления пользователя после теста. cleanup_users: Фикстура для автоматического удаления пользователя после теста.
""" """
user_data: Dict[str, str] = {"name": "TestUser", "role": "Администратор", "password": "987654"} user_data: Dict[str, str] = {"name": "TestUser", "role": "Администратор", "password": "987654321abcd"}
mp = MainPage(browser) mp = MainPage(browser)
ut = UsersTab(browser) ut = UsersTab(browser)
@ -208,6 +214,7 @@ class TestUsersTab:
ut.should_not_be_user_in_table(user_data["name"], user_data["role"]) ut.should_not_be_user_in_table(user_data["name"], user_data["role"])
# @pytest.mark.develop # @pytest.mark.develop
@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_add_AD_user(self, browser: Page, cleanup_users: None) -> None: def test_add_AD_user(self, browser: Page, cleanup_users: None) -> None:
"""Проверяет добавление пользователя Active Directory. """Проверяет добавление пользователя Active Directory.
@ -226,6 +233,7 @@ class TestUsersTab:
ut.open_add_user_window() ut.open_add_user_window()
ut.add_new_user(user_data) ut.add_new_user(user_data)
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_reset_password(self, browser: Page, cleanup_users: None) -> None: def test_reset_password(self, browser: Page, cleanup_users: None) -> None:
"""Проверяет сброс пароля пользователя. """Проверяет сброс пароля пользователя.
@ -234,7 +242,7 @@ class TestUsersTab:
cleanup_users: Фикстура для автоматического удаления пользователя после теста. cleanup_users: Фикстура для автоматического удаления пользователя после теста.
""" """
user_data: Dict[str, str] = {"name": "TestUserAutoAdmin", "role": "Администратор", "password": "123456"} user_data: Dict[str, str] = {"name": "TestUserAutoAdmin", "role": "Администратор", "password": "123456789abcd"}
mp = MainPage(browser) mp = MainPage(browser)
ut = UsersTab(browser) ut = UsersTab(browser)
@ -266,6 +274,7 @@ class TestUsersTab:
mp_1.click_subpanel_item("Пользователи") mp_1.click_subpanel_item("Пользователи")
ut_1.should_not_be_user_in_table(user_data["name"], user_data["role"]) ut_1.should_not_be_user_in_table(user_data["name"], user_data["role"])
#@pytest.mark.skip(reason=" Временно исключено из тестирования")
def test_edit_user_role(self, browser: Page, cleanup_users: None) -> None: def test_edit_user_role(self, browser: Page, cleanup_users: None) -> None:
"""Проверяет изменение роли пользователя. """Проверяет изменение роли пользователя.
@ -274,7 +283,7 @@ class TestUsersTab:
cleanup_users: Фикстура для автоматического удаления пользователя после теста. cleanup_users: Фикстура для автоматического удаления пользователя после теста.
""" """
user_data: Dict[str, str] = {"name": "TestUserAutoOperator", "role": "Оператор", "password": "123245"} user_data: Dict[str, str] = {"name": "TestUserAutoOperator", "role": "Оператор", "password": "1232456789abcd"}
mp = MainPage(browser) mp = MainPage(browser)
ut = UsersTab(browser) ut = UsersTab(browser)