selenium_automation_project/tests/conftest.py

58 lines
2.1 KiB
Python

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.
"""
# Configure Chrome options to disable the password manager and related pop-ups
chrome_options = webdriver.ChromeOptions()
prefs = {
"credentials_enable_service": False,
"profile.password_manager_enabled": False
}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
# Initialize the Chrome WebDriver with the specified options
driver = webdriver.Chrome(options=chrome_options)
# 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}")