如何在 Python 中获取依赖注入对象的每个测试用例范围?
我正在使用 python-inject,python 2.6(带有unittest2)。
我们有使用注入进行测试的类,以及也使用相同值的测试用例。我们目前使用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
支持类似的操作(一组本地范围的实例),但我真的不知道在哪里调用注册()
& unregister()
(重置注入对象缓存)。在 setUp()
和 tearDown()
中为时已晚,因为 Foo.a 可能已经在 Foo.__init__()
中为每个他们。
关于如何做到这一点的任何想法,或者我应该使用不同的方法?
I'm using python-inject, python 2.6 (with unittest2).
We have classes to test that use injection, and test-cases which also use the same values. We currently use inject.appscope, to "singletonize" the values. Otherwise they're instantiated per user.
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()
Ideally, I'd like to reset A after each test run, to avoid cross-contamination.
(Currently do something like A.reset() in tearDown()..)
inject.reqscope
supports something like this (a locally scoped set of instances), but I don't really know where to call register()
& unregister()
(which resets the injection objet cache). Ot's too late in setUp()
and tearDown()
, since Foo.a may already be called in Foo.__init__()
for each of them.
Any ideas on how to do this, or should I use a different approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
setUp
和tearDown
来注册/取消注册范围,将每个测试方法调用视为一个新的“请求”。通过以下更改,您的示例单元测试将通过:
并使用
inject.reqscope
绑定您的A
实例:You can use
setUp
andtearDown
to register/unregister the scope, treating each test method invocation as a new "request".With the following changes your sample unit tests pass:
And bind your
A
instance usinginject.reqscope
: