jeudi 1 août 2019

Testing a function that has some code dependent on a service that's unavailable during local testing?

I'm using pytest to test a Flask API that also makes use of MQTT. I'm late to the TDD game so this question could well be answered elsewhere but I can't think of the right way to frame it, so can't find anything that seems to answer it for me. This question that deals with mocking during integration tests sounds like it's on the right track.

Basically one of my tests looks like this

response = testing_client.post(
         "/api/users/1/devices",
         data=json.dumps(dict(device)),
         headers={"Authorization": "Token %s" % auth_token},
         content_type="application/json",
     )
assert response.status_code == 200

The problem is that the corresponding bit of code that handles these POST requests also publishes an MQTT message when the request has been handled i.e.

publish.single(f"{device_id}/active", msg, hostname=os.environ.get("MQTT_BROKER_URL"), retain=True, qos=0, port=int(os.environ.get("MQTT_BROKER_PORT")))

The API and MQTT broker are separate containers managed using Docker compose. When I'm testing locally there is no MQTT broker running and so any test here fails (even though I don't actually care about testing the MQTT code).

For any calls to the DB (Postgres) I actually set up a specific postgres container for testing and run tests against this. Should I do the same thing for MQTT testing (I would then also have to do it during the CI pipeline on GitLab), or is there a much more obvious solution that I am missing?

Aucun commentaire:

Enregistrer un commentaire