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?
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.
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.
You can delete files from your computer using Python. The os. remove() method deletes single Python files.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With