Coverage for faststream/mqtt/utils.py: 72%

26 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1from dataclasses import dataclass 

2from urllib.parse import unquote, urlsplit 

3 

4 

5@dataclass(frozen=True, slots=True, kw_only=True) 

6class MQTTUrl: 

7 """Parsed MQTT connection URL.""" 

8 

9 host: str 

10 port: int 

11 tls: bool 

12 username: str | None 

13 password: str | None 

14 port_provided: bool 

15 

16 

17def parse_mqtt_url(url: str) -> MQTTUrl: 

18 """Parse an MQTT TCP/TLS connection URL.""" 

19 parsed = urlsplit(url if "://" in url else f"//{url}", scheme="mqtt") 

20 scheme = parsed.scheme.lower() 

21 

22 if scheme not in {"mqtt", "mqtts"}: 22 ↛ 23line 22 didn't jump to line 23 because the condition on line 22 was never true

23 msg = "MQTT URL scheme must be either 'mqtt' or 'mqtts'." 

24 raise ValueError(msg) 

25 

26 if parsed.path not in {"", "/"} or parsed.query or parsed.fragment: 26 ↛ 27line 26 didn't jump to line 27 because the condition on line 26 was never true

27 msg = "MQTT URL must not include a path, query, or fragment." 

28 raise ValueError(msg) 

29 

30 host = parsed.hostname 

31 if host is None: 31 ↛ 32line 31 didn't jump to line 32 because the condition on line 31 was never true

32 msg = "MQTT URL must include a host." 

33 raise ValueError(msg) 

34 

35 parsed_port = parsed.port 

36 tls = scheme == "mqtts" 

37 

38 return MQTTUrl( 

39 host=host, 

40 port=parsed_port if parsed_port is not None else (8883 if tls else 1883), 

41 tls=tls, 

42 username=unquote(parsed.username) if parsed.username is not None else None, 

43 password=unquote(parsed.password) if parsed.password is not None else None, 

44 port_provided=parsed_port is not None, 

45 ) 

46 

47 

48def build_mqtt_url(*, host: str, port: int, tls: bool) -> str: 

49 """Build a credential-free MQTT connection URL.""" 

50 formatted_host = f"[{host}]" if ":" in host else host 

51 scheme = "mqtts" if tls else "mqtt" 

52 return f"{scheme}://{formatted_host}:{port}"