Testing your code
In this post, you will learn about tools to check that your code works and is written well.
Unit testing
The purpose of the test subfolder in a project is unit testing: automatically checking that your code behaves the way you want it to.
For instance, if you write your own square root function, you may want to test that it gives the correct results for positive numbers, and errors for negative numbers.
julia> using Test julia> @test sqrt(4) ≈ 2 Test.Pass(:test, :(sqrt(4) ≈ 2), :(2.0 ≈ 2), true, :(#= REPL:3 =#), false) julia> @testset "Invalid inputs" begin @test_throws DomainError sqrt(-1) @test_throws MethodError sqrt("abc") end; Test Summary: | Pass Total Time Invalid inputs | 2 2 0.1s
Such tests belong in test/runtests.jl, and they are executed with the ]test command (in the REPL's Pkg mode).
Unit testing may seem rather naive, or even superfluous, but as your code grows more complex, it becomes easier to break something without noticing.
Testing each part separately will increase the reliability of the software you write.
Advanced: To test the arguments provided to the functions within your code (for instance their sign or value), avoid @assert (which can be deactivated) and use ArgCheck.jl instead.
Test dependencies
At some point, your project may require test-specific dependencies.
This often happens when you need to test compatibility with another package, on which you do not depend for the source code itself.
Or it may simply be due to testing-specific packages like the code quality checkers presented below.
For interactive testing work, use TestEnv.jl to activate the full test environment (faster than running ]test repeatedly).
Test frameworks
VS Code: The Julia extension also has its own testing framework, which relies on sprinkling "test items" throughout the code. See TestItemRunner.jl for indications on how to use them optimally.
Advanced: If you want to have more control over your tests, you can try
- ReferenceTests.jl to compare function outputs with reference files.
- ReTest.jl to define tests next to the source code and control their execution.
- TestSetExtensions.jl to make test set outputs more readable.
- TestReadme.jl to test whatever code samples are in your README.
- ReTestItems.jl for an alternative take on VS Code's test item framework.
Code coverage
Code coverage refers to the fraction of lines in your source code that are covered by tests. It is a good indicator of the exhaustiveness of your test suite, albeit not sufficient. Codecov is a website that provides easy visualization of this coverage, and many Julia packages use it. It is available as a PkgTemplates.jl plugin, but you have to perform an additional configuration step on the repo for Codecov to communicate with it.
Advanced: For local coverage analysis, LocalCoverage.jl provides trivial functions for working with coverage locally without requiring external services.
Code quality
Unit tests check what your code does, but some problems only show up when you inspect the project as a whole.
Aqua.jl provides a set of routines that examine other aspects of your project, from unused dependencies to ambiguous methods.
It is usually a good idea to include the following in your tests, with MyAwesomeCode replaced by the name of your project:
julia> using Aqua, MyAwesomeCode Precompiling packages... 394.2 ms ✓ MyAwesomeCode 1 dependency successfully precompiled in 0 seconds julia> Aqua.test_all(MyAwesomeCode) Test Summary: | Pass Total Time Method ambiguity | 1 1 1.1s Test Summary: | Pass Total Time Unbound type parameters | 1 1 0.0s Test Summary: | Pass Total Time Undefined exports | 1 1 0.0s Test Summary: | Pass Total Time Compare Project.toml and test/Project.toml | 1 1 0.0s Test Summary: | Pass Total Time Stale dependencies | 1 1 0.6s Test Summary: | Pass Total Time Compat bounds | 4 4 0.4s Test Summary: | Pass Total Time Piracy | 1 1 0.0s Test Summary: | Pass Total Time Persistent tasks | 1 1 1.8s
Meanwhile, JET.jl is a complementary tool, similar to a static linter. Here we focus on its error analysis, which can detect errors or typos without even running the code by leveraging type inference. You can either use it in report mode (with a nice VS Code display) or in test mode as follows:
julia> using JET, MyAwesomeCode julia> JET.report_package(MyAwesomeCode) [toplevel-info] Analyzing top-level definitions (progress: 0/0 | interval: 1) [toplevel-info] Analyzing top-level definitions (progress: 0/0) [toplevel-info] Analyzed all top-level definitions (all: 0 | analyzed: 0 | cached: 0 | took: 0.091 sec) JET.JETToplevelResult{JET.BasicJETAnalyzer, Base.Pairs{Symbol, IOContext{Base.PipeEndpoint}, Nothing, @NamedTuple{toplevel_logger::IOContext{Base.PipeEndpoint}}}}(JET.BasicJETAnalyzer(JET.AnalyzerState(0x00000000000097ba, Compiler.InferenceResult[], Compiler.InferenceParams(3, 4, 8, 32, 3, true, true, true, false, false), Compiler.OptimizationParams(true, 100, 1000, 250, 32, true, false, false), IdDict{Compiler.InferenceResult, JET.AnalysisResult}(), JET.InferenceErrorReport[], nothing, Bool[], nothing, JET.AbstractBindings(IdDict{Core.BindingPartition, JET.AbstractBindingState}(), Base.Threads.SpinLock(0)), IdDict{Core.Binding, JET.AbstractAssignmentSites}(), nothing, nothing), JET.AnalysisToken(), Compiler.CachedMethodTable{Compiler.OverlayMethodTable}(0 entries), JET.JETAnalyzerConfig(true, true)), JET.VirtualProcessResult(Dict{String, JET.AnalyzedFileInfo}(), nothing, JET.ToplevelWarningReport[], JET.InferenceErrorReport[], JET.SignatureInfo[], nothing), "BasicJETAnalyzer: MyAwesomeCode", Base.Pairs{Symbol, IOContext{Base.PipeEndpoint}, Nothing, @NamedTuple{toplevel_logger::IOContext{Base.PipeEndpoint}}}(:toplevel_logger => IOContext(Base.PipeEndpoint(RawFD(-1) closed, 0 bytes waiting)))) julia> JET.test_package(MyAwesomeCode) Test.Pass(:test_package, :((JET.report_package)(MyAwesomeCode; toplevel_logger = nothing)), nothing, nothing, :(#= /home/runner/.julia/packages/JET/4Ferj/src/JETBase.jl:1405 =#), false)
Note that both Aqua.jl and JET.jl might pick up false positives: refer to their respective documentations for ways to make them less sensitive.
Finally, ExplicitImports.jl can help you get rid of generic imports to specify where each of the names in your project comes from. This is a good practice and makes your code more robust to name conflicts between dependencies.
Advanced: For additional code quality tools, consider ReLint.jl, which provides another linter for Julia code with different rules and checks compared to JET.jl.
You can also use pre-commit to set up hooks that automatically run code quality checks before each commit, ensuring consistent code standards across your project.