"""Модуль компонента задания даты и времени. Содержит класс для работы с компонентом задания даты и времени через Playwright. """ from playwright.sync_api import Page, Locator, expect from tools.logger import get_logger from elements.text_input_element import TextInput from elements.tooltip_button_element import TooltipButton from components.date_picker_component import DatePickerComponent from components.base_component import BaseComponent logger = get_logger("DATE_INPUT") class DateInput(BaseComponent): """Компонент задания даты и времени. Предоставляет методы для взаимодействия с элементами компонентом задания даты и времени. """ def __init__(self, page: Page, locator: str | Locator): """Инициализирует компонент задания даты и времени. Args: page: Экземпляр страницы Playwright. locator: Локатор формы ввода даты и времени (строка или объект Locator) """ super().__init__(page) self.date_input_locator = self.get_locator(locator) self.switch_mode_button = TooltipButton(page, self.date_input_locator.get_by_role("button"), "switch_mode_button") loc = self.date_input_locator.get_by_placeholder("дд.мм.гггг") self.date_input_field = TextInput(page, loc, "date_input") loc = self.date_input_locator.get_by_placeholder("00:00") self.time_input_field = TextInput(page, loc, "time_input") self.date_picker = DatePickerComponent(self.page) # Действия: def click_switch_mode_button(self) -> None: """ Нажатие на кнопку переключения режимов ввода (текстовый или календарь).""" self.switch_mode_button.click() def get_date_picker(self) -> DatePickerComponent: """ Возвращает экземпляр компонента средства выбора даты. """ return self.date_picker def get_date_field_value(self) -> str: """ Возвращает текущее значение поля ввода даты. """ return self.date_input_field.get_input_value() def get_time_field_value(self) -> str: """ Возвращает текущее значение поля ввода времени. """ return self.time_input_field.get_input_value() def input_date(self, date: str) -> None: """ Ввод даты в формате дд.мм.гггг """ day, month, year = date.split('.') assert len(day) == 2, "Incorrect day format: should be 'dd.mm.yyyy'" assert len(month) == 2, "Incorrect month format: should be 'dd.mm.yyyy'" assert len(year) == 4, "Incorrect year format: should be 'dd.mm.yyyy'" try: _ = int(day) except ValueError: assert False, f"Incorrect day value {day} for selection" try: _ = int(month) except ValueError: assert False, f"Incorrect month value {month} for selection" try: _ = int(year) except ValueError: assert False, f"Incorrect year value {year} for selection" # Temporarily due to error in UI if not self.is_text_input_mode(): # if self.is_text_input_mode(): # print("by keyboard") self.date_input_field.check_editable_input("Text field for date input should be editable") self.date_input_field.clear() self.date_input_field.input_value(date) else: # print("by date picker") self.date_picker.select_year_and_month(year, month) self.date_picker.select_day(day) def input_time(self, time: str) -> None: """ Ввод даты в формате чч:мм """ hours, minutes = time.split(':') assert len(hours) == 2, "Incorrect time format: should be 'hh:mm'" assert len(minutes) == 2, "Incorrect time format: should be 'hh:mm'" try: _ = int(hours) except ValueError: assert False, f"Incorrect hours value {hours} for selection" try: _ = int(minutes) except ValueError: assert False, f"Incorrect minutes value {minutes} for selection" self.time_input_field.check_editable_input("Text field for date input should be editable") self.time_input_field.clear() self.time_input_field.input_value(time) # Проверки: def check_content(self, label: str) -> None: """Проверка состава компонента ввода даты.""" self.check_switch_mode_button_visibility() # Temporarily: due to error in UI # label_locator = self.date_input_locator.get_by_label(label) # expect(label_locator).to_be_visible() self.date_input_field.check_visibility("Text field for date input is missing") self.date_input_field.check_empty_input("Text field for date input should be empty") self.click_switch_mode_button() self.page.wait_for_timeout(300) self.click_switch_mode_button() self.page.wait_for_timeout(300) self.date_picker.check_content() self.check_switch_mode_button_tooltip() self.click_switch_mode_button() self.check_switch_mode_button_tooltip() self.click_switch_mode_button() self.page.wait_for_timeout(1000) self.input_date("11.11.2011") label_locator = self.date_input_locator.get_by_label("Время") expect(label_locator).to_be_visible() self.time_input_field.check_visibility("Text field for time input is missing") current_time_value = self.get_time_field_value() assert current_time_value == "", \ "Should be empty time input field" def check_switch_mode_button_visibility(self) -> None: """ Проверка видимости кнопки переключения режимов ввода.""" self.switch_mode_button.check_visibility("Switch Mode Button is missing") def check_switch_mode_button_tooltip(self) -> None: """ Проверка tooltip кнопки переключения режимов ввода.""" text_mode = self.is_text_input_mode() tooltip_text = self.switch_mode_button.get_tooltip_text() if text_mode: assert tooltip_text == "Ручной ввод", \ "Should be 'Ручной ввод' tooltip for switch mode button" else: assert tooltip_text == "Выбрать в календаре", \ "Should be 'Выбрать в календаре' tooltip for switch mode button" def is_text_input_mode(self) -> bool: """ Проверка текстового режима ввода.""" result = False inner_text = self.switch_mode_button.get_text(0).strip() if inner_text == "keyboard": result = True return result