PyO3プロジェクトの下に、pytestによるPythonのテストを置くことが出来る。
テストの書き方自体はpytestのルールに従う。
PyO3プロジェクトでpytestのテストを記述・実行する例。
まず、pytestをインストールする。
cd example-pyo3 uv add --dev pytest
テストコードを記述する。
プロジェクトディレクトリー直下にtestsというディレクトリーを作り、テストコードを書くソースファイルを作る。
import example_pyo3
def test_sum_as_string():
assert example_pyo3.sum_as_string(1, 2) == "3"
assert example_pyo3.sum_as_string(10, 5) == "15"
ちなみに、例外が発生することを確認するテストは以下のような感じ。
import example_pyo3
import pytest
def test_throw_exception():
with pytest.raises(example_pyo3.MyError, match="error message1"):
example_pyo3.throw_exception(1)
with pytest.raises(example_pyo3.MyError2, match="error message2"):
example_pyo3.throw_exception(2)
with pytest.raises(example_pyo3.MyError3, match="error message3"):
example_pyo3.throw_exception(3)
matchには、エラーメッセージを正規表現で指定する。
エラーメッセージのテストをしない場合は省略可。
pytestを実行する。
cd example-pyo3 uv run pytest