Reputation: 4571
Imagine one writes a unit test for handle
for a case when path
does not exist:
def handle(path):
try:
with open(path) as f:
pass
except FileNotFoundError:
raise FileNotFoundError(path)
I would write something like below for such test:
import pytest
def test_handle_on_non_existent_path():
x = "abc" # some unbelievable string
with pytest.raises(FileNotFoundError):
handle(x)
My question is what is a better way to generate non-existent path for a unit-test.
My ideas are:
"abc"
is fairly concise, but in principle does guarantee path does not exist.
Update: in this question x
is "no_exist.txt"
Upvotes: 3
Views: 647
Reputation: 5939
With respect to unit-testing, it seems your intent is to test the behaviour of your code for the case that open(path)
will throw a FileNotFoundError
. Your approach is to have the code actually perform the open
call, but with a non-existent path name. This has some disadvantages: As you already noticed, the dependency on the real file system brings the question how to create a value for path
that reliably does not exist as a file on the file system. But, there is another point, namely that you are not even sure that there could not exist another problem with the file system, for example some permission related problem, which could cause some other exception to be raised (OSError
).
Put together, performing the call to open
itself means you are not in full control of what happens. Therefore, a better approach can be, for this unit test case, to mock open
and make your mock raise the FileNotFoundError
.
Upvotes: 1