Skip to content

Commit

Permalink
Unsusbcribe from MQTT topics after stage is finished (#250)
Browse files Browse the repository at this point in the history
* Add initial change to unsusbcribe after

[ci skip]

* Implement unsubscribe
  • Loading branch information
michaelboulton authored and benhowes committed Feb 2, 2019
1 parent f4469ea commit a5e4a7b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 13 deletions.
5 changes: 5 additions & 0 deletions tavern/_plugins/mqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,11 @@ def subscribe(self, topic, *args, **kwargs):
else:
logger.error("Error subscribing to '%s'", topic)

def unsubscribe_all(self):
"""Unsubscribe from all topics"""
for (topic, _) in self._subscribed.values():
self._client.unsubscribe(topic)

def _on_subscribe(self, client, userdata, mid, granted_qos):
# pylint: disable=unused-argument
if mid in self._subscribed:
Expand Down
39 changes: 26 additions & 13 deletions tavern/_plugins/mqtt/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,7 @@ def __str__(self):
else:
return "<Not run yet>"

def verify(self, response):
"""Ensure mqtt message has arrived
Args:
response: not used
"""
# pylint: disable=too-many-statements

self.response = response

topic = self.expected["topic"]
timeout = self.expected.get("timeout", 1)

def _get_payload_vals(self):
# TODO move this check to initialisation/schema checking
if "json" in self.expected:
if "payload" in self.expected:
Expand All @@ -73,8 +61,19 @@ def verify(self, response):
payload = None
json_payload = False

return payload, json_payload

def _await_response(self):
"""Actually wait for response"""
topic = self.expected["topic"]
timeout = self.expected.get("timeout", 1)

payload, json_payload = self._get_payload_vals()

time_spent = 0

msg = None

while time_spent < timeout:
t0 = time.time()

Expand Down Expand Up @@ -162,3 +161,17 @@ def verify(self, response):
)

return {}

def verify(self, response):
"""Ensure mqtt message has arrived
Args:
response: not used
"""

self.response = response

try:
return self._await_response()
finally:
self._client.unsubscribe_all()

0 comments on commit a5e4a7b

Please sign in to comment.