103 lines
4.1 KiB
Python
103 lines
4.1 KiB
Python
"""Модуль 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 update_locator(self, new_locator: Locator) -> None:
|
||
"""Меняет значение локатора для элемента"""
|
||
|
||
logger.info(f"Update locator for {self.type_of} '{self.name}'")
|
||
self.locator = new_locator
|
||
|
||
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
|