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
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