简体   繁体   中英

guaranteed unit test fixture for non-existent file

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:

  • force delete a temporary file
  • genereate a random string like uuid?

"abc" is fairly concise, but in principle does guarantee path does not exist.

Update: in this question x is "no_exist.txt"

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM