2 Tests in the hook
Read the tutorial. Build it yourself is the other way to read this part.
just setupCode that compiles can still count wrong. The tests find that, so the hook must run them too. First we write a test, then the hook runs the tests after the check.
The code before this part. The code after it.
2.1 A first test
The hook can run tests only if there are tests. A first test, in tests/test_count.py, checks that count counts
the words of a b a.
A patch to tests/test_count.py.
The new file tests/test_count.py has one test, test_words. It expects {"a": 2, "b": 1} for a b a.
uv run python -m unittest discover -s tests -qThe test passes.
What changed
tests/test_count.py: one test of counting. New, 9 lines. The file.- look at
self.assertEqual(count("a b a"), {"a": 2, "b": 1})
- look at
The diff of tests/test_count.py
@@ -0,0 +1,9 @@
+import unittest
+
+from tally import count
+
+
+class Count(unittest.TestCase):
+ def test_words(self):
+ self.assertEqual(count("a b a"), {"a": 2, "b": 1})
+2.2 The hook runs the tests too
The hook compiles the code, but a failing test does not stop a git commit. One more line in the hook runs the
tests after the check.
A patch to hooks/pre-commit.
At the end of hooks/pre-commit, the new line runs the tests after just check.
sh hooks/pre-commit && echo "the hook passed"The hook compiles the code, runs the tests, and prints the hook passed.
What changed
hooks/pre-commit: the tests run after the check. 1 line added. The file.- look at
uv run python -m unittest discover -s tests -q
- look at
The diff of hooks/pre-commit
@@ -1,3 +1,4 @@
#!/bin/sh
# Run before each commit: refuse it if the code does not compile.
just check
+uv run python -m unittest discover -s tests -q