Wash entire module in python

I have an application that imports a module from PyPI. I want to write unittests for this application source code, but I do not want to use the module from PyPI in these tests.
I want to mock him completely (the test computer will not contain this PyPI module, so any import will fail).

Currently, every time I try to load the class that I want to test in unittests, I immediately get an import error. so I thought that maybe using

try: except ImportError: 

and catch this import error, then use command_module.run (). This seems pretty risky / ugly, and I was wondering if there is another way.

Another idea was to write an adapter to port this PyPI module, but I'm still working on it.

If you know any way, I can make fun of the entire python package, I would really appreciate it. Thanks.

+5
source share
1 answer

If you want to delve into the Python import system, I highly recommend David Bezley's talk .

As for your specific question, here is an example that checks a module when its dependency is missing.

bar.py - the module you want to check when my_bogus_module is missing

 from my_bogus_module import foo def bar(x): return foo(x) + 1 

mock_bogus.py - file with your tests that will load the mock module

 from mock import Mock import sys import types module_name = 'my_bogus_module' bogus_module = types.ModuleType(module_name) sys.modules[module_name] = bogus_module bogus_module.foo = Mock(name=module_name+'.foo') 

test_bar.py - tests bar.py when my_bogus_module unavailable

 import unittest from mock_bogus import bogus_module # must import before bar module from bar import bar class TestBar(unittest.TestCase): def test_bar(self): bogus_module.foo.return_value = 99 x = bar(42) self.assertEqual(100, x) 

You should probably make this a little safer by setting that my_bogus_module is not actually available when you run the test. You can also look at the pydoc.locate() method, which will try to import something, and return None if it does not work. Apparently this is a public method, but it is not documented.

+2
source

Source: https://habr.com/ru/post/1261495/


All Articles