Reputation: 1657
I have a function in my program that list all the files in a given path and I am trying to write a test that passes when there are no files exists in the path provided (empty output i.e []
) I am learning about mocker fixture of pytest
to do it. Here is what i have written,
def test_no_dirs(mocker):
mocker.patch('os.listdir')
assert get_list() #get_list returns ['abc.json', 'test.json', 'test2.json']
os.listdir.assert_called_with('/etc/app_data/',stdout=[])
I have used mocker as a parameter first then patch the os.listdir
function. os.listdir
is called in get_list()
, but i don't know how to change the return
value of os.listdir
to empty list, []
to mock empty directory.
When I run above command I get the following error,
E AssertionError: Expected call: listdir('/etc/app_data/', stdout='[]')
E Actual call: listdir('/etc/app_data/')
E
E pytest introspection follows:
E
E Kwargs:
E assert {} == {'stdout': '[]'}
E Right contains more items:
E {'stdout': '[]'}
E Full diff:
E - {}
E + {'stdout': '[]'}
How can I mock os.listdir
to return empty value and pass the test?
If i remove stdout=[]
, the test PASS
but its not really doing what i want to do, which is to pass when there are no files.
That's the code for get_list()
import os
def get_list():
return os.listdir('/etc/app_data/')
Upvotes: 2
Views: 1685
Reputation: 363556
The pytest-mock
version should look something like this:
def test_no_dirs(mocker):
mock = mocker.patch('os.listdir', return_value=[])
result = get_list()
assert result == [] # because that's the `return_value` mocked
mock.assert_called_once_with('/etc/app_data/')
Note that users who do from os import listdir
will need to mock in a different namespace!
Upvotes: 3