Hi team, I’m currently having some issues with moc...
# general
w
Hi team, I’m currently having some issues with mocking with pants Currently I’m using
unittest.mock.patch
to mock, but it works when testing with pytests but not pants, I am wondering if there’s extra setup required to mock external apis with pants
conftest.py
Copy code
@pytest.fixture(scope="session")
def mock_api():
   mock_get_response_patcher = patch("some-api")
   mock_get_response = mock_get_response_patcher.start()
   mock_get_response.return_value = {....}
Then in my test, I have
A.py
Copy code
def test_A(..., mock_api):
   .....
   irrelevant code
   .....
I have verified the mock_api function is called correctly, but when I test it with pants, the mock function is called, but the
mock_get_response
value is not what I expected, and it will actually call the mocked function instead of returning the value I set it to be. However, when testing it with pytest, it works perfectly(it actually mocks), so I wonder if I had missed anything?
e
There's not much to go on here except session scope. It does not mean the same thing in Pants as under pytest since Pants runs 1 session per test file. If that sounds like it could be related to you given your mocking setup, then that's the issue.
Better put, Pants runs pytest against each test file individually.
w
yeah, but currently I just use
Copy code
pytest A.py
and
Copy code
./pants test --force A.py
to run a single file though, why is there difference
is there a suggested pytest mock setup to integrate with pants?
e
Ok, then something else. There should be nothing special about Pants here. I think you'll need to provide a repro example.
👍 1
I guess one obvious thing to check is the version of
pytest
you're running bare vs the version pants uses. Perhaps there is a relevant difference.
w
Resolved, this turned out is not a pants issue