import pytest

from lr_modbus.codec import ModbusCrcError, build_frame, parse_frame


def test_round_trip_encoding() -> None:
    payload = b"\x00\x10"
    frame = build_frame(1, 3, payload)
    parsed = parse_frame(frame)
    assert parsed.unit_id == 1
    assert parsed.function_code == 3
    assert parsed.payload == payload


def test_detects_crc_error() -> None:
    frame = bytearray(build_frame(2, 6, b"\x00\x01\x00\x02"))
    frame[-1] ^= 0xFF
    with pytest.raises(ModbusCrcError):
        parse_frame(bytes(frame))
