In my tests I need repeat this a block of tests for each function. In this case I'm testing bad-request function, the things that need change between each test is the bad-request call, code, and error.
(deftest t-bad-request
...
(testing "with data"
(equal (merge error code message DATA) (bad-request MESSAGE DATA)))
(testing "without message and with data"
(equal (merge error code DATA) (bad-request nil, DATA))))
What is the "correct way" to resolve it in clojure? macros?
Yes, I think macros is the way to do this in clojure. Taking your code and doing some liberal assumptions about bad-request, error and the other stuff, I made up the following example:
(require '[clojure.test :refer [deftest testing is]])
; dummy implementations, here will be your real bad-request & error
(defn bad-request [& more] more)
(def error {:status :error})
(defmacro deftest-request [name code message MESSAGE DATA & body]
`(deftest ~name
(testing "with data"
(is (= (merge error ~code ~message ~DATA) (bad-request ~MESSAGE ~DATA))))
(testing "with data"
(is (= (merge error ~code ~message ~DATA) (bad-request ~MESSAGE ~DATA))))
~#body))
; Some messages will only be tested about bad requests
(deftest-request some-request-test
{:code 401} {:message "hello"} "HELO" {:data "WORLD"})
; Other messages can have more tests at the end of a deftest-request
(deftest-request some-complex-request-test
{:code 829} {:message "a-complex-message"} "IM COMPLEX" {:data "VERY COMPLEX"}
(testing "request returns something interesting"
(is (= "I'm cool" (run-request {:message "a-complex-message"})))))
deftest-request will run the two common bad-request tests, and any additional form passed to it.
Of course you should consider the tradeoffs of using this approach versus plain old tests... In most cases it's more clear to have plain old tests... But if you have a lot of similar tests and/or a complex test preparation, a macro can be of help.
A good example of applying this technique is in the sqlingvo test suite
Related
Using clojure.test, when running lein test, the default settings only print out the number of assertions, like "Ran 12 tests containing 19 assertions," the details for failed tests, and the namespaces tested. I would like an output of the successful tests as well, so I can see what tests were actually run. Frameworks like Mocha in JS have this behavior by default.
For instance, if the following test passed:
(deftest aTest
(testing "Simple test"
(is (= 1 1))))
I would like an output like (formatting is arbitrary):
Testing <namespace>
Passed: aTest -> Simple test
Ideally, the passed test would also be color coded.
I looked at a few libraries, including lein-test-refresh and humane-test-output, but didn't see what I needed. The other option looks like to rewrite the report function in clojure.test, but I'd like to avoid that if possible.
I think you'll have to write it yourself. If you would like an example of how to leverage the existing deftest into a custom macro, here is an example from the Tupelo library that automatically picks a "name" for the deftest group based on the line number:
(defmacro dotest [& body]
(let [test-name-sym (symbol (str "dotest-line-" (:line (meta &form))))]
`(clojure.test/deftest ~test-name-sym ~#body)))
(dotest
(is (= 5 (+ 2 3)))) ; works!
You could just add in a println and voila!
I remember, the Eftest library provides nice colored output when running tests, you may take a look.
Also, the standard clojure.test framework supports adding your own reports. Check the Test report library for the reference.
Probably, when running the tests from your editor or IDE, it could provide the colored output. Here is my Cider-powered Emacs screenshot with the failure report:
I have searched multiple times for an answer to this question, so here is a complete solution building on #ivan-grishaev's hint using Test Report:
Test Report hooks into clojure.test to provide custom reporters that are then being run with every event occuring through a test run. Those events are passed as maps called "messages". The minimal example just appliesclojure.pprint/pprint to the messages, but this only gets you so far. Here is a bit more code to give you a feel how to write custom reporters. The indenting-reporter indents test namespaces, deftests and testing vars, and lists them all independent of test outcome.
Create a file like this in your project:
(ns my.own.test-reporter
(:require [clojure.pprint :refer [pprint]]
[clojure.test :as ct]
[clojure.core.match :refer [match]]))
(defn simple-reporter [msg]
(pprint msg))
(defn indenting-reporter [msg]
(match (:type msg)
:begin-test-ns (println (str "Testing " (:ns msg) "\n"))
:begin-test-var (println (str " " (-> msg :var meta :name)))
:pass (do (println (str " " (-> msg :context first) " :pass"))
(ct/inc-report-counter :pass))
:fail (do (println (str " " (-> msg :context first) " :fail"))
(ct/inc-report-counter :fail))
:error (do (println (str " " (-> msg :context first) " :error"))
(ct/inc-report-counter :error))
:end-test-ns (println)
:end-test-var ()
:summary (pprint msg)
:else (pprint msg)))
and then use it in the :test profile of your project.clj:
:injections [(require '[my.own.test-reporter :as tr])]
:test-report {:reporters [tr/indenting-reporter]}
You could now go on an add color to the outputs.
I am super confused by Clojure Spec. When I run in the repl by entering:
(require '[clojure.spec.alpha :as s])
And then add:
(s/valid? even? 10)
I get //true. And when I run:
(s/valid? even? 11)
//False. Ok so that works. Then when I require spec in my core.clj as:
(ns spam-problem.core
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]))
And try a simple validation to get it to throw an error, nothing happens:
(defn -main
"I don't do a whole lot ... yet."
[& args]
(s/valid? even? 11))
I have no idea what I'm doing wrong here and am very confused about how spec is supposed to work. I am running this by using command lein run. Is there another way you're supposed to run it?
I understand what you are feeling because once I got into Spec it caused me the same thoughts. What really helped me to solve the problem in my mind is to considering Spec being not a final library but rather a framework. In my projects, usually I've got a special module with high-level wrappers above basic spec capabilities. I believe, you might do the same: define a function that takes data, spec and raises those error message you desire to have in terms of your business-logic. Here is a small example of my code:
(ns project.spec
(:require [clojure.spec.alpha :as s]))
;; it's better to define that value is a constant
(def invalid :clojure.spec.alpha/invalid)
(defn validate
"Either returns coerced data or nil in case of error."
[spec value]
(let [result (s/conform spec value)]
(if (= result invalid)
nil
result)))
(defn spec-error
"Returns an error map for data structure that does not fit spec."
[spec data]
(s/explain-data spec data))
Now, let's prepare some specs:
(defn x-integer? [x]
(if (integer? x)
x
(if (string? x)
(try
(Integer/parseInt x)
(catch Exception e
invalid))
invalid)))
(def ->int (s/conformer x-integer?))
(s/def :opt.visits/fromDate ->int)
(s/def :opt.visits/toDate ->int)
(s/def :opt.visits/country string?)
(s/def :opt.visits/toDistance ->int)
(s/def :opt.visits/params
(s/keys :opt-un [:opt.visits/fromDate
:opt.visits/toDate
:opt.visits/country
:opt.visits/toDistance]))
And here are some usage examples:
(let [spec :opt.visits/params
data {:some :map :goes :here}]
(if-let [cleaned-data (validate spec data)]
;; cleaned-data has values coerced from strings to integers,
;; quite useful for POST parameters
(positive-logic cleaned-data)
;; error values holds a map that describes an error
(let [error (spec-error spec data)]
(error-logic-goes-here error))))
What might be improved here is to have a combo-function with both validate and error functionality. Such a function could return a vector of two values: success flag and either result or error data structure as follows:
[true {:foo 42}] ;; good result
[false {:error :map}] ;; bad result
The Spec library does not dictate a single way of processing data; that's why it's really good and flexible.
valid? is a predicate that returns true or false. Your program isn’t doing anything with the return value. Try printing it to console or using s/assert if you want to throw an exception:
If (check-asserts?) is false at runtime, always returns x. Defaults to
value of 'clojure.spec.check-asserts' system property, or false if not
set. You can toggle check-asserts? with (check-asserts bool).
So you may need to set (s/check-asserts true) to have s/assert throw exceptions:
(clojure.spec.alpha/assert even? 3)
=> 3
(clojure.spec.alpha/check-asserts?)
=> false
(clojure.spec.alpha/check-asserts true)
=> true
(clojure.spec.alpha/assert even? 3)
ExceptionInfo Spec assertion failed
val: 3 fails predicate: :clojure.spec.alpha/unknown
clojure.core/ex-info (core.clj:4739)
I am implementing an app using Stuart Sierra component. As he states in the README :
Having a coherent way to set up and tear down all the state associated
with an application enables rapid development cycles without
restarting the JVM. It can also make unit tests faster and more
independent, since the cost of creating and starting a system is low
enough that every test can create a new instance of the system.
What would be the preferred strategy here ? Something similar to JUnit oneTimeSetUp / oneTimeTearDown , or really between each test (similar to setUp / tearDown) ?
And if between each test, is there a simple way to start/stop a system for all tests (before and after) without repeating the code every time ?
Edit : sample code to show what I mean
(defn test-component-lifecycle [f]
(println "Setting up test-system")
(let [s (system/new-test-system)]
(f s) ;; I cannot pass an argument here ( https://github.com/clojure/clojure/blob/master/src/clj/clojure/test.clj#L718 ), so how can I pass a system in parameters of a test ?
(println "Stopping test-system")
(component/stop s)))
(use-fixtures :once test-component-lifecycle)
Note : I am talking about unit-testing here.
I would write a macro, which takes a system-map and starts all components before running tests and stop all components after testing.
For example:
(ns de.hh.new-test
(:require [clojure.test :refer :all]
[com.stuartsierra.component :as component]))
;;; Macro to start and stop component
(defmacro with-started-components [bindings & body]
`(let [~(bindings 0) (component/start ~(bindings 1))]
(try
(let* ~(destructure (vec (drop 2 bindings)))
~#body)
(catch Exception e1#)
(finally
(component/stop ~(bindings 0))))))
;; Test Component
(defprotocol Action
(do-it [self]))
(defrecord TestComponent [state]
component/Lifecycle
(start [self]
(println "====> start")
(assoc self :state (atom state)))
(stop [self]
(println "====> stop"))
Action
(do-it [self]
(println "====> do action")
#(:state self)))
;: TEST
(deftest ^:focused component-test
(with-started-components
[system (component/system-map :test-component (->TestComponent"startup-state"))
test-component (:test-component system)]
(is (= "startup-state" (do-it test-component)))))
Running Test you should see the out put like this
====> start
====> do action
====> stop
Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
I'm writing tests for a Clojure app using Speclj. I'm accustomed in BDD to do things like this:
context "some context"
stub my-function :return true
it "has behavior one"
should true my-function
it "has behavior two"
should_not false my-function
But in Speclj I can't seem to find an example of how to share the stub across the characteristics, so I'm currently stuck writing code like this:
(describe "this"
(context "that"
(it "accepts nil"
(with-redefs [called-fn (constantly nil)]
(should= nil (my-fn nil)))))
(it "accepts 1"
(with-redefs [called-fn (constantly nil)]
(should= 100 (my-fn 1))))))
(I realize this is a somewhat contrived example and arguably those assertions could all go under one characteristic, but let's suppose for now that I have good reason to write the code like this.)
I want, however, to just have to stub called-fn once, but moving this up out of the its raises errors because the real called-fn gets called instead of my redef.
Is there a way to reuse redefs (or use Speclj stubs) in Speclj so I'm not stuck pushing them all down inside the characteristics?
You can use the around macro to accomplish this.
Here's an example spec:
(ns sample.core-spec
(:require [speclj.core :refer :all]
[sample.core :refer :all]))
(describe "a test"
(it "returns output from fn-a"
(should= 1 (fn-b)))
(describe "using with-redef"
(around [it] (with-redefs [fn-a (fn [] 2)] (it)))
(it "returns the output from redefined function"
(should= 2 (fn-b)))))
Source:
(ns sample.core)
(defn fn-a []
1)
(defn fn-b []
(fn-a))
I am adding Swagger annotations to JaxRs annotated services.
I have the following:
(^{
GET true
Path "/{who}"
ApiOperation {:value "Get a hello" :notes "simple clojure GET"}
Produces ["text/plain; charset=UTF-8"]
ApiResponses {:value [(ApiResponse {:code 200 :message "yay!"})]}
}
If I decompile the produced class the annotations look like this:
#ApiResponses({#com.wordnik.swagger.annotations.ApiResponse(code=200L, message="yay!")})
#Produces({"text/plain; charset=UTF-8"})
#ApiOperation(value="Get a hello", notes="simple clojure GET")
#Path("/{who}")
#GET(true)
notes that in the first annotation code = 200L
During runtime, this value must be an int, and I cannot figure out how to make this happen
if I try
ApiResponses {:value [(ApiResponse {:code (int 200) :message "yay!"})]}
I get a compilation error (using the maven swagger plugin)
Exception in thread "main" java.lang.ClassCastException: clojure.lang.Var cannot be cast to java.lang.Class, compiling:(pocclj/resourceclj.clj:14)
I have tried
(def success (int 200))
...
ApiResponses {:value [(ApiResponse {:code success :message "yay!"})]}
Which produces this compilation error:
Exception in thread "main" java.lang.IllegalArgumentException: Unsupported annotation value: success of class class java.lang.Integer, compiling:(pocclj/resourceclj.clj:14)
I have tried a bunch of other stuff (deref etc) but cant find the secret sauce.
I am fairly new to clojure and desperate for some help on this.
Thanks in advance
Martin
You are setting the type of ':code' correctly. Which can be tested independently:
user> (def something ^{:ApiResponses {:code (int 200) :message "yay!"}} {:some :data :goes :here})
#'user/something
user> (meta something)
{:ApiResponses {:code 200, :message "yay!"}}
user> (-> (meta something) :ApiResponses :code type)
java.lang.Integer
And without the cast the metadata contains the wrong type:
user> (def something-wrong ^{:ApiResponses {:code 200 :message "yay!"}} {:some :data :goes :here})
#'user/something-wrong
user> (meta something)
{:ApiResponses {:code 200, :message "yay!"}}
user> (-> (meta something-wrong) :ApiResponses :code type)
java.lang.Long
From the exception it looks like perhaps the call to ApiResponse is crashing. If ApiResponse is a macro that expects a number and not an s-expression, then I could see it not handling this properly. If it is a function you would need to look into why it is crashing.
If I provide a stub implementation for ApiResponse then It works for me:
user> (definterface Fooi (Something []))
user.Fooi
user> (def ApiResponse identity)
#'user/ApiResponse
user> (deftype Foo []
Fooi
(Something
^{GET true
Path "/{who}"
ApiOperation {:value "Get a hello" :notes "simple clojure GET"}
Produces ["text/plain; charset=UTF-8"]
ApiResponses {:value [(ApiResponse {:code (int 200) :message "yay!"})]}}
[this] (identity this)))
user.Foo
I don't know about ApiResponse, or much about annotations really, but: it looks like some macro (deftype?) is producing annotations for you, and you need it to see 200 as an int. Clojure doesn't have int literals, so the only way to hand an Integer object directly to a macro is through some other macro that calls it. It's not really possible to do this in a nice way; as far as I know you have to either use eval, or be very narrow by aiming specifically at int literals. Here's a sketch of a solution:
user> (use 'clojure.walk)
user> (defmacro with-int-literals [named-ints & body]
(prewalk-replace (into {}
(for [[k v] (partition 2 named-ints)]
[k (int v)]))
`(do ~#body)))
user> (map class (second (macroexpand-1 '(with-int-literals [x 100, y 200] [x y]))))
(java.lang.Integer java.lang.Integer)
So if you wrap your entire deftype (or whatever macro is generating these annotations) with a with-int-literals form, you can produce integers for it instead of longs. I don't actually know that this will work; perhaps there's something in the annotation processor that's fundamentally unable to handle ints for some reason. But at least this way you can offer it ints and hope for the best.
Edit
Since you actually need int literals in metadata, rather than in "ordinary" code, prewalk won't actually look at the data you care about. You'll have to write a version of walk that treats metadata in a sensible way, and then use it instead of prewalk here.