Wednesday, May 10, 2023

Running Godot unit tests using GUT with a pre-commit hook

I've been tinkering with a project idea for months, creating and discarding over a dozen variations. I was hoping to have a prototype or vertical slice complete before the start of summer, but I was unable to do so. This current variation is promising, but I ran into a situation where a lot of the code I had laid down was hard to test. In particular, I needed to check the interaction of subsystems that were probabilistic, and that's not only difficult to do manually, it's also prone to regression. Time for unit tests!

I'm using Godot Engine 4.0, and so I brought in GUT and started redesigning my code to be more testable. This alone is almost certainly worth the effort. Tests lose their value if they are not executed, and so I started looking into automatic ways to run my tests. Godot Engine has no such system built in, but I am using git, and so I investigated pre-commit hooks. This is something I've known about, and I think I may have even tinkered with before, but I don't believe I have ever incorporated them into a project. My previous work with automation used IDEs with built-in capability to run tests on commit, or I used server-side integration tests to check my work.

Someone who does a lot of shell scripting and git hooks would probably laugh at how simple this is. However, I want to share the script here in part because the "live" version is currently hidden away in a private repository. Here is the executable script that I put into my project's .git/hooks directory:

#!/bin/sh
if godot -d -s --path project addons/gut/gut_cmdln.gd -gdir=res://test/ -gprefix="" -gsuffix="_test.gd" -gexit
then
    echo "Tests passed"
else
    cat <<\EOF
Unit tests failed. Commit aborted.
EOF
    exit 1
fi

This works pretty well. One downside is that it has to pop up a window during the tests. I would like to find a way to prevent that. Also, I could probably get away with having the tests run only when I'm committing to master rather than on feature branches.

No comments:

Post a Comment