Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock so that `from x import *` works

I am trying to produce a Mock of matplotlib so that I can compile my docs using ReadTheDocs, but have run into a problem.

In my code, I import matplotlib using from matplotlib.pyplot import *.

I am using the following code for my Mocks (as suggested by the ReadTheDocs FAQ):

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():
            return type(name, (), {})
        else:
            return Mock()

MOCK_MODULES = ['numpy', 'scipy', 'matplotlib', 'matplotlib.pyplot']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = Mock()

However, when running from matplotlib.pyplot import * I get an error saying that TypeError: 'type' object does not support indexing.

Is there a way that I can change my Mock so that it allows me to import matplotlib using the from x import * style? I don't need any particular functions to be made available, I just need it to be able to be imported so that ReadTheDocs can import the code properly.

like image 861
robintw Avatar asked Aug 09 '12 06:08

robintw


1 Answers

In case of importing via * you need to define the __all__ list in the module. The same goes with your class: just add the __all__ attribute to the class and it should work fine:

class Mock(object):
    __all__ = []
like image 72
Zaur Nasibov Avatar answered Sep 17 '22 19:09

Zaur Nasibov