背景:我正在开发一个网络爬虫来跟踪在线商店的价格。它使用 Django。每个商店都有一个模块,功能类似于 get_price()
和 get_product_name()
为每个模块编写,以便这些模块可以由主刮板模块互换使用。我有 store_a.py、store_b.py、store_c.py 等,每个都定义了这些函数。
为了防止代码重复,我做了StoreTestCase,继承自TestCase。对于每个商店,我都有一个 StoreTestCase 的子类,例如 StoreATestCase 和 StoreBTestCase。
当我手动测试 StoreATestCase 类时,测试运行程序会执行我想要的操作。它使用子类中的数据 self.data
用于其测试,并且不会尝试自行设置和测试父类:
python manage.py test myproject.tests.test_store_a.StoreATest
但是,当我手动测试模块时,例如:
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 ( child 类)
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 测试运行器只测试子类,而不是父类?
最佳答案
解决此问题的一种方法是使用 Mixins
:
from django.test import TestCase
class StoreTestCase(object):
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'])
class StoreATestCase(StoreTestCase, TestCase):
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}]
StoreTestCase
不会执行,因为它不是 TestCase
, 但你的 StoreATestCase
仍将受益于遗产。我认为您的问题发生是因为
StoreTestCase
是 TestCase
实例,因此它会在您运行测试时执行。编辑:
我还建议在
StoreTestCase.setUp
中提出异常,明确表示未实现。看看these exception .你最终会得到这样的结果:
import exceptions # At the top of the file
[...]
def setUp(object):
raise exceptions.NotImplementedError('Please override this method in your subclass')
关于python - 子类化TestCase时如何防止Django在父类上运行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917882/