This repository was archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_package_example_test.py
More file actions
97 lines (73 loc) · 2.36 KB
/
python_package_example_test.py
File metadata and controls
97 lines (73 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""This file contains examples of how to write tests using pytest!
Some good practices for writting great Python tests:
Source: https://www.nerdwallet.com/blog/engineering/5-pytest-best-practices/
* Prefer mocker over mock
* Parametrize the same behavior, have different tests for different behaviors
* Don’t modify fixture values in other fixtures
* Prefer responses over mocking outbound HTTP requests
* Prefer tmpdir over global test artifacts
"""
from typing import TypeVar
import pytest
from python_package_example import python_module_example as m
Self = TypeVar("Self", bound="TestGroup")
@pytest.mark.parametrize(
("param1", "param2"),
[
("a", "b"),
("c", "d"),
],
)
class TestGroup:
"""A class with common parameters, `param1` and `param2`."""
@pytest.fixture()
def fixt(self: Self) -> int:
"""This fixture will only be available within the scope of TestGroup.
Returns:
int: A common value to be used by multiple tests
"""
return 123
def test_one(self: Self, param1: str, param2: str, fixt: int) -> None:
"""Run the first test using the fixture.
Args:
param1 (str): First parameter.
param2 (str): Second parameter.
fixt (int): Value from fixture.
"""
print("\ntest_one", param1, param2, fixt)
@pytest.mark.parametrize(
("a", "b", "expected"),
[
(1, 1, 1),
(42, 1, 42),
(84, 2, 42),
],
)
def test_divide_ok(a: float, b: float, expected: float) -> None:
"""Check if divide works for expected entries.
Args:
a (float): Dividend.
b (float): Divisor.
expected (float): expected result.
"""
assert m.Calculator.divide(a, b) == expected
@pytest.mark.parametrize(
("a", "b", "expected"),
[
(42, "b", TypeError),
("a", 42, TypeError),
(42, 0, ZeroDivisionError),
],
)
def test_divide_error(
a: str | float, b: str | float, expected: float | Exception
) -> None:
"""Check if divide returns correct Exceptions for known entries.
Issue raised by https://github.com/nullhack/python-project-example/issues/1337
Args:
a (float): Dividend.
b (float): Divisor.
expected (Exception): expected Exception.
"""
with pytest.raises(expected):
m.Calculator.divide(a, b)