在我的Clojure项目中,我使用的是命名空间来存储配置:
(ns clojure-bgproc.settings
(:require [environ.core :refer [env]]
[clojure.edn :as edn]))
(def ^:dynamic *app-env* (env :app-env "production"))
(def ^:private config-path
(if (= *app-env* "test") "settings_test.edn" "settings.edn"))
(def config (-> config-path slurp edn/read-string))
(def db-config (:db config))
对于测试环境,我使用夹具重新定义*app-env*
:
(ns helpers.config
(:require [clojure-bgproc.settings :refer :all]))
(defn with-test-config [f]
(with-redefs [*app-env* "test"]
(f)))
虽然重新定义了*app-env*
,但其他所有配置变量却没有:
FAIL in (app-config-test) (core_test.clj:14)
expected: (s/ends-with? (:dbname db-config) "test")
actual: (not (s/ends-with? "rmq-reports-development" "test"))
我是否可以轻松地重新定义所有其他配置变量,而无需手动重新计算它们?
答案 0 :(得分:1)
我认为您可以使用配置文件和lein-environ
来完成您想做的所有事情。
容易配置environ
。请注意,它还需要lein-environ
插件。
您的project.clj
:
:dependencies [
[environ "1.1.0"] ...] ; ********** REQUIRED *********
:plugins [[com.jakemccrary/lein-test-refresh "0.22.0"]
[lein-ancient "0.6.15"]
[lein-codox "0.10.3"]
[lein-environ "1.1.0"]] ; ********** REQUIRED *********
:db "jdbc:postgresql://localhost/default" ; *** default vals ***
:settings "settings-default.edn"
然后创建一个profiles.clj
:
{:dev {:env {:db "jdbc:postgresql://localhost/dev"
:settings "settings-dev.edn"}}
:test {:env {:db "jdbc:postgresql://localhost/test"
:settings "settings-test.edn"}}}
然后在您的proj.core
ns中:
(ns demo.core
(:use tupelo.core)
(:require
[environ.core :as env]
))
(defn -main []
(println "main -enter")
(spyx (env/env :db))
(spyx (env/env :settings)) )
以及您的测试文件:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:require
[clojure.string :as str]
[environ.core :as env]))
(dotest
(spyx (env/env :db))
(spyx (env/env :settings))
)
运行代码:
~/expr/demo > lein run
main -enter
(env/env :db) => "jdbc:postgresql://localhost/dev"
(env/env :settings) => "settings-dev.edn"
运行测试:
〜/ expr / demo>莱因测试
lein test _bootstrap
--------------------------------------
Clojure 1.10.0-alpha8 Java 11
--------------------------------------
lein test tst.demo.core
(env/env :db) => "jdbc:postgresql://localhost/test"
(env/env :settings) => "settings-test.edn"
Ran 2 tests containing 0 assertions.
0 failures, 0 errors.