e-nms_qa_automation/components/alert_component.py

149 lines
5.7 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.

"""Модуль для работы с компонентом alert-окна в Playwright.
Содержит класс AlertComponent для взаимодействия с различными типами
alert-окон (error, success, info, warning) и проверки их состояния.
"""
from playwright.sync_api import Page, expect
from tools.logger import get_logger
from elements.text_element import Text
from components.base_component import BaseComponent
from locators.alert_locators import AlertLocators
logger = get_logger("ALERT")
class AlertComponent(BaseComponent):
"""Компонент для работы с alert-окнами Playwright.
Поддерживает типы: error, success, info, warning.
Позволяет проверять наличие, отсутствие и текст сообщений.
"""
def __init__(self, page: Page) -> None:
"""Инициализирует компонент alert-окна.
Args:
page: Экземпляр страницы Playwright.
"""
super().__init__(page)
self.text = Text(page, AlertLocators.ALERT_MESSAGE, "Alert message")
# Действия:
def get_alert_type(self) -> str:
"""Возвращает тип alert-окна.
Returns:
str: Тип alert-окна.
Raises:
ValueError: Если получен неподдерживаемый тип alert-окна.
"""
class_attr = self.page.get_by_role(AlertLocators.ALERT_ROLE).locator('>div').get_attribute('class')
alert_type = None
if 'v-alert' in class_attr:
alert_type = class_attr.replace("v-alert ", "")
alert_types = ["error", "success", "info", "warning"]
if alert_type not in alert_types:
raise ValueError("Unsupported type of alert window")
return alert_type
def get_text(self) -> str:
"""Возвращает текст сообщения из alert-окна.
Returns:
str: Текст сообщения.
"""
return self.text.get_text(0)
def close_alert_by_text(self, text: str) -> None:
"""Закрывает alert-окно с заданным текстом с помощью кнопки закрытия.
Args:
text: Текст alert-окна, которое нужно закрыть.
Raises:
AssertionError: Если не удалось найти или закрыть alert-окно.
"""
# Находим alert с нужным текстом
alert_locator = self.page.get_by_role(AlertLocators.ALERT_ROLE).filter(has_text=text)
# Проверяем, что alert видим
expect(alert_locator).to_be_visible()
# Находим кнопку закрытия внутри alert
close_button = alert_locator.locator(AlertLocators.ALERT_DISMISS_BUTTON)
# Проверяем, что кнопка закрытия доступна и кликаем
expect(close_button).to_be_visible()
expect(close_button).to_be_enabled()
# Кликаем по кнопке закрытия
close_button.click()
# Проверяем, что alert исчез после закрытия
expect(alert_locator).to_be_hidden()
logger.info(f"Alert with text '{text}' closed successfully")
# Проверки:
def check_alert_presence(self, text: str) -> None:
"""Проверяет наличие alert-окна с заданным текстом.
Args:
text: Текст для проверки. Если пустая строка - проверяет только
наличие окна.
Raises:
AssertionError: Если alert-окно не найдено.
"""
msg = "Alert window is missing"
if text == "":
expect(self.page.get_by_role(AlertLocators.ALERT_ROLE)).to_be_visible(), msg
logger.info("Alert window successfully displayed")
else:
expect(self.page.get_by_role(AlertLocators.ALERT_ROLE).filter(has_text=text)).to_be_visible(), msg
logger.info(f"Alert window with text '{text}' successfully displayed")
def check_alert_absence(self, text: str, timeout: int = 30000) -> None:
"""Проверяет отсутствие alert-окна с заданным текстом.
Args:
text: Текст для проверки.
timeout: Время ожидания исчезновения (мс).
Raises:
AssertionError: Если окно не исчезает в течение заданного времени.
"""
seconds = int(timeout/1000)
msg = f"Alert window should disappear after {seconds} seconds"
if text == "":
expect(self.page.get_by_role(AlertLocators.ALERT_ROLE)).to_be_hidden(timeout=timeout), msg
logger.info("Alert window successfully disappeared")
else:
expect(self.page.get_by_role(AlertLocators.ALERT_ROLE).filter(has_text=text)).to_be_hidden(timeout=timeout), msg
logger.info(f"Alert window with text '{text}' successfully disappeared")
def check_text(self, alert_text: str) -> None:
"""Проверяет точное соответствие текста в alert-окне.
Args:
alert_text: Ожидаемый текст сообщения.
Raises:
AssertionError: Если текст не соответствует ожидаемому.
"""
self.text.check_have_text(alert_text,
"Unexpected message in alert window")