Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete a test file after finished testing in python?

I create a test where in setUp I create file like so :

 class TestSomething :
     def setUp(self):
         # create file
         fo = open('some_file_to_test','w')
         fo.write('write_something')
         fo.close()

     def test_something(self):
         # call some function to manipulate file
         ...
         # do some assert
         ...

     def test_another_test(self):
         # another testing with the same setUp file
         ...

at the end of testing, regardless either succeed or not, I want the testing file gone,so how to delete the file after i have finished testing?

like image 875
whale_steward Avatar asked Sep 02 '14 03:09

whale_steward


People also ask

How do you delete a file after reading Python?

Using the os module in python To use the os module to delete a file, we import it, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter. You can not just delete a file but also a directory using the os module.

How do you clear a test case in python?

If you want to only delete this file after all the tests, you could create it in the method setUpClass and delete it in the method tearDownClass , which will run before and after all tests have run, respectively.

Can you delete code in Python?

You can delete files from your computer using Python. The os. remove() method deletes single Python files.


2 Answers

Assuming you're using a unittest-esque framework (i.e. nose, etc.), you would want to use the tearDown method to delete the file, as that will run after each test.

def tearDown(self):
    os.remove('some_file_to_test')

If you want to only delete this file after all the tests, you could create it in the method setUpClass and delete it in the method tearDownClass, which will run before and after all tests have run, respectively.

like image 178
khampson Avatar answered Oct 15 '22 06:10

khampson


Write a tearDown method:

https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown

def tearDown(self):
    import os
    os.remove('some_file_to_test')

Also have a look at the tempfile module and see if it's useful in this case.

like image 39
Steven Kryskalla Avatar answered Oct 15 '22 06:10

Steven Kryskalla