Test for import of optional dependencies in __init__.py with pytest: Python 3.5 /3.6 differs in behaviour

后端 未结 3 1489
太阳男子
太阳男子 2020-12-20 22:09

I have a package for python 3.5 and 3.6 that has optional dependencies for which I want tests (pytest) that run on either version.

I made a reduced example below co

3条回答
  •  鱼传尺愫
    2020-12-20 22:48

    import sys
    from unittest.mock import patch
    
    def test_without_dependency(self):
        with patch.dict(sys.modules, {'optional_dependency': None}):
            # do whatever you want
    

    What the above code does is, it mocks that the package optional_dependency is not installed and runs your test in that isolated environment inside the context-manager(with).

    Keep in mind, you may have to reload the module under test depending upon your use case

    import sys
    from unittest.mock import patch
    from importlib import reload
    
    def test_without_dependency(self):
        with patch.dict(sys.modules, {'optional_dependency': None}):
            reload(sys.modules['my_module_under_test'])
            # do whatever you want
    

提交回复
热议问题