Wednesday, April 28, 2021
Java Haiku: Forever
Thursday, April 15, 2021
Creating AWS resources in pytest fixtures with moto
When unit testing functions that access AWS resources, the easiest way is to use the moto library. For instance, I have to test several functions that access an SQS queue, so I proceed this way:
Since I had this create_queue() call at the beginning of most of my test functions, I wanted to make it a fixture. So i tried this way:
Unfortunately, this raised an error in my test functions stating that the queue does not exist. The reason for it is that the decorator @mock_sqs on the fixture would destroy my SQS queue as soon as it would leave the queue() method.
The solution is simple: do not use the mock as a decorator, but trigger it when the fixture is initializing and destroy it when it terminates. That means using a yield within the fixture to return the queue:
Notice that we have to drop the decorator on the test function as well.
Thanks for the answers to this moto issue.