Senior
import random from time import sleep from playwright.sync_api import sync_playwright def test_1(): wait = 12 browser = sync_playwright().start().chromium.launch(headless=False) page = browser.new_page() def handle_route(route): route.fulfill( status=200, content_type="application/json", json={"symbols": [{"symbol": "SPY", "description": "test purposes"}]} ) page.route("**/symbol_search/**", handle_route) page.goto("[link] sleep(wait) l = page.locator("//*[ @id='header-toolbar-symbol-search']/div") l.click() sleep(3) tickers = ["AAPL", "BTCUSD", "TSLA", "NVDA"] symbol = random.choice(tickers) page.get_by_placeholder("Search").fill(symbol) page.keyboard.press("Enter") return page def test_2(): page = test_1() sleep(5) page.locator("//*[ @id='header-toolbar-user-menu']/div[2]/div/div[2]/div[1]/div/div[3]/button").click() page.locator("//span[contains(text(), 'Sign in')]") sleep(7) page.locator("//span[contains(text(), 'Sign in')]").click()
sobes.tech AI
Answer from AI
The provided code uses Playwright for browser automation with a synchronous API. Key points:
- A Chromium browser is launched in UI mode (headless=False).
- Request interception is set up for URLs matching
**/symbol_search/**, returning a mock JSON with a single symbol "SPY". - A page is opened at the specified URL (in the code
[link]— replace with the actual URL). - After waiting, an element with a XPath locator is clicked, then a random ticker from a list is entered into the "Search" placeholder field, and Enter is pressed.
The second function test_2 calls test_1, waits, then clicks on user menu items, including the "Sign in" button.
Using route in Playwright allows mocking server responses for UI testing without a real backend. This is useful for isolating tests and controlling data.
To improve the code:
- Use Playwright's
page.wait_for_selectorinstead ofsleepfor reliability. - Replace XPath locators with more stable selectors.
Example of replacing sleep with wait:
page.locator("//*[ @id='header-toolbar-symbol-search']/div").click()
page.wait_for_selector("input[placeholder='Search']")
This will increase test stability.