inire/inire/tests/test_primitives.py

75 lines
2.1 KiB
Python

from dataclasses import FrozenInstanceError
from typing import Any
from hypothesis import given, strategies as st
import pytest
from inire.geometry.primitives import Port, port_local_coordinates, rotate_cardinal
@pytest.mark.parametrize(
("heading", "expected"),
[(0, (3.5, 7.25)), (90, (7.25, -3.5)), (180, (-3.5, -7.25)), (270, (-7.25, 3.5))],
)
def test_port_local_coordinates_preserve_fractional_points(heading, expected) -> None:
origin = Port(10, -4, heading)
local = port_local_coordinates(origin, 13.5, 3.25)
assert local == expected
assert rotate_cardinal(*local, heading) == (3.5, 7.25)
@st.composite
def port_strategy(draw: Any) -> Port:
x = draw(st.floats(min_value=-1e6, max_value=1e6))
y = draw(st.floats(min_value=-1e6, max_value=1e6))
orientation = draw(st.sampled_from([0, 90, 180, 270]))
return Port(x, y, orientation)
def test_port_snapping() -> None:
p = Port(0.123456, 0.654321, 90)
assert p.x == 0
assert p.y == 1
def test_port_rotation_preserves_coordinates_beyond_int32() -> None:
assert Port(-2**31, 20, 0).rotated(180) == Port(2**31, -20, 180)
assert Port(3_000_000_004, 25, 270).rotated(90, origin=(3_000_000_000, 20)) == Port(2_999_999_995, 24, 0)
@given(p=port_strategy())
def test_port_transform_invariants(p: Port) -> None:
# Rotating 90 degrees 4 times should return to same orientation
p_rot = p
for _ in range(4):
p_rot = p_rot.rotated(90)
assert abs(p_rot.x - p.x) < 1e-6
assert abs(p_rot.y - p.y) < 1e-6
assert (p_rot.r % 360) == (p.r % 360)
@given(
p=port_strategy(),
dx=st.floats(min_value=-1000, max_value=1000),
dy=st.floats(min_value=-1000, max_value=1000),
)
def test_translate_snapping(p: Port, dx: float, dy: float) -> None:
p_trans = p.translate(dx, dy)
assert isinstance(p_trans.x, int)
assert isinstance(p_trans.y, int)
def test_orientation_normalization() -> None:
p = Port(0, 0, 360)
assert p.r == 0
p2 = Port(0, 0, -90)
assert p2.r == 270
def test_port_is_immutable_value_type() -> None:
p = Port(1, 2, 90)
with pytest.raises(FrozenInstanceError):
p.x = 3