When writing unit tests in Python you may find yourself switching back and forth between your code editor window and terminal to re-run your tests.
You can avoid this by using inotify. In short, it can re-run your tests when you change any Python files in your project. Here are some little scripts to help you do that.
First, install:
sudo apt install -y inotify-tools
If you’re using bash, add this to your ~/.bashrc
and restart your terminal:
function ptw() {
pytest $1
while find -name "*.py" | inotifywait -e close_write --fromfile - ;
do pytest $1
done
}
If you’re using Fish, add to ~/.config/fish/config.fish
and restart your terminal:
function ptw
pytest $argv
while find -name "*.py" | inotifywait -e close_write --fromfile - ;
pytest $argv
end
end
Now instead of running your tests like:
pytest test_stuff.py
Just do:
ptw test_stuff.py
When the tests finish you’ll see the process does not exit, and when you edit a .py file in your project the tests will automatically re-run.
This saves a tonne of time, enjoy.