In order to mock file open in python, we can use the unittest.mock
module. Specifically, we can use the patch
decorator to replace the built-in open()
function with a mock version.
Here's an example of how to mock file open:
main.py611 chars19 lines
In this example, we create a mock file object using MagicMock()
. We then use the return_value
attribute to specify what data the mock should return when its read()
method is called.
We then use the patch
decorator to replace the built-in open()
function with a mock version that returns our mock file object. We pass the name of the function to patch as a string as the first argument to patch
.
Inside the with
block, any call to open()
will now return our mock file object instead of the built-in function. We can then make assertions about how our function interacts with the file object, such as calling read()
once and opening the file with the correct arguments.
gistlibby LogSnag