5

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 may want to look into the patch functionality of pytest-mock. Commented May 9, 2018 at 12:32

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I had a kind of eclipse of the mind because i know it, and I used it. Doesn't matter. Thanks for your help :)
How to mock if I have a list comprehension assigned as variable ? Eg ``` def xyx(): x = [s for i in list_example if i >0] # I want to mock this expression. ```
-1

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

2 Comments

Ok I can mock os.listdir but i need to variable path_dir.
If you mock it with the result you need to return, it will return that when it is called so it will be automatically stored to path_dir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.