Skip to content

Commit

Permalink
improved logger: added filtering
Browse files Browse the repository at this point in the history
added locators strategy
added test_input.py
  • Loading branch information
dmy.berezovskyi committed Oct 15, 2024
1 parent ecc271a commit 9874e25
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 18 deletions.
12 changes: 11 additions & 1 deletion src/base_page.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Literal

from playwright.sync_api import Page
from utils.logger import log

Expand All @@ -11,6 +13,15 @@ def navigate_to(self, url: str):
"""Navigate to a specified URL."""
self.page.goto(url)

@log()
def reload_page(
self,
state: Literal["commit", "domcontentloaded", "networkidle", "load"] = "networkidle", # noqa
timeout: float = 10000,
):
"""Reload page"""
self.page.reload(timeout=timeout, wait_until=state)

@log()
def click(self, selector: str):
"""Click an element by selector."""
Expand All @@ -20,7 +31,6 @@ def click(self, selector: str):
@log()
def fill(self, selector: str, value: str):
"""Fill an input field with a specified value."""
self.wait_for_selector(selector)
self.page.locator(selector).fill(value)

@log()
Expand Down
2 changes: 2 additions & 0 deletions src/locators/input_locators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class InputLocators:
FULL_NAME_SELECTOR: str = 'input[id="userName"]'
15 changes: 15 additions & 0 deletions src/pages/input_form.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from playwright.sync_api import Page

from base_page import BasePage
from locators.input_locators import InputLocators
from utils.logger import log


class InputForm(BasePage):
def __init__(self, page: Page):
super().__init__(page)
self.locators = InputLocators()

def fill_full_name(self, name: str):
"""Fill user full name"""
self.fill(self.locators.FULL_NAME_SELECTOR, name)
36 changes: 19 additions & 17 deletions src/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,12 @@ def _create_log_file(self) -> str:
current_time = time.strftime("%Y-%m-%d")
log_directory = os.path.join(self.log_base_directory, "reports/logs")

os.makedirs(log_directory,
exist_ok=True) # Create directory if it doesn't exist
os.makedirs(log_directory, exist_ok=True) # Create directory if it doesn't exist

return os.path.join(log_directory, f"log_{current_time}.log")

def _initialize_logging(self, log_lvl: LogLevel, log_mode: str,
console_logging: bool) -> None:
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
def _initialize_logging(self, log_lvl: LogLevel, log_mode: str, console_logging: bool) -> None:
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# File handler
fh = logging.FileHandler(self.log_file, mode=log_mode)
Expand All @@ -67,10 +64,7 @@ def _initialize_logging(self, log_lvl: LogLevel, log_mode: str,
def get_instance(self) -> logging.Logger:
return self._log

def annotate(
self, message: str,
level: Literal["info", "warn", "debug", "error"] = "info"
) -> None:
def annotate(self, message: str, level: Literal["info", "warn", "debug", "error"] = "info") -> None:
"""Log a message at the specified level."""
log_methods = {
"info": self._log.info,
Expand All @@ -85,10 +79,7 @@ def annotate(
log_methods[level](message)


def log(
data: Optional[str] = None,
level: Literal["info", "warn", "debug", "error"] = "info",
) -> Callable:
def log(data: Optional[str] = None, level: Literal["info", "warn", "debug", "error"] = "info") -> Callable:
"""Decorator to log the current method's execution.
:param data: Custom log message to use if no docstring is provided.
Expand All @@ -109,10 +100,13 @@ def wrapper(self, *args, **kwargs) -> Any:
kwargs_str = ", ".join(f"{k}={v!r}" for k, v in kwargs.items())
all_params_str = ", ".join(filter(None, [params_str, kwargs_str]))

# Filter out unwanted <Locator> information
filtered_params_str = filter_locator_info(all_params_str)

logs = (
f"{method_docs + '.' if method_docs else data}"
f" Method :: {func.__name__}() "
f"with parameters: {all_params_str}"
f"{method_docs + '.' if method_docs else data} "
f"Method :: {func.__name__}() "
f"with parameters: {filtered_params_str}"
)

logger_instance.annotate(logs, level)
Expand All @@ -130,3 +124,11 @@ def format_method_doc_str(doc_str: Optional[str]) -> Optional[str]:
if doc_str and not doc_str.endswith("."):
return doc_str + "."
return doc_str


def filter_locator_info(param_str: str) -> str:
"""Filter out unwanted <Locator> details from the parameters string."""
# Example regex to filter out the specific Locator format, modify as needed
import re
filtered = re.sub(r"<Locator.*?>", "", param_str)
return filtered.strip()
15 changes: 15 additions & 0 deletions tests/test_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from pages.input_form import InputForm


class TestFillForm:

def test_fill_full_name(self, page):
"""Test filling in the full name in the input form."""
input_form = InputForm(page)

# Navigate to the input form page
input_form.navigate_to(
"https://demoqa.com/text-box")

# Fill in the full name
input_form.fill_full_name("John Doe")

0 comments on commit 9874e25

Please sign in to comment.