Replay network requests on your tests: VCR.py

Today I'm happy to present you another library to aid with testing, this time related to tests that need network conectivity: VCR.py

VCR.py, a Python version of Ruby's VCR, works by recording the HTTP requests and responses your test makes, and then replays them when the tests is run again, thus achieving network independence. As a side effect, it also makes the test much faster, which is always nice.

Using it on a typical test is very easy, you just need to import it, and then surround the test that will interact with the network with a with vcr.cassete() block:



def test_colors_from_mapi(self):
    with vcr.use_cassette('tests/assets/vcr_cassettes/'\
            'color_mismatches-colors_from_mapi.yaml'):
        expected_result = set(self.mapi_colors)
        actual_result = color_mismatches.colors_from_mapi()

        self.assertEqual(expected_result, actual_result)

Here, I had a test that was making a request to an API, and building a color list with it. By adding the vcr block, and running the test once, a cassette in the path I specified was created with the contents of the HTTP interaction. When I run the test again, I could see by the speed that it was not making the request anymore, but working straight from the cassette.

You can find many configuration options on the repo for the library, I will not explain them here because I didn't even need them, which tells a lot about the simplicity of the tool ;)

This is yet another time when I find a library in Python doing just what I needed compared to when I was coding in Ruby (remember freezegun?). The switch between both languages is being much easier than I expected :)