Skip to content

Commit

Permalink
Allow specifying 'unexpected' messages in MQTT to fail a test (#794)
Browse files Browse the repository at this point in the history
Closes #621
  • Loading branch information
michaelboulton committed Jun 26, 2022
1 parent e7afb27 commit d41c278
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
22 changes: 22 additions & 0 deletions example/mqtt/test_mqtt_failures.tavern.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,25 @@ stages:
topic: /device/123/status/response
timeout: 3
qos: 1

---

test_name: Test unexpected message fails

includes:
- !include common.yaml

paho-mqtt: *mqtt_spec

_xfail: run

stages:
- name: step 1 - ping/pong
mqtt_publish:
topic: /devices/status
mqtt_response:
topic: /device/123/status/response
payload: !anything
timeout: 3
qos: 1
unexpected: true
7 changes: 7 additions & 0 deletions tavern/_plugins/mqtt/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,13 @@ def addwarning(w, *args, **kwargs):
time_spent += time.time() - t0

if msg:
if self.expected.get("unexpected"):
self._adderr(
"Got '%s' on topic '%s' marked as unexpected",
expected_payload,
topic,
)

self._maybe_run_validate_functions(msg)
else:
self._adderr(
Expand Down
3 changes: 3 additions & 0 deletions tavern/schemas/tests.schema.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ schema;stage:
type: map
required: false
mapping:
unexpected:
type: bool
required: false
topic:
type: str
required: true
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/response/test_mqtt_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,18 @@ def test_correct_message_eventually(self, includes):
assert len(verifier.received_messages) == 2
assert verifier.received_messages[0].topic == fake_message_bad.topic
assert verifier.received_messages[1].topic == fake_message_good.topic

def test_unexpected_fail(self, includes):
"""Messages marked unexpected fail test"""

expected = {"topic": "/a/b/c", "payload": "hello", "unexpected": True}

fake_message = FakeMessage(expected)

verifier = self._get_fake_verifier(expected, [fake_message], includes)

with pytest.raises(exceptions.TestFailError):
verifier.verify(expected)

assert len(verifier.received_messages) == 1
assert verifier.received_messages[0].topic == fake_message.topic

0 comments on commit d41c278

Please sign in to comment.