0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

unittest pytestの一歩踏み込んだ使い方

Last updated at Posted at 2024-07-24

pytestの一歩踏み込んだ使い方

pytestを使ってテストを書いて~
中の関数呼び出しは mock があるから~
と言われたけれど、
関数のテストするには、例外処理とか、例にない mockの書き方とか
検索しても assert x == y までの書き方までが多くて、
リファレンス的なものにたどり着けなかったので、まとめ

その関数がどの引数で呼ばれたか

from unittest import mock
mock_instance = mock.MagicMock(spec=MockModule)
mock_instance.method_name.assert_called_once_with(a, b, c)

何回呼ばれたか

from unittest import mock
mock_instance = mock.MagicMock(spec=MockModule)
mock_instance.method_name.call_count == 1

メソッドの中で呼んだメソッドで例外を起こしたい

from unittest import mock
mock_instance = mock.MagicMock(spec=MockModule)
mock_instance.method_name.side_effect = ExceptionName

# 例外をキャッチ
```python
import pytest
with pytest.raises(ExceptionName) as e:
    _ = target.method()
assert e.value.error_type == 'exception_type'

引数を変えて同じテストを繰り返す

import pytest
@pytest.mark.paramaize(
    [
        "number"
    ],
    [
        pytest.param(
            123
            id="number_test_123"
        ),
        pytest.param(
            456
            id="number_test_456"
        ),
    ]
)
def test_some_method(number)

これで number123456 のテストを同じコードで実施できる

テストしたいモジュールにある関数のスタブを作りたい

def test_some_method
    from path.to.TargetObject
    
    with patch.object(TargetObject, 'method_for_stub', return_value=1) as mock_method
        target = TargetObject()
        target.some_method()
        # 呼び出されたことを確認
        mock_method.call_count = 1
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?