【问题标题】:how to delete a test file after finished testing in python?在python中完成测试后如何删除测试文件?
【发布时间】:2014-09-02 03:38:25
【问题描述】:

我创建了一个测试,在 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
         ...

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

【问题讨论】:

    标签: python unit-testing testing


    【解决方案1】:

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

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

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

    【讨论】:

    • 我认为您的意思是在setupClass() 中创建文件并在tearDownClass() 中删除它。还有一个类似的setupModule()tearDownModule()
    • @mhawke 感谢您指出正确的方向,tearDownClass() 是我正在寻找的
    【解决方案2】:

    其他选项是使用 TestCase 的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()在文件很多的情况下或者用随机名称创建的情况下更方便,因为您可以在文件创建后添加清理方法。

    【讨论】:

      【解决方案3】:

      写一个tearDown方法:

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

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

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

      【讨论】:

        【解决方案4】:

        如果您使用pytest 或其他无类测试框架,请改用自删除临时文件:

        import tempfile
        with tempfile.NamedTemporaryFile() as f:
             f.write('write_something')
             # assert stuff here
        
        # Here the file is closed and thus deleted
        

        【讨论】:

          猜你喜欢
          • 2018-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-24
          • 1970-01-01
          • 1970-01-01
          • 2015-08-10
          • 1970-01-01
          相关资源
          最近更新 更多