Thursday, February 25, 2016

Interesting use case example for `are` macro in Clojure test

I found an interesting use case for are in Clojure test.

You might have ever written a test for your data conversion logic. E.g.
  • Converting data pulled from third-party web service into your internal schema.
  • Converting data fetched from your database to more mobile friendly schema before sending out.
This is an example snippet of test for such a scenario.
(ns demo-are.core-test
(:require [clojure.test :refer :all]
[demo-are.core :refer [convert]]))
(deftest convert-test1
(let [in {:user-name "tap"
:email1 "tap@pat.tap"
:email2 "pat@tap.pat"
:address {:steet "Rama 1"}
:latitude "123"
:longitude "456"}
out {:username "tap"
:emails ["tap@pat.tap" "pat@tap.pat"]
:address {:street "Rama 1"}
:location {:latitude "123" :longitude "456"}}]
(is (= (convert in) out))))
(deftest convert-test2
(let [in {:user-name "tap"
:email1 "tap@pat.tap"
:email2 "pat@tap.pat"
:address {:steet "Rama 1"}
:latitude "123"
:longitude "456"}
out (convert in)]
(are [x y] (= (get-in in x) (get-in out y))
[:user-name] [:username]
[:email1] [:emails 0]
[:email2] [:emails 1]
[:address :steet] [:address :street]
[:latitude] [:location :latitude]
[:longitude] [:location :longitude])))
view raw are-demo.clj hosted with ❤ by GitHub

convert-test1 shows the style I had been writing until recently. convert-test2 shows how using are making the test better.

Pros:
  • No more duplication of field values between input and output.
  • No more duplication between output schema and code under test schema.
  • It can be use as a document showing clearly how each individual field is mapped.
Cons:
An error message in convert-test1 is better. It shows clearly which field is wrong while convert-test2 throw out the whole problematic result data.

Updated: I have retested, are does report problem for an individual case as well.

No comments:

Collectd PostgreSQL Plugin

I couldn't find this link when searching with google https://www.collectd.org/documentation/manpages/collectd.conf.html#plugin-postgresq...