import random from decimal import Decimal import pytest from dx_productivity.domain.models import SortOrder from dx_productivity.domain.ordering import order_components def test_default_order_is_sheet_top_to_bottom_then_left_to_right( group_factory, settings ): groups = ( group_factory("b", sheet=1, x="30", y="100"), group_factory("a", sheet=1, x="10", y="100"), group_factory("c", sheet=1, x="5", y="80"), group_factory("d", sheet=2, x="1", y="500"), ) ordered = order_components(groups, settings(row_tolerance=Decimal("5"))) assert [group.key for group in ordered] == ["a", "b", "c", "d"] def test_row_clustering_uses_fixed_anchor_not_chain_drift(group_factory, settings): groups = ( group_factory("a", x="30", y="100"), group_factory("b", x="10", y="96"), group_factory("c", x="20", y="92"), ) ordered = order_components(groups, settings(row_tolerance=Decimal("5"))) assert [group.key for group in ordered] == ["b", "a", "c"] @pytest.mark.parametrize( ("sort_order", "expected"), [ (SortOrder.TOP_DOWN_LEFT_RIGHT, ["tl", "tr", "bl", "br"]), (SortOrder.TOP_DOWN_RIGHT_LEFT, ["tr", "tl", "br", "bl"]), (SortOrder.LEFT_RIGHT_TOP_DOWN, ["tl", "bl", "tr", "br"]), (SortOrder.RIGHT_LEFT_TOP_DOWN, ["tr", "br", "tl", "bl"]), ], ) def test_all_scan_directions(sort_order, expected, group_factory, settings): groups = ( group_factory("br", x="100", y="0"), group_factory("tl", x="0", y="100"), group_factory("bl", x="0", y="0"), group_factory("tr", x="100", y="100"), ) ordered = order_components( groups, settings(sort_order=sort_order, row_tolerance=Decimal("5")), ) assert [group.key for group in ordered] == expected def test_order_is_deterministic_for_equal_coordinates(group_factory, settings): original = [group_factory(key, x="10", y="10") for key in "dbca"] expected = ["a", "b", "c", "d"] randomizer = random.Random(795) for _ in range(50): randomizer.shuffle(original) ordered = order_components(tuple(original), settings()) assert [group.key for group in ordered] == expected def test_negative_tolerance_is_rejected(group_factory, settings): with pytest.raises(ValueError, match="row_tolerance"): order_components( (group_factory("a"),), settings(row_tolerance=Decimal("-1")), )