-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
307 lines (253 loc) · 11.4 KB
/
Copy pathconftest.py
File metadata and controls
307 lines (253 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
Shared pytest fixtures and hooks for the framework.
- Adds --browser and --headless CLI options.
- Provides a `driver` fixture that spins up Chrome, Firefox, or Edge
using MANUALLY INSTALLED driver binaries from the /drivers folder
(no webdriver-manager, no auto-download).
- Navigates to the application under test (APP_URL, below) as soon as
the browser is up, so individual test files never need to know the URL.
- On test failure, captures a screenshot and attaches it (plus the
page source) to the Allure report.
- With --send-email, sends a total/passed/failed summary email after
the run finishes - the same code path Jenkins uses.
"""
import os
import shutil
import subprocess
from datetime import datetime
import allure
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.edge.service import Service as EdgeService
from pages.title_page import TitlePage
from pages.checkbox.click_checkbox import ClickCheckbox
from pages.checkbox.checkbox_group import CheckboxGroup
from utils.email_report import build_summary, send_summary_email
from utils.logger import get_logger
logger = get_logger(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SCREENSHOT_DIR = os.path.join(BASE_DIR, "screenshots")
DRIVERS_DIR = os.path.join(BASE_DIR, "drivers")
ALLURE_RESULTS_DIR = os.path.join(BASE_DIR, "reports", "allure-results")
ALLURE_REPORT_DIR = os.path.join(BASE_DIR, "reports", "allure-report")
os.makedirs(SCREENSHOT_DIR, exist_ok=True)
# The single place the application URL is defined. Test files never
# reference it directly - the `driver` fixture below navigates here
# automatically before handing control to the test.
APP_URL = "https://seleniumbase.io/demo_page"
# Manually installed driver executables, expected in /drivers.
# See drivers/README.md for download links and exact filenames.
DRIVER_PATHS = {
"chrome": os.path.join(DRIVERS_DIR, "chromedriver.exe"),
"firefox": os.path.join(DRIVERS_DIR, "geckodriver.exe"),
"edge": os.path.join(DRIVERS_DIR, "msedgedriver.exe"),
}
# Optional: if a browser isn't installed in its default Windows location,
# set its binary path here (leave as None to use the system default).
BROWSER_BINARY_PATHS = {
"chrome": None,
"firefox": None,
"edge": None,
}
def pytest_addoption(parser):
parser.addoption(
"--browser",
action="store",
default="chrome",
choices=["chrome", "firefox", "edge"],
help="Browser to run tests against: chrome, firefox, or edge",
)
parser.addoption(
"--headless",
action="store_true",
default=False,
help="Run the browser in headless mode",
)
parser.addoption(
"--send-email",
action="store_true",
default=False,
help="Send a total/passed/failed summary email after the run finishes "
"(requires EMAIL_SENDER and EMAIL_PASSWORD environment variables)",
)
def _require_driver_binary(browser: str) -> str:
driver_path = DRIVER_PATHS[browser]
if not os.path.isfile(driver_path):
raise FileNotFoundError(
f"Driver binary for '{browser}' not found at: {driver_path}\n"
f"Download it manually and place it there. See drivers/README.md "
f"for the exact filename and download link."
)
return driver_path
def _build_driver(browser: str, headless: bool):
browser = browser.lower()
if browser == "chrome":
driver_path = _require_driver_binary("chrome")
options = webdriver.ChromeOptions()
if BROWSER_BINARY_PATHS["chrome"]:
options.binary_location = BROWSER_BINARY_PATHS["chrome"]
if headless:
options.add_argument("--headless=new")
options.add_argument("--start-maximized")
options.add_argument("--disable-notifications")
service = ChromeService(executable_path=driver_path)
driver = webdriver.Chrome(service=service, options=options)
elif browser == "firefox":
driver_path = _require_driver_binary("firefox")
options = webdriver.FirefoxOptions()
if BROWSER_BINARY_PATHS["firefox"]:
options.binary_location = BROWSER_BINARY_PATHS["firefox"]
if headless:
options.add_argument("-headless")
service = FirefoxService(executable_path=driver_path)
driver = webdriver.Firefox(service=service, options=options)
driver.maximize_window()
elif browser == "edge":
driver_path = _require_driver_binary("edge")
options = webdriver.EdgeOptions()
if BROWSER_BINARY_PATHS["edge"]:
options.binary_location = BROWSER_BINARY_PATHS["edge"]
if headless:
options.add_argument("--headless=new")
options.add_argument("--start-maximized")
service = EdgeService(executable_path=driver_path)
driver = webdriver.Edge(service=service, options=options)
else:
raise ValueError(f"Unsupported browser: {browser}")
return driver
@pytest.fixture(scope="function")
def driver(request):
"""Yields a WebDriver instance, already navigated to APP_URL."""
browser = request.config.getoption("--browser")
headless = request.config.getoption("--headless")
logger.info(f"Starting '{browser}' browser (headless={headless}) for test: {request.node.name}")
drv = _build_driver(browser, headless)
drv.implicitly_wait(5)
# Stash so the failure hook below can reach it even though fixtures
# aren't directly visible from pytest_runtest_makereport.
request.node._driver = drv
logger.info(f"Navigating to {APP_URL}")
drv.get(APP_URL)
yield drv
logger.info(f"Quitting browser for test: {request.node.name}")
drv.quit()
@pytest.fixture(scope="function")
def page(driver):
"""Generic Page Object factory - the scalable alternative to writing
one dedicated fixture per page in conftest.py.
Call it inside any test with the page class you want:
def test_something(page):
title = page(TitlePage)
title.get_title()
It builds the page object with the current `driver`, calls its
`wait_for_page_to_load()` if the page defines one, and caches the
instance per test so calling `page(TitlePage)` twice in the same
test returns the same object instead of rebuilding it.
Adding a 101st page to the site never requires touching this file -
just write pages/new_page.py and call page(NewPage) in the test.
"""
_cache = {}
def _get_page(page_class):
if page_class not in _cache:
logger.info(f"Building page object: {page_class.__name__}")
instance = page_class(driver)
wait_method = getattr(instance, "wait_for_page_to_load", None)
if callable(wait_method):
wait_method()
_cache[page_class] = instance
return _cache[page_class]
return _get_page
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
"""After each test phase, check the outcome; on failure during the
'call' phase, grab a screenshot and attach it (+ page source) to Allure."""
outcome = yield
report = outcome.get_result()
if report.when == "call" and report.failed:
drv = getattr(item, "_driver", None)
if drv is None:
return
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
safe_name = item.name.replace("[", "_").replace("]", "").replace("/", "_")
screenshot_path = os.path.join(SCREENSHOT_DIR, f"{safe_name}_{timestamp}.png")
try:
drv.save_screenshot(screenshot_path)
logger.error(f"Test FAILED: {item.name}. Screenshot saved to {screenshot_path}")
with open(screenshot_path, "rb") as image_file:
allure.attach(
image_file.read(),
name=f"screenshot_{safe_name}",
attachment_type=allure.attachment_type.PNG,
)
allure.attach(
drv.current_url,
name="failed_test_url",
attachment_type=allure.attachment_type.TEXT,
)
allure.attach(
drv.page_source,
name="page_source",
attachment_type=allure.attachment_type.HTML,
)
except Exception as exc:
logger.error(f"Could not capture failure artifacts for {item.name}: {exc}")
def pytest_sessionfinish(session, exitstatus):
"""After every test run, automatically build the Allure HTML report
from the raw results, so a fresh report is ready without a manual
`allure generate` step. Requires the Allure commandline tool on PATH
(used only to render the HTML - not to collect results, which
allure-pytest already writes to reports/allure-results)."""
alluredir = getattr(session.config.option, "allure_report_dir", None) or ALLURE_RESULTS_DIR
if not os.path.isdir(alluredir) or not os.listdir(alluredir):
logger.warning(f"No Allure results found in {alluredir}; skipping report generation.")
return
allure_cmd = shutil.which("allure")
if not allure_cmd:
logger.warning(
"Allure commandline tool not found on PATH - skipping HTML report generation. "
f"Raw results are still available in: {alluredir}. "
"Install it from https://allurereport.org/docs/install/ to enable this."
)
return
try:
result = subprocess.run(
[allure_cmd, "generate", alluredir, "-o", ALLURE_REPORT_DIR, "--clean"],
capture_output=True,
text=True,
)
if result.returncode == 0:
logger.info(f"Allure HTML report generated at: {ALLURE_REPORT_DIR}")
else:
logger.error(f"Allure report generation failed:\n{result.stderr}")
except Exception as exc:
logger.error(f"Unexpected error while generating the Allure report: {exc}")
def pytest_terminal_summary(terminalreporter, exitstatus, config):
"""After pytest prints its own terminal summary, optionally send a
total/passed/failed/percentage email. Runs only when --send-email is
passed - the same flag and the same code path whether that flag was
typed by a person locally or supplied by the Jenkinsfile."""
if not config.getoption("--send-email"):
return
passed = len(terminalreporter.stats.get("passed", []))
failed = len(terminalreporter.stats.get("failed", [])) + len(terminalreporter.stats.get("error", []))
skipped = len(terminalreporter.stats.get("skipped", []))
stats = build_summary(passed, failed, skipped)
logger.info(f"Test run summary: {stats}")
send_summary_email(stats)
# Retrieving a web page's title (pages/title_page.py).
@pytest.fixture(scope="function")
def title_page(page) -> TitlePage:
"""Convenience fixture wrapping page(TitlePage), kept for readability
in test signatures - see the `page` factory fixture above for why
this is optional rather than required for every new page."""
return page(TitlePage)
# Clicking single checkbox (pages/checkbox/click_checkbox.py)
@pytest.fixture(scope="function")
def checkbox(page) -> ClickCheckbox:
return page(ClickCheckbox)
# Clicking checkbox group (pages/checkbox/checkbox_group.py)
@pytest.fixture(scope="function")
def checkbox_group(page) -> CheckboxGroup:
return page(CheckboxGroup)