Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

2016/09/10

Python, Mock, Unittest and missing module dependency

Sometimes you end up in a situation where you don't have access to a depending module. It might be that it's only available in the target environment. Or, for some unknown reason the API libs are just not there on the company CI system.  

How to unit test the code without having the depending modules available at all?


This happens often when you work with API libraries, which are provided as a part of an installed product. And worst of all, the development kits are only provided for the certain OS - but not for yours.

Unit testing and mocking is less painful when the API is based on objects and classes. If the depending module is static and has a state, unit tests end up being a bit of a mess. 

Unit testing without the depending module


Luckily with the Python it's possible to work out these issues in several different ways. Here I present my solution. It took a while for me to figure out all the details, so I hope this proves useful for someone. 

Assuming the following is the code you've created. You don't have the missing_module implementation around for the unit tests.

mocked.py
_____________________________________________

import missing_module

class ClassWithDependency:


    def call_dependency(self):

        try:
            return missing_module.things.do()
        except missing_module.Error as ne:
            raise RuntimeError()
_____________________________________________