1
0

test_helpers.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """Tests for helper functions."""
  2. import pytest
  3. from switchbot.helpers import parse_power_data
  4. def test_parse_power_data_basic():
  5. """Test basic power data parsing."""
  6. # Test data: bytes with value 0x1234 (4660 decimal) at offset 0
  7. data = b"\x12\x34\x56\x78"
  8. # Test without scale (should return raw value)
  9. assert parse_power_data(data, 0) == 4660
  10. # Test with scale of 10
  11. assert parse_power_data(data, 0, 10.0) == 466.0
  12. # Test with scale of 100
  13. assert parse_power_data(data, 0, 100.0) == 46.6
  14. def test_parse_power_data_with_offset():
  15. """Test power data parsing with different offsets."""
  16. data = b"\x00\x00\x12\x34\x56\x78"
  17. # Value at offset 2 should be 0x1234
  18. assert parse_power_data(data, 2, 10.0) == 466.0
  19. # Value at offset 4 should be 0x5678
  20. assert parse_power_data(data, 4, 10.0) == 2213.6
  21. def test_parse_power_data_with_mask():
  22. """Test power data parsing with bitmask."""
  23. # Test data: 0xFFFF
  24. data = b"\xff\xff"
  25. # Without mask
  26. assert parse_power_data(data, 0, 10.0) == 6553.5
  27. # With mask 0x7FFF (clear highest bit)
  28. assert parse_power_data(data, 0, 10.0, 0x7FFF) == 3276.7
  29. def test_parse_power_data_insufficient_data():
  30. """Test error handling for insufficient data."""
  31. data = b"\x12" # Only 1 byte
  32. # Should raise ValueError when trying to read 2 bytes
  33. with pytest.raises(ValueError, match="Insufficient data"):
  34. parse_power_data(data, 0)
  35. # Should also fail at offset 1 with 2-byte data
  36. data = b"\x12\x34"
  37. with pytest.raises(ValueError, match="Insufficient data"):
  38. parse_power_data(data, 1) # Would need to read bytes 1-2
  39. def test_parse_power_data_real_world_examples():
  40. """Test with real-world examples from relay switch."""
  41. # Simulate relay switch data structure
  42. raw_data = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdc\x00\x0f\x00\xe8"
  43. # Voltage at offset 9-10: 0x00DC = 220 / 10.0 = 22.0V
  44. assert parse_power_data(raw_data, 9, 10.0) == 22.0
  45. # Current at offset 11-12: 0x000F = 15 / 1000.0 = 0.015A
  46. assert parse_power_data(raw_data, 11, 1000.0) == 0.015
  47. # Power at offset 13-14: 0x00E8 = 232 / 10.0 = 23.2W
  48. assert parse_power_data(raw_data, 13, 10.0) == 23.2