unittest基类是否是良好的做法?(蟒/ webapp2的)

Que*_*lan 7 python unit-testing webtest testbed webapp2

我对单元测试很陌生,并试图找出最佳实践.我在这里看到了几个关于unit-test继承一个基类的问题,这个基类本身包含几个测试,例如:

class TestBase(unittest.TestCase):
    # some standard tests

class AnotherTest(TestBase):
    # run some more tests in addition to the standard tests
Run Code Online (Sandbox Code Playgroud)

我认为我从社区收集的是,为每个实现编写单独的测试并使用多重继承更好.但是,如果该基类实际上不包含任何测试 - 只是所有其他测试的助手.例如,假设我有一些基础测试类,我曾经用它来存储一些常用方法,如果不是所有其他测试都会使用这些方法.我们还假设我有一个models.py被调用的数据库模型ContentModel

test_base.py

import webtest
from google.appengine.ext import testbed
from models import ContentModel

class TestBase(unittest.TestCase):

    def setUp(self):
        self.ContentModel = ContentModel
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        # other useful stuff

    def tearDown(self):
        self.testbed.deactivate()

    def createUser(self, admin=False):
        # create a user that may or may not be an admin

    # possibly other useful things
Run Code Online (Sandbox Code Playgroud)

这似乎可以节省我所有其他测试的大量时间:

another_test.py

from test_base import TestBase

class AnotherTest(TestBase):
    def test_something_authorized(self):
        self.createUser(admin=True)
        # run a test

    def test_something_unauthorized(self):
        self.createUser(admin=False)
        # run a test

    def test_some_interaction_with_the_content_model(self):
        new_instance = self.ContentModel('foo' = 'bar').put()
        # run a test
Run Code Online (Sandbox Code Playgroud)

注意:这是基于我在谷歌应用引擎上的webapp2的一些工作,但我希望几乎任何python Web应用程序出现类似的情况

我的问题

使用包含所有其他测试继承的有用方法/变量的base/helper类,或者每个测试类是否应该"自包含",这是一种好习惯吗?

谢谢!

Fre*_*ell 3

很棒的问题。我认为几乎所有自动化测试的工作都非常出色。也就是说,测试确实是唯一可靠的文档来源。因此,测试应该非常容易阅读和理解。与评论不同,测试是可靠的,因为它们显示了软件的真正功能以及如何使用它。

我喜欢这种方法。但你也可以尝试一下鼻子。Nose 的设置有点“轻量级”,如果您使用Jenkins之类的持续集成路线进行自动化构建/测试/部署,它会得到很好的支持。Nose 的消息格式不如 xUnit 风格(当然,在我看来)。但对于很多事情,你可能愿意放弃。

顺便提一句。Python 不是 Java。因此,仅重用一个普通的旧 python 函数进行重用是完全可以接受的。