Weholt Weholt - 5 months ago 10
Python Question

Can I "fake" a package ( or at least a module ) in python for testing purposes?

I want to fake a package in python. I want to define something so that the code can do

from somefakepackage.morefakestuff import somethingfake


And somefakepackage is defined in code and so is everything below it. Is that possible? The reason for doing this is to trick my unittest that I got a package ( or as I said in the title, a module ) in the python path which actually is just something mocked up for this unittest.

Thanks!

Answer

Sure. Define a class, put the stuff you need inside that, assign the class to sys.modules["classname"].

class fakemodule(object):

    @staticmethod
    def method(a, b):
        return a+b

import sys
sys.modules["package.module"] = fakemodule

You could also use a separate module (call it fakemodule.py):

import fakemodule, sys

sys.modules["package.module"] = fakemodule