nicholas.reichel
nicholas.reichel

Reputation: 2270

Inject into python class for testing, without modifying the class

I am tasked with create unit test code for our production pipeline, without modifying the production pipeline whatsoever. The pipeline has methods for writing to and reading from queues. I'm using mock to override those calls to create the single "unit" test. But am stuck with one last part.

I need access to the object created in the pipeline, but the method that creates it does not return the object. It's also not acceptable to set the object to self so that it stays in memory after the method returns.

We were wondering if theres a way to inject into the class method while it is running, so that I can retrieve the production object before the method returns.

I created a dummy example below, but the methodology is the same. Please let me know if you have questions or if I'm not explaining this well. Thanks.

class production(object):
    def __init__(self):
        self.object_b = 'Test Object'

    def run(self):
        "Other lines of code"
        object_a = self.create_production_object()
        "Other lines of code"
        "Test object here"
        return 0




    def create_production_object(self):
        return 'Production Object'

test_prod_class = production()
test_prod_class.run()
assert(test_prod_class.object_a, 'Production Object')

Upvotes: 1

Views: 82

Answers (1)

Graipher
Graipher

Reputation: 7186

How about overwriting the method that creates the object so that it also stores the object in self?

class MockProduction(production):

    def create_production_object(self):
        self.object_a = super(MockProduction, self).create_production_object()
        return self.object_a

Upvotes: 1

Related Questions