How to get a test case view for dependent objects in Python?

I am using python-inject , python 2.6 (with unittest2).

We have test classes that use injection and test cases that also use the same values. We are currently using the inject.appscope method to "match" the values. Otherwise, they are created for each 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 would like to reset A after each test run to avoid cross-contamination. (For now, do something like A.reset () in tearDown () ..)

inject.reqscope - ( ), , register() unregister() ( - ). Ot setUp() tearDown(), Foo.a Foo.__init__() .

, , ?

+3
1

setUp tearDown / , "".

:

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()

    ...

A, inject.reqscope:

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

All Articles