next-jdbc/test/next/jdbc/middleware_test.clj

76 lines
3 KiB
Clojure
Raw Normal View History

2020-01-01 21:13:41 +00:00
;; copyright (c) 2019-2020 Sean Corfield, all rights reserved
(ns next.jdbc.middleware-test
2020-05-31 07:20:00 +00:00
(:require [clojure.test :refer [deftest is use-fixtures]]
[next.jdbc :as jdbc]
[next.jdbc.middleware :as mw]
[next.jdbc.test-fixtures :refer [with-test-db db ds
2020-05-31 07:20:00 +00:00
default-options]]
[next.jdbc.result-set :as rs]
2020-05-31 07:20:00 +00:00
[next.jdbc.specs :as specs]))
(set! *warn-on-reflection* true)
(use-fixtures :once with-test-db)
(specs/instrument)
(deftest logging-test
(let [logging (atom [])
logger (fn [data _] (swap! logging conj data) data)
sql-p ["select * from fruit where id in (?,?) order by id desc" 1 4]]
(jdbc/execute! (mw/wrapper (ds))
sql-p
2019-11-16 06:37:42 +00:00
(assoc (default-options)
:builder-fn rs/as-lower-maps
:sql-params-fn logger
:row!-fn logger
:rs!-fn logger))
;; should log four things
(is (= 4 (-> @logging count)))
;; :next.jdbc/sql-params value
(is (= sql-p (-> @logging (nth 0))))
;; first row (with PK 4)
(is (= 4 (-> @logging (nth 1) :fruit/id)))
;; second row (with PK 1)
(is (= 1 (-> @logging (nth 2) :fruit/id)))
;; full result set with two rows
(is (= 2 (-> @logging (nth 3) count)))
(is (= [4 1] (-> @logging (nth 3) (->> (map :fruit/id)))))
;; now repeat without the row logging
(reset! logging [])
(jdbc/execute! (mw/wrapper (ds)
{:builder-fn rs/as-lower-maps
:sql-params-fn logger
:rs!-fn logger})
2019-11-16 06:37:42 +00:00
sql-p
(default-options))
;; should log two things
(is (= 2 (-> @logging count)))
;; :next.jdbc/sql-params value
(is (= sql-p (-> @logging (nth 0))))
;; full result set with two rows
(is (= 2 (-> @logging (nth 1) count)))
(is (= [4 1] (-> @logging (nth 1) (->> (map :fruit/id)))))))
(deftest timing-test
(let [timing (atom {:calls 0 :total 0.0})
2020-05-31 07:20:00 +00:00
start-fn (fn [_ opts]
(swap! (:timing opts) update :calls inc)
(assoc opts :start (System/nanoTime)))
exec-fn (fn [_ opts]
(let [end (System/nanoTime)]
(swap! (:timing opts) update :total + (- end (:start opts)))
opts))
sql-p ["select * from fruit where id in (?,?) order by id desc" 1 4]]
(jdbc/execute! (mw/wrapper (ds) {:timing timing
:sql-params-fn start-fn
:execute-fn exec-fn})
sql-p)
(jdbc/execute! (mw/wrapper (ds) {:timing timing
:sql-params-fn start-fn
:execute-fn exec-fn})
sql-p)
2020-05-31 07:20:00 +00:00
(println (:dbtype (db)) (:calls @timing) "calls took" (long (:total @timing)) "nanoseconds")))