e-nms_qa_automation/elements/base_element.py

97 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.

"""Модуль base_element содержит базовый класс для работы с элементами страницы.
Класс BaseElement предоставляет основные методы взаимодействия с элементами
и их проверки через Playwright.
"""
from playwright.sync_api import Page, Locator, expect, TimeoutError
from tools.logger import get_logger
logger = get_logger("BASE_ELEMENT")
class BaseElement:
"""Базовый класс для работы с элементами страницы через Playwright.
Предоставляет основные методы взаимодействия с элементами:
клики, получение текста, ожидание и проверки состояния.
"""
def __init__(self, page: Page, locator: str | Locator, name: str) -> None:
"""Инициализирует базовый элемент страницы.
Args:
page: Экземпляр страницы Playwright
locator: Локатор элемента (строка или объект Locator)
name: Имя элемента для логирования
"""
self.page = page
self.name = name
self.locator: Locator
if isinstance(locator, Locator):
self.locator = locator
elif isinstance(locator, str):
self.locator = self.page.locator(locator)
else:
raise TypeError("locator value should be string type or Locator type")
@property
def type_of(self) -> str:
"""Возвращает тип элемента (для логирования)."""
return "base element"
# Действия:
def click(self) -> None:
"""Выполняет клик по элементу."""
logger.info(f"Clicking {self.type_of} '{self.name}'")
self.locator.click()
def get_text(self, index: int) -> str:
"""Возвращает текст элемента по указанному индексу."""
logger.info(f"Get text for {self.type_of} '{self.name}'")
return self.locator.nth(index).text_content()
def wait_for_element(self, timeout: int = 12000) -> None:
"""Ожидает появление элемента в течение заданного времени."""
logger.info(f"Wait for {self.type_of} '{self.name}'")
self.locator.wait_for(timeout=timeout)
# Проверки:
def check_have_text(self, text: str, msg: str) -> None:
"""Проверяет наличие указанного текста в элементе."""
logger.info(f"Check that {self.type_of} '{self.name}' has text '{text}'")
expect(self.locator).to_have_text(text), msg
def check_presence(self, msg: str) -> None:
"""Проверяет видимость элемента на странице."""
logger.info(f"Check that {self.type_of} '{self.name}' is present")
print(self.locator)
expect(self.locator).to_be_visible(visible=True, timeout=12000), msg
def is_present(self, timeout: int = 5000) -> bool:
"""Проверяет наличие элемента в течение заданного времени."""
logger.info(f"Check that {self.type_of} '{self.name}' is present")
try:
self.locator.wait_for(timeout=timeout)
except TimeoutError:
return False
return True
def is_not_present(self, timeout: int = 5000) -> bool:
"""Проверяет отсутствие элемента в течение заданного времени."""
logger.info(f"Check that {self.type_of} '{self.name}' is missing")
try:
self.locator.wait_for(timeout=timeout)
except TimeoutError:
return True
return False