问题
I have a problem with replace variable inside method which i have to test, namely:
def find_files(path):
path_dir = os.listdir(path)
...
and for needs of test I have to replace path_dir
from real result of os.listdir
to some test list i.e. ['whatever1.txt', 'whatever2.txt', 'whatever3.txt']
How to do it? BR, Damian
回答1:
You can use mock.patch to set return value for your variable. For example
with patch('os.listdir') as mocked_listdir:
mocked_listdir().return_value = ['.', '..']
find_files(path)
or alternatively you can set a side effect
with patch('os.listdir') as mocked_listdir:
mocked_listdir().side_effect = some_other_function
find_files(path)
回答2:
You should try mock os.listdir to return the mock test data.
来源:https://stackoverflow.com/questions/50253429/how-to-replace-variable-inside-function-in-unittest-pytest