【发布时间】:2015-04-28 11:14:18
【问题描述】:
背景:我正在开发一个网络爬虫来跟踪在线商店的价格。它使用 Django。我为每个商店都有一个模块,为每个商店编写了get_price() 和get_product_name() 之类的功能,以便主刮板模块可以互换使用这些模块。我有 store_a.py、store_b.py、store_c.py 等,每个都定义了这些函数。
为了防止代码重复,我做了StoreTestCase,继承自TestCase。对于每个商店,我都有一个 StoreTestCase 的子类,例如 StoreATestCase 和 StoreBTestCase。
当我手动测试 StoreATestCase class 时,测试运行程序会执行我想要的操作。它使用子类self.data 中的数据进行测试,不会尝试自行设置和测试父类:
python manage.py test myproject.tests.test_store_a.StoreATest
但是,当我手动测试 module 时,例如:
python manage.py test myproject.tests.test_store_a
它首先为子类运行测试并成功,然后为父类运行它们并返回以下错误:
for page in self.data:
TypeError: 'NoneType' object is not iterable
store_test.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 测试运行器只测试子类,而不是父类?
【问题讨论】:
-
如果你不直接调用
super或StoreTestCase.__init__,它不应该执行它,因为它已经被覆盖了。
标签: python django unit-testing