Skip to content

Instantly share code, notes, and snippets.

@tyalie
Last active August 13, 2020 17:11
Show Gist options
  • Save tyalie/01ae0d2650e65c13c47e7fac0b6ce90f to your computer and use it in GitHub Desktop.
Save tyalie/01ae0d2650e65c13c47e7fac0b6ce90f to your computer and use it in GitHub Desktop.
Import all modules into global that are contained in folders named `tests`

This script traverses through the whole module tree starting from my_parent_module to find all python files that are contained inside a folder / module named tests (can be changed).

Usage

This script finds all modules / files that contain the module_to_search in their module path (my_parent_module.network.tests).

For that to work, the tests folder must a valid python module. Which means, that at least an empty __init__.py must be included.

Example

├── my_parent_module
│   ├── __init__.py
│   ├── network
│   │   ├── __init__.py
│   │   ├── network.py
│   │   └── tests
│   │       ├── __init__.py
│   │       └── network_test.py
│   └── security
│       ├── __init__.py
│       ├── CRC.py
│       └── tests
│           ├── __init__.py
│           └── CRC_test.py
└── tests.py

After executing this script starting from tests.py all classes, functions, ... from CRC_test.py, network_test.py and the corresponding __init__.pys are loaded into globals() and can now be accessed in the context of tests.py.

import my_parent_module # replace this with your module
import pkgutil
import importlib
module_to_search = "tests"
def import_all_attr(module):
if "__all__" in module.__dict__:
names = module.__dict__["__all__"]
else:
names = [x for x in module.__dict__ if not x.startswith("_")]
globals().update({k: getattr(module, k) for k in names if k not in globals()})
for pkg in pkgutil.walk_packages(my_parent_module.__path__, my_parent_module.__name__ + "."):
if module_to_search in pkg.name.split('.') and not pkg.ispkg:
mod = importlib.import_module(pkg.name, __package__)
import_all_attr(mod)
# one can now execute e.g. unittests.main() and all unittests included in my_parent_module are executed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment