Friday, July 24, 2020

Clojure Database Testing

Set up a simple project: luminus +postgres. The sample database test called test-users passes. 

Added a game table using migrate then using hugsql a simple add to the game table, create-game, and a simple list rows in the table, list-games. Copy and pasted test-user, renamed it test-game and then replace the calls with my methods and the tests failed.

After a few hours of research and troubleshooting I found that I was only passing 2 arguments to the list-games function but it requires 3 arguments to (db/list-games t-conn {})
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
(deftest game-test
  (jdbc/with-transaction [t-conn *db* {:rollback-only true}]
                         (db/create-game!
                           t-conn
                           {:first_name "test1"})
                         (db/create-game!
                           t-conn
                           {:first_name "test2"})
                         (prn (count (jdbc/execute! t-conn ["SELECT * FROM games"])))
                         (is (= '("test1" "test2") (map :games/first_name (jdbc/execute! t-conn ["SELECT * FROM games"]))))
                         (is (= '("test1" "test2") (map :first_name (db/list-games t-conn {}))))))

Along the way I learned several things:
1.  use  (jdbc/execute! t-conn ["SELECT * FROM games"]) to do anything you need to without opening a psql shell.

2. execute! -- executes the SQL statement and produces a vector of realized hash maps, that use qualified keywords for the column names, of the form :<table>/<column>

3. Everything can be deleted with: drop schema public cascade; create schema public.

4. use-fixtures is the clojure @setup/@teardown mechanisim.  https://clojuredocs.org/clojure.test/use-fixtures

No comments:

Post a Comment