-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscratch.txt
More file actions
553 lines (400 loc) · 15.8 KB
/
scratch.txt
File metadata and controls
553 lines (400 loc) · 15.8 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# ✅ **Playwright Framework Setup and Best Practices**
## 🛠️ Installation Commands
Test too fast slowdown using slow_mo = 500
```bash
# Install Pytest and Playwright
pip install pytest-playwright
# Install Playwright browsers (Chromium, Firefox, WebKit)
playwright install
# Install Allure for reporting
pip install allure-pytest
🧱 Project Folder Structure
bash
Copy code
playwright_framework/
│
├── tests/
│ └── test_search_thar.py # Your test scripts
│
├── utils/
│ ├── logger.py # Custom logger utility
│ └── screenshot.py # Screenshot capture utility
│
├── conftest.py # Global fixtures and hooks
├── pytest.ini # Pytest configuration
├── requirements.txt # Pinned dependencies
└── README.md # Project documentation (optional but recommended)
💡 Key Concepts Explained
✅ Playwright Test Execution
bash
Copy code
pytest # Run all tests
pytest -v # Verbose output
pytest -s # Show print/log output
pytest -m smoke # Run tests marked with @pytest.mark.smoke
pytest tests/test_file.py # Run a specific test file
✅ Allure Reporting
bash
Copy code
pytest --alluredir=reports/allure-results # Generate raw allure results
allure serve reports/allure-results # Open HTML report in browser
✅ Capturing Requirements
To freeze your environment:
bash
Copy code
pip freeze > requirements.txt
To install from requirements:
bash
Copy code
pip install -r requirements.txt
🧪 Pytest Core Concepts
✅ Writing a Test
python
Copy code
def test_example():
assert 1 + 1 == 2
✅ Using Fixtures
Fixtures allow reusable setup/teardown logic.
python
Copy code
import pytest
@pytest.fixture
def setup_env():
print("Setup logic here")
yield
print("Teardown logic here")
def test_using_fixture(setup_env):
print("Test logic here")
The yield statement separates setup and teardown.
Fixture scope can be: function, class, module, or session.
Example:
python
Copy code
@pytest.fixture(scope="module")
def db_connection():
print("Opening DB connection")
yield
print("Closing DB connection")
🧰 Pytest Fixture Scoping
Scope Behavior
function Runs before each test function
class Runs once per test class
module Runs once per test file
session Runs once per test session
✅ Test Markers
python
Copy code
@pytest.mark.smoke
def test_login():
...
To skip a test:
python
Copy code
@pytest.mark.skip(reason="Under development")
def test_payment():
...
Run specific marker:
bash
Copy code
pytest -m smoke
🔁 Conftest.py
Global fixtures go in conftest.py.
Tests will automatically look for fixtures in this file.
Example:
python
Copy code
# conftest.py
@pytest.fixture
def browser_context():
...
🌐 Playwright Core Concepts (Python)
✅ Launch Browser (Manual)
python
Copy code
from playwright.sync_api import sync_playwright
def test_browser_control():
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com")
browser.close()
✅ Headless vs Headed
headless=True → browser runs without UI (default in CI).
headless=False → useful for local debugging.
✅ Using Built-in page Fixture
Playwright provides its own page fixture if you don't need custom setup:
python
Copy code
from playwright.sync_api import Page
def test_google(page: Page):
page.goto("https://google.com")
assert "Google" in page.title()
But:
It always runs headless
Always uses Chromium
So if you want:
headless=False
Fullscreen window
Custom browser (e.g., Firefox, WebKit)
👉 You must define your own fixture using sync_playwright().
✅ Browser Context = Incognito Mode
Every call to new_context() creates a separate, isolated browser session:
python
Copy code
context1 = browser.new_context()
context2 = browser.new_context()
They don't share cookies, localStorage, sessions, etc.
🎯 Launching in Fullscreen (like Selenium maximize)
Playwright does not have a .maximize_window() like Selenium, but you can mimic it by:
python
Copy code
browser = p.chromium.launch(headless=False, args=["--start-fullscreen"])
context = browser.new_context(viewport={'width': 1920, 'height': 1080})
✅ Tip: Always pass integers, not strings, to viewport.
🧰 Debugging Tools
✅ Playwright Inspector
Record and debug interactions visually:
bash
Copy code
playwright codegen https://demo.playwright.dev/todomvc
✅ Tracing
Capture a trace (screenshots, network, DOM snapshots):
bash
Copy code
pytest --tracing=on
Then open the trace viewer:
bash
Copy code
playwright show-trace trace.zip
❌ Limitations
Playwright does not support native Android/iOS apps (unlike Appium).
Codegen is great for fast start but:
❌ Does not auto-generate assertions
❌ Does not handle assertion logic
⚠️ Best used for learning selectors, not production tests.
🎯 Advanced Locators
✅ Aria Locators
Playwright supports accessibility-first locators:
python
Copy code
page.get_by_role("button", name="Submit")
page.get_by_label("Email")
More stable than raw CSS or XPath.
🔄 BDD vs TDD in Playwright
TDD BDD
Write tests before code Write behavior specs before tests
Tests for developers Specs for business + devs
Example: assert page.title() Example: Given-When-Then syntax
Tools: pytest Tools: behave, pytest-bdd
✅ Final Summary: Pro-Level Playwright Tips
🔄 Use viewport={'width': 1920, 'height': 1080} for fullscreen-like behavior.
📁 Keep conftest.py for global reusable fixtures.
📷 Integrate Allure for beautiful reports.
🧪 Use pytest.mark to categorize and filter tests.
🧰 Use codegen for quick prototyping, not real tests.
🔥 Master tracing, locators, and context management.
💬 Use BDD if your team includes non-technical stakeholders.
The Problem:
Strict Mode: Playwright is in strict mode, which means it expects that locators should resolve to a single element. If a locator resolves to more than one element, Playwright will throw this error to avoid ambiguity.
Use nth() to Specify the Element:
If there are multiple elements with the same label, you can specify which one you want to interact with by using the nth() function, which allows you to select the nth occurrence of an element.
For example, if the second "Password" field is the one you want to interact with, you can use:
page.locator('label:has-text("Password")').nth(1).click()
This will click on the second element with the label "Password".
page.locator('#password')
page.locator('button[tabindex="2"]').click()
pytest Hook:
- pytest_runtest_makereport:
This hook is triggered after a test is executed. It provides details about the test execution, including whether it passed or failed.
result.when == "call": This ensures that the hook only runs after the actual test code (not before or after hooks).
result.failed: Checks if the test has failed.
Capturing Screenshot:
If the test fails, the capture_screenshot function is called to save a screenshot of the current state of the browser.
The screenshot is saved locally and the path to the screenshot is logged.
Attaching Screenshot in Allure Report:
The page.screenshot() method captures the current page view and attaches it to the Allure report as a PNG file.
Attaching Logs to Allure:
Additionally, a reference to the log file (path) is attached to the Allure report, which can be useful for debugging.
pytest --mybrowser=firefox --headless=True
playwright.chromium.launch() launches browser,new_context() creates incognito session
to assert uses expect() with to_be_visible(),to_have_text(),to_have_url() etc..
global timeout is 10 either it wait samrtly till emement visible and if find early gets done
its to fast it doesnt wait sometimes we can use wait_for_timeout(2000) 2 sec OR use
Assertion andvalidation
we have filled wrong email we need to get alert visible or not -
we can use page.get_by_text("message").is_visible()
we nned to either this was visible or not we expect it to be true or false or visible
Use expect() from playwright.sync_api import expect ,
expect(page.get_by_text("message")).to_be_visible() or .not_to_be_visible()
base will by deafault runs chromium in headless mode but if ant tot run in frirefox need to ue Playwright
by creating objecy of it (playwright : Playwright) and then use playwright.firefox.launch(headless=False)
and importing from playwright.sync_api import Playwright,expect,page
firefox = playwright.firefox
browser = firefox.launch(headless=False)
page = firefox.new_page() Note for single page we can skip using context
in playwright there imp method called get_by_role() asking to identify role based components
combobox having 3 feilds then we will use .select_option(value="option1")
Identify locator for playwright
label - has-text("Password")
when ever identifying lable we need to make sure it have lable attribute or tag and
if we want to do fill it should have Input tag in it so we can use .fill() method
input not wrapped in label tag but id=username relates to for=username is present
<label> for=Password</label>
<br>
<input type="password" id="password" name="password">
input wrapped in label tag
<label>password <input type="password"/></label> # valid
page.get_by_role("button", name="Sign in").click()
we passing another check there will be multiple button on page
Anchor tag - a - have link in href link and there will all anchor tag
have role link to identify uniqque link ,try getting it from name attribute for
exaple click here to open pdf
checkbox using css selector - to use we will use locator method
page.locator('input[type="checkbox"]').check() # to check
page.locator('input[type="checkbox"]').uncheck() # to uncheck
if ID is present #id
if class name present .classname
if name attribute present [name="name"]
if href present [href="link"]
You can use XPath selectors directly in Playwright using:
📌 Syntax:
page.locator('//your/xpath/here')
Dynamic writting
Scenario
Xpath //div[@data-cy='title-recipe']/a/h2/span
titles = page.locator('[data-cy="title-recipe"]')
# Find the specific one
target = titles.filter(has_text="Apple iPhone 15 (128 GB) - Blue")
for i in range(titles.count()):
print(await titles.nth(i).inner_text())
we nned to click and assert or print atext from new opened page
we will use expect_popup() method
Event method like with page.expect_popup() know as closer to handle new tab or window
with page.expect_popup() as popup_info:
as popup_info: - collecting that popu p infor in element
new_page = popup_info.value - new_page will be child page where we can perform action as new page
new_page.wait_for_load_state()
new_page.goto("https://example.com")
# Wait for the new page to load
new_page.wait_for_load_state()
store text content in variable
text_content = page.locator('selector').text_content()
assert aactual and expected
assert text_content == "Expected Text" core pytest assertation
,split"" ,.strip() ,replace(" ","") - to remove space
get_by_placeholder("Search recipes...").fill("apple")
handel alert by trigriing java script event
lambda help to write anaonamys function
page.on("dialog", lambda dialog: dialog.accept()) type of event like dialog box,
how to handel it that need to be delacalered like dialog.accept() or dismiss()
Handel frames
frae are another html code embedded in main html page
frame = page.frame(name="frame_name") or by url or by locator
frame = page.frame(url="frame_url")
frame = page.frame_locator("iframe_selector")
frame.locator("selector_inside_frame").click()
handel Web tables
hover using .hover()
page.locator("selector").hover()
Playwright codegen
playwright codegen https://example.com
pytest-xdist to run parallel test pip install pytest-xdist
pytest -n 3 # Run tests in parallel using 3 CPU cores or pytest -n auto to auto detect
smoke tag and use pytest -m smoke to run only smoke tests
installing pytest-html
pip install pytest-html
pytest --html=report.html --self-contained-html
pytest -n auto --html=report.html --self-contained-html
--self-contained-html to embed CSS in HTML file
Playwright Test viewer
# ✅ Generate Trace headless mode only
pytest -s -v Testcases/test_login.py --mybrowser=chromium --headless --alluredir=reports/allure-results --tracing on
# Parallel test execution
pytest -n 3 -s -v Testcases/test_base.py --mybrowser=chromium --headless --alluredir=reports/allure-results
# with Trace
pytest -n auto -s -v --mybrowser=chromium --headless --alluredir=reports/allure-results --tracing on
# Trace viewer-paralell test execution with HTml report
pytest -s -v -n auto --mybrowser=chromium --headless --html=report.html --tracing on
# View Trace
# After running tests with tracing enabled, you can view the trace files in the 'trace' directory.
# Open the trace viewer using the following command:
playwright show-trace trace/trace.zip
playwright show-trace traces/test_search_iphone.zip
Can ue claude ai and inastall locally and then use plugin in IDE
npm install -g @anthropic-ai/claude-code
MCP serverin in local system or vs code
using Windsurf plugin from codieum name cascade
2m ago
hi can you read my project structre and code
I'll help you explore your project structure and code. Let's start by listing the contents of your project directory.
Analyzed
c:/Users/lakshya757/Desktop/playwright_framework
Let me explore the key files and directories to better understand your Playwright test automation framework. I'll start by checking the
requirements.txt
file to see the project dependencies.
Let's explore the test cases to understand what's being tested. I'll check the Testcases directory:
Analyzed
Testcases
Let's take a look at the
test_login.py
file to understand the test cases better:
Let's also check the PageObject directory to understand the page object model structure:
Analyzed
PageObject
Let's take a look at the
LoginPage.py
file to understand the page object implementation:
I've analyzed your Playwright test automation framework. Here's a summary of your project structure and key components:
Project Structure
Base/: Contains base classes and configurations
PageObject/: Implements the Page Object Model (POM) pattern
Testcases/: Contains test scripts
Utilities/: Houses utility functions and helpers
reports/: Stores test execution reports
screenshots/: For storing test execution screenshots
traces/: Contains Playwright trace files
Key Dependencies
Playwright: For browser automation
Pytest: Test framework
Pytest-html: HTML test reports
Allure-pytest: For advanced test reporting
Other utilities: For logging, test data handling, etc.
Test Implementation
Page Object Model (POM):
LoginPage.py
implements login functionality with proper locators and methods
Uses a base page class for common functionality
Includes proper logging and error handling
Test Cases:
test_login.py
: Tests login functionality with parameterized test data
test_amazon.py
: Likely contains Amazon-specific tests
test_api.py
: For API testing
test_search_thar.py
: Appears to be a specific search test case
Configuration:
Uses a config.json file for test data and environment configuration
Supports different environments (dev, staging, etc.)
Reporting:
Generates HTML reports
Includes screenshots for failed tests
Supports Allure reporting
Utilities:
Custom logging implementation
Helper functions for common operations
Observations
Well-structured framework following best practices
Good separation of concerns (test logic, page objects, utilities)
Includes proper error handling and logging
Supports both UI and API testing
Uses environment-specific configurations
Would you like me to explore any specific part of the codebase in more detail? For example:
The base page implementation
Test data structure
API testing implementation
Reporting configuration
Any specific test case
Feedback submitted. Thank you!