我创建了一个测试,在安装程序中,我创建文件如下:
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
...
在测试结束时,不管成功与否,我都希望测试文件消失,所以 完成测试后如何删除文件?
另一个选项是使用TestCase的^{} 方法在tearDown()之后添加要调用的函数:
它比
tearDown()
更方便,在有很多文件的情况下,或者在使用随机名称创建文件时,因为您可以在文件创建后添加清理方法。假设您使用的是一个unittest-esque框架(即nose等),那么您需要使用
tearDown
方法删除该文件,因为它将在每次测试之后运行。如果只想在所有测试之后删除该文件,可以在方法
setUpClass
中创建该文件,并在方法tearDownClass
中删除该文件,该方法将分别在所有测试运行之前和之后运行。写一个拆卸方法:
https://docs.python.org/3/library/unittest.html#unittest.TestCase.tearDown
还要查看tempfile模块,看看它在这种情况下是否有用。
相关问题 更多 >
编程相关推荐