背景:我正在开发一个网络刮板,跟踪在线商店的价格。Django使用它。我为每个存储都有一个模块,为每个存储编写了get_price()
和{
为了防止代码重复,我创建了StoreTestCase,它继承了TestCase。对于每个存储,我都有一个子类StoreTestCase,比如StoreATestCase和StoreBTestCase。在
当我手动测试StoreATestCase类时,测试运行器执行我想要的操作。它使用子类self.data
中的数据进行测试,不尝试单独设置和测试父类:
python manage.py test myproject.tests.test_store_a.StoreATest
但是,当我手动测试模块时,比如:
^{pr2}$它首先为子类运行测试并成功,然后为父类运行测试并返回以下错误:
for page in self.data:
TypeError: 'NoneType' object is not iterable
储存_测试.py(父类)
from django.test import TestCase
class StoreTestCase(TestCase):
def setUp(self):
'''This should never execute but it does when I test test_store_a'''
self.data = None
def test_get_price(self):
for page in self.data:
self.assertEqual(store_a.get_price(page['url']), page['expected_price'])
test_store_a.py(子类)
import store_a
from store_test import StoreTestCase
class StoreATestCase(StoreTestCase):
def setUp(self):
self.data = [{'url': 'http://www.foo.com/bar', 'expected_price': 7.99},
{'url': 'http://www.foo.com/baz', 'expected_price': 12.67}]
如何确保Django测试运行器只测试子类,而不是父类?在
您可以将基类隐藏在另一个基类中:
储存_测试.py(父类)
test_store_a.py(子类)
^{pr2}$解决此问题的一种方法是使用^{} :
不会执行}仍将受益于继承。在
StoreTestCase
,因为它不是TestCase
,但您的{我认为您的问题之所以发生是因为
StoreTestCase
是一个TestCase
实例,因此它在您运行测试时被执行。在编辑:
我还建议在
^{pr2}$StoreTestCase.setUp
中引发一个异常,明确地说它没有实现。看看these exception。 你最终会得到这样的结果:相关问题 更多 >
编程相关推荐