So if we place fixtures in a file called conftest.py inside a directory then all tests in the files in that directory will be able to use that fixture without needing to import it.
Use monkeypatch inbuilt pytest fixture with conftest.py for some amazing effects. For eg, if we have written code which uses secondary API calls and we want to test our code, we dont want to accidentally call the API's but instead mock them in our tests. This could be because we intend to run our tests on the cloud where we dont have access to the internet and hence API calls would fail or that the API calls are paid and so we dont want to invoke them in tests unnecessarily.
So in conftest.py, we could define a pytest fixture as below
@pytest.fixture(autouse=True)
def disable_network_calls(monkeypatch):
def stunted_get():
raise requests.exceptions.ConnectionError("Network calls are disabled in tests.")
monkeypatch.setattr(requests, "get", lambda *args, **kwargs: stunted_get())
and in our test file, we would then do the below
import requests
def test_monkeypatch_check():
try:
requests.get("https://google.com")
except requests.exceptions.ConnectionError as e:
assert str(e) == "Network calls are disabled in tests."
else:
assert False, "Expected ConnectionError was not raised."
Well the above test is kinda pointless. Its just to show how the monkeypatch with conftest.py works.
We can categorize tests as well. See this