pyqttier 0.2.14__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. {pyqttier-0.2.14 → pyqttier-0.3.0}/.agents/skills/release-pyqttier/SKILL.md +4 -0
  2. {pyqttier-0.2.14 → pyqttier-0.3.0}/PKG-INFO +2 -1
  3. {pyqttier-0.2.14 → pyqttier-0.3.0}/examples/connection_check.py +0 -1
  4. {pyqttier-0.2.14 → pyqttier-0.3.0}/examples/connection_ping.py +1 -1
  5. {pyqttier-0.2.14 → pyqttier-0.3.0}/examples/mock_example.py +1 -1
  6. {pyqttier-0.2.14 → pyqttier-0.3.0}/examples/smoke_test.py +1 -1
  7. {pyqttier-0.2.14 → pyqttier-0.3.0}/examples/usage_example.py +1 -1
  8. {pyqttier-0.2.14 → pyqttier-0.3.0}/pyproject.toml +2 -1
  9. {pyqttier-0.2.14 → pyqttier-0.3.0}/src/pyqttier/__init__.py +2 -1
  10. {pyqttier-0.2.14 → pyqttier-0.3.0}/src/pyqttier/connection.py +1 -2
  11. {pyqttier-0.2.14 → pyqttier-0.3.0}/src/pyqttier/lwt.py +1 -1
  12. {pyqttier-0.2.14 → pyqttier-0.3.0}/src/pyqttier/mock.py +1 -2
  13. {pyqttier-0.2.14 → pyqttier-0.3.0}/tests/test_pyqttier.py +2 -2
  14. {pyqttier-0.2.14 → pyqttier-0.3.0}/uv.lock +15 -2
  15. pyqttier-0.2.14/src/pyqttier/contenttype.py +0 -85
  16. pyqttier-0.2.14/src/pyqttier/interface.py +0 -59
  17. pyqttier-0.2.14/src/pyqttier/message.py +0 -85
  18. pyqttier-0.2.14/tests/test_contenttype.py +0 -140
  19. pyqttier-0.2.14/tests/test_message.py +0 -333
  20. {pyqttier-0.2.14 → pyqttier-0.3.0}/.github/workflows/python-tests.yml +0 -0
  21. {pyqttier-0.2.14 → pyqttier-0.3.0}/.github/workflows/python37.yml +0 -0
  22. {pyqttier-0.2.14 → pyqttier-0.3.0}/.gitignore +0 -0
  23. {pyqttier-0.2.14 → pyqttier-0.3.0}/LICENSE +0 -0
  24. {pyqttier-0.2.14 → pyqttier-0.3.0}/README.md +0 -0
  25. {pyqttier-0.2.14 → pyqttier-0.3.0}/Taskfile.yml +0 -0
  26. {pyqttier-0.2.14 → pyqttier-0.3.0}/examples/README.md +0 -0
  27. {pyqttier-0.2.14 → pyqttier-0.3.0}/src/pyqttier/py.typed +0 -0
  28. {pyqttier-0.2.14 → pyqttier-0.3.0}/src/pyqttier/transport.py +0 -0
  29. {pyqttier-0.2.14 → pyqttier-0.3.0}/tests/__init__.py +0 -0
@@ -44,6 +44,10 @@ Automate a standard Python release workflow for the `pyqttier` project.
44
44
 
45
45
  `uv version --bump=major`
46
46
 
47
+ - After bumping any version component, update the `uv.lock` file with this command:
48
+
49
+ `uv sync`
50
+
47
51
  - Format:
48
52
 
49
53
  `task format`
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pyqttier
3
- Version: 0.2.14
3
+ Version: 0.3.0
4
4
  Summary: Convenient wrapper around Paho MQTT
5
5
  Author-email: Jacob Brunson <github@jacobbrunson.com>
6
6
  License-File: LICENSE
7
7
  Requires-Python: >=3.7
8
8
  Requires-Dist: paho-mqtt>=2.1.0
9
+ Requires-Dist: py-stinger-conn-iface>=0.1.3
9
10
  Description-Content-Type: text/markdown
10
11
 
11
12
  # PyQTTier
@@ -16,7 +16,6 @@ import sys
16
16
 
17
17
  from pyqttier.connection import Mqtt5Connection
18
18
  from pyqttier.transport import MqttTransport, MqttTransportType
19
- from pyqttier.message import Message
20
19
 
21
20
 
22
21
  def signal_handler(sig, frame):
@@ -15,7 +15,7 @@ import sys
15
15
 
16
16
  from pyqttier.connection import Mqtt5Connection
17
17
  from pyqttier.transport import MqttTransport, MqttTransportType
18
- from pyqttier.message import Message
18
+ from pyqttier import Message
19
19
 
20
20
 
21
21
  def signal_handler(sig, frame):
@@ -18,7 +18,7 @@ from pathlib import Path
18
18
  sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
19
19
 
20
20
  from pyqttier.mock import MockConnection
21
- from pyqttier.message import Message
21
+ from pyqttier import Message
22
22
 
23
23
 
24
24
  def example_basic_publish_subscribe():
@@ -26,7 +26,7 @@ import threading
26
26
  from typing import Callable, Dict, List
27
27
 
28
28
  from pyqttier.connection import Mqtt5Connection
29
- from pyqttier.message import Message
29
+ from pyqttier import Message
30
30
  from pyqttier.transport import MqttTransport, MqttTransportType
31
31
 
32
32
  # ── Configuration ──────────────────────────────────────────────────────────────
@@ -15,7 +15,7 @@ import time
15
15
 
16
16
  from pyqttier.connection import Mqtt5Connection
17
17
  from pyqttier.transport import MqttTransport, MqttTransportType
18
- from pyqttier.message import Message
18
+ from pyqttier import Message
19
19
 
20
20
 
21
21
  def example_basic_connection():
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyqttier"
3
- version = "0.2.14"
3
+ version = "0.3.0"
4
4
  description = "Convenient wrapper around Paho MQTT"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -9,6 +9,7 @@ authors = [
9
9
  requires-python = ">=3.7"
10
10
  dependencies = [
11
11
  "paho-mqtt>=2.1.0",
12
+ "py-stinger-conn-iface>=0.1.3",
12
13
  ]
13
14
 
14
15
  [tool.hatch.build.targets.wheel]
@@ -1,6 +1,7 @@
1
+ from pystingerconniface import Message
2
+
1
3
  from .connection import Mqtt5Connection
2
4
  from .transport import MqttTransportType, MqttTransport
3
- from .message import Message
4
5
 
5
6
  __all__ = [
6
7
  "Mqtt5Connection",
@@ -8,9 +8,8 @@ from paho.mqtt.enums import MQTTProtocolVersion, CallbackAPIVersion
8
8
  from paho.mqtt.properties import Properties as MqttProperties
9
9
  from paho.mqtt.packettypes import PacketTypes
10
10
  from queue import Queue, Empty
11
- from .interface import IBrokerConnection, MessageCallback
11
+ from pystingerconniface import IBrokerConnection, Message, MessageCallback
12
12
  from .transport import MqttTransport, MqttTransportType
13
- from .message import Message
14
13
  from .lwt import OnlinePresence
15
14
  from dataclasses import dataclass
16
15
 
@@ -1,4 +1,4 @@
1
- from .message import Message
1
+ from pystingerconniface import Message
2
2
  from dataclasses import dataclass
3
3
 
4
4
 
@@ -1,8 +1,7 @@
1
1
  from concurrent.futures import Future
2
2
  from typing import Optional, List, Dict, Tuple # noqa: F401
3
3
  from copy import copy
4
- from .interface import IBrokerConnection, MessageCallback
5
- from .message import Message
4
+ from pystingerconniface import IBrokerConnection, Message, MessageCallback
6
5
  import threading
7
6
  import logging
8
7
 
@@ -1,5 +1,5 @@
1
1
  import unittest
2
- from pyqttier.message import Message
2
+ from pyqttier import Message
3
3
  from pyqttier.mock import MockConnection
4
4
  from pyqttier.transport import MqttTransport, MqttTransportType
5
5
  import threading
@@ -229,7 +229,7 @@ class TestInterface(unittest.TestCase):
229
229
 
230
230
  def test_mock_implements_interface(self):
231
231
  """Test that MockConnection implements all interface methods."""
232
- from pyqttier.interface import IBrokerConnection
232
+ from pystingerconniface import IBrokerConnection
233
233
 
234
234
  conn = MockConnection()
235
235
  self.assertIsInstance(conn, IBrokerConnection)
@@ -705,6 +705,15 @@ wheels = [
705
705
  { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
706
706
  ]
707
707
 
708
+ [[package]]
709
+ name = "py-stinger-conn-iface"
710
+ version = "0.1.3"
711
+ source = { registry = "https://pypi.org/simple" }
712
+ sdist = { url = "https://files.pythonhosted.org/packages/92/26/db82f184c55ad7c8db4b44339c8038e0caff2d611aa4f93256c84bbddb36/py_stinger_conn_iface-0.1.3.tar.gz", hash = "sha256:81a274ef64beac11e3f6512a481aa4fdc4d852da47347c8a55f6fc927888d520", size = 36415, upload-time = "2026-09-18T23:09:24.294Z" }
713
+ wheels = [
714
+ { url = "https://files.pythonhosted.org/packages/e9/33/18e802b27d6154c6fdd6dc0632ec5a27ed1f4f657643972f07cdf7c9ea66/py_stinger_conn_iface-0.1.3-py3-none-any.whl", hash = "sha256:47d0eb708ba69aa75f1af0dd16266cecfcbae118ff0d175e8afbdb142f086152", size = 8444, upload-time = "2026-09-18T23:09:23.394Z" },
715
+ ]
716
+
708
717
  [[package]]
709
718
  name = "pygments"
710
719
  version = "2.19.2"
@@ -716,10 +725,11 @@ wheels = [
716
725
 
717
726
  [[package]]
718
727
  name = "pyqttier"
719
- version = "0.2.14"
728
+ version = "0.3.0"
720
729
  source = { editable = "." }
721
730
  dependencies = [
722
731
  { name = "paho-mqtt" },
732
+ { name = "py-stinger-conn-iface" },
723
733
  ]
724
734
 
725
735
  [package.dev-dependencies]
@@ -739,7 +749,10 @@ dev = [
739
749
  ]
740
750
 
741
751
  [package.metadata]
742
- requires-dist = [{ name = "paho-mqtt", specifier = ">=2.1.0" }]
752
+ requires-dist = [
753
+ { name = "paho-mqtt", specifier = ">=2.1.0" },
754
+ { name = "py-stinger-conn-iface", specifier = ">=0.1.3" },
755
+ ]
743
756
 
744
757
  [package.metadata.requires-dev]
745
758
  dev = [
@@ -1,85 +0,0 @@
1
- import re
2
- from typing import Dict, Union
3
-
4
-
5
- class ContentType(str):
6
- """
7
- A string subclass representing an HTTP Content-Type.
8
- Main value: 'type/subtype'
9
- Attributes: parameters (e.g., charset, boundary)
10
- """
11
-
12
- parameters: Dict[str, str]
13
-
14
- def __new__(cls, content_type_header: Union[str, "ContentType"]):
15
- if isinstance(content_type_header, ContentType):
16
- obj = super().__new__(cls, str(content_type_header))
17
- obj.parameters = dict(content_type_header.parameters)
18
- for key, val in obj.parameters.items():
19
- if key.isidentifier():
20
- setattr(obj, key, val)
21
- return obj
22
-
23
- if not content_type_header or not content_type_header.strip():
24
- raise ValueError("Content-Type header cannot be empty.")
25
-
26
- # 1. Separate main media type from parameter block
27
- parts = content_type_header.split(";", 1)
28
- full_type = parts[0].strip().lower()
29
-
30
- if "/" not in full_type:
31
- raise ValueError(f"Invalid Content-Type format: '{parts[0]}'")
32
-
33
- # 2. Instantiate the str primitive with 'type/subtype'
34
- obj = super().__new__(cls, full_type)
35
-
36
- # 3. Parse parameters
37
- params = {}
38
- if len(parts) > 1:
39
- param_pattern = re.compile(
40
- r';\s*([^\s=;]+)=(?:"((?:[^\\"]|\\.)*)"|([^\s;]+))'
41
- )
42
- param_string = ";" + parts[1]
43
-
44
- for match in param_pattern.finditer(param_string):
45
- key = match.group(1).lower()
46
- quoted_val = match.group(2)
47
- unquoted_val = match.group(3)
48
-
49
- # Unescape quoted strings if present
50
- if quoted_val is not None:
51
- value = re.sub(r"\\(.)", r"\1", quoted_val)
52
- else:
53
- value = unquoted_val
54
-
55
- params[key] = value
56
-
57
- # 4. Attach parameter dict and set each parameter as an attribute
58
- obj.parameters = params
59
- for key, val in params.items():
60
- # Use valid Python identifiers or fallback access via obj.parameters
61
- if key.isidentifier():
62
- setattr(obj, key, val)
63
-
64
- return obj
65
-
66
- def __getattr__(self, name: str) -> str:
67
- try:
68
- return self.parameters[name]
69
- except KeyError:
70
- raise AttributeError(
71
- f"{type(self).__name__!r} object has no attribute {name!r}"
72
- ) from None
73
-
74
- def to_header(self) -> str:
75
- """
76
- Reconstruct the full Content-Type header string, including parameters.
77
- """
78
- header = str(self)
79
- for key, value in self.parameters.items():
80
- if re.search(r'[\s";=]', value):
81
- escaped = value.replace("\\", "\\\\").replace('"', '\\"')
82
- header += f'; {key}="{escaped}"'
83
- else:
84
- header += f"; {key}={value}"
85
- return header
@@ -1,59 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from typing import Callable, Optional
3
- from .message import Message
4
- from concurrent.futures import Future
5
-
6
- MessageCallback = Callable[[Message], None]
7
-
8
-
9
- class IBrokerConnection(ABC):
10
-
11
- @abstractmethod
12
- def publish(self, message: Message) -> Future:
13
- """
14
- Publishes a message to the provided topic with the provided parameters. If the connection to the broker is not established,
15
- the message may be queued until the connection is established.
16
- """
17
- pass
18
-
19
- @abstractmethod
20
- def subscribe(
21
- self, topic: str, callback: Optional[MessageCallback] = None, qos: int = 1
22
- ) -> int:
23
- """
24
- Subscribes to the provided topic. May queue the subscription until the connection to the broker is established.
25
- When a message is received on the topic, the provided callback will be executed if provided.
26
- Returns a subscription identifier for the subscription.
27
- """
28
- pass
29
-
30
- @abstractmethod
31
- def add_message_callback(self, callback: MessageCallback) -> None:
32
- """
33
- The provided callback is called for all received messages that do not have a specific callback registered via the subscribe method.
34
- """
35
- pass
36
-
37
- @abstractmethod
38
- def is_topic_sub(self, topic: str, sub: str) -> bool:
39
- """Returns True if the provided topic matches the provided subscription filter."""
40
- pass
41
-
42
- @property
43
- @abstractmethod
44
- def online_topic(self) -> Optional[str]:
45
- pass
46
-
47
- @property
48
- @abstractmethod
49
- def client_id(self) -> str:
50
- pass
51
-
52
- @abstractmethod
53
- def is_connected(self) -> bool:
54
- """Returns True if the connection to the broker is established."""
55
- pass
56
-
57
- def unpublish_retained(self, topic):
58
- msg = Message(topic=topic, payload=b"", qos=1, retain=True)
59
- self.publish(msg)
@@ -1,85 +0,0 @@
1
- from dataclasses import dataclass, field
2
- from typing import Optional, Dict, Any, List
3
- from paho.mqtt.client import MQTTMessage
4
- from paho.mqtt.properties import Properties as MqttProperties
5
- from paho.mqtt.packettypes import PacketTypes
6
-
7
- from .contenttype import ContentType
8
-
9
-
10
- @dataclass
11
- class Message:
12
- topic: str
13
- payload: bytes
14
- qos: int
15
- retain: bool = False
16
- content_type: Optional[str] = None
17
- correlation_data: Optional[bytes] = None
18
- response_topic: Optional[str] = None
19
- subscription_ids: List[int] = field(default_factory=list) # Ignored on publish
20
- message_expiry_interval: Optional[int] = None
21
- user_properties: Dict[str, str] = field(default_factory=dict)
22
-
23
- def __post_init__(self):
24
- if self.user_properties is None:
25
- self.user_properties = dict()
26
-
27
- def set_user_property(self, key: str, value: str) -> None:
28
- if self.user_properties is None:
29
- self.user_properties = dict()
30
- self.user_properties[key] = value
31
-
32
- def paho_kwargs(self) -> Dict[str, Any]:
33
- props = MqttProperties(PacketTypes.PUBLISH)
34
- if self.content_type is not None:
35
- props.ContentType = (
36
- self.content_type.to_header()
37
- if isinstance(self.content_type, ContentType)
38
- else self.content_type
39
- )
40
- if self.correlation_data is not None:
41
- props.CorrelationData = self.correlation_data
42
- if self.response_topic is not None:
43
- props.ResponseTopic = self.response_topic
44
- if self.message_expiry_interval is not None:
45
- props.MessageExpiryInterval = self.message_expiry_interval
46
- if self.user_properties is not None and len(self.user_properties) > 0:
47
- props.UserProperty = list(self.user_properties.items())
48
- kwargs = {
49
- "topic": self.topic,
50
- "payload": self.payload,
51
- "qos": self.qos,
52
- "retain": self.retain,
53
- "properties": props,
54
- }
55
- return kwargs
56
-
57
- @classmethod
58
- def from_paho_message(cls, paho_msg: MQTTMessage) -> "Message":
59
- msg_obj = cls(
60
- topic=paho_msg.topic,
61
- payload=paho_msg.payload,
62
- qos=paho_msg.qos,
63
- retain=paho_msg.retain,
64
- )
65
- properties = (
66
- paho_msg.properties.__dict__ if hasattr(paho_msg, "properties") else {}
67
- )
68
- if "UserProperty" in properties:
69
- msg_obj.user_properties = dict(properties["UserProperty"])
70
- if "ContentType" in properties and isinstance(properties["ContentType"], str):
71
- msg_obj.content_type = ContentType(properties["ContentType"])
72
- if "CorrelationData" in properties:
73
- msg_obj.correlation_data = properties["CorrelationData"]
74
- if "ResponseTopic" in properties:
75
- msg_obj.response_topic = properties["ResponseTopic"]
76
- if "MessageExpiryInterval" in properties:
77
- msg_obj.message_expiry_interval = properties["MessageExpiryInterval"]
78
- if "SubscriptionIdentifier" in properties:
79
- sub_ids = (
80
- properties["SubscriptionIdentifier"]
81
- if isinstance(properties["SubscriptionIdentifier"], list)
82
- else [properties["SubscriptionIdentifier"]]
83
- )
84
- msg_obj.subscription_ids = sub_ids
85
- return msg_obj
@@ -1,140 +0,0 @@
1
- import unittest
2
- from pyqttier.contenttype import ContentType
3
-
4
-
5
- class TestContentType(unittest.TestCase):
6
- def test_standard_text_html_with_charset(self):
7
- """Standard text/html with charset parameter"""
8
- ct = ContentType("text/html; charset=utf-8")
9
-
10
- self.assertEqual(str(ct), "text/html")
11
- self.assertEqual(ct, "text/html")
12
- self.assertEqual(ct.charset, "utf-8")
13
- self.assertEqual(ct.upper(), "TEXT/HTML")
14
-
15
- def test_multipart_form_data_with_quoted_boundary(self):
16
- """Multipart form-data with quoted boundary and ttl parameters"""
17
- header = 'multipart/form-data; boundary="---WebKitFormBoundary7MA4YWxk"; ttl=30'
18
- ct = ContentType(header)
19
-
20
- self.assertEqual(str(ct), "multipart/form-data")
21
- self.assertEqual(ct.boundary, "---WebKitFormBoundary7MA4YWxk")
22
- self.assertEqual(ct.ttl, "30")
23
-
24
- def test_simple_content_type_no_parameters(self):
25
- """Content type with no parameters defaults to standard string behavior"""
26
- ct = ContentType("application/json")
27
-
28
- self.assertEqual(str(ct), "application/json")
29
- self.assertFalse(hasattr(ct, "charset"))
30
- self.assertEqual(ct.parameters, {})
31
-
32
- def test_content_type_is_string_subclass(self):
33
- """ContentType is a str subclass and supports string methods"""
34
- ct = ContentType("text/plain")
35
-
36
- self.assertIsInstance(ct, str)
37
- self.assertEqual(ct.upper(), "TEXT/PLAIN")
38
- self.assertTrue(ct.startswith("text"))
39
-
40
- def test_empty_content_type_raises_error(self):
41
- """Empty or whitespace-only Content-Type raises ValueError"""
42
- with self.assertRaises(ValueError):
43
- ContentType("")
44
-
45
- with self.assertRaises(ValueError):
46
- ContentType(" ")
47
-
48
- def test_invalid_content_type_format_raises_error(self):
49
- """Content-Type without '/' raises ValueError"""
50
- with self.assertRaises(ValueError):
51
- ContentType("invalid")
52
-
53
- def test_parameters_dict_access(self):
54
- """Parameters can be accessed via parameters dict"""
55
- ct = ContentType("text/html; charset=utf-8; boundary=test")
56
-
57
- self.assertEqual(ct.parameters["charset"], "utf-8")
58
- self.assertEqual(ct.parameters["boundary"], "test")
59
- self.assertEqual(len(ct.parameters), 2)
60
-
61
- def test_case_insensitive_parsing(self):
62
- """Content-Type and parameters are parsed case-insensitively"""
63
- ct = ContentType("TEXT/HTML; CHARSET=utf-8")
64
-
65
- self.assertEqual(str(ct), "text/html")
66
- self.assertEqual(ct.charset, "utf-8")
67
-
68
- def test_construct_from_existing_content_type_clones_parameters(self):
69
- """Constructing from an existing ContentType clones its parameters"""
70
- original = ContentType("text/html; charset=utf-8; boundary=test")
71
- clone = ContentType(original)
72
-
73
- self.assertEqual(str(clone), "text/html")
74
- self.assertEqual(clone.parameters, original.parameters)
75
- self.assertEqual(clone.charset, "utf-8")
76
- self.assertEqual(clone.boundary, "test")
77
-
78
- def test_construct_from_existing_content_type_is_independent_copy(self):
79
- """Cloned parameters dict is a separate object from the original"""
80
- original = ContentType("text/html; charset=utf-8")
81
- clone = ContentType(original)
82
-
83
- self.assertIsNot(clone.parameters, original.parameters)
84
-
85
- def test_to_header_no_parameters(self):
86
- """to_header returns just the type/subtype when there are no parameters"""
87
- ct = ContentType("application/json")
88
-
89
- self.assertEqual(ct.to_header(), "application/json")
90
-
91
- def test_to_header_unquoted_parameter(self):
92
- """to_header leaves simple parameter values unquoted"""
93
- ct = ContentType("text/html; charset=utf-8")
94
-
95
- self.assertEqual(ct.to_header(), "text/html; charset=utf-8")
96
-
97
- def test_to_header_leaves_simple_boundary_unquoted(self):
98
- """to_header omits quotes for values with no characters requiring them"""
99
- ct = ContentType(
100
- 'multipart/form-data; boundary="---WebKitFormBoundary7MA4YWxk"'
101
- )
102
-
103
- self.assertEqual(
104
- ct.to_header(),
105
- "multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxk",
106
- )
107
-
108
- def test_to_header_quotes_values_with_special_characters(self):
109
- """to_header quotes parameter values containing whitespace, quotes, ';' or '='"""
110
- ct = ContentType('text/plain; label="hello world"')
111
-
112
- self.assertEqual(
113
- ct.to_header(),
114
- 'text/plain; label="hello world"',
115
- )
116
-
117
- def test_to_header_round_trips_through_content_type(self):
118
- """Reconstructed header can be parsed again into an equivalent ContentType"""
119
- original = ContentType(
120
- 'multipart/form-data; boundary="---WebKitFormBoundary7MA4YWxk"; ttl=30'
121
- )
122
- roundtripped = ContentType(original.to_header())
123
-
124
- self.assertEqual(original, roundtripped)
125
- self.assertEqual(original.parameters, roundtripped.parameters)
126
-
127
- def test_to_header_escapes_embedded_quotes(self):
128
- """to_header escapes embedded double quotes in quoted values"""
129
- ct = ContentType('text/plain; label="say \\"hi\\""')
130
-
131
- self.assertEqual(ct.label, 'say "hi"')
132
-
133
- header = ct.to_header()
134
- reparsed = ContentType(header)
135
-
136
- self.assertEqual(reparsed.label, ct.label)
137
-
138
-
139
- if __name__ == "__main__":
140
- unittest.main()
@@ -1,333 +0,0 @@
1
- import unittest
2
- from pyqttier.message import Message
3
- from pyqttier.contenttype import ContentType
4
- from paho.mqtt.client import MQTTMessage
5
- from paho.mqtt.properties import Properties as MqttProperties
6
- from paho.mqtt.packettypes import PacketTypes
7
-
8
-
9
- class TestMessage(unittest.TestCase):
10
- """Test Message class."""
11
-
12
- def test_set_user_property_initializes_dict(self):
13
- """Test that set_user_property initializes user_properties when None."""
14
- msg = Message(topic="test", payload=b"data", qos=0)
15
- # user_properties should be initialized to empty dict in __post_init__
16
- self.assertIsNotNone(msg.user_properties)
17
-
18
- msg.set_user_property("key1", "value1")
19
- self.assertEqual(msg.user_properties["key1"], "value1")
20
-
21
- def test_set_user_property_single_property(self):
22
- """Test setting a single user property."""
23
- msg = Message(topic="test", payload=b"data", qos=0)
24
- msg.set_user_property("color", "red")
25
-
26
- self.assertEqual(len(msg.user_properties), 1)
27
- self.assertEqual(msg.user_properties["color"], "red")
28
-
29
- def test_set_user_property_multiple_properties(self):
30
- """Test setting multiple user properties."""
31
- msg = Message(topic="test", payload=b"data", qos=0)
32
- msg.set_user_property("color", "red")
33
- msg.set_user_property("size", "large")
34
- msg.set_user_property("quantity", "10")
35
-
36
- self.assertEqual(len(msg.user_properties), 3)
37
- self.assertEqual(msg.user_properties["color"], "red")
38
- self.assertEqual(msg.user_properties["size"], "large")
39
- self.assertEqual(msg.user_properties["quantity"], "10")
40
-
41
- def test_set_user_property_overwrites_existing(self):
42
- """Test that set_user_property overwrites existing values."""
43
- msg = Message(topic="test", payload=b"data", qos=0)
44
- msg.set_user_property("key", "value1")
45
- self.assertEqual(msg.user_properties["key"], "value1")
46
-
47
- msg.set_user_property("key", "value2")
48
- self.assertEqual(msg.user_properties["key"], "value2")
49
- self.assertEqual(len(msg.user_properties), 1)
50
-
51
- def test_set_user_property_empty_string_value(self):
52
- """Test setting a user property with an empty string value."""
53
- msg = Message(topic="test", payload=b"data", qos=0)
54
- msg.set_user_property("empty", "")
55
-
56
- self.assertEqual(msg.user_properties["empty"], "")
57
-
58
- def test_set_user_property_special_characters(self):
59
- """Test setting user properties with special characters."""
60
- msg = Message(topic="test", payload=b"data", qos=0)
61
- msg.set_user_property("special-key_123", "value-with-special_chars!@#")
62
-
63
- self.assertEqual(
64
- msg.user_properties["special-key_123"], "value-with-special_chars!@#"
65
- )
66
-
67
- def test_set_user_property_with_initial_properties(self):
68
- """Test set_user_property when initialized with existing properties."""
69
- initial_props = {"existing": "value"}
70
- msg = Message(
71
- topic="test", payload=b"data", qos=0, user_properties=initial_props
72
- )
73
-
74
- msg.set_user_property("new_key", "new_value")
75
-
76
- self.assertEqual(len(msg.user_properties), 2)
77
- self.assertEqual(msg.user_properties["existing"], "value")
78
- self.assertEqual(msg.user_properties["new_key"], "new_value")
79
-
80
- def test_default_values(self):
81
- """Test that a minimal Message has the expected default field values."""
82
- msg = Message(topic="test/topic", payload=b"data", qos=1)
83
-
84
- self.assertEqual(msg.topic, "test/topic")
85
- self.assertEqual(msg.payload, b"data")
86
- self.assertEqual(msg.qos, 1)
87
- self.assertFalse(msg.retain)
88
- self.assertIsNone(msg.content_type)
89
- self.assertIsNone(msg.correlation_data)
90
- self.assertIsNone(msg.response_topic)
91
- self.assertEqual(msg.subscription_ids, [])
92
- self.assertIsNone(msg.message_expiry_interval)
93
- self.assertEqual(msg.user_properties, {})
94
-
95
- def test_post_init_with_explicit_none_user_properties(self):
96
- """Test that passing user_properties=None explicitly is normalized to {}."""
97
- msg = Message(topic="test", payload=b"", qos=0, user_properties=None) # type: ignore[arg-type]
98
- self.assertEqual(msg.user_properties, {})
99
-
100
- def test_paho_kwargs_minimal_fields(self):
101
- """Test paho_kwargs with only required fields set."""
102
- msg = Message(topic="test/topic", payload=b"hello", qos=1)
103
- kwargs = msg.paho_kwargs()
104
-
105
- self.assertEqual(kwargs["topic"], "test/topic")
106
- self.assertEqual(kwargs["payload"], b"hello")
107
- self.assertEqual(kwargs["qos"], 1)
108
- self.assertFalse(kwargs["retain"])
109
-
110
- props = kwargs["properties"]
111
- self.assertNotIn("ContentType", props.__dict__)
112
- self.assertNotIn("CorrelationData", props.__dict__)
113
- self.assertNotIn("ResponseTopic", props.__dict__)
114
- self.assertNotIn("MessageExpiryInterval", props.__dict__)
115
- self.assertNotIn("UserProperty", props.__dict__)
116
-
117
- def test_paho_kwargs_retain_flag(self):
118
- """Test that the retain flag is passed through to paho_kwargs."""
119
- msg = Message(topic="test", payload=b"", qos=2, retain=True)
120
- kwargs = msg.paho_kwargs()
121
- self.assertTrue(kwargs["retain"])
122
- self.assertEqual(kwargs["qos"], 2)
123
-
124
- def test_paho_kwargs_with_optional_properties(self):
125
- """Test that optional properties are set on the paho Properties object."""
126
- msg = Message(
127
- topic="test",
128
- payload=b"data",
129
- qos=1,
130
- content_type="application/json",
131
- correlation_data=b"corr-id",
132
- response_topic="resp/topic",
133
- message_expiry_interval=60,
134
- )
135
- props = msg.paho_kwargs()["properties"]
136
-
137
- self.assertEqual(props.ContentType, "application/json")
138
- self.assertEqual(props.CorrelationData, b"corr-id")
139
- self.assertEqual(props.ResponseTopic, "resp/topic")
140
- self.assertEqual(props.MessageExpiryInterval, 60)
141
-
142
- def test_paho_kwargs_content_type_with_extra_properties_uses_full_header(self):
143
- """Test that a ContentType with parameters is serialized as a full header string."""
144
- msg = Message(
145
- topic="test",
146
- payload=b"data",
147
- qos=1,
148
- content_type=ContentType("text/html; charset=utf-8; boundary=xyz"),
149
- )
150
- props = msg.paho_kwargs()["properties"]
151
-
152
- self.assertEqual(props.ContentType, "text/html; charset=utf-8; boundary=xyz")
153
-
154
- def test_paho_kwargs_content_type_plain_string_unaffected(self):
155
- """Test that a plain str content_type (not a ContentType) is passed through as-is."""
156
- msg = Message(
157
- topic="test", payload=b"data", qos=1, content_type="application/json"
158
- )
159
- props = msg.paho_kwargs()["properties"]
160
-
161
- self.assertEqual(props.ContentType, "application/json")
162
-
163
- def test_from_paho_message_content_type_parses_extra_properties(self):
164
- """Test that a Content-Type header with parameters is parsed into a ContentType."""
165
- props = MqttProperties(PacketTypes.PUBLISH)
166
- props.ContentType = "multipart/form-data; boundary=xyz; charset=utf-8"
167
- paho_msg = self._make_paho_message("test", b"data", properties=props)
168
-
169
- msg = Message.from_paho_message(paho_msg)
170
-
171
- assert isinstance(msg.content_type, ContentType)
172
- self.assertEqual(str(msg.content_type), "multipart/form-data")
173
- self.assertEqual(msg.content_type.boundary, "xyz")
174
- self.assertEqual(msg.content_type.charset, "utf-8")
175
-
176
- def test_round_trip_content_type_with_extra_properties(self):
177
- """Test that content_type parameters survive a full publish/receive round trip."""
178
- original = Message(
179
- topic="round/trip",
180
- payload=b"payload-data",
181
- qos=1,
182
- content_type=ContentType("text/html; charset=utf-8; boundary=xyz"),
183
- )
184
-
185
- kwargs = original.paho_kwargs()
186
- paho_msg = MQTTMessage(topic=kwargs["topic"].encode())
187
- paho_msg.payload = kwargs["payload"]
188
- paho_msg.qos = kwargs["qos"]
189
- paho_msg.retain = kwargs["retain"]
190
- paho_msg.properties = kwargs["properties"]
191
-
192
- reconstructed = Message.from_paho_message(paho_msg)
193
-
194
- assert isinstance(reconstructed.content_type, ContentType)
195
- assert isinstance(original.content_type, ContentType)
196
- self.assertEqual(str(reconstructed.content_type), "text/html")
197
- self.assertEqual(
198
- reconstructed.content_type.parameters, original.content_type.parameters
199
- )
200
- self.assertEqual(reconstructed.content_type.charset, "utf-8")
201
- self.assertEqual(reconstructed.content_type.boundary, "xyz")
202
-
203
- def test_paho_kwargs_with_user_properties(self):
204
- """Test that non-empty user_properties are converted to UserProperty pairs."""
205
- msg = Message(topic="test", payload=b"", qos=0)
206
- msg.set_user_property("k1", "v1")
207
- msg.set_user_property("k2", "v2")
208
-
209
- props = msg.paho_kwargs()["properties"]
210
- self.assertEqual(
211
- sorted(props.UserProperty), sorted([("k1", "v1"), ("k2", "v2")])
212
- )
213
-
214
- def test_paho_kwargs_empty_user_properties_omitted(self):
215
- """Test that empty user_properties do not set UserProperty on the properties object."""
216
- msg = Message(topic="test", payload=b"", qos=0)
217
- props = msg.paho_kwargs()["properties"]
218
- self.assertNotIn("UserProperty", props.__dict__)
219
-
220
- @staticmethod
221
- def _make_paho_message(topic, payload, qos=0, retain=False, properties=None):
222
- """Helper to build a real paho MQTTMessage for from_paho_message tests."""
223
- paho_msg = MQTTMessage(topic=topic.encode())
224
- paho_msg.payload = payload
225
- paho_msg.qos = qos
226
- paho_msg.retain = retain
227
- if properties is not None:
228
- paho_msg.properties = properties
229
- return paho_msg
230
-
231
- def test_from_paho_message_basic_fields(self):
232
- """Test conversion of core fields with no MQTT v5 properties set."""
233
- props = MqttProperties(PacketTypes.PUBLISH)
234
- paho_msg = self._make_paho_message(
235
- "test/topic", b"hello", qos=1, retain=True, properties=props
236
- )
237
-
238
- msg = Message.from_paho_message(paho_msg)
239
-
240
- self.assertEqual(msg.topic, "test/topic")
241
- self.assertEqual(msg.payload, b"hello")
242
- self.assertEqual(msg.qos, 1)
243
- self.assertTrue(msg.retain)
244
- self.assertIsNone(msg.content_type)
245
- self.assertEqual(msg.user_properties, {})
246
- self.assertEqual(msg.subscription_ids, [])
247
-
248
- def test_from_paho_message_with_all_properties(self):
249
- """Test conversion of all optional MQTT v5 properties."""
250
- props = MqttProperties(PacketTypes.PUBLISH)
251
- props.ContentType = "text/plain"
252
- props.CorrelationData = b"abc123"
253
- props.ResponseTopic = "reply/topic"
254
- props.MessageExpiryInterval = 3600
255
- props.UserProperty = [("a", "1"), ("b", "2")]
256
- paho_msg = self._make_paho_message("test", b"data", properties=props)
257
-
258
- msg = Message.from_paho_message(paho_msg)
259
-
260
- self.assertEqual(msg.content_type, "text/plain")
261
- self.assertEqual(msg.correlation_data, b"abc123")
262
- self.assertEqual(msg.response_topic, "reply/topic")
263
- self.assertEqual(msg.message_expiry_interval, 3600)
264
- self.assertEqual(msg.user_properties, {"a": "1", "b": "2"})
265
-
266
- def test_from_paho_message_subscription_id_single_int(self):
267
- """Test that a single SubscriptionIdentifier is wrapped into a list."""
268
- props = MqttProperties(PacketTypes.PUBLISH)
269
- props.SubscriptionIdentifier = 5
270
- paho_msg = self._make_paho_message("test", b"", properties=props)
271
-
272
- msg = Message.from_paho_message(paho_msg)
273
- self.assertEqual(msg.subscription_ids, [5])
274
-
275
- def test_from_paho_message_subscription_id_list(self):
276
- """Test that a list of SubscriptionIdentifiers is preserved as-is."""
277
- props = MqttProperties(PacketTypes.PUBLISH)
278
- props.SubscriptionIdentifier = [1, 2, 3]
279
- paho_msg = self._make_paho_message("test", b"", properties=props)
280
-
281
- msg = Message.from_paho_message(paho_msg)
282
- self.assertEqual(msg.subscription_ids, [1, 2, 3])
283
-
284
- def test_from_paho_message_missing_properties_raises(self):
285
- """Test current behavior when paho_msg.properties is left as None (default).
286
-
287
- MQTTMessage initializes `properties` to None, and from_paho_message
288
- unconditionally accesses `.properties.__dict__`, so this raises
289
- AttributeError rather than falling back to an empty dict.
290
- """
291
- paho_msg = MQTTMessage(topic=b"test/topic")
292
- paho_msg.payload = b"data"
293
- with self.assertRaises(AttributeError):
294
- Message.from_paho_message(paho_msg)
295
-
296
- def test_round_trip_paho_kwargs_and_from_paho_message(self):
297
- """Test that paho_kwargs -> MQTTMessage -> from_paho_message round-trips."""
298
- original = Message(
299
- topic="round/trip",
300
- payload=b"payload-data",
301
- qos=2,
302
- retain=True,
303
- content_type="application/json",
304
- correlation_data=b"corr",
305
- response_topic="resp",
306
- message_expiry_interval=120,
307
- )
308
- original.set_user_property("x", "y")
309
-
310
- kwargs = original.paho_kwargs()
311
- paho_msg = MQTTMessage(topic=kwargs["topic"].encode())
312
- paho_msg.payload = kwargs["payload"]
313
- paho_msg.qos = kwargs["qos"]
314
- paho_msg.retain = kwargs["retain"]
315
- paho_msg.properties = kwargs["properties"]
316
-
317
- reconstructed = Message.from_paho_message(paho_msg)
318
-
319
- self.assertEqual(reconstructed.topic, original.topic)
320
- self.assertEqual(reconstructed.payload, original.payload)
321
- self.assertEqual(reconstructed.qos, original.qos)
322
- self.assertEqual(reconstructed.retain, original.retain)
323
- self.assertEqual(reconstructed.content_type, original.content_type)
324
- self.assertEqual(reconstructed.correlation_data, original.correlation_data)
325
- self.assertEqual(reconstructed.response_topic, original.response_topic)
326
- self.assertEqual(
327
- reconstructed.message_expiry_interval, original.message_expiry_interval
328
- )
329
- self.assertEqual(reconstructed.user_properties, original.user_properties)
330
-
331
-
332
- if __name__ == "__main__":
333
- unittest.main()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes