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

2024-06-26 17:47:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个测试,在安装程序中,我创建文件如下:

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

在测试结束时,不管成功与否,我都希望测试文件消失,所以 完成测试后如何删除文件?


Tags: 文件totestselfdefcreatesetupanother
3条回答

另一个选项是使用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')

它比tearDown()更方便,在有很多文件的情况下,或者在使用随机名称创建文件时,因为您可以在文件创建后添加清理方法。

假设您使用的是一个unittest-esque框架(即nose等),那么您需要使用tearDown方法删除该文件,因为它将在每次测试之后运行。

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

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

写一个拆卸方法:

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

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

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

相关问题 更多 >