如何在python中完成测试后删除测试文件?

wha*_*ard 4 python testing unit-testing

我创建了一个测试,在setUp中我创建了这样的文件:

 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
         ...
Run Code Online (Sandbox Code Playgroud)

在测试结束时,无论是否成功,我都希望测试文件不见了,所以 在完成测试后如何删除文件?

kha*_*son 7

假设您正在使用unittest -esque框架(即鼻子等),您可能希望使用该tearDown方法删除文件,因为这将在每次测试后运行.

def tearDown(self):
    os.remove('some_file_to_test')
Run Code Online (Sandbox Code Playgroud)

如果您只想在所有测试之后删除此文件,您可以在方法中创建它并在方法中setUpClass删除它,该方法tearDownClass将在所有测试运行之前和之后运行.

  • 我认为你的意思是在`setupClass()`中创建文件并在`tearDownClass()`中删除它.还有一个类似`setupModule()`和`tearDownModule()`. (2认同)

mig*_*var 7

其他选项是使用addCleanup()TestCase方法添加要在tearDown()之后调用的函数:

class TestSomething(TestCase):
     def setUp(self):
         # create file
         fo = open('some_file_to_test','w')
         fo.write('write_something')
         fo.close()
         # register remove function
         self.addCleanup(os.remove, 'some_file_to_test')
Run Code Online (Sandbox Code Playgroud)

它比tearDown()有大量文件或使用随机名称创建更方便,因为您可以在创建文件后添加清理方法.


Ste*_*lla 5

编写一个tearDown方法:

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

def tearDown(self):
    import os
    os.remove('some_file_to_test')
Run Code Online (Sandbox Code Playgroud)

另请查看tempfile模块,看看它在这种情况下是否有用。