Skip to content

Instantly share code, notes, and snippets.

@plajjan
Last active January 3, 2016 06:29
Show Gist options
  • Save plajjan/8423031 to your computer and use it in GitHub Desktop.
Save plajjan/8423031 to your computer and use it in GitHub Desktop.
Python import mocking
""" Trying to mock my imports as I don't need this code to run, only load so
that readthedocs.org can generate nice documentation from my docstrings.
"""
#!/usr/bin/python
import sys
class Mock(object):
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return Mock()
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
elif name[0] == name[0].upper():
mockType = type(name, (), {})
mockType.__module__ = __name__
return mockType
else:
return Mock()
# TODO: fill in MOCK_MODULES so that my imports don't fail
# test mock...
#MOCK_MODULES = ['flask.Flask', 'flask.ext.compress.Compress', 'flaskext.xmlrpc', 'flaskext']
MOCK_MODULES = []
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = Mock()
from flask import Flask
from flask import request, Response
from flaskext.xmlrpc import XMLRPCHandler, Fault
from flask.ext.compress import Compress
app = Flask('test')
# get our virtualenv going to avoid actually importing flask
kll@lingloi320 ~/kod/venv $ . bin/activate
# MOCK_MODULES = []
(venv)kll@lingloi320 ~/kod $ python mocktest.py
Traceback (most recent call last):
File "mocktest.py", line 29, in <module>
from flask import Flask
ImportError: No module named flask
# MOCK_MODULES = ['flask']
Traceback (most recent call last):
File "mocktest.py", line 31, in <module>
from flaskext.xmlrpc import XMLRPCHandler, Fault
ImportError: No module named flaskext.xmlrpc
# MOCK_MODULES = ['flask', 'flaskext', 'flaskext.xmlrpc']
Traceback (most recent call last):
File "mocktest.py", line 32, in <module>
from flask.ext.compress import Compress
ImportError: No module named ext.compress
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment