Skip to content

A peer-to-peer stack for code collaboration

4.6 KB
Raw Blame
{:module 'prelude/test
 :doc "Provides eval that adds a `:test` macro."
 :exports '[run-all make-suite assert-equal]}


(import prelude/basic :unqualified)
(import prelude/bool :unqualified)
(import prelude/io :unqualified)
(import prelude/list :unqualified)
(import prelude/patterns :unqualified)
(import prelude/validation :as 'validate)

(def assert-equal
  "Compares `actual` with `expected` with `eq?`. If the values are not equal an
  `'assertion-error` is thrown. Otherwise `actual` is retuned."
  (fn [actual expected]
    (if (eq? actual expected)
        actual
        (throw 'assertion-error (string-append "failed: got " (show actual) " but expected " (show expected))))
))

;; Utils

(def try
  "Call `f` and catch any errors with `tag`. If no errors were thrown
  then return `[:ok r]` where `r` is the result of calling `f`. If an
  error was thrown return `[:error e]` where `e` is the second argument
  to `throw`."
  (fn [tag f]
    (def handle-error
      (fn [msg] [:error msg]))
    (catch tag [:ok (f)] handle-error)
  ))

(def foldl-with-index
  "Like `(fold f r xs)` but evaluates `(f acc x i)` where `i` is an
  additional index argument that starts with 0."
  (fn [f r xs]
    (head
      (foldl
        (fn [acc x]
          (match acc ['r 'i] [(f r x i) (+ i 1)]))
        [r 0]
        xs))
  ))

(def parse-doc-test-step
  "Parse a doc test step of the form `[ actual ==> expected ]` and
  returns a function that when called with an environments runs the
  step.

  Running a doc step means evluating `actual` in the given environment
  and comparing the result with `expected` using `assert-equal`."
  (fn [step]
    (def lhs (nth 0 step))
    (def marker (nth 1 step))
    (def rhs (nth 2 step))
    (if (eq? marker '==>)
        (fn [env]
          (def lhs-res (head (eval lhs env)))
          (assert-equal lhs-res rhs))
        (throw 'parse-test-step "Expected and actual not separate by ==>"))
  ))

(def extract-setup
  "Extracts the setup step from the test steps. Returns a `[setup steps]` tuple."
  (fn [steps]
    (def first-step (first steps))
    (def first-lhs (first first-step))
    (match first-lhs
      :setup
        [(rest first-step) (rest steps)]
      'otherwise
        [:nothing steps]
  )))

(def parse-doc-test
  "Parse a doc test definition `test-def` and return a simple test. A
  doc test definition is a  `{:env env :doc-tests tests :name name}`
  dictionary where `env` is a radicle environment and `tests` is a list
  of quoted test cases with an optional `:setup` item.
  ```
  '(
    [:setup (do
      (def foo #t)
    )]
    [ foo ==> #t ]
    [ (not foo) ==> #f ]
  )
  ```
  "
  (fn [test-def]
    (def test-env (lookup :env test-def))
    (def test-name (lookup :name test-def))
    (def test-contents (lookup :doc-test test-def))
    (def setup-and-steps (extract-setup test-contents))
    (def setup (nth 0 setup-and-steps))
    (def steps (nth 1 setup-and-steps))
    (def step-runners (map parse-doc-test-step steps))
    (def test-env (nth 1 (eval setup test-env)))
    (def run
      (fn []
        (map (fn [r] (r test-env)) step-runners)
        :nil))
    {:name test-name :run run}
    ))


(def parse-test
  "If the test is a doc test, parse it. Otherwise just return the test definition."
  (fn [test]
    (if (member? :doc-test test)
      (parse-doc-test test)
      test
      )))


(def run-test
  "Executes a test and print the result. Returns `#t` if the test
  passed, `#f` otherwise."
  (fn [test-def index]
    (match (parse-test test-def)
      {:name 'name :run 'run} (do
        (def result (try 'any run))
        (match result
          [:ok _]       (do
            (put-str! (string-append "ok " (show index) " - " name))
            #t
            )
          [:error 'msg] (do
            (put-str! (string-append "not ok " (show index) " - " name "\n" (show msg)))
            #f
            )
          )))))

(def make-suite
  "Define a set of tests from a dictionary. The keys of `tests` are
  test names as strings. The values are functions that run the test.
  Test names are prefixed with `suite-name`."
  (fn [suite-name tests]
    (map
      (fn [item]
        (match item ['test-name 'run] (do
          ((validate/type :function) run)
          ((validate/type :string) test-name)
          {:name (string-append suite-name ": " test-name) :run run})))
      (seq tests))))


(def run-all
  "Run all `tests` and print the results. Returns `#f` if at least one test fails and `#t` otherwise."
  (fn [tests]
    (put-str! (string-append "1.." (show (length tests))))
    (foldl-with-index
      (fn [ok t i] (and ok (run-test t (+ 1 i))))
      #t
      tests)
  ))