這是關於playwright系列介紹的最後一篇。搭建基於 playwright 的自動化項目。html
GitHub地址: https://github.com/defnngj/playwright-pronode
關鍵技術:python
非關鍵技術:git
實現功能:github
headless/headful
模式一個自動化具有的基本功能差很少就這些了。其實主要是使用了一堆框架和插件,主要是整合能力。web
$ pip install -r requirements.txt
注:安裝requirements.txt
指定依賴庫的版本,這是通過測試的,有時候新的版本可會有錯。shell
在 config.py
文件配置設計模式
class RunConfig: """ 運行測試配置 """ # 運行測試用例的目錄或文件 cases_path = "./test_dir/test_parametrize.py" # 配置瀏覽器驅動類型(chromium, firefox, webkit)。 browser = "chromium" # 運行模式(headless, headful) mode = "headful" # 配置運行的 URL url = "https://www.baidu.com" # 失敗重跑次數 rerun = "0" # 當達到最大失敗數,中止執行 max_fail = "5"
運行測試api
$ python run.py
page object是自動化測試最經常使用的設計模式。瀏覽器
但 playwright 中的只提供了操做方法,元素定位
和測試數據
都只是參數。
# 輸入 page.type('#kw', "playwright") # 點擊 page.click('#su')
咱們依然,能夠將元素定位單獨封裝一層。
class BaiduElem: search_input = "#kw" # 搜索框 search_button = "#su" # 搜索按鈕 settings = "#s-usersetting-top" # 設置 search_setting = "#s-user-setting-menu > div > a.setpref" # 搜索設置 save_setting = 'text="保存設置"' # 保存設置
在測試用例中的使用
from element.baidu_element import BaiduElem from playwright.sync_api import Page def test_baidu_search(page: Page, base_url): """ """ page.goto(base_url) page.type(BaiduElem.search_input, text="playwright") page.click(BaiduElem.search_button) sleep(2) assert page.title() == "playwright_百度搜索"
這確定不是什麼好的設計。用例層寫起來會比較囉嗦, 最好能夠page.elem.type("playwright")
的語法實現,這就須要在playwright的基礎上再封裝一套API, 看playwright 源碼仍是有些複雜的,主要是用了不少就異步,成本比較大,暫時先這麼用。
自動截圖須要 pytest/pytest-html 和 playwright 配合完成, pytest/pytest-html 判斷用例實現,並把圖片插入到報告中。 playwright 實現截圖動做。
@pytest.mark.hookwrapper def pytest_runtest_makereport(item): """ 用於向測試用例中添加用例的開始時間、內部註釋,和失敗截圖等. :param item: """ pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() report.description = description_html(item.function.__doc__) extra = getattr(report, 'extra', []) page = item.funcargs["page"] if report.when == 'call': xfail = hasattr(report, 'wasxfail') if (report.skipped and xfail) or (report.failed and not xfail): case_path = report.nodeid.replace("::", "_") + ".png" if "[" in case_path: case_name = case_path.split("-")[0] + "].png" else: case_name = case_path capture_screenshots(case_name, page) img_path = "image/" + case_name.split("/")[-1] if img_path: html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \ 'onclick="window.open(this.src)" align="right"/></div>' % img_path extra.append(pytest_html.extras.html(html)) report.extra = extra def capture_screenshots(case_name, page): """ 配置用例失敗截圖路徑 :param case_name: 用例名 :return: """ global driver file_name = case_name.split("/")[-1] if RunConfig.NEW_REPORT is None: raise NameError('沒有初始化測試報告目錄') else: image_dir = os.path.join(RunConfig.NEW_REPORT, "image", file_name) page.screenshot(path=image_dir)
經過page = item.funcargs["page"]
拿到playwright的驅動,截圖判斷邏輯有點複雜,不過我已經實現了。