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

10 投票
4 回答
17960 浏览
提问于 2025-04-19 07:38

我创建了一个测试,在设置阶段我这样创建文件:

 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
         ...

在测试结束时,无论测试成功还是失败,我都想把测试文件删除,所以我该怎么做才能在测试结束后删除这个文件呢?

4 个回答

2

如果你在使用 pytest 或其他不需要类的测试框架,可以使用自我删除的临时文件:

import tempfile
with tempfile.NamedTemporaryFile() as f:
     f.write('write_something')
     # assert stuff here

# Here the file is closed and thus deleted
5

写一个 tearDown 方法:

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

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

另外,可以看看 tempfile 模块,看看它在这个情况下是否有用。

11

另一种选择是使用 addCleanup() 方法,在 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')

在处理很多文件或者文件名是随机生成的情况下,这种方法比 tearDown() 更方便,因为你可以在文件创建后立即添加一个清理的方法。

13

假设你正在使用一个类似于 unittest 的框架(比如 nose 等),你可以使用 tearDown 方法来删除文件,因为这个方法会在每个测试之后运行。

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

如果你只想在所有测试结束后再删除这个文件,可以在 setUpClass 方法中创建它,然后在 tearDownClass 方法中删除它。这样的话,setUpClass 会在所有测试开始之前运行,而 tearDownClass 则会在所有测试结束之后运行。

撰写回答