S-JIS[2026-02-22]

Rust PyO3 pytestメモ

Rustpyo3のテスト方法のメモ。


概要

PyO3プロジェクトの下に、pytestによるPythonのテストを置くことが出来る。


テストの書き方自体はpytestのルールに従う。


PyO3プロジェクトでpytestのテストを記述・実行する例。


pytestのインストール

まず、pytestをインストールする。

cd example-pyo3
uv add --dev pytest

テストコードの実装

テストコードを記述する。

プロジェクトディレクトリー直下にtestsというディレクトリーを作り、テストコードを書くソースファイルを作る。

example-pyo3/tests/example_pyo3_test.py:

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"

ちなみに、例外が発生することを確認するテストは以下のような感じ。

example-pyo3/tests/example_pyo3_test.py:

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

pyo3へ戻る / Rustへ戻る / 技術メモへ戻る
メールの送信先:ひしだま