【发布时间】:2012-08-24 04:07:05
【问题描述】:
在使用 Python 2.7 中的新发现功能时,我遇到了一个奇怪的错误。我有一些单元测试需要一些额外的设置和文件中的一些成员数据。我正在尝试将我的设置测试用例添加到传递给load_tests() 的当前测试套件中。但是因为测试套件tests 已经包含标准测试(包括当前模块中的TestCase 对象),所以自动添加的测试用例的正确设置没有完成,我得到了一个AttributeError。
在下面的代码中,load_tests() 用于为 csv 文件中的每一行数据创建一个测试用例。该文件有三行,但由于某种原因正在创建第四个测试用例。
#!/usr/bin/python
import unittest
class Foo(unittest.TestCase):
def setup(self,bar):
print "Foo.setup()"
self.bar = bar
def runTest(self):
print self.bar
def load_tests(loader, tests, pattern):
f = open('data.csv') # data.csv contains three lines: "a\nb\nc"
for line in f:
tc = Foo()
tc.setup(line)
tests.addTest(tc)
return tests
unittest.main()
当我执行这段代码时,输出显示执行了 4 个测试,其中一个失败了。数据文件只包含三行,Foo.setup() 只被调用了 3 次。所以load_tests() 按设计创建了三个测试用例。
Foo.setup()
Foo.setup()
Foo.setup()
Ea
.b
.c
.
======================================================================
ERROR: runTest (__main__.Foo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./foo.py", line 11, in runTest
print self.bar
AttributeError: 'Foo' object has no attribute 'bar'
----------------------------------------------------------------------
Ran 4 tests in 0.002s
有没有办法删除套件中自动加载的 TestCase?我无法创建一个新的空 TestSuite,因为我需要已经存在的所有其他测试。我只想将这些测试添加到套件中。
编辑:澄清了我的问题和代码示例。我之前有点模棱两可。
【问题讨论】:
标签: python unit-testing