Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure equivalent to Python doctest?

Python doctests associate simple tests with the source code (in Python they are in the function documentation). More info and examples here.

Is there anything similar for Clojure?

I am aware of unit tests with clojure.test, but looking for something more closely integrated with the source (typically unit tests are in different files; here I want to have the test "inside" the defn).

Searching around I found this, but it seems very un-lispy (the tests are in actual text, like Python - surely a macro that extends defn would be preferable?).

Or perhaps there is some other way to solve the general problem, which is that I have some tests (generally simple things that demonstrate basic properties of the function) that would be better included with the documentation (I am using marginalia) than in separate unit test files.

update Here's an example: I have a function that calculates the (manhattan) distance (in pixels) from a rectangle of pixels to the centre of the image. That sounds simple, but is complicated by things like the difference in meaning of "centre" for images with odd or even numbers of pixels on sides, or which part of the block you measure from. So I had to write some tests just to get the code straight. And now I look at the docs and really it would be best if the docs included those tests because they explain better than words what the function does...

like image 887
andrew cooke Avatar asked Jun 05 '12 01:06

andrew cooke


2 Answers

and the test flag in metadata, http://clojure.org/special_forms

(defn
 ^{:doc "mymax [xs+] gets the maximum value in xs using > "
   :test (fn []
             (assert (= 42  (mymax 2 42 5 4))))
   :user/comment "this is the best fn ever!"}
  mymax
  ([x] x)
  ([x y] (if (> x y) x y))
  ([x y & more]
   (reduce mymax (mymax x y) more)))

user=> (test #'mymax)
:ok
user=> (doc test)
-------------------------
clojure.core/test
([v])
  test [v] finds fn at key :test in var metadata and calls it,
  presuming failure will throw exception
nil
like image 86
number23_cn Avatar answered Oct 12 '22 21:10

number23_cn


How about :pre and :post expressions? http://blog.fogus.me/2009/12/21/clojures-pre-and-post/

like image 26
KaKa Avatar answered Oct 12 '22 22:10

KaKa