微軟自動化測試工具palywright
阿新 • • 發佈:2020-12-27
前言
我們介紹許多e2e的自動化測試工具
一類是基於 Selenium 的測試框架:
- robot framework
- gauge
- SeleniumBase
- seldom(我自己維護的)
另一類是基於JS語言的測試工具:
- cypress
- puppeteer
前都本身就是基於Selenium的自動化測試工具,後者在測試人員這個圈子也是未能撼動Selenium的地位,我認為有兩個原因,一是Selenium是一個非常成熟的自動化測試工具,有大量的學習資料;另一方面selenium支援Python,沒錯Python以其簡單的語法已經成為了測試人員學習程式語言的不二之選。
好了,介紹個新的自動化測試工具還要鋪墊這麼多?這是因為我看了palywright的文件之後,覺得這工具大概率能在測試人員這個群體中流行起來。
playwright 介紹
介紹
Playwright enables fast, reliable and capable automation across all modern browsers.
支援平臺&瀏覽器
Linux | macOS | Windows | |
---|---|---|---|
Chromium 89.0.4344.0 | ✅ | ✅ | ✅ |
WebKit 14.1 | ✅ | ✅ | ✅ |
Firefox 84.0b9 | ✅ | ✅ | ✅ |
支援語言
- JavaScript and TypeScript: https://github.com/microsoft/playwright
- Java: https://github.com/microsoft/playwright-java
- Python: https://github.com/microsoft/playwright-python
- C#: https://github.com/microsoft/playwright-sharp
從支援的平臺、語言和瀏覽器來看,是不是有Selenium的味道。這是微軟爸爸的專案,從微軟這幾年擁抱開源的態度來看,這個工具應該會得到持續的支援。
安裝
不同的語言安裝方式不同,根據上面的連結,到對應的專案下面檢視安裝方式。本文以Python為例。
安裝plywright
> pip install playwright
安裝瀏覽器
> python -m playwright install
Downloading chromium v827102 - 89.4 Mb [====================] 100% 0.0s
chromium v827102 downloaded to C:\Users\fnngj\AppData\Local\ms-playwright\chromium-827102
Downloading firefox v1205 - 74.9 Mb [====================] 100% 0.0s
firefox v1205 downloaded to C:\Users\fnngj\AppData\Local\ms-playwright\firefox-1205
Downloading webkit v1383 - 51.4 Mb [====================] 100% 0.0s
webkit v1383 downloaded to C:\Users\fnngj\AppData\Local\ms-playwright\webkit-1383
錄製指令碼
plywright可以在瀏覽器中記錄使用者的互動並生成程式碼。
執行命令
> python -m playwright codegen
視訊
接下來,對錄製的指令碼做簡單的修飾。
from time import sleep
from playwright import sync_playwright
def run(playwright):
pw = playwright().start()
browser = pw.chromium.launch(headless=False)
context = browser.newContext()
# Open new page
page = context.newPage()
# Go to https://www.baidu.com/
page.goto("https://www.baidu.com/")
# Fill input[name="wd"]
page.fill('input[name="wd"]', "playwright")
# Click input[type="submit"]
page.click('input[type="submit"]')
sleep(2)
# assert title
assert page.title() == "playwright_百度搜索"
# ---------------------
context.close()
browser.close()
if __name__ == '__main__':
run(sync_playwright)
從API來看,和大多數自動化工具都差不多。
非同步的寫法
playwright官方例子中給出的非同步的寫法。 從它提供的API sync_playwright
的命名也可以看出,它很喜歡非同步。
import asyncio
from playwright import async_playwright
async def main():
async with async_playwright() as p:
for browser_type in [p.chromium, p.firefox, p.webkit]:
browser = await browser_type.launch(headless=False)
page = await browser.newPage()
await page.goto('https://www.baidu.com')
await page.screenshot(path=f'example-{browser_type.name}.png')
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
後續:
- playwrigth 與其他自動化工具的比較
- playwright API介紹
- playwright 與單元測試框架unittest/pytest的使用