Coverage for src / zmqtt / _internal / types / topic.py: 100%

32 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-11-12 08:49 +0000

1from zmqtt.errors import MQTTInvalidTopicError 

2 

3 

4def validate_publish(topic: str) -> None: 

5 if not topic: 

6 msg = "Topic must not be empty" 

7 raise MQTTInvalidTopicError(msg) 

8 if "#" in topic or "+" in topic: 

9 msg = f"Wildcards not allowed in publish topic: {topic!r}" 

10 raise MQTTInvalidTopicError(msg) 

11 if "$" in topic[1:]: 

12 msg = f"'$' is only valid as the first character of a topic: {topic!r}" 

13 raise MQTTInvalidTopicError(msg) 

14 

15 

16def validate_subscribe_topic(topic: str) -> None: 

17 if not topic: 

18 msg = "Topic filter must not be empty" 

19 raise MQTTInvalidTopicError(msg) 

20 if "$" in topic[1:]: 

21 msg = f"'$' is only valid as the first character of a topic filter: {topic!r}" 

22 raise MQTTInvalidTopicError(msg) 

23 if "#" in topic: 

24 idx = topic.index("#") 

25 if idx != len(topic) - 1: 

26 msg = f"'#' must be the last character in a topic filter: {topic!r}" 

27 raise MQTTInvalidTopicError(msg) 

28 if idx > 0 and topic[idx - 1] != "/": 

29 msg = f"'#' must be preceded by '/' in a topic filter: {topic!r}" 

30 raise MQTTInvalidTopicError(msg) 

31 for level in topic.split("/"): 

32 if "+" in level and level != "+": 

33 msg = f"'+' must occupy an entire topic level in filter: {topic!r}" 

34 raise MQTTInvalidTopicError(msg) 

35 

36 

37def validate_response_topic(topic: str) -> None: 

38 validate_publish(topic)