문제

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...

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top