You could use mock_open
, but that would be a glass-box test breaking the encapsulation of the function. If the filename changes, the test breaks. If it changes its implementation, the test breaks.
More importantly, it ignores what your test is telling you.
Testing is a great way to find out where your design is too rigid. If you find a function hard to test, its probably hard to use. Hard coded filenames are a classic example. This is an opportunity to make the code more flexible. For example, introduce a configuration object.
def function():
with open(MyApp.config('function','file'), 'r') as file:
# read for information in file
return information_from_file
Exactly how this is implemented depends on your situation. You can use Python's built in ConfigParser to work with the config file. And here I've gone with an application singleton object to store application-wide information.
Then you have two tests. One which checks the default MyApp.config('function','file')
is as expected. And other which sets MyApp.config('function','file')
to a temp file and tests the function reads it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…