Skip to content

Instantly share code, notes, and snippets.

@dcragusa
Created March 8, 2022 23:09
Show Gist options
  • Save dcragusa/3cb6a0ee48743ab6279643c84d601c62 to your computer and use it in GitHub Desktop.
Save dcragusa/3cb6a0ee48743ab6279643c84d601c62 to your computer and use it in GitHub Desktop.
A zsh script to quickly run a test in any part of a repository by any part of its name. Prompts for input when multiple matches are found.
test() {
# strip test_ and .py from input
stripped=$(echo "$1" | sed "s/^test_//;s/\.py$//")
# declare empty array
test_matches=()
# pipe matches from find command into array
# exclude tests in venv dirs
while IFS= read -r -d $'\0'; do
# strip repo location and starting slash from path name
test_name=$(echo "$REPLY" | sed "s/${REPO_LOCATION//\//\\/}//;s/^\///")
test_matches+=("$test_name")
done < <(find $REPO_LOCATION -iname "test_*${stripped}*.py" -print0 -o -path '*venv*' -prune)
# find length of array
length=${#test_matches[@]}
# deal with 0 or 1 match
if [ $length -eq 0 ]; then
echo "No matching tests found."
return
elif [ $length -eq 1 ]; then
echo "Running ${test_matches[1]}"
docker exec -it web bash -c "source /venv/bin/activate; cd /code/; pytest -s --ds=app.settings.localtest ${test_matches[1]}"
return
fi
# print choices
for (( i=1; i<=length; i++ )); do
printf "[%d] %s\n" $i "${test_matches[$i]}"
done
# prompt for reply
printf "--> "
read
# deal with out of range
if [ $REPLY -lt 1 ] || [ $REPLY -gt $length ]; then
echo "Not a valid choice."
return
fi
echo "Running ${test_matches[$REPLY]}"
docker exec -it web bash -c "source /venv/bin/activate; cd /code/; pytest -s --ds=app.settings.localtest ${test_matches[$REPLY]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment