e-nms_qa_automation/components/alert_component.py

110 lines
3.9 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
logger = get_logger("ALERT")
class AlertComponent(BaseComponent):
"""Компонент для работы с alert-окнами Playwright.
Поддерживает типы: error, success, info, warning.
Позволяет проверять наличие, отсутствие и текст сообщений.
"""
def __init__(self, page: Page):
"""Инициализирует компонент alert-окна.
Args:
page: Экземпляр страницы Playwright.
"""
super().__init__(page)
self.text = Text(page, "//div[contains(@class,'v-alert')]/div", "Alert message")
# Действия:
def get_alert_type(self) -> str:
"""Возвращает тип alert-окна.
Returns:
str: Тип alert-окна.
Raises:
ValueError: Если получен неподдерживаемый тип alert-окна.
"""
class_attr = self.page.get_by_role("alert").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 check_alert_presence(self, text: str):
"""Проверяет наличие alert-окна с заданным текстом.
Args:
text: Текст для проверки. Если пустая строка - проверяет только
наличие окна.
Raises:
AssertionError: Если alert-окно не найдено.
"""
msg = "Alert window is missing"
if text == "":
expect(self.page.get_by_role("alert")).to_be_visible(), msg
else:
expect(self.page.get_by_role("alert").filter(has_text=text)).to_be_visible(), msg
def check_alert_absence(self, text: str, timeout: int = 30000):
"""Проверяет отсутствие alert-окна с заданным текстом.
Args:
text: Текст для проверки.
timeout: Время ожидания исчезновения (мс).
Raises:
AssertionError: Если окно не исчезает в течение заданного времени.
"""
seconds = int(timeout/1000)
msg = f"Alert window should disappear after {seconds} seconds"
expect(self.page.get_by_role("alert").filter(has_text=text)).to_be_hidden(timeout=timeout), msg
def check_text(self, alert_text: str):
"""Проверяет точное соответствие текста в alert-окне.
Args:
alert_text: Ожидаемый текст сообщения.
Raises:
AssertionError: Если текст не соответствует ожидаемому.
"""
self.text.check_have_text(alert_text,
"Unexpected message in alert window")