Mock testing in python using vcrpy
As a developer, someday or the other you will stumble into the world of testing. For legacy code, test is a necessity. The code is full of logic, it’s alive and it’s core to any application. We need to keep going back to the code to update it, so tests are crucial.
While working with the open human api , I landed into the area of mock testing in python. I mocked the API tests using vcrpy . It’s just like Thor’s stormbreaker(Marvel fan will understand ) in the field of unit testing. It’s apt for those applications which make http calls to external services.
Why vcrpy
The external service should not be tightly coupled with the application. If the external services fail, the application should still run correctly. One absolute novice testing way is to hard code error prone request and code the necessary error handling portions. But, this is highly not recommended because once you update even a few line of code, you have to manually test it again. So, we hop on to the more sophisticated way of testing: Unittesting.
Running tests which call the external service every time will be very slow. Apart from it, the tests won’t work offline and sending too many requests to the external service can be a problem too. So, here steps the protagonist, vcrpy. 😃
You just need to run the test online once when the cassette file which stores all the important information related to the requests response has not been created. Once, it is done, the response of requests will just be compared with the cassette file and yes , it’s done 😃 . You have became successful in making your application more sturdy.
How to use vcrpy
For each function serving a particular feature, a class for testing is created. For testing different lines of code of a particular feature, different tests(functions with assertion) is created in the test class. Tests for valid response, invalid responses are written.
Get Tarannum Khan’s stories in your inbox
Join Medium for free to get updates from this writer.
A simple example for testing a message feature which uses external API is shown below. The pseudo code of the message feature is shown below for valid and invalid access token (for digging deeper about access token, you can visit OAuth2).
def message(subject, message, access_token):
url = urlparse.urljoin('https://www.somexyz.org/api/message/{}'.
format(urlparse.urlencode(
{'access_token': access_token})))
response = requests.post(url, data={'subject': subject,
'message': message})
return responseThe message function take three arguments: subject, message and access_token. The function just uses post requests to hit an external url which give a response stored in the response variable. The tests for valid and invalid access_token for the message function is given below.
import vcr
from api import messageclass APITestMessage(TestCase): def setUp(self):
pass @my_vcr.use_cassette()
def test_message_valid_access_token(self):
response = message(subject=SUBJECT, message=MESSAGE,
access_token=ACCESS_TOKEN)
self.assertEqual(response.status_code, 200) @my_vcr.use_cassette()
def test_message_invalid_access_token(self):
with self.assertRaises(Exception):
response = message(subject=SUBJECT, message=MESSAGE,
access_token=ACCESS_TOKEN)
assert response.json() == {"detail": "Invalid token."}
In this portion of code, in the first test, subject, message and correct access_token is provided by the tester for getting the proper API response. The response is stored in a cassette file for each test. Response from the cassette file is retrieved and compared for testing. For the second test, subject, message and incorrect access_token is provided by the tester. For this function, exception will be raised accordingly. Again, in a different cassette file, response will be stored. The cassette files generated for the valid and invalid token is given below.
For the first time, when the test is run, the request really hits the external service and a cassette file is formed. Once the cassette is formed which contain status codes, status, etc, the response of tests is just compared with the cassette file when the tests are run again. It really speeds up the testing process and saves us from sending requests to the external service again and again. Whether you are offline at your home or 35,000 feet above the ground anytime you can test your code, once the cassettes are formed.
Want to try a hand on this cool stuff? You can follow https://github.com/OpenHumans/open-humans-api/blob/master/ohapi/tests/test_api.py. The link contains a lot of examples to write tests using vcrpy. You can see the bigger picture by observing any function in the https://github.com/OpenHumans/open-humans-api/blob/master/ohapi/api.py and how for each functions tests and cassettes are formed.
Till then, happy coding. 😃








