Skip to content

Instantly share code, notes, and snippets.

@cbodley
Created May 4, 2017 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbodley/7cee5a75100ffca4b81a1e63a0b39667 to your computer and use it in GitHub Desktop.
Save cbodley/7cee5a75100ffca4b81a1e63a0b39667 to your computer and use it in GitHub Desktop.
run pytest.main() against already-imported modules
import pytest
from rgw_multi import tests
def run_tests(realm, user):
tests.init_multi(realm, user) # inject dependencies
test_modules = [tests] # more in future
args = ['-s', '-v', '--pyargs']
for mod in test_modules:
args += [mod.__name__]
plugin = loaded_module_plugin(test_modules)
pytest.main(args, [plugin])
def loaded_module_plugin(modules):
""" return a list of plugins for pytest.main() """
class LoadedModule(pytest.Module):
""" Collector for a module that has already been imported """
def __init__(self, mod, path, parent):
super(LoadedModule, self).__init__(path, parent)
self.mod = mod
def _importtestmodule(self):
self.config.pluginmanager.consider_module(self.mod)
return self.mod
class LoadedModulePlugin:
""" plugin that returns LoadedModule collectors for matching modules """
def __init__(self, modules):
self.modules = modules
def pytest_pycollect_makemodule(self, path, parent):
for mod in self.modules:
# path is given as /path/to/foo.py, __file__ may end in .pyc
if mod.__file__ in path.strpath:
return LoadedModule(mod, path, parent)
return pytest.Module(path, parent)
return LoadedModulePlugin(modules)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment