We’ll use pytest
to add a simple test for the new library mylib
we added.
Make a new file mylib/moo_test.py
containing the basic syntax for a Python test:
from mylib import say
def test_mooing():
assert say.moo("test") == "intentionally wrong"
Now we need to update the dependency graph, so run aspect configure
. The BUILD
file now has a py_test
target named mylib_test
which we can test with bazel test
. Of course it fails, since our assertion was “intentionally wrong” but the function returns None
- that’s good to know the test is running correctly! We can just replace that with None
to see the test pass.
Debugging
To debug this test, we’ll want it to run correctly in the editor, which doesn’t require Bazel at all. We can just use a virtualenv again. Let’s find that venv
target again:
alexeagle@aspect-build bazel_102 % bazel query --output=label_kind mylib:all
py_library rule //mylib:__test__
_py_pytest_main rule //mylib:__test___template
determine_main rule //mylib:_mylib_test.find_main
_jq_rule rule //mylib:data
_run_binary rule //mylib:make_header
py_library rule //mylib:mylib
py_test rule //mylib:mylib_test
py_venv_rule rule //mylib:mylib_test.venv
pip_compile rule //mylib:pip_compile
alias rule //mylib:pip_compile.update
pip_compile_test rule //mylib:pip_compile_test
filegroup rule //mylib:requirements
//mylib:mylib_test.venv
will create a virtualenv specific to this test target, with the right set of dependencies included. Let’s bazel run
that target - the editor should offer to activate the new environment.
We can open a new terminal in the editor which uses the new virtualenv and see that we can directly run the Bazel-managed pytest. That’s great since it means all tooling should just work here, including debuggers.
For Visual Studio Code, the steps to debug are:
- open the “Testing” extension, pick “Configure Python tests” and choose “pytest”, then choose the “mylib” folder.
- Set a breakpoint, maybe at line 11 of
mylib/say.py
which we know will be called by the test - Choose the “debug test” icon for the file, and we stop at the breakpoint: