python - 子类化TestCase时如何防止Django在父类上运行单元测试?

标签 python django unit-testing

背景:我正在开发一个网络爬虫来跟踪在线商店的价格。它使用 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仍将受益于遗产。

我认为您的问题发生是因为 StoreTestCaseTestCase实例,因此它会在您运行测试时执行。

编辑:

我还建议在 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/

相关文章:

python - 将数据拉入 pandas 数据框架以进行机器学习的正确且最有效的方法

python - 为什么 Python 不包含从文件名加载 pickle 的函数?

python - Robot Framework - 由 IAM 保护的 AWS API 网关

c# - 从 AutoFixture/AutoMaq 请求模拟时,NUnit 会忽略测试

javascript - Angular 服务中的单元测试 $q promise - Karma、Jasmine

python - Discord.py 如何删除每个文本 channel ?

django - 如何使用 docker-compose 设置 nginx 和 django?

javascript - 即使功能正常工作后, Angular 过滤器也会出现奇怪的错误

django - 如何仅更新 django 模型中的特定字段?

matlab - 在不调用 `clear all` 的情况下破坏 Matlab Singleton 类实例