Automatic testing in Python on file change

The problem

I am trying to move to test driven development in python lately and I work on my VM in google cloud mostly either thru SSH or VSCode. It gets super annoying when you are coding, to constantly switch between terminals to run test scripts. So I was looking for a simple way to run the tests automatically whenever there is a file change.

Solution

Curbing my instict to write the solution in Python, I tried to search solutions on the internet, but I could not find a definitive solution specifically for python unittest. So I tried to put together a solution using bash and an Linux tool called INotify.

Install inotify tools

Assuming you are on ubuntu or else you can follow instructions here.

sudo apt-get install inotify-tools

Write a bash script run_test.sh

⚠️ Please change code_dir and test_dir, otherwise it’ll start executing the tests without waiting for change.


while true; do 
	inotifywait code_dir/ test_dir/ -q -e create -e close_write -e attrib -e move 
	clear
	python3 -m unittest discover
done

Keep this script running in one window and write your code and tests as usual. The tests will be executed whenever you save either your code or tests.

$ bash  run_test.sh

Here’s how it works (I’m using tmux+vim over ssh).

Now adding a demo test to fail the test, it runs the tests automatically-

Hope you found something new. 😄