pytest Tests
from src.shapes.Square import Square
class TestSquare:
def test_square_constructor_should_set_length(self):
square = Square(2.0)
assert square.length == 2.0
pytest Parameterized Tests
from src.shapes.Square import Square
import pytest
class TestSquare:
@pytest.mark.parametrize("value", [1.0, 2.1, 3.2, 4.3, 5.9])
def test_set_length_to_positive_value(self, value):
square = Square(value)
assert square.length == value
pytest Assertions
- assert <boolean expression>
- assert actual == pytest.approx(expected)
- assert actual is expected
- assert actual is None
Catching Exceptions
def test_zero_division():
with pytest.raises(ZeroDivisionError):
calculator.divide(1, 0)
Checking Output
from pytest import CaptureFixture
from _pytest.capture import CaptureResult
from typing import Any
from src.hello.HelloWorld import HelloWorld
def test_hello_world(self, capsys: CaptureFixture[Any]) -> None:
HelloWorld.main(["HelloWorld"])
captured: CaptureResult[Any] = capsys.readouterr()
assert captured.out == "Hello World\n", "Unexpected Output"