Skip to content
Advertisement

How do I mock a file open for a specific path in python?

So I know that in my unit test I can mock a context manager open(), i.e.:

JavaScript

mocked with

JavaScript

but is there a way for me to only mock it for a specific file path? Or maybe some other way to ensure that the context manager gets called with the correct path in a unit test?

Advertisement

Answer

To mock open only for a specific path, you have to provide your own mock object that handles open differently, depending on the path. Assuming we have some function:

JavaScript

where open shall be mocked to return a file with the content “bar” if path is “foo”, but otherwise just work as usual, you could do something like this:

JavaScript

If you don’t want to save the original open in a global variable, you could also wrap that into a class:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement