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!
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
Yes, you can make a fake module:
from types import ModuleType m = ModuleType("fake_module") import sys sys.modules[m.__name__] = m # some scripts may expect a file # even though this file doesn't exist, # it may be used by Python for in error messages or introspection. m.__file__ = m.__name__ + ".py" # Add a function def my_function(): return 10 m.my_function = my_function
Note, in this example its using an actual module (of ModuleType
) since some Python code may expect modules, (instead of a dummy class).
This can be made into a utility function:
def new_module(name, doc=None): import sys from types import ModuleType m = ModuleType(name, doc) m.__file__ = name + '.py' sys.modules[name] = m return m print(new_module("fake_module", doc="doc string"))
Now other scripts can run:
import fake_module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With