Damian Silkowski
Damian Silkowski

Reputation: 137

How to replace variable inside function in unittest- pytest

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

Upvotes: 4

Views: 10865

Answers (2)

Radostin Stoyanov
Radostin Stoyanov

Reputation: 336

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)

Upvotes: 4

Sriram
Sriram

Reputation: 1738

You should try mock os.listdir to return the mock test data.

Upvotes: -1

Related Questions