I want to mock requests.session() in unit test. It works when I don’t use with
statement, however it fails when I start using it. This is the code I execute:
main.py:
import requests def parse(): with requests.session() as s: return s.get('foo') if __name__ == "__main__": parse()
test_main.py:
import unittest import mock from unittest.mock import patch from main import parse class TestDoSessionGet(unittest.TestCase): @mock.patch('main.requests.session') def test_should_mock_session_get(self, session_mock): session_mock.return_value = mock.MagicMock(get=mock.MagicMock(return_value='bar')) self.assertEqual(parse(), 'bar')
Advertisement
Answer
Your test setup is ignoring the fact that s
comes from the __enter__
method of the context manager class.
You need to mock that call as well
import unittest from unittest import mock from main import parse class TestDoSessionGet(unittest.TestCase): @mock.patch('main.requests.session') def test_should_mock_session_get(self, session_mock): mocked_session = mock.MagicMock() mocked_session.__enter__.return_value = mock.MagicMock(get=mock.MagicMock(return_value='bar')) session_mock.return_value = mocked_session self.assertEqual(parse(), 'bar')