Open3

[mac]pythonのpdmでテスト実行環境構築

れおろめれおろめ

pdm インストール

  • homebrew使用
brew install pdm

pdm init

pdm init
Creating a pyproject.toml for PDM...
Please enter the Python interpreter to use
0. /opt/anaconda3/bin/python (3.7)
1. /usr/local/bin/python3.12 (3.12)
2. /usr/local/bin/python3.11 (3.11)
3. /usr/bin/python3 (3.9)
4. /usr/local/bin/python3.8 (3.8)
5. /opt/anaconda3/bin/python3.7 (3.7)
6. /usr/local/Cellar/python@3.12/3.12.1_1/Frameworks/Python.framework/Versions/3.12/bin/python3.12 (3.12)
Please select (0): 6
Would you like to create a virtualenv with /usr/local/Cellar/python@3.12/3.12.1_1/Frameworks/Python.framework/Versions/3.12/bin/python3.12? [y/n] (y): y
Virtualenv is created successfully at /Users/reorome/Desktop/projects/CoinTrade/.venv
Project name (CoinTrade): 
Project version (0.1.0): 
Do you want to build this project for distribution(such as wheel)?
If yes, it will be installed by default when running `pdm install`. [y/n] (n): 
License(SPDX name) (MIT): 
Author name (*Qa9bUkHqhT): reorome
Author email (): 
Python requires('*' to allow any) (==3.12.*): 
Project is initialized successfully

pyproject.tomlにテスト実行コマンド追加

[tool.pdm.scripts]
test = "python -m unittest discover tests"
れおろめれおろめ

pytestを導入

pdm add pytest

テスト実行を常駐させる

  • pytest-watchをインストール
pdm add pytest-watch
  • pyprojet.tomlに追加
test = "pytest-watch"

pytest-watchコマンドをコンソール上で実行しても動かないけどそれはpdm内の依存関係で管理しているのでプロジェクト内だけのコマンドとして有効

れおろめれおろめ

pytest-mocker を追加して非同期処理やライブラリをモックする

  • pytest-mockerを追加
pdm add pytest-mocker
  • conftest.pyを作成
conftest.py
@pytest.fixture(scope="module", autouse=True)
def scope_module(mocker):
    print("    setup before module")
    mocker.patch("python_bitbankcc.private", new=bitbankcc_private_Dummy)
    yield
    print("    teardown after module")
  • エラーになる「Failed: ScopeMismatch: You tried to access the function scoped fixture mocker with a module scoped request object, involved factories」
  • mocker から module_mocker に変更する
conftest.py
@pytest.fixture(scope="module", autouse=True)
def scope_module(module_mocker):
    print("    setup before module")
    module_mocker.patch("python_bitbankcc.private", new=bitbankcc_private_Dummy)
    yield
    print("    teardown after module")