How to replace variable inside function in unittest- pytest

走远了吗. 提交于 2021-02-08 10:00:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!