LoginSignup
0
0

More than 1 year has passed since last update.

Docker環境でPlaywright (Python)を並列実行する方法メモ

Posted at
  • Docker環境でPlaywright +pytest-xdistを用いた並列アクセス方法についてメモする。

プロジェクト構成

├── Dockerfile
├── docker-compose.yml
└── scenario
    └── test.py

コード

  • docker-compose.yml※entrypointでpytestコマンドを実行させる

    version: '3.8'
    services:
      playwright:
        build: 
          context: ./
        volumes:
            - ./scenario:/var/scenario
        entrypoint: >
          sh -c "
            cd /var/scenario &&
            pytest -n 3 --dist each test.py
          "
    
  • Dockerfilepytest-xdistインストール

    FROM mcr.microsoft.com/playwright/python:v1.29.0-focal
    RUN pip install playwright
    RUN pip install pytest-xdist
    
  • test.py

    • Playwright公式サイトにアクセスし、title要素の確認を行う。
    • pytest-xdistワーカー別にログ出力を行う。
    from playwright.sync_api import sync_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(worker_id):
        with sync_playwright() as p:
            browser = p.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()
    
    

動作確認

  • 以下のコマンドを実行する

    docker-compose up --build
    ...
    playwright_1  | ============================= test session starts ==============================
    playwright_1  | platform linux -- Python 3.8.10, pytest-7.2.0, pluggy-1.0.0
    playwright_1  | rootdir: /var/scenario
    playwright_1  | plugins: xdist-3.1.0
    playwright_1  | gw0 I / gw1 I / gw2 I
    playwright_1  | gw0 [1] / gw1 [1] / gw2 [1]
    playwright_1  | 
    playwright_1  | .                                                                        [100%]. [100%]. [100%]
    playwright_1  | ============================== 3 passed in 9.41s ===============================
    

    以下のように、test_{worker_id}.logファイルにログ出力も行われる

参考情報

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0