Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate missing package for testing?

I have a project that has functionality that may be extended depending on which packages you have available. Specifically, it has 3D graphics if you have VTK, and it has a GUI if you have PyQt, and some fall-backs if you don't.

Is there any way to create a test file that simulates these packages being unavailable project-wide, so that I can check that the correct error messages and warnings and recommendations are raised?

like image 484
user3557216 Avatar asked Jul 29 '14 23:07

user3557216


1 Answers

I had a similar situation where I have developed an application that can make use of the requests library but it is an optional dependency, so this is my approach. First have a module that collected these dependencies

try:
    import requests
except ImportError:
    _has_requests = None

Repeat for all other modules you may need. Then on the import of this module the code then can check for the value of _has_requests (and the like) and generate the appropriate log messages. As for the test case, it will look something like this:

from ... import vendor

class FunctionTestCase(unittest.TestCase):

    def setUp(self):
        self._has_requests = vendor._has_requests
        vendor._has_requests = False

    def tearDown(self):
        vendor._has_requests = self._has_requests

Naturally, you may have code that tests interaction with the actual modules, so you will need to make use of unittest.skipIf (or the unittest2 version if you are using Python 2.6). This is done so you can correctly skip the tests for systems that do not have this module installed, if you wish to run these tests on systems that do not have the complete list of optional dependencies.

@unittest.skipIf(not vendor._has_requests, '`requests` not available')
class FunctionWithRequestsTestCase(unittest.TestCase):

    def setUp(self):
        ...
like image 100
metatoaster Avatar answered Sep 30 '22 13:09

metatoaster