Reputation: 8533
I am trying to write a unit test for an existing function:
def _fetch_law(self, task, storage):
number, link = task
if not self.silent:
print 'Requesting page %s' % number
r = requests.get(link, headers=self.headers)
if r.status_code != 200:
sys.exit('CONNECTION ERROR!!! HTTP ERROR %d' % r.status_code)
vs = LawPages(r.text)
storage.extend(vs.extract())
For my unit testing, how do I use mocking or other means to get to the final value that is passed to storage ?
Upvotes: 0
Views: 99
Reputation: 829
Lawrence is correct, just do something simple like:
def test_fetch_law():
store = []
task = ...
cls = ClassWithFetchLaw()
cls._fetch_law(task, store)
assert len(store) > 0
On another note, if you're going down the unit test route, why not have the sys.exit throw an exception and write another test for it? Unless you really want the sys.exit in there...
def test_fetch_law_throws():
store = []
bad_task = ...
cls = ClassWithFetchLaw()
with pytest.raises(Exception):
cls._fetch_law(bad_task, store)
Upvotes: 0
Reputation: 310099
I generally use the mock
library (unittest.mock
in python3.x). It would look something like:
mock_storage = mock.Mock()
obj._fetch_law(some_task, mock_storage)
mock_storage.extend.assert_called_with(expected_value)
Of course, in this example, you might want to mock out requests as well... mock.patch
is great for that:
with mock.patch.object(requests, 'get') as mock_get:
mock_get.return_value = ' ... '
mock_storage = mock.Mock()
obj._fetch_law(some_task, mock_storage)
mock_storage.extend.assert_called_with(expected_value)
Upvotes: 0
Reputation: 1406
As you are passing storage
to the function, why don't you just create an empty list which you pass on. The function will append to storage
and you can then check, what is in that list and if it is the expected result.
Upvotes: 2