Weholt Weholt - 4 months ago 7x
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.



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

class fakemodule(object):

    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