pepero
pepero

Reputation: 7513

test for the file related function in python

I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows.

def copy_file (self):   
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    try:
        shutil.copy2(src_path, dest_path)
    except IOError as e:
        print e

What should I do about testing above function? what should I assert (directory, file content, exceptions)?

Upvotes: 1

Views: 762

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114767

Think about requirements you put on your method, like:

  • The method shall report an error in case source_dir does not exist or either source or destination director are not accessible
  • The method shall report create destination_dir if it does not exist and report an error if destination dir cannot be created
  • The method shall report an error if either source or destination dir have illegal values (null or illegal chars for directories)
  • The method shall copy all files from source to destination directory
    • check, if all files have been copied
  • The method shall replace existing files (maybe)
    • check, if existing files are replaced

Those are just some thoughts. Don't put any possible requirement and don't test too much, keep in mind what want to do with this method. If it's private or only used in your own code, you can reduce the scope, but if you provide a public API, then you have to make sure that any input has a defined result (which may be an error message).

Upvotes: 0

Senthil Kumaran
Senthil Kumaran

Reputation: 56831

I think, you can get some clue from test_shutil itself and see how it is testing the copy functionality. Namely it is moving files and testing if it exists using another module. The difference in behavior of standard shutil.copy to your wrapper is in dealing with destination if it not already exists. In shutil.copy2, if the destination not already exists, then a file is created which is move from the source, in your case, it is not file, but a destination directory is created and you move your source into that. So write tests there destination does not exists and ensure that after your wrapper runs, the destination is still a directory and and it contains the file that shutil moved.

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172239

You can rely on shutil.copy2 copying the contents correctly. You only need to test your code. In this case that it creates the directories if they don't exist, and that it swallows IOErrors.

And don't forget to clean up. ;)

Upvotes: 1

Related Questions