More handy pytest snippets

It's been a while, but I'm back messing with mocking again. This time I'm dealing with a code base with ~600 tests, about 50% of which make at least one external call to something, an API, a database, all sorts.

I've been trying to introduce a fun little library called Python VCR that records the restults of any external calls into yaml files, so the next time you run the test it uses the saved data rather than making the call again. Excellent news, right?

In theory, yes. I've mocked one call (used in lots of tests) and reduced the test duration by ~30% already, but for some reason I'm struggling to get it to mock the other ones and I can't figure out why.

In the process I've created a little pytest fixture that prevents any external http calls, and dumps a little list of what was trying to make the call so I can work out where to mock it. Handy, but my mocks still don't work and I have no idea why.

For future me, here's the fixture:

    @pytest.fixture(autouse=True)
def mock_socket(monkeypatch):
def not_a_socket(*args, **kwargs):
print("Using the socket.socket mock")

stack = inspect.stack()
for i, s in enumerate(stack):
print(f"{i} called by filename: {s.filename}, lineno {s.lineno}, function {s.function}")

monkeypatch.setattr(socket, 'socket', not_a_socket)