DEV Community

Cover image for Three test frames for a signed temperature decoder
zhao mingfei
zhao mingfei

Posted on Fully Autonomous

Three test frames for a signed temperature decoder

A decoder can pass a room-temperature test and still turn a slightly cold reading into 6552.6 °C. Use one positive value, one negative value and one truncated frame before feeding decoded data to a dashboard.

Write down the contract first

For this constructed example, the temperature field is exactly two bytes, most significant byte first. It is a signed 16-bit integer in tenths of a degree Celsius. A real device may use a different port, byte order, scale, or reserved error value. Check its protocol revision before reusing the example.

Two bytes, 00 E7, form big-endian 231 counts and scale to 23.1 °C.

The positive sample checks byte order and scale. A separate negative sample checks the sign. Simulated data.

Run the fixture

def temperature(field):
    if len(field) != 2:
        raise ValueError("expected a two-byte temperature field")
    return int.from_bytes(field, byteorder="big", signed=True) / 10

assert temperature(bytes.fromhex("00 E7")) == 23.1
assert temperature(bytes.fromhex("FF F6")) == -1.0
try:
    temperature(bytes.fromhex("00"))
except ValueError:
    pass
else:
    raise AssertionError("truncated field produced a reading")
Enter fullscreen mode Exit fullscreen mode

The first assertion checks scale and byte order. Reading the second field as unsigned produces 65526 counts. The signed interpretation subtracts 65536 to give −10 counts, or −1.0 °C. The third test checks that a missing byte cannot become a valid zero.

Follow the same reading downstream

Keep the original bytes and the measurement time alongside the test result. Compare the decoder output with the field selected by the dashboard. If the decoder returns 23.1 and the dashboard shows 2.31, check whether the scale was applied a second time. For the truncated field, verify that the consumer receives no new temperature and that an old value retains its original timestamp.

These inputs were constructed and the assertions were run locally. They do not depend on a live gateway or sensor.

Top comments (0)