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)
在测试结束时,无论是否成功,我都希望测试文件不见了,所以 在完成测试后如何删除文件?
假设您正在使用unittest -esque框架(即鼻子等),您可能希望使用该tearDown方法删除文件,因为这将在每次测试后运行.
def tearDown(self):
os.remove('some_file_to_test')
Run Code Online (Sandbox Code Playgroud)
如果您只想在所有测试之后删除此文件,您可以在方法中创建它并在方法中setUpClass删除它,该方法tearDownClass将在所有测试运行之前和之后运行.
其他选项是使用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()有大量文件或使用随机名称创建更方便,因为您可以在创建文件后添加清理方法.
编写一个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模块,看看它在这种情况下是否有用。
| 归档时间: |
|
| 查看次数: |
5891 次 |
| 最近记录: |