Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 420
Weholt Avatar asked Feb 25 '11 20:02

Weholt


2 Answers

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 
like image 147
kindall Avatar answered Nov 13 '22 00:11

kindall


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 
like image 34
ideasman42 Avatar answered Nov 12 '22 23:11

ideasman42