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:
JavaScript
x
9
1
import requests
2
3
def parse():
4
with requests.session() as s:
5
return s.get('foo')
6
7
if __name__ == "__main__":
8
parse()
9
test_main.py:
JavaScript
1
12
12
1
import unittest
2
import mock
3
from unittest.mock import patch
4
from main import parse
5
6
7
class TestDoSessionGet(unittest.TestCase):
8
@mock.patch('main.requests.session')
9
def test_should_mock_session_get(self, session_mock):
10
session_mock.return_value = mock.MagicMock(get=mock.MagicMock(return_value='bar'))
11
self.assertEqual(parse(), 'bar')
12
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
JavaScript
1
13
13
1
import unittest
2
from unittest import mock
3
from main import parse
4
5
6
class TestDoSessionGet(unittest.TestCase):
7
@mock.patch('main.requests.session')
8
def test_should_mock_session_get(self, session_mock):
9
mocked_session = mock.MagicMock()
10
mocked_session.__enter__.return_value = mock.MagicMock(get=mock.MagicMock(return_value='bar'))
11
session_mock.return_value = mocked_session
12
self.assertEqual(parse(), 'bar')
13