python - 如何在 Python 中获取依赖注入(inject)对象的每个测试用例范围?

标签 python unittest2

我正在使用 python-inject , python 2.6(带有 unittest2)。

我们有使用注入(inject)来测试的类,以及也使用相同值的测试用例。我们目前使用 inject.appscope 来“单一化”这些值。否则,它们将按用户实例化。

import inject

class A(object):
    '''shared data between many parts'''
    ...

class Foo(object):
    '''uses a to do stuff'''

    a = inject.attr('a', A)

    def bar(self):
        self.a.doStuff()

class TestFoo(TestCase):
    a = inject.attr('a', A)

    def setUp(self):
        self.foo = Foo()

    def testBar(self):
        self.foo.bar()
        self.assertTrue(self.a.stuffWasDone())
        self.assertFalse(self.a.stuffWasDoneTwice())

    def testBarTwice(self):
        self.foo.bar()
        self.foo.bar()
        self.assertTrue(self.a.stuffWasDoneTwice())


injector = inject.Injector()
injector.bind(A, scope=inject.appscope)
inject.register(injector)

runTests()

理想情况下,我想在每次测试运行后重置 A,以避免交叉污染。 (目前在 tearDown() 中执行类似 A.reset() 的操作。)

inject.reqscope 支持这样的东西(一组局部范围的实例),但我真的不知道在哪里调用 register() & unregister()(重置注入(inject)对象缓存)。在 setUp()tearDown() 中为时已晚,因为 Foo.a 可能已经在 Foo.__init__() 中被调用他们。

关于如何执行此操作的任何想法,或者我应该使用不同的方法吗?

最佳答案

您可以使用setUptearDown 注册/注销范围,将每个测试方法调用视为一个新的“请求”。

通过以下更改,您的示例单元测试通过了:

class TestFoo(unittest2.TestCase):

    a = inject.attr('a', A)

    def __init__(self, *n, **kw):
        unittest2.TestCase.__init__(self, *n, **kw)
        self.unit_scope = inject.reqscope

    def setUp(self):
        self.foo = Foo()
        self.unit_scope.register()

    def tearDown(self):
        self.unit_scope.unregister()

    ...

并使用 inject.reqscope 绑定(bind)您的 A 实例:

injector = inject.Injector()
injector.bind(A, scope=inject.reqscope)

关于python - 如何在 Python 中获取依赖注入(inject)对象的每个测试用例范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6151024/

相关文章:

python - 从调用者的角度发出警告(又名 Python 等同于 Perl 的鲤鱼)?

python - 使用来自 matplotlib 的 maplot3d 的 3D 图 -

python - 如何从我的 Django 数据库中检索行数据作为列表?

python - ImportError : No module named test_data, 但 test_data.py 与 PyCharm 下的 test.py 在同一目录中使用 virtualenv

python - python中离散点(LDDP)的限制密度

python - 如何在 Ubuntu 11.10 上安装 Django?

python - 如何从 "python setup.py test"运行 unittest discover ?

python - 如何断言一个方法是用 python unittest 装饰的?

来自脚本的 python Nose ,从文件中收集测试类,然后运行测试

python - python 3.1 unittest 中不可用的断言方法