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类,或者每个测试类是否应该"自包含",这是一种好习惯吗?
谢谢!