Files
tbd/test/tbd/sqlite_test.clj
ajet 187252177c
CI / Test + coverage (push) Successful in 46s
merge db sources
2026-09-21 14:11:00 -09:00

45 lines
2.3 KiB
Clojure

(ns tbd.sqlite-test
(:require [clojure.java.io :as io]
[clojure.test :refer [deftest is testing]]
[next.jdbc :as jdbc]
[tbd.oauth.db :as oauth-db]
[tbd.sqlite :as sqlite]
[tbd.todo.db :as todo-db])
(:import (java.nio.file Files)
(java.nio.file.attribute FileAttribute)))
(defn temp-db-path
"A path for a database file inside a fresh temp directory (which `open` has to create a
subdirectory of, as with the default data/tbd.db)."
[]
(str (Files/createTempDirectory "tbd" (make-array FileAttribute 0)) "/data/tbd.db"))
(deftest env-config-test
(is (= {:db-path "data/tbd.db"} (sqlite/env-config {})))
(is (= {:db-path "data/tbd.db"} (sqlite/env-config {"DB_PATH" " "})))
(is (= {:db-path "/var/tbd.db"} (sqlite/env-config {"DB_PATH" " /var/tbd.db "}))))
(deftest open-test
(testing "creates the file and its directory"
(let [path (temp-db-path)]
(sqlite/open path todo-db/migrate!)
(is (.exists (io/file path)))))
(testing "no path is an error, not a database in the working directory"
(is (thrown? clojure.lang.ExceptionInfo (sqlite/open nil)))
(is (thrown? clojure.lang.ExceptionInfo (sqlite/open " "))))
(testing "every migration runs on the datasource, and again (harmlessly) on reopening"
(let [path (temp-db-path)
tables #(set (map :name (jdbc/execute! % ["SELECT name FROM sqlite_master WHERE type = 'table'"]
{:builder-fn next.jdbc.result-set/as-unqualified-maps})))]
(is (every? (tables (sqlite/open path todo-db/migrate! oauth-db/migrate!))
["todos" "clients" "codes" "grants"]))
(is (every? (tables (sqlite/open path todo-db/migrate! oauth-db/migrate!))
["todos" "clients" "codes" "grants"]))))
(testing "the groups keep their data apart in the one file"
(let [path (temp-db-path)
ds (sqlite/open path todo-db/migrate! oauth-db/migrate!)]
(todo-db/insert! ds {:owner-id 7 :title "buy milk" :done false :created-at 1 :updated-at 1})
(oauth-db/insert-client! ds {:id "c1" :name "Test client" :redirect-uris ["http://localhost/cb"] :created-at 1})
(is (= ["buy milk"] (map :title (todo-db/list-todos ds 7))))
(is (= "c1" (:id (oauth-db/find-client ds "c1")))))))