<style> .txt_underline{ text-decoration:underline; } </style> # Playwright 錄影 以下程式碼, 可以將測試`錯誤`的測試過程錄影紀錄下來. 建立 <span class="txt_underline">conftest.py</span>, 放置在與測試檔案的同層目錄下, 並新增以下內容. ```python import asyncio from asyncio import AbstractEventLoop from typing import Any, Callable, Dict, Generator, List, Optional from playwright.async_api import async_playwright import pytest from playwright.sync_api import ( Browser, BrowserContext, Page, Playwright, sync_playwright, ) from pathlib import Path import os import shutil @pytest.fixture def context( browser: Browser, browser_context_args: Dict, browser_name, video_path, request ) -> Generator[BrowserContext, None, None]: context = browser.new_context(**browser_context_args) current_failed_tests = request.session.testsfailed yield context current_video_path = f'{video_path}/{context.current_path_name}' updated_video_path = f'{video_path}/{request.node.originalname}_{browser_name}.mp4' context.close() os.rename(current_video_path, updated_video_path) if request.session.testsfailed == current_failed_tests: # test should have been successful no real reason to keep it os.remove(updated_video_path) @pytest.fixture(scope="session") def browser_context_args(browser_context_args, video_path): return { **browser_context_args, "record_video_dir": video_path, # 調整儲存影片的尺寸 "record_video_size": { "width": 1280, "height": 768 } # "viewport": { # "width": 800, # "height": 600 # } # "screen": { # "width": 1280, # "height": 720 # } # "no_viewport": False } @pytest.fixture(scope="session") def video_path(): return "./videos" # def pytest_sessionstart(session): # """ # Called before test run starts # """ # if os.path.exists("./videos"): # for filename in os.listdir("./videos"): # filepath = os.path.join("./videos", filename) # try: # shutil.rmtree(filepath) # except OSError: # os.remove(filepath) @pytest.fixture def page(context: BrowserContext, base_url: str) -> Generator[Page, None, None]: page = context.new_page() # page._goto = page.goto # type: ignore # page.goto = lambda *args, **kwargs: _handle_page_goto( # type: ignore # page, list(args), kwargs, base_url # ) yield page # save off the test unique id context.current_path_name = Path(context.pages[0].video.path()).name page.close() def _handle_page_goto( page: Page, args: List[Any], kwargs: Dict[str, Any], base_url: str ) -> None: url = args.pop() if not (url.startswith("http://") or url.startswith("https://")): url = base_url + url return page._goto(url, *args, **kwargs) # type: ignore ``` <hr> <!-- [End to End 目錄](https://hackmd.io/F41miM4aRP2eljbPy6grCg) --> ###### tags: `Playwright` `End to End`