python - 如何将测试方法添加到一组 Django TestCase 派生类中?

标签 python django unit-testing subclassing

我有一组测试用例,它们都应该完成完全相同的测试,按照“方法 x 是否返回现有文件的名称?”

我认为最好的方法是从它们共享的 TestCase 派生一个基类,然后简单地将测试添加到该类。不幸的是,测试框架仍然尝试为基类运行测试,这没有意义。

class SharedTest(TestCase):
    def x(self):
        ...do test...

class OneTestCase(SharedTest):
    ...my tests are performed, and 'SharedTest.x()'...

如果它是在基类的对象而不是像这样的派生类上调用的,我试图破解一个检查以简单地跳过测试:

    class SharedTest(TestCase):
        def x(self):
            if type(self) != type(SharedTest()):
                ...do test...
            else:
                pass

但是出现了这个错误:

ValueError: no such test method in <class 'tests.SharedTest'>: runTest

首先,我想要任何关于执行此操作的优雅建议。其次,虽然我真的不想使用 type() hack,但我想了解为什么它不起作用。

最佳答案

您可以通过利用测试运行器仅运行继承自 unittest.TestCase(Django 的 TestCase 继承自。)的测试来使用混合。例如:

class SharedTestMixin(object):
    # This class will not be executed by the test runner (it inherits from object, not unittest.TestCase.
    # If it did, assertEquals would fail , as it is not a method that exists in `object`
    def test_common(self):
         self.assertEquals(1, 1)


class TestOne(TestCase, SharedTestMixin):
    def test_something(self):
         pass

    # test_common is also run

class TestTwo(TestCase, SharedTestMixin):
    def test_another_thing(self):
        pass

    # test_common is also run

有关为什么这有效的更多信息,请搜索 python 方法解析顺序和多重继承。

关于python - 如何将测试方法添加到一组 Django TestCase 派生类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3605936/

相关文章:

python - 当 session.flush() 在 SQLAlchemy 上失败时,我应该调用回滚吗?

python - 如何追踪这个?属性错误 : 'NoneType' object has no attribute 'is_relation' during makemigrations

python - 跟踪和测试 GUI 应用程序中的功能 (Python + Gtk3)

django - 生成随机字符串(用于唯一代码)不断返回相同的随机字符串

python - 无法连接 django 和 Angular 2

c# - 如何模拟/覆盖单元测试的只读字段

unit-testing - 如何运行并发单元测试?

Python Pandas : Convert to 2D List of Column Headers whereas row values are not NaN

python - django 调试工具栏抛出配置不当的异常

python - 很好地打印了 python 类的 "public"方法