Skip to content

Commit

Permalink
#24 Test redundancy_check module.
Browse files Browse the repository at this point in the history
  • Loading branch information
OrangeTux committed Jan 27, 2016
1 parent 999dae2 commit fed0771
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
Empty file.
23 changes: 23 additions & 0 deletions tests/unit/client/serial/test_redundancy_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import struct
import pytest

from umodbus.client.serial.redundancy_check import get_crc, validate_crc


def test_get_crc():
""" Test if correct CRC is calculated. """
# Values are equal to those used in example in MODBUS over serial line
# specification and implementation guide V1.02, chapter 6.2.2.
assert struct.unpack('<H', get_crc(b'\x02\x07')) ==\
struct.unpack('<H', b'\x41\x12')


def test_validate_valid_crc():
"""" Method should not raise assertion error. """
validate_crc(b'\x02\x07', b'\x41\x12')


def test_validate_invalid_crc():
"""" Method should raise assertion error. """
with pytest.raises(AssertionError):
validate_crc(b'\x02\x07', b'\x41\x11')
6 changes: 3 additions & 3 deletions umodbus/client/serial/redundancy_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ def generate_look_up_table():
def get_crc(msg):
""" Return CRC of 2 byte for message.
>>> assert get_crc('<H', b'\x02\x07') ==\
struct.unpack('<H', b'\x41\x12')
>>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12')
:param msg: A byte array.
:return: Byte array of 2 bytes.
"""
register = 0xFFFF

for byte_ in msg:
val = struct.unpack('<B', byte_)[0]
register = \
(register >> 8) ^ look_up_table[(register ^ byte_) & 0xFF]
(register >> 8) ^ look_up_table[(register ^ val) & 0xFF]

# CRC is little-endian!
return struct.pack('<H', register)
Expand Down

0 comments on commit fed0771

Please sign in to comment.