lundi 26 octobre 2015

How to do basic dependency injection in Python (for mocking/testing purposes)

Python is a relatively new language for me. Unit Testing and Dependency Injection are something that I've been doing for a little while now, so I'm familiar with it from a C# perspective.

Recently, I wrote this piece of Python code:

import requests  # my dependency: http://ift.tt/Rh9Af7

class someClass:
    def __init__(self):
        pass

    def __do(self, url, datagram):
        return requests.post(self, url, datagram)

And then I realized that I had just created a hard-coded dependency. Bleh.

I had considered changing my code to do "Constructor" Dependency Injection:

def __init__(self,requestLib=requests):
    self.__request = requestLib

def __do(self, url, datagram):
    return self.__request.post(self, url, datagram)

This now allows me to inject a fake/mock dependency for the sake of Unit Testing, but wasn't sure if this was considered Python-ic. So I'm appealing to the Python community for guidance.

What are some examples of Python-ic ways to do basic DI (mostly for the sake of writing Unit Tests that utilize Mocks/Fakes)?

Aucun commentaire:

Enregistrer un commentaire