0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今更pytest&pytest-cov

Last updated at Posted at 2023-05-31

テスト対象

main.py
import re


def sum_up(a: int, b: int) -> int:
    return a + b


def subtract(a: int, b: int) -> int:
    return a - b


def sum_up_str(a: int | str, b: int | str) -> int:
    # check if a and b are castable to int
    if re.match(r"^\d+$", str(a)) is None:
        raise ValueError("a is not castable to int")
    if re.match(r"^\d+$", str(b)) is None:
        raise ValueError("b is not castable to int")
    if isinstance(a, str):
        a = int(a)
    if isinstance(b, str):
        b = int(b)
    return a + b

テストコード

test_main.py
import pytest

from src.main import subtract, sum_up, sum_up_str


def test_sum_up():
    assert sum_up(1, 2) == 3
    assert sum_up(2, 2) == 4


def test_subtract():
    assert subtract(1, 2) == -1
    assert subtract(2, 2) == 0


def test_sum_up_str():
    assert sum_up_str(1, 2) == 3
    assert sum_up_str("1", "2") == 3
    assert sum_up_str("1", 2) == 3
    with pytest.raises(ValueError) as a_exc:
        sum_up_str("a", 2)
    assert a_exc.value.args[0] == "a is not castable to int"
    with pytest.raises(ValueError) as b_exc:
        sum_up_str("1", "b")
    assert b_exc.value.args[0] == "b is not castable to int"

ディレクトリ構造

.
├── src
│   ├── __init__.py
│   ├── main.py
├── tests
│   ├── __init__.py
    ├── test_main.py

実行

インストールして

$ pip install pytest pytest-cov

実行

$ pytest tests --cov
---------- coverage: platform linux, python 3.10.9-final-0 -----------
Name                 Stmts   Miss  Cover
----------------------------------------
src/__init__.py          0      0   100%
src/main.py             24      0   100%
tests/__init__.py        0      0   100%
tests/test_main.py      18      0   100%
----------------------------------------
TOTAL                   42      0   100%

test_main.pyの解説

test_main.pytest_sum_up_strassertを幾つか削除するとカバレッジが低下します。
これはテスト対象のコードの一部が実行されなくなるため。

カバレッジを見ながらテストの網羅性を確認しましょう。

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?