<astyle="font-size: 120%"href="https://www.udemy.com/course/common-lisp-programming/?couponCode=LISPY-XMAS2023"title="This course is under a paywall on the Udemy platform. Several videos are freely available so you can judge before diving in. vindarel is (I am) the main contributor to this Cookbook."> Discover our contributor's Lisp course with this Christmas coupon.</a>
📕 <ahref="index.html#download-in-epub">Get the EPUB and PDF</a>
</p>
<divid="content"
<p>So you want to easily test the code you’re writing? The following
recipe covers how to write automated tests and see their code
coverage. We also give pointers to plug those in modern continuous
integration services like GitHub Actions, Gitlab CI, Travis CI or Coveralls.</p>
<p>We will be using a mature testing framework called
<ahref="https://github.com/lispci/fiveam">FiveAM</a>. It supports test suites,
random testing, test fixtures (to a certain extent) and, of course,
interactive development.</p>
<p>Previously on the Cookbook, the recipe was cooked with <ahref="https://github.com/fukamachi/prove">Prove</a>. It used to be a widely liked testing framework but, because of some shortcomings, its repository was later archived. Its successor <ahref="https://github.com/fukamachi/rove">Rove</a> is not stable enough and lacks some features, so we didn’t pick it. There are also some <ahref="https://github.com/CodyReichert/awesome-cl#unit-testing">other testing frameworks</a> to explore if you feel like it.</p>
<p>FiveAM has an <ahref="https://common-lisp.net/project/fiveam/docs/index.html">API documentation</a>. You may inspect it or simply read the docstrings in code. Most of the time, they would provide sufficient information that answers your questions… if you didn’t find them here. Let’s get started.</p>
<h2id="testing-with-fiveam">Testing with FiveAM</h2>
<p>FiveAM has 3 levels of abstraction: check, test and suite. As you may have guessed:</p>
<ol>
<li>A <strong>check</strong> is a single assertion that checks that its argument is truthy. The most used check is <code>is</code>. For example, <code>(is (= 2 (+ 1 1)))</code>.</li>
<li>A <strong>test</strong> is the smallest runnable unit. A test case may contain multiple checks. Any check failure leads to the failure of the whole test.</li>
<li>A <strong>suite</strong> is a collection of tests. When a suite is run, all tests inside would be performed. A suite allows paternity, which means that running a suite will run all the tests defined in it and in its children suites.</li>
</ol>
<p>A simple code sample containing the 3 basic blocks mentioned above can be shown as follows:</p>
<p>The package is named <code>fiveam</code> with a nickname <code>5am</code>. For the sake of simplicity, we will ignore the package prefix in the following code samples.</p>
<p>It is like we <code>:use</code>d fiveam in our test package definition. You
can also follow along in the REPL with <code>(use-package :fiveam)</code>.</p>
<p>Testing in FiveAM usually starts by defining a suite. A suite helps separating tests to smaller collections that makes them more organized. It is highly recommended to define a single <em>root</em> suite for the sake of ASDF integration. We will talk about it later, now let’s focus on the testing itself.</p>
<p>The code below defines a suite named <code>my-system</code>. We will use it as the root suite for the whole system.</p>
<p>Then let’s define another suite for testing the <code>read-file-as-string</code> function.</p>
<pre><codeclass="language-lisp">;; Define a suite and set it as the default for the following tests.
(def-suite read-file-as-string
:description "Test the read-file-as-string function."
:in my-system)
(in-suite read-file-as-string)
;; Alternatively, the following line is a combination of the 2 lines above.
(def-suite* read-file-as-string :in my-system)
</code></pre>
<p>Here a new suite named <code>read-file-as-string</code> has been defined. It is declared to be a child suite of <code>my-system</code> as specified by the <code>:in</code> keyword. The macro <code>in-suite</code> sets it as the default suite for the tests defined later.</p>
<h3id="defining-tests">Defining tests</h3>
<p>Before diving into tests, here is a brief introduction of the available checks you may use inside tests:</p>
<ul>
<li>The <code>is</code> macro is likely the most used check. It simply checks if the given expression returns a true value and generates a <code>test-passed</code> or <code>test-failure</code> result accordingly.</li>
<li>The <code>skip</code> macro takes a reason and generates a <code>test-skipped</code> result.</li>
<li>The <code>signals</code> macro checks if the given condition was signaled during execution.</li>
</ul>
<p>There is also:</p>
<ul>
<li><code>finishes</code>: passes if the assertion body executes to normal completion. In other words if body does signal, return-from or throw, then this test fails.</li>
<li><code>pass</code>: just make the test pass.</li>
<li><code>is-true</code>: like <code>is</code>, but unlike it this check does not inspect the assertion body to determine how to report the failure. Similarly, there is <code>is-false</code>.</li>
</ul>
<p>Please note that all the checks accept an optional reason, as string, that can be formatted with format directives (see more below). When omitted, FiveAM generates a report that explains the failure according to the arguments passed to the function.</p>
<p>The <code>test</code> macro provides a simple way to define a test with a name.</p>
<p><em>Note that below, we expect two files to exist: <code>/tmp/hello.txt</code> should contain “hello” and <code>/tmp/empty.txt</code> should be empty.</em></p>
<pre><codeclass="language-lisp">;; Our first "base" case: we read a file that contains "hello".
"Reading a file should return NIL when :ERROR-IF-NOT-EXISTS is set to NIL"))
;; SIGNALS accepts the unquoted name of a condition and a body to evaluate.
;; Here it checks if FILE-NOT-EXISTING-ERROR is signaled.
(signals file-not-existing-error
(read-file-as-string "/tmp/non-existing-file.txt"
:error-if-not-exists t)))
</code></pre>
<p>In the above code, three tests were defined with 5 checks in total. Some checks were actually redundant for the sake of demonstration. You may put all the checks in one big test, or in multiple scenarios. It is up to you.</p>
<p>The macro <code>test</code> is a convenience for <code>def-test</code> to define simple tests. You may read its docstring for a more complete introduction, for example to read about <code>:depends-on</code>.</p>
<h3id="running-tests">Running tests</h3>
<p>FiveAm provides multiple ways to run tests. The macro <code>run!</code> is a good start point during development. It accepts a name of suite or test and run it, then prints testing report in standard output. Let’s run the tests now!</p>
<pre><codeclass="language-lisp">(run! 'my-system)
; Running test suite MY-SYSTEM
; Running test READ-FILE-AS-STRING-EMPTY-FILE ..
; Running test READ-FILE-AS-STRING-NON-EXISTING-FILE ..
; Running test READ-FILE-AS-STRING-NORMAL-FILE .
; Did 5 checks.
; Pass: 5 (100%)
; Skip: 0 ( 0%)
; Fail: 0 ( 0%)
; => T, NIL, NIL
</code></pre>
<p>If we mess <code>read-file-as-string-non-existing-file</code> up by replacing <code>/tmp/non-existing-file.txt</code> with <code>/tmp/hello.txt</code>, the test would fail (sure!) as expected:</p>
<p>The behavior of the suite/test runner can be customized by the <code>*on-failure*</code> variable, which controls what to do when a check failure happens. It can be set to one of the following values:</p>
<ul>
<li><code>:debug</code> to drop to the debugger.</li>
<li><code>:backtrace</code> to print a backtrace and continue.</li>
<li><code>NIL</code> (default) to simply continue and print the report.</li>
</ul>
<p>There is also <code>*on-error*</code>.</p>
<h4id="running-tests-as-they-are-compiled">Running tests as they are compiled</h4>
<p>Under normal circumstances, a test is written and compiled (with the
usual <code>C-c C-c</code> in Slime) separately from the moment it is run. If you
want to run the test when it is defined (with <code>C-c C-c</code>), set this:</p>
<h3id="custom-and-shorter-tests-explanations">Custom and shorter tests explanations</h3>
<p>We said earlier that a check accepts an optional custom reason that can be formatted with <code>format</code> directives. Here’s a simple example.</p>
<p>And we have a function to run 100 checks, taking each turn a new value from the given generators: <code>for-all</code>:</p>
<pre><codeclass="language-lisp">(test randomtest
(for-all ((a (gen-integer :min 1 :max 10))
(b (gen-integer :min 1 :max 10)))
"Test random tests."
(is (<= a b))))
</code></pre>
<p>When you <code>run! 'randomtest</code> this, I expect you will hit an error. You can’t
possibly always get <code>a</code> lower than <code>b</code>, can you?</p>
<p>For more, see <ahref="https://common-lisp.net/project/fiveam/docs/Checks.html#Random_0020_0028QuickCheck-ish_0029_0020testing">FiveAM’s documentation</a>.</p>
<p>See also <ahref="https://github.com/mcandre/cl-quickcheck">cl-quickcheck</a> and <ahref="https://github.com/DalekBaldwin/check-it">Check-it</a>, inspired by Haskell’s <ahref="https://en.wikipedia.org/wiki/QuickCheck">QuickCheck</a> test framework.</p>
<h3id="asdf-integration">ASDF integration</h3>
<p>So it would be nice to provide a one-line trigger to test our <code>my-system</code> system. Recall that we said it is better to provide a root suite? Here is the reason:</p>
<p>The last line tells ASDF to load symbol <code>:my-system</code> from <code>my-system/test</code> package and call <code>fiveam:run!</code>. It fact, it is equivalent to <code>(run! 'my-system)</code> as mentioned above.</p>
<h3id="running-tests-on-the-terminal">Running tests on the terminal</h3>
<p>Until now, we ran our tests from our editor’s REPL. How can we run them from a terminal window?</p>
<p>As always, the required steps are as follow:</p>
<ul>
<li>start our Lisp</li>
<li>make sure Quicklisp is enabled (if we have external dependencies)</li>
<li>load our main system</li>
<li>load the test system</li>
<li>run the FiveAM tests.</li>
</ul>
<p>You could put them in a new <code>run-tests.lisp</code> file:</p>
<p>It is possible to generate our own testing report. The macro <code>run!</code> is nothing more than a composition of <code>explain!</code> and <code>run</code>.</p>
<p>Instead of generating a testing report like its cousin <code>run!</code>, the function <code>run</code> runs suite or test passed in and returns a list of <code>test-result</code> instance, usually instances of <code>test-failure</code> or <code>test-passed</code> sub-classes.</p>
<p>A class <code>text-explainer</code> is defined as a basic class for testing report generator. A generic function <code>explain</code> is defined to take a <code>text-plainer</code> instance and a <code>test-result</code> instance (returned by <code>run</code>) and generate testing report. The following 2 code snippets are equivalent:</p>
<p>By creating a new sub-class of <code>text-explainer</code> and a method <code>explain</code> for it, it is possible to define a new test reporting system.</p>
<p>The following code just provides a proof-of-concept implementation. You may need to read the source code of <code>5am::detailed-text-explainer</code> to fully understand it.</p>
<p>Continuous Integration is important to run automatic tests after a
commit or before a pull request, to run code quality checks, to build
and distribute your software… well, to automate everything about software.</p>
<p>We want our programs to be portable across Lisp implementations, so
we’ll set up our CI pipeline to run our tests against several of them (it
could be SBCL and CCL of course, but while we’re at it ABCL, ECL and
possibly more).</p>
<p>We have a choice of Continuous Integration services: Travis CI, Circle, Gitlab CI, now also GitHub Actions, etc (many existed before GitHub Actions, if you wonder). We’ll have a look at how to configure a CI pipeline for Common Lisp, and we’ll focus a little more on Gitlab CI on the last part.</p>
<p>We’ll also quickly show how to publish coverage reports to the <ahref="https://coveralls.io/">Coveralls</a> service. <ahref="https://github.com/fukamachi/cl-coveralls">cl-coveralls</a> helps to post our coverage to the service.</p>
<h3id="github-actions-circle-ci-travis-with-ci-utils">GitHub Actions, Circle CI, Travis… with CI-Utils</h3>
<p>We’ll use <ahref="https://neil-lindquist.github.io/CI-Utils/">CI-Utils</a>, a set of utilities that comes with many examples. It also explains more precisely what is a CI system and compares a dozen of services.</p>
<p>It relies on <ahref="https://github.com/roswell/roswell/">Roswell</a> to install the Lisp implementations and to run the tests. They all are installed with a bash one-liner:</p>
<p>(note that on the Gitlab CI example, we use a ready-to-use Docker image that contains them all)</p>
<p>It also ships with a test runner for FiveAM, which eases some rough parts (like returning the right error code to the terminal). We install ci-utils with Roswell, and we get the <code>run-fiveam</code> executable.</p>
<p>Then we can run our tests:</p>
<pre><code>run-fiveam -e t -l foo/test :foo-tests # foo is our project
</code></pre>
<p>Following is the complete <code>.travis.yml</code> file.</p>
<p>The first part should be self-explanatory:</p>
<pre><codeclass="language-yml">### Example configuration for Travis CI ###
language: generic
addons:
homebrew:
update: true
packages:
- roswell
apt:
packages:
- libc6-i386 # needed for a couple implementations
- default-jre # needed for abcl
# Runs each lisp implementation on each of the listed OS
<p>This is how we configure the implementations matrix, to run our tests on several Lisp implementations. We also send the test coverage made with SBCL to Coveralls.</p>
- curl -L https://raw.githubusercontent.com/roswell/roswell/release/scripts/install-for-ci.sh | sh
- ros install ci-utils #for run-fiveam
# - ros install rove #for [run-] rove
# If asdf 3.16 or higher is needed, uncomment the following lines
#- mkdir -p ~/common-lisp
#- if [ "$LISP" == "ccl-bin" ]; then git clone https://gitlab.common-lisp.net/asdf/asdf.git ~/common-lisp; fi
script:
- run-fiveam -e t -l foo/test :foo-tests
#- rove foo.asd
</code></pre>
<p>Below with Gitlab CI, we’ll use a Docker image that already contains the Lisp binaries and every Debian package required to build Quicklisp libraries.</p>
<h3id="gitlab-ci">Gitlab CI</h3>
<p><ahref="https://docs.gitlab.com/ce/ci/README.html">Gitlab CI</a> is part of
Gitlab and is available on <ahref="https://gitlab.com/">Gitlab.com</a>, for
public and private repositories. Let’s see straight away a simple
<p>Here, examples of the <ahref="https://shinmera.github.io/parachute/">Parachute</a> testing
library are shown. As shown elsewhere, in order for the CI job to fail when any
test fails, we manually check the test result status and return <code>1</code> when there’s
a problem.</p>
<h2id="emacs-integration-running-tests-using-slite">Emacs integration: running tests using Slite</h2>
<p><ahref="https://github.com/tdrhq/slite">Slite</a> stands for SLIme TEst runner. It allows you to see the summary of test failures, jump to test definitions, rerun tests with the debugger… all from inside Emacs. We get a dashboard-like buffer with green and red badges, from where we can act on tests. It makes the testing process <em>even more</em> integrated and interactive.</p>
<p>It consists of an ASDF system and an Emacs package. It is a new project (it appeared mid 2021) so, as of September 2021, neither can be installed via Quicklisp or MELPA yet. Please refer to its <ahref="https://github.com/tdrhq/slite">repository</a> for instructions.</p>
<h2id="references">References</h2>
<ul>
<li><ahref="http://turtleware.eu/posts/Tutorial-Working-with-FiveAM.html">Tutorial: Working with FiveAM</a>, by Tomek “uint” Kurcz</li>
<li><ahref="https://sabracrolleton.github.io/testing-framework">Comparison of Common Lisp Testing Frameworks</a>, by Sabra Crolleton.</li>
<li>the <ahref="https://hub.docker.com/u/clfoundation">CL Foundation Docker images</a></li>
</ul>
<h2id="see-also">See also</h2>
<ul>
<li><ahref="https://github.com/vindarel/cl-cookieproject">cl-cookieproject</a>, a project skeleton with a FiveAM tests structure.</li>