Best Python code snippet using playwright-python
Autotest03_001.py
Source: Autotest03_001.py
...47 if ACTIVE_LOCK == "ON":48 page.click("div[id=\"activity_locked\"] >> text=\"OK\"")49 # assert page.url == "https://localhost/workflow/activity/detail/A-20220203-00001?status="50 # Click text=/.*Click to select.*/51 with page.expect_file_chooser() as fc_info:52 page.click("text=/.*Click to select.*/")53 file_chooser = fc_info.value54 file_chooser.set_files("sample.pdf")55 page.screenshot(path=f'{"Autotest03_001_1"}_capture.png')56 # Click text="Start upload"57 page.click("text=\"Start upload\"")58 page.wait_for_timeout(int(SET_WAIT))59 page.screenshot(path=f'{"Autotest03_007_1"}_capture.png')60 # Click text=/.*Click to select.*/61 with page.expect_file_chooser() as fc_info:62 page.click("text=/.*Click to select.*/")63 file_chooser = fc_info.value64 file_chooser.set_files("sample.pptx")65 # Click text="Start upload"66 page.click("text=\"Start upload\"")67 page.wait_for_timeout(int(SET_WAIT))68 page.screenshot(path=f'{"Autotest03_009_1"}_capture.png')69 # Click text=/.*Click to select.*/70 with page.expect_file_chooser() as fc_info:71 page.click("text=/.*Click to select.*/")72 file_chooser = fc_info.value73 file_chooser.set_files("sample.docx")74 # Click text="Start upload"75 page.click("text=\"Start upload\"")76 page.wait_for_timeout(int(SET_WAIT))77 page.screenshot(path=f'{"Autotest03_011_1"}_capture.png')78 # Click text=/.*Click to select.*/79 with page.expect_file_chooser() as fc_info:80 page.click("text=/.*Click to select.*/")81 file_chooser = fc_info.value82 file_chooser.set_files("sample.xlsx")83 # Click text="Start upload"84 page.click("text=\"Start upload\"")85 page.wait_for_timeout(int(SET_WAIT))86 page.screenshot(path=f'{"Autotest03_013_1"}_capture.png')87 # Click text=/.*Click to select.*/88 with page.expect_file_chooser() as fc_info:89 page.click("text=/.*Click to select.*/")90 file_chooser = fc_info.value91 file_chooser.set_files("sample.txt")92 # Click text="Start upload"93 page.click("text=\"Start upload\"")94 page.wait_for_timeout(int(SET_WAIT))95 page.screenshot(path=f'{"Autotest03_015_1"}_capture.png')96 # Click text=/.*Click to select.*/97 with page.expect_file_chooser() as fc_info:98 page.click("text=/.*Click to select.*/")99 file_chooser = fc_info.value100 file_chooser.set_files("sample.mpeg")101 # Click text="Start upload"102 page.click("text=\"Start upload\"")103 page.wait_for_timeout(int(SET_WAIT))104 page.screenshot(path=f'{"Autotest03_017_1"}_capture.png')105 # Click text=/.*Click to select.*/106 with page.expect_file_chooser() as fc_info:107 page.click("text=/.*Click to select.*/")108 file_chooser = fc_info.value109 file_chooser.set_files("sample.swf")110 # Click text="Start upload"111 page.click("text=\"Start upload\"")112 page.wait_for_timeout(int(SET_WAIT))113 page.screenshot(path=f'{"Autotest03_019_1"}_capture.png')114 # Click text=/.*Click to select.*/115 with page.expect_file_chooser() as fc_info:116 page.click("text=/.*Click to select.*/")117 file_chooser = fc_info.value118 file_chooser.set_files("sample.mp3")119 # Click text="Start upload"120 page.click("text=\"Start upload\"")121 page.wait_for_timeout(int(SET_WAIT))122 page.screenshot(path=f'{"Autotest03_021_1"}_capture.png')123 # Click text=/.*Click to select.*/124 with page.expect_file_chooser() as fc_info:125 page.click("text=/.*Click to select.*/")126 file_chooser = fc_info.value127 file_chooser.set_files("sample.png")128 # Click text="Start upload"129 page.click("text=\"Start upload\"")130 page.wait_for_timeout(int(SET_WAIT))131 page.screenshot(path=f'{"Autotest03_023_1"}_capture.png')132 133 # Click text=/.*Click to select.*/134 with page.expect_file_chooser() as fc_info:135 page.click("text=/.*Click to select.*/")136 file_chooser = fc_info.value137 file_chooser.set_files("sample.png")138 page.wait_for_timeout(int(SET_WAIT))139 page.screenshot(path=f'{"Autotest03_024_1"}_capture.png')140 # Click div[id="step_page"] div[role="document"] >> text=/.*Cancel.*/141 page.click("div[id=\"step_page\"] div[role=\"document\"] >> text=/.*Cancel.*/")142 # Click //tr[normalize-space(.)='sample.png ... 28 Kb 100 % Processing... Error ']/td[4]/a/i143 page.click('//*[@id="file_upload"]/div/invenio-files-list/div/table/tbody/tr[2]/td[4]/a/i')144 #//*[@id="file_upload"]/div/invenio-files-list/div/table/tbody/tr[2]145 page.wait_for_timeout(int(SET_WAIT))146 page.screenshot(path=f'{"Autotest03_025_1"}_capture.png')147 # Click input[name="pubdate"]148 page.click("input[name=\"pubdate\"]")...
test_input.py
Source: test_input.py
...65 file_chooser = await fc_done66 assert file_chooser67async def test_should_work_when_file_input_is_attached_to_dom(page: Page):68 await page.set_content("<input type=file>")69 async with page.expect_file_chooser() as fc_info:70 await page.click("input")71 file_chooser = await fc_info.value72 assert file_chooser73async def test_should_work_when_file_input_is_not_attached_to_DOM(page):74 async with page.expect_file_chooser() as fc_info:75 await page.evaluate(76 """() => {77 el = document.createElement('input')78 el.type = 'file'79 el.click()80 }"""81 )82 file_chooser = await fc_info.value83 assert file_chooser84async def test_should_return_the_same_file_chooser_when_there_are_many_watchdogs_simultaneously(85 page: Page,86):87 await page.set_content("<input type=file>")88 results = await asyncio.gather(89 page.wait_for_event("filechooser"),90 page.wait_for_event("filechooser"),91 page.eval_on_selector("input", "input => input.click()"),92 )93 assert results[0] == results[1]94async def test_should_accept_single_file(page: Page):95 await page.set_content('<input type=file oninput="javascript:console.timeStamp()">')96 async with page.expect_file_chooser() as fc_info:97 await page.click("input")98 file_chooser = await fc_info.value99 assert file_chooser.page == page100 assert file_chooser.element101 await file_chooser.set_files(FILE_TO_UPLOAD)102 assert await page.eval_on_selector("input", "input => input.files.length") == 1103 assert (104 await page.eval_on_selector("input", "input => input.files[0].name")105 == "file-to-upload.txt"106 )107async def test_should_be_able_to_read_selected_file(page: Page):108 page.once(109 "filechooser", lambda file_chooser: file_chooser.set_files(FILE_TO_UPLOAD)110 )111 await page.set_content("<input type=file>")112 content = await page.eval_on_selector(113 "input",114 """async picker => {115 picker.click();116 await new Promise(x => picker.oninput = x);117 const reader = new FileReader();118 const promise = new Promise(fulfill => reader.onload = fulfill);119 reader.readAsText(picker.files[0]);120 return promise.then(() => reader.result);121 }""",122 )123 assert content == "contents of the file\n"124async def test_should_be_able_to_reset_selected_files_with_empty_file_list(125 page: Page, server126):127 await page.set_content("<input type=file>")128 page.once(129 "filechooser", lambda file_chooser: file_chooser.set_files(FILE_TO_UPLOAD)130 )131 file_length = 0132 async with page.expect_file_chooser():133 file_length = await page.eval_on_selector(134 "input",135 """async picker => {136 picker.click();137 await new Promise(x => picker.oninput = x);138 return picker.files.length;139 }""",140 )141 assert file_length == 1142 page.once("filechooser", lambda file_chooser: file_chooser.set_files([]))143 async with page.expect_file_chooser():144 file_length = await page.eval_on_selector(145 "input",146 """async picker => {147 picker.click();148 await new Promise(x => picker.oninput = x);149 return picker.files.length;150 }""",151 )152 assert file_length == 0153async def test_should_not_accept_multiple_files_for_single_file_input(154 page, server, assetdir155):156 await page.set_content("<input type=file>")157 async with page.expect_file_chooser() as fc_info:158 await page.click("input")159 file_chooser = await fc_info.value160 with pytest.raises(Exception) as exc_info:161 await file_chooser.set_files(162 [163 os.path.realpath(assetdir / "file-to-upload.txt"),164 os.path.realpath(assetdir / "pptr.png"),165 ]166 )167 assert exc_info.value168async def test_should_emit_input_and_change_events(page):169 events = []170 await page.expose_function("eventHandled", lambda e: events.append(e))171 await page.set_content(172 """173 <input id=input type=file></input>174 <script>175 input.addEventListener('input', e => eventHandled({ type: e.type }))176 input.addEventListener('change', e => eventHandled({ type: e.type }))177 </script>178 """179 )180 await (await page.query_selector("input")).set_input_files(FILE_TO_UPLOAD)181 assert len(events) == 2182 assert events[0]["type"] == "input"183 assert events[1]["type"] == "change"184async def test_should_work_for_single_file_pick(page):185 await page.set_content("<input type=file>")186 async with page.expect_file_chooser() as fc_info:187 await page.click("input")188 file_chooser = await fc_info.value189 assert file_chooser.is_multiple() is False190async def test_should_work_for_multiple(page):191 await page.set_content("<input multiple type=file>")192 async with page.expect_file_chooser() as fc_info:193 await page.click("input")194 file_chooser = await fc_info.value195 assert file_chooser.is_multiple()196async def test_should_work_for_webkitdirectory(page):197 await page.set_content("<input multiple webkitdirectory type=file>")198 async with page.expect_file_chooser() as fc_info:199 await page.click("input")200 file_chooser = await fc_info.value...
Autotest05_182.py
Source: Autotest05_182.py
...49 # assert page.url == "https://localhost/workflow/activity/detail/A-20220203-00001?status="50 page.wait_for_timeout(int(SET_WAIT))51 page.screenshot(path=f'{path.splitext(path.basename(__file__))[0]+"_1"}_capture.png')52 # Click text=/.*Click to select.*/53 with page.expect_file_chooser() as fc_info:54 page.click("text=/.*Click to select.*/")55 file_chooser = fc_info.value56 file_chooser.set_files("sample.md")57 # Click text="Start upload"58 page.click("text=\"Start upload\"")59 page.wait_for_timeout(int(SET_WAIT))60 page.screenshot(path=f'{"Autotest05_213_1"}_capture.png')61 # Click text=/.*Click to select.*/62 with page.expect_file_chooser() as fc_info:63 page.click("text=/.*Click to select.*/")64 file_chooser = fc_info.value65 file_chooser.set_files("sample.json")66 # Click text="Start upload"67 page.click("text=\"Start upload\"")68 page.wait_for_timeout(int(SET_WAIT))69 page.screenshot(path=f'{"Autotest05_214_1"}_capture.png')70 # Click text=/.*Click to select.*/71 with page.expect_file_chooser() as fc_info:72 page.click("text=/.*Click to select.*/")73 file_chooser = fc_info.value74 file_chooser.set_files("sample.xmll")75 # Click text="Start upload"76 page.click("text=\"Start upload\"")77 page.wait_for_timeout(int(SET_WAIT))78 page.screenshot(path=f'{"Autotest05_215_1"}_capture.png')79 # Click text=/.*Click to select.*/80 with page.expect_file_chooser() as fc_info:81 page.click("text=/.*Click to select.*/")82 file_chooser = fc_info.value83 file_chooser.set_files("sample.csv")84 # Click text="Start upload"85 page.click("text=\"Start upload\"")86 page.wait_for_timeout(int(SET_WAIT))87 page.screenshot(path=f'{"Autotest05_216_1"}_capture.png')88 # Click text=/.*Click to select.*/89 with page.expect_file_chooser() as fc_info:90 page.click("text=/.*Click to select.*/")91 file_chooser = fc_info.value92 file_chooser.set_files("sample.pdf")93 # Click text="Start upload"94 page.click("text=\"Start upload\"")95 page.wait_for_timeout(int(SET_WAIT))96 page.screenshot(path=f'{"Autotest05_217_1"}_capture.png')97 # Click text=/.*Click to select.*/98 with page.expect_file_chooser() as fc_info:99 page.click("text=/.*Click to select.*/")100 file_chooser = fc_info.value101 file_chooser.set_files("sample.png")102 # Click text="Start upload"103 page.click("text=\"Start upload\"")104 page.wait_for_timeout(int(SET_WAIT))105 page.screenshot(path=f'{"Autotest05_218_1"}_capture.png')106 # Click text=/.*Click to select.*/107 with page.expect_file_chooser() as fc_info:108 page.click("text=/.*Click to select.*/")109 file_chooser = fc_info.value110 file_chooser.set_files("sample.jpg")111 # Click text="Start upload"112 page.click("text=\"Start upload\"")113 page.wait_for_timeout(int(SET_WAIT))114 page.screenshot(path=f'{"Autotest05_219_1"}_capture.png')115 # Close page116 page.close()117 # ---------------------118 context.close()119 browser.close()120 return 0121def test_OK():...
create.py
Source: create.py
...28 def upload_heatmap_picture(self):29 # çåå¾å¾çä¸ä¼ 30 self.heatmap_field().click()31 if self.heatmap_upload_field().is_visible():32 with self.page.expect_file_chooser() as fc_info:33 self.heatmap_upload_field().click()34 file_chooser = fc_info.value35 generate_pic() # çæä¸å¼ 临æ¶å¾ç36 file_chooser.set_files(G.TMP_PIC_PATH)37 time.sleep(1.5)38 else:39 self.upload_heatmap_picture()40 @allure.step('Click create empty field')41 def create_empty(self, title):42 self.create_empty_field().click()43 self.empty_text_filed().should_be_visible()44 self.empty_text_filed().click()45 self.pop_up_filed().should_be_visible()46 if title:47 self.input_name_field().val(title)48 self.create_button_field().click()49 self.tab_questions().should_be_visible()50 G.SURVEY_ID = self.page.url.split('surveyId=')[1]51 return self52 @allure.step('Add the all of basic questions')53 def add_basic_questions(self):54 items = self.ques_basic_items()55 for item in items.elements:56 item.click()57 time.sleep(0.3)58 @allure.step('Add the all of advanced questions')59 def add_advanced_questions(self):60 items = self.ques_advanced_items()61 for item in items.elements:62 item.click()63 time.sleep(0.3)64 def add_all_ques(self):65 self.add_basic_questions()66 self.add_advanced_questions()67 @allure.step('Add the single choice item')68 def add_single_option(self):69 self.add_identify_filed().click()70 @allure.step('Add the identify item')71 def add_identify(self): # çå«é¢72 self.add_identify_filed().click()73 """the editor field"""74 def cascade_txt(self):75 return el(self.page, selector='text=级èé¢')76 def survey_total(self):77 """æ£æ¥æ»é¢æ¯å¦æ£ç¡®"""78 return el(self.page, selector=f'text={G.QUESTION_TOTAL}.')79 80 81 @allure.step('Add the cascade item with uploading')82 def upload_item_cascade(self):83 # click preview and show cascade_upload84 self.cascade_preview_field().click()85 with self.page.expect_file_chooser() as fc_info:86 self.cascade_upload_field().click()87 file_chooser = fc_info.value88 file_chooser.set_files(G.CASCADE_TEMPLATE)89 time.sleep(1)90 """survey setting"""91 @allure.step('Set aim total number')92 def set_aim_total(self):93 self.aim_total_field()94 self.aim_total_field().val(random_str())95 timeout = 096 while self.plan_number_msg_field().is_visible():97 self.aim_total_field().val(random_str())98 timeout += 199 time.sleep(1)...
Why are the values yielded by a pytest fixture and a function called directly different?
Playwright - Checking Class Name of an Element
Playwright page.wait_for_event function how to access the page and other variables from inside the callable?
Python Selenium Actions into Playwirght
How to make Playwright not to raise exceptions when the browser is closed
TikTokApi Problem with Selenium (width) on Colab
Playwright Python - Tab Link Not Visible
Is there a way to return response body in Playwright?
How can I download an embeded PDF with PlayWright (python)?
How to get playwright working on a docker container and deploy it to AWS Lambda
For the 1st form:
def get_playwright():
with sync_playwright() as playwright:
yield playwright
print(get_playwright()) # <generator object get_playwright at 0x108aac580>
That is expected because get_playwright
is a generator, which returns a generator iterator, which you have to call next(...)
on to get each yielded value from the iterator.
Consider a simpler, non-playwright example:
In [14]: def generate_nums():
...: for num in range(10):
...: yield num
...:
In [15]: nums = generate_nums()
In [16]: nums
Out[16]: <generator object generate_nums at 0x11115e6d0>
In [17]: next(nums)
Out[17]: 0
In [18]: next(nums)
Out[18]: 1
In [19]: next(nums)
Out[19]: 2
For more examples, see Understanding generators in Python.
Since your get_playwright
returns an iterator, you need to call next()
once to get the actual object:
from playwright.sync_api import sync_playwright
def get_playwright():
with sync_playwright() as playwright:
yield playwright
playwright_generator = get_playwright()
print(playwright_generator) # <generator object get_playwright at 0x104031580>
playwright = next(playwright_generator)
print(playwright) # <playwright._impl._playwright.Playwright object at 0x1041aabb0>
For the 2nd form:
@pytest.fixture()
def get_playwright():
with sync_playwright() as playwright:
yield playwright
def test(get_playwright):
print(get_playwright)
It should be the same case, but it's just that pytest automatically calls next()
on the fixture value if it's a generator. I could not find documentation for this behavior from the pytest docs, but it was mentioned by one of the pytest author's/maintainer's in a different answer:
Here's roughly the execution here
- pytest notices your fixture is used for the test function
- pytest calls the fixture function
- since it is a generator, it returns immediately without executing code
- pytest notices it is a generator, calls
next(...)
on it
- this causes the code to execute until the
yield
and then "pausing". you can think of it kind of as a co-routine ...- pytest then executes your test function
...which is probably why the value passed to your test function is already the next
-ed value, the playwright object.
Check out the latest blogs from LambdaTest on this topic:
Web applications continue to evolve at an unbelievable pace, and the architecture surrounding web apps get more complicated all of the time. With the growth in complexity of the web application and the development process, web application testing also needs to keep pace with the ever-changing demands.
Open MCT is a next-generation mission control framework for data visualization on desktop and mobile devices. It was created at NASA’s Ames Research Center, and NASA uses it to analyze spacecraft mission data.
The web development industry is growing, and many Best Automated UI Testing Tools are available to test your web-based project to ensure it is bug-free and easily accessible for every user. These tools help you test your web project and make it fully compatible with user-end requirements and needs.
The sky’s the limit (and even beyond that) when you want to run test automation. Technology has developed so much that you can reduce time and stay more productive than you used to 10 years ago. You needn’t put up with the limitations brought to you by Selenium if that’s your go-to automation testing tool. Instead, you can pick from various test automation frameworks and tools to write effective test cases and run them successfully.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!