mirror of
https://github.com/esphome/esphome.git
synced 2026-05-27 11:56:11 +08:00
This commit is contained in:
@@ -279,6 +279,77 @@ def test_sanitize(text, expected):
|
||||
assert actual == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "expected_hash"),
|
||||
(
|
||||
# Basic strings - hash of sanitize(snake_case(name))
|
||||
("foo", 0x408F5E13),
|
||||
("Foo", 0x408F5E13), # Same as "foo" (lowercase)
|
||||
("FOO", 0x408F5E13), # Same as "foo" (lowercase)
|
||||
# Spaces become underscores
|
||||
("foo bar", 0x3AE35AA1), # Transforms to "foo_bar"
|
||||
("Foo Bar", 0x3AE35AA1), # Same (lowercase + underscore)
|
||||
# Already snake_case
|
||||
("foo_bar", 0x3AE35AA1),
|
||||
# Special chars become underscores
|
||||
("foo!bar", 0x3AE35AA1), # Transforms to "foo_bar"
|
||||
("foo@bar", 0x3AE35AA1), # Transforms to "foo_bar"
|
||||
# Hyphens are preserved
|
||||
("foo-bar", 0x438B12E3),
|
||||
# Numbers are preserved
|
||||
("foo123", 0xF3B0067D),
|
||||
# Empty string
|
||||
("", 0x811C9DC5), # FNV1_OFFSET_BASIS (no chars processed)
|
||||
# Single char
|
||||
("a", 0x050C5D7E),
|
||||
# Mixed case and spaces
|
||||
("My Sensor Name", 0x2760962A), # Transforms to "my_sensor_name"
|
||||
),
|
||||
)
|
||||
def test_fnv1_hash_object_id(name, expected_hash):
|
||||
"""Test fnv1_hash_object_id produces expected hashes.
|
||||
|
||||
These expected values were computed to match the C++ implementation
|
||||
in esphome/core/helpers.h. If this test fails after modifying either
|
||||
implementation, ensure both Python and C++ versions stay in sync.
|
||||
"""
|
||||
actual = helpers.fnv1_hash_object_id(name)
|
||||
|
||||
assert actual == expected_hash
|
||||
|
||||
|
||||
def _fnv1_hash_py(s: str) -> int:
|
||||
"""Python implementation of FNV-1 hash for verification."""
|
||||
hash_val = 2166136261 # FNV1_OFFSET_BASIS
|
||||
for c in s:
|
||||
hash_val = (hash_val * 16777619) & 0xFFFFFFFF # FNV1_PRIME
|
||||
hash_val ^= ord(c)
|
||||
return hash_val
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
(
|
||||
"Simple",
|
||||
"With Space",
|
||||
"MixedCase",
|
||||
"special!@#chars",
|
||||
"already_snake_case",
|
||||
"123numbers",
|
||||
),
|
||||
)
|
||||
def test_fnv1_hash_object_id_matches_manual_calculation(name):
|
||||
"""Verify fnv1_hash_object_id matches snake_case + sanitize + standard FNV-1."""
|
||||
# Manual calculation: snake_case -> sanitize -> fnv1_hash
|
||||
transformed = helpers.sanitize(helpers.snake_case(name))
|
||||
expected = _fnv1_hash_py(transformed)
|
||||
|
||||
# Direct calculation via fnv1_hash_object_id
|
||||
actual = helpers.fnv1_hash_object_id(name)
|
||||
|
||||
assert actual == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text, expected",
|
||||
((["127.0.0.1", "fe80::1", "2001::2"], ["2001::2", "127.0.0.1", "fe80::1"]),),
|
||||
|
||||
Reference in New Issue
Block a user