Skip to content

Commit

Permalink
Wrap test runs in a fixture to perform database setup and teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
sernamar committed Oct 18, 2024
1 parent 53cfc3f commit fd3e44f
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions test/dinero/conversion/db_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,37 @@
(:import [clojure.lang ExceptionInfo]
[org.h2.jdbc JdbcSQLSyntaxErrorException]))

(defn- create-db-for-testing
(def db-spec {:dbtype "h2:mem" :dbname "db-test"})

(defn- setup-db
[]
(jdbc/execute-one! db-spec ["CREATE TABLE IF NOT EXISTS exchange_rate (from_currency VARCHAR(3), to_currency VARCHAR(3), rate DOUBLE, date DATE)"])
(jdbc/execute-one! db-spec ["INSERT INTO exchange_rate (from_currency, to_currency, rate, date) VALUES ('EUR', 'GBP', 0.80, '2024-09-08')"]))

(defn- teardown-db
[]
(let [db (jdbc/get-datasource {:dbtype "h2:mem" :dbname "db-test"})]
(jdbc/execute-one! db ["CREATE TABLE exchange_rate (from_currency VARCHAR(3), to_currency VARCHAR(3), rate DOUBLE, date DATE)"])
(jdbc/execute-one! db ["INSERT INTO exchange_rate (from_currency, to_currency, rate, date) VALUES ('EUR', 'GBP', 0.80, '2024-09-08')"])
db))
(jdbc/execute-one! db-spec ["DROP TABLE IF EXISTS exchange_rate"]))

(defn- db-fixture
[f]
(setup-db)
(f)
(teardown-db))

(defonce db (create-db-for-testing))
(t/use-fixtures :once db-fixture)

(t/deftest create-db-rates-provider
(let [db-rate-provider (sut/create-db-rate-provider db "exchange_rate" "from_currency" "to_currency" "rate")]
(let [db-rate-provider (sut/create-db-rate-provider db-spec "exchange_rate" "from_currency" "to_currency" "rate")]
(t/is (= 0.80 (db-rate-provider :eur :gbp)))
(t/is (= 1.25 (db-rate-provider :gbp :eur)))
(t/is (thrown? ExceptionInfo (db-rate-provider :eur :jpy))))
(t/testing "Wrong db"
(let [wrong-db (jdbc/get-datasource {:dbtype "h2:mem" :dbname "wrong_db"})
(let [wrong-db {:dbtype "h2:mem" :dbname "wrong-db"}
db-rate-provider (sut/create-db-rate-provider wrong-db "exchange_rate" "from_currency" "to_currency" "rate")]
(t/is (thrown? JdbcSQLSyntaxErrorException (db-rate-provider :eur :gbp)))))
(t/testing "Wrong table name"
(let [db-rate-provider (sut/create-db-rate-provider db "wrong_table_name" "from_currency" "to_currency" "rate")]
(let [db-rate-provider (sut/create-db-rate-provider db-spec "wrong_table_name" "from_currency" "to_currency" "rate")]
(t/is (thrown? JdbcSQLSyntaxErrorException (db-rate-provider :eur :gbp)))))
(t/testing "Wrong column name"
(let [db-rate-provider (sut/create-db-rate-provider db "exchange_rate" "wrong_column_name" "to_currency" "rate")]
(let [db-rate-provider (sut/create-db-rate-provider db-spec "exchange_rate" "wrong_column_name" "to_currency" "rate")]
(t/is (thrown? JdbcSQLSyntaxErrorException (db-rate-provider :eur :gbp))))))

0 comments on commit fd3e44f

Please sign in to comment.