Andrey Braslavskiy
Andrey Braslavskiy

Reputation: 221

Unittest tearDown() method depends on finished test

I write Selenium tests, and have a problem. Before each test I upload different files for every test, and after test is done, I want to remove these files from application even if test failed. There are two methods setUp and tearDown. They are called before and after every test, but how can I define which test was finished in the tearDown method? It is important for me, because after each test I want to remove different files from application, depending on the finished test.

I want something like:

def tearDown(self):
    if test1_is_finished():
       remove_test1_files
    if test2_is_finished():
       remove_test2_files
    # and so on

I am new to Python and Selenium tests, and maybe a better approach exists to do some job after after the test was finished, even if it failed.

Upvotes: 1

Views: 1335

Answers (1)

unutbu
unutbu

Reputation: 879073

In the setUp method (to be run before every test), create a list, to_be_removed:

def setUp(self):
    self.to_be_removed = []

In each unit test, append the filenames to to_be_removed:

def test1(self):
    ...
    self.to_be_removed.append(filename)

Then, in tearDown, remove all files listed in to_be_removed:

def tearDown(self):
    for filename in self.to_be_removed:
        os.unlink(filename)

This way, you can handle all tearDowns the same way.

Upvotes: 2

Related Questions