Ignoring hosts with python vcr when writing tests with pytest and generating cassettes

How to ignore hosts with python vcr when writing tests with pytest and generating cassettes

If you are already using pytest to write your tests and are also using vcr to record and replay http responses, you already know that any http request is being recorded, so the next time the same request is made, the test won’t hit the real endpoint but it will use the recorded response.

Sometimes you need to exclude localhost (or other hosts) from being recorded and you can do thanks to this vcr parameter:

1
2
3
4
@pytest.mark.vcr(ignore_hosts=["localhost"])
def test_is_true():
    # Intentionally dumb test to make things simple
    assert True

This works, but what if you have many tests and you want to ignore localhost globally?

You can do it by adding this to your main conftest.py and all your vcr tests will ignore it by default:

1
2
3
4
5
@pytest.fixture(scope="module")
def vcr_config():
    return {
        "ignore_hosts": ["localhost"],
    }

That’s it! I hope you find this suggestion useful.

comments powered by Disqus
source code available on GitHub
Built with Hugo
Theme Stack designed by Jimmy