Kyle Bridburg
Kyle Bridburg

Reputation: 23

Mocking requests.Session() with pytest's mocker.patch.object

I'm attempting to mock a requests Session created in a class I'm testing. When the mock is created it appears to work but the mock created in the class isn't the same

class ClassToTest:
  def make_request(url):
    with requests.Session() as session:
      print(session)
      response = session.request(url)
    return response
@pytest.fixture
def mock_session(mocker):
    mock_session = mocker.patch.object(requests, 'Session', autospec=True)
    return mock_session
@pytest.mark.usefixtures('mock_session')
def test(self, mock_session):
  mock_session.request.return_value = expected
  print(mock_session)
  res = ClassToTest().make_request(url)
  assert expected == res

This test currently fails and the prints look like:

< MagicMock name='Session' spec='Session' id='1'>

< MagicMock name='Session().\__enter__()' id='2'>

Upvotes: 2

Views: 3666

Answers (1)

hoefling
hoefling

Reputation: 66451

That's because the ClassToTest is initializing the session in a with context. You need to tell the session mock to return itself on entering a with context, mimicking what the Session class does:

@pytest.fixture
def mock_session(mocker):
    mock_session = mocker.patch.object(requests, 'Session', autospec=True)
    mock_session.return_value.__enter__.return_value = mock_session
    return mock_session

Upvotes: 2

Related Questions