示例工程 33-numpy-vectorization
33-numpy-vectorization/02-broadcasting/test_broadcasting.py
"""test_broadcasting.py"""
from __future__ import annotations
import pytest
pytest.importorskip("numpy")
import numpy as np
from broadcasting import grid, main
def test_broadcast_grid() -> None:
result = grid()
assert result.shape == (4, 3)
assert result.tolist() == [
[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
]
def test_broadcast_shapes() -> None:
assert np.broadcast_shapes((3, 1), (1, 4)) == (3, 4)
def test_incompatible_shapes() -> None:
with pytest.raises(ValueError, match="could not be broadcast"):
_ = np.arange(3) + np.arange(4)
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
main()
out = capsys.readouterr().out
assert "shape: (4, 3)" in out
assert "could not be broadcast" in out