Last active
August 18, 2020 13:48
-
-
Save wolkenarchitekt/7755f2386e2d04ffcf8ed49644ce67b0 to your computer and use it in GitHub Desktop.
Bash completion to autocomplete all python tests within current project (using pytest)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This will allow to autocomplete tests in Terminal like this: | |
$ pytest tests/test_user_management.py::[TAB] | |
$ pytest tests/test_user_management.py::TestUserManagement[TAB] | |
$ pytest tests/test_user_management.py::TestUserManagement::test_user_create | |
# Add command writing fully qualified names of all test functions to a file | |
# conftest.py: | |
def pytest_addoption(parser): | |
parser.addoption( | |
"--collect-tests", | |
action="store_true", | |
help="Collect tests", | |
default=False, | |
) | |
def pytest_collection_modifyitems(config, items): | |
tests = set() | |
if config.option.collect_tests: | |
for item in items: | |
# filename::test_class[optional]::test_function | |
path = os.path.relpath(item.module.__file__) | |
item.add_marker(pytest.mark.skipif(True, reason="Skip")) | |
tests.add("{}\n".format(path)) | |
test_str = path | |
if item.cls: | |
test_str += f"::{item.cls.__name__}" | |
if item.function: | |
test_str += f"::{item.function.__name__}" | |
tests.add(f"{test_str}\n") | |
with open(".pytest.completion", "w") as file: | |
file.writelines(tests) | |
# Bash completion script | |
# If there is a .pytest.completion within current dir, | |
# all its tests will be collected and provided to Bash completion | |
# /etc/bash_completion.d/pytest.completion | |
_pytest () { | |
local cur | |
_get_comp_words_by_ref -n : cur | |
if [ -f ".pytest.completion" ]; then | |
COMPREPLY=( $( compgen -W '$(cat ".pytest.completion" | tr "\n" " ")' -- "$cur" ) ) | |
__ltrim_colon_completions "$cur" | |
fi | |
} | |
complete -F _pytest pytest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment