-
Playwright
+pytest-xdist
で並列ブラウザアクセスした際のノード(ワーカー)別にログ出力する方法についてメモする。
コード
-
test.py
-
Playwright
公式サイトにアクセスし、title
要素の確認を行う。 -
pytest-xdist
ワーカー別にログ出力を行う。
from playwright.sync_api import Playwright import logging # ワーカー別ロガーを定義する def _get_logger(worker_id): logger = logging.getLogger("logger_{}".format(worker_id)) handler = logging.FileHandler(filename="test_{}.log".format(worker_id)) handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) logger.setLevel(logging.INFO) logger.addHandler(handler) return logger # `worker_id`にワーカープロセスIDが格納される def test_parallel(playwright: Playwright,worker_id): browser = playwright.chromium.launch(headless=True) page = browser.new_page() # ページアクセス+タイトルチェック page.goto('https://playwright.dev/python/') assert page.title() == 'Fast and reliable end-to-end testing for modern web apps | Playwright Python' # ワーカー別ログファイルにログ出力を行う # ワーカープロセスID,URL,タイトル logger = _get_logger(worker_id) logger.info('worker:{} url:{} title:{}'.format(worker_id,page.url, page.title())) page.close()
-
動作確認
-
以下のコマンドを実行する
pytest -n 3 --dist each test.py ===================================================== test session starts ===================================================== platform linux -- Python 3.8.10, pytest-7.2.0, pluggy-1.0.0 rootdir: /home/u5008506/dev/playwright-test plugins: html-3.2.0, playwright-0.3.0, metadata-2.0.4, cov-4.0.0, base-url-2.0.0, xdist-3.1.0, parallel-0.1.1, anyio-3.3.4 gw0 [1] / gw1 [1] / gw2 [1] ... [100%] [100%] [100%] ====================================================== 3 passed in 9.98s ======================================================
以下のように、
test_{worker_id}.log
ファイルにログ出力が行われる -
test_gw0.log
2023-01-09 10:50:45,884 INFO worker:gw0 url:https://playwright.dev/python/ title:Fast and reliable end-to-end testing for modern web apps | Playwright Python
-
test_gw1.log
2023-01-09 10:50:45,898 INFO worker:gw1 url:https://playwright.dev/python/ title:Fast and reliable end-to-end testing for modern web apps | Playwright Python
-
test_gw2.log
2023-01-09 10:50:46,002 INFO worker:gw2 url:https://playwright.dev/python/ title:Fast and reliable end-to-end testing for modern web apps | Playwright Python