Clojure 1.8参考手册
Clojure 1.8
clojure.test
概述
A unit testing framework.
ASSERTIONS
The core of the library is the "is" macro, which lets you make
assertions of any arbitrary expression:
(is (= 4 (+ 2 2)))
(is (instance? Integer 256))
(is (.startsWith "abcde" "ab"))
You can type an "is" expression directly at the REPL, which will
print a message if it fails.
user> (is (= 5 (+ 2 2)))
FAIL in (:1)
expected: (= 5 (+ 2 2))
actual: (not (= 5 4))
false
The "expected:" line shows you the original expression, and the
"actual:" shows you what actually happened. In this case, it
shows that (+ 2 2) returned 4, which is not = to 5. Finally, the
"false" on the last line is the value returned from the
expression. The "is" macro always returns the result of the
inner expression.
There are two special assertions for testing exceptions. The
"(is (thrown? c ...))" form tests if an exception of class c is
thrown:
(is (thrown? ArithmeticException (/ 1 0)))
"(is (thrown-with-msg? c re ...))" does the same thing and also
tests that the message on the exception matches the regular
expression re:
(is (thrown-with-msg? ArithmeticException #"Divide by zero"
(/ 1 0)))
DOCUMENTING TESTS
"is" takes an optional second argument, a string describing the
assertion. This message will be included in the error report.
(is (= 5 (+ 2 2)) "Crazy arithmetic")
In addition, you can document groups of assertions with the
"testing" macro, which takes a string followed by any number of
assertions. The string will be included in failure reports.
Calls to "testing" may be nested, and all of the strings will be
joined together with spaces in the final report, in a style
similar to RSpec <http://rspec.info/>
(testing "Arithmetic"
(testing "with positive integers"
(is (= 4 (+ 2 2)))
(is (= 7 (+ 3 4))))
(testing "with negative integers"
(is (= -4 (+ -2 -2)))
(is (= -1 (+ 3 -4)))))
Note that, unlike RSpec, the "testing" macro may only be used
INSIDE a "deftest" or "with-test" form (see below).
DEFINING TESTS
There are two ways to define tests. The "with-test" macro takes
a defn or def form as its first argument, followed by any number
of assertions. The tests will be stored as metadata on the
definition.
(with-test
(defn my-function [x y]
(+ x y))
(is (= 4 (my-function 2 2)))
(is (= 7 (my-function 3 4))))
As of Clojure SVN rev. 1221, this does not work with defmacro.
See http://code.google.com/p/clojure/issues/detail?id=51
The other way lets you define tests separately from the rest of
your code, even in a different namespace:
(deftest addition
(is (= 4 (+ 2 2)))
(is (= 7 (+ 3 4))))
(deftest subtraction
(is (= 1 (- 4 3)))
(is (= 3 (- 7 4))))
This creates functions named "addition" and "subtraction", which
can be called like any other function. Therefore, tests can be
grouped and composed, in a style similar to the test framework in
Peter Seibel's "Practical Common Lisp"
<http://www.gigamonkeys.com/book/practical-building-a-unit-test-framework.html>
(deftest arithmetic
(addition)
(subtraction))
The names of the nested tests will be joined in a list, like
"(arithmetic addition)", in failure reports. You can use nested
tests to set up a context shared by several tests.
RUNNING TESTS
Run tests with the function "(run-tests namespaces...)":
(run-tests 'your.namespace 'some.other.namespace)
If you don't specify any namespaces, the current namespace is
used. To run all tests in all namespaces, use "(run-all-tests)".
By default, these functions will search for all tests defined in
a namespace and run them in an undefined order. However, if you
are composing tests, as in the "arithmetic" example above, you
probably do not want the "addition" and "subtraction" tests run
separately. In that case, you must define a special function
named "test-ns-hook" that runs your tests in the correct order:
(defn test-ns-hook []
(arithmetic))
Note: test-ns-hook prevents execution of fixtures (see below).
OMITTING TESTS FROM PRODUCTION CODE
You can bind the variable "*load-tests*" to false when loading or
compiling code in production. This will prevent any tests from
being created by "with-test" or "deftest".
FIXTURES
Fixtures allow you to run code before and after tests, to set up
the context in which tests should be run.
A fixture is just a function that calls another function passed as
an argument. It looks like this:
(defn my-fixture [f]
Perform setup, establish bindings, whatever.
(f) Then call the function we were passed.
Tear-down / clean-up code here.
)
Fixtures are attached to namespaces in one of two ways. "each"
fixtures are run repeatedly, once for each test function created
with "deftest" or "with-test". "each" fixtures are useful for
establishing a consistent before/after state for each test, like
clearing out database tables.
"each" fixtures can be attached to the current namespace like this:
(use-fixtures :each fixture1 fixture2 ...)
The fixture1, fixture2 are just functions like the example above.
They can also be anonymous functions, like this:
(use-fixtures :each (fn [f] setup... (f) cleanup...))
The other kind of fixture, a "once" fixture, is only run once,
around ALL the tests in the namespace. "once" fixtures are useful
for tasks that only need to be performed once, like establishing
database connections, or for time-consuming tasks.
Attach "once" fixtures to the current namespace like this:
(use-fixtures :once fixture1 fixture2 ...)
Note: Fixtures and test-ns-hook are mutually incompatible. If you
are using test-ns-hook, fixture functions will *never* be run.
SAVING TEST OUTPUT TO A FILE
All the test reporting functions write to the var *test-out*. By
default, this is the same as *out*, but you can rebind it to any
PrintWriter. For example, it could be a file opened with
clojure.java.io/writer.
EXTENDING TEST-IS (ADVANCED)
You can extend the behavior of the "is" macro by defining new
methods for the "assert-expr" multimethod. These methods are
called during expansion of the "is" macro, so they should return
quoted forms to be evaluated.
You can plug in your own test-reporting framework by rebinding
the "report" function: (report event)
The 'event' argument is a map. It will always have a :type key,
whose value will be a keyword signaling the type of event being
reported. Standard events with :type value of :pass, :fail, and
:error are called when an assertion passes, fails, and throws an
exception, respectively. In that case, the event will also have
the following keys:
:expected The form that was expected to be true
:actual A form representing what actually occurred
:message The string message given as an argument to 'is'
The "testing" strings will be a list in "*testing-contexts*", and
the vars being tested will be a list in "*testing-vars*".
Your "report" function should wrap any printing calls in the
"with-test-out" macro, which rebinds *out* to the current value
of *test-out*.
For additional event types, see the examples in the code.
公共变量和函数
*load-tests*动态变量
True by default. If set to false, no test functions will
be created by deftest, set-test, or with-test. Use this to omit
tests when compiling or loading production code.
在Clojure版本1.1中添加
来源
*stack-trace-depth*动态变量
The maximum depth of stack traces to print when an Exception
is thrown during a test. Defaults to nil, which means print the
complete stack trace.
在Clojure版本1.1中添加
来源
区域宏
Usage: (are argv expr & args)
Checks multiple assertions with a template expression.
See clojure.template/do-template for an explanation of
templates.
Example: (are [x y] (= x y)
2 (+ 1 1)
4 (* 2 2))
Expands to:
(do (is (= 2 (+ 1 1)))
(is (= 4 (* 2 2))))
Note: This breaks some reporting features, such as line numbers.
在Clojure版本1.1中添加
来源
断言-任意函数
Usage: (assert-any msg form)
Returns generic assertion code for any test, including macros, Java
method calls, or isolated symbols.
在Clojure版本1.1中添加
来源
断言-谓词函数
Usage: (assert-predicate msg form)
Returns generic assertion code for any functional predicate. The
'expected' argument to 'report' will contains the original form, the
'actual' argument will contain the form with all its sub-forms
evaluated. If the predicate returns false, the 'actual' form will
be wrapped in (not...).
在Clojure版本1.1中添加
来源
组合固定函数
Usage: (compose-fixtures f1 f2)
Composes two fixture functions, creating a new fixture function
that combines their behavior.
在Clojure版本1.1中添加
来源
deftest宏
Usage: (deftest name & body)
Defines a test function with no arguments. Test functions may call
other tests, so tests may be composed. If you compose tests, you
should also define a function named test-ns-hook; run-tests will
call test-ns-hook instead of testing all vars.
Note: Actually, the test body goes in the :test metadata on the var,
and the real function (the value of the var) calls test-var on
itself.
When *load-tests* is false, deftest is ignored.
在Clojure版本1.1中添加
来源
deftest-宏
Usage: (deftest- name & body)
Like deftest but creates a private var.
在Clojure版本1.1中添加
来源
do-report函数
Usage: (do-report m)
Add file and line information to a test result and call report.
If you are writing a custom assert-expr method, call this function
to pass test results to report.
在Clojure版本1.2中添加
来源
文件位置函数
Usage: (file-position n)
Returns a vector [filename line-number] for the nth call up the
stack.
Deprecated in 1.2: The information needed for test reporting is
now on :file and :line keys in the result map.
在Clojure版本1.1中添加
自Clojure版本1.2以来就不再推荐了
来源
function?函数
Usage: (function? x)
Returns true if argument is a function or a symbol that resolves to
a function (not a macro).
在Clojure版本1.1中添加
来源
get-possibly-unbound-var函数
Usage: (get-possibly-unbound-var v)
Like var-get but returns nil if the var is unbound.
在Clojure版本1.1中添加
来源
inc-report-counter功能
Usage: (inc-report-counter name)
Increments the named counter in *report-counters*, a ref to a map.
Does nothing if *report-counters* is nil.
在Clojure版本1.1中添加
来源
is宏
Usage: (is form)
(is form msg)
Generic assertion macro. 'form' is any predicate test.
'msg' is an optional message to attach to the assertion.
Example: (is (= 4 (+ 2 2)) "Two plus two should be 4")
Special forms:
(is (thrown? c body)) checks that an instance of c is thrown from
body, fails if not; then returns the thing thrown.
(is (thrown-with-msg? c re body)) checks that an instance of c is
thrown AND that the message on the exception matches (with
re-find) the regular expression re.
在Clojure版本1.1中添加
来源
连接-固定函数
Usage: (join-fixtures fixtures)
Composes a collection of fixtures, in order. Always returns a valid
fixture function, even if the collection is empty.
在Clojure版本1.1中添加
来源
报告动态多重方法
No usage documentation available
Generic reporting function, may be overridden to plug in
different report formats (e.g., TAP, JUnit). Assertions such as
'is' call 'report' to indicate results. The argument given to
'report' will be a map with a :type key. See the documentation at
the top of test_is.clj for more information on the types of
arguments for 'report'.
在Clojure版本1.1中添加
来源
运行所有测试函数
Usage: (run-all-tests)
(run-all-tests re)
Runs all tests in all namespaces; prints results.
Optional argument is a regular expression; only namespaces with
names matching the regular expression (with re-matches) will be
tested.
在Clojure版本1.1中添加
来源
运行测试函数
Usage: (run-tests)
(run-tests & namespaces)
Runs all tests in the given namespaces; prints results.
Defaults to current namespace if none given. Returns a map
summarizing test results.
在Clojure版本1.1中添加
来源
SET-test宏
Usage: (set-test name & body)
Experimental.
Sets :test metadata of the named var to a fn with the given body.
The var must already exist. Does not modify the value of the var.
When *load-tests* is false, set-test is ignored.
在Clojure版本1.1中添加
来源
successful?函数
Usage: (successful? summary)
Returns true if the given test summary indicates all tests
were successful, false otherwise.
在Clojure版本1.1中添加
来源
测试全变函数
Usage: (test-all-vars ns)
Calls test-vars on every var interned in the namespace, with fixtures.
在Clojure版本1.1中添加
来源
测试函数
Usage: (test-ns ns)
If the namespace defines a function named test-ns-hook, calls that.
Otherwise, calls test-all-vars on the namespace. 'ns' is a
namespace object or a symbol.
Internally binds *report-counters* to a ref initialized to
*initial-report-counters*. Returns the final, dereferenced state of
*report-counters*.
在Clojure版本1.1中添加
来源
测试变量动态函数
Usage: (test-var v)
If v has a function in its :test metadata, calls that function,
with *testing-vars* bound to (conj *testing-vars* v).
在Clojure版本1.1中添加
来源
测试变量函数
Usage: (test-vars vars)
Groups vars by their namespace and runs test-vars on them with
appropriate fixtures applied.
在Clojure版本1.6中添加
来源
testing宏
Usage: (testing string & body)
Adds a new string to the list of testing contexts. May be nested,
but must occur inside a test function (deftest).
在Clojure版本1.1中添加
来源
testing-contexts-str函数
Usage: (testing-contexts-str)
Returns a string representation of the current test context. Joins
strings in *testing-contexts* with spaces.
在Clojure版本1.1中添加
来源
testing-vars-str函数
Usage: (testing-vars-str m)
Returns a string representation of the current test. Renders names
in *testing-vars* as a list, then the source file and line of
current assertion.
在Clojure版本1.1中添加
来源
try-expr宏
Usage: (try-expr msg form)
Used by the 'is' macro to catch unexpected exceptions.
You don't call this.
在Clojure版本1.1中添加
来源
use-fixtures多方法
No usage documentation available
Wrap test runs in a fixture function to perform setup and
teardown. Using a fixture-type of :each wraps every test
individually, while :once wraps the whole run in a single function.
在Clojure版本1.1中添加
来源
with-test宏
Usage: (with-test definition & body)
Takes any definition form (that returns a Var) as the first argument.
Remaining body goes in the :test metadata function for that Var.
When *load-tests* is false, only evaluates the definition, ignoring
the tests.
在Clojure版本1.1中添加
来源
with-test-out宏
Usage: (with-test-out & body)
Runs body with *out* bound to the value of *test-out*.
在Clojure版本1.1中添加
来源
clojure.test.junit
clojure.test extension for JUnit-compatible XML output.
JUnit (http://junit.org/) is the most popular unit-testing library
for Java. As such, tool support for JUnit output formats is
common. By producing compatible output from tests, this tool
support can be exploited.
To use, wrap any calls to clojure.test/run-tests in the
with-junit-output macro, like this:
(use 'clojure.test)
(use 'clojure.test.junit)
(with-junit-output
(run-tests 'my.cool.library))
To write the output to a file, rebind clojure.test/*test-out* to
your own PrintWriter (perhaps opened using
clojure.java.io/writer).
公共变量和函数
with-junit-output宏
Usage: (with-junit-output & body)
Execute body with modified test-is reporting functions that write
JUnit-compatible XML output.
在Clojure版本1.1中添加
来源
cljure.test.tp
clojure.test extensions for the Test Anything Protocol (TAP)
TAP is a simple text-based syntax for reporting test results. TAP
was originally developed for Perl, and now has implementations in
several languages. For more information on TAP, see
http://testanything.org/ and
http://search.cpan.org/~petdance/TAP-1.0.0/TAP.pm
To use this library, wrap any calls to
clojure.test/run-tests in the with-tap-output macro,
like this:
(use 'clojure.test)
(use 'clojure.test.tap)
(with-tap-output
(run-tests 'my.cool.library))
公共变量和函数
print-tap-diagnostic功能
Usage: (print-tap-diagnostic data)
Prints a TAP diagnostic line. data is a (possibly multi-line)
string.
在Clojure版本1.1中添加
来源
print-tap-fail函数
Usage: (print-tap-fail msg)
Prints a TAP 'not ok' line. msg is a string, with no line breaks
在Clojure版本1.1中添加
来源
print-tap-pass函数
Usage: (print-tap-pass msg)
Prints a TAP 'ok' line. msg is a string, with no line breaks
在Clojure版本1.1中添加
来源
print-tap-plan函数
Usage: (print-tap-plan n)
Prints a TAP plan line like '1..n'. n is the number of tests
在Clojure版本1.1中添加
来源
with-tap-output宏
Usage: (with-tap-output & body)
Execute body with modified test reporting functions that produce
TAP output
在Clojure版本1.1中添加
来源
Clojure 1.8相关
Clojure 是一种运行在 Java 平台上的 Lisp 方言,Lisp 是一种以表达性和功能强大著称的编程语言,但人们通常认为它不太适合应用于一般情况,而 Clojure 的出现彻底改变了这一现状。如今,在任何具备 Java 虚拟机的地方,您都可以利用 Lisp 的强大功能。
版本 | 1.8 |
发布版本 | 1.8 |