import pytest import allure from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager @pytest.fixture(scope="function") def driver(): """ Initializes and returns a Chrome WebDriver instance for each test function. Automatically quits the driver after the test function completes. """ # Initialize the Chrome WebDriver driver = webdriver.Chrome() # Maximize the browser window driver.maximize_window() # Yield the driver instance to the test function yield driver # Quit the driver after the test is done driver.quit() @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): """ Hook to capture test results and attach screenshots on failure. """ # Execute all other hooks to obtain the report object outcome = yield report = outcome.get_result() # Check if the test failed if report.when == "call" and report.failed: try: # Get the driver instance from the test item driver = item.funcargs["driver"] # Define the path for the screenshot screenshot_path = f"reports/screenshots/{item.name}.png" # Save the screenshot driver.save_screenshot(screenshot_path) # Attach the screenshot to the Allure report allure.attach.file(screenshot_path, name="Screenshot", attachment_type=allure.attachment_type.PNG) except Exception as e: print(f"Failed to capture screenshot: {e}")