【发布时间】:2015-05-03 07:10:46
【问题描述】:
我正在尝试使用 Midje 单独测试我的路由。对于一些命中数据库的路由,我可以使用(provided ...) 将路由与真正的数据库调用隔离开来。我已经介绍了 Friend 进行身份验证,但我无法伪造对凭据函数的调用。
我的凭证函数看起来像这样(它是这样实现的,因为我不希望它被调用):
(defn cred-fn
[creds]
(println (str "hey look I got called with " creds))
(throw (Exception.)))
路由的中间件如下所示:
(def app
(-> app-routes
(wrap-json-body {:keywords? true :bigdecimals? true})
wrap-json-response
(wrap-defaults defaults)
(friend/authenticate
{:unauthorized-handler json-auth/login-failed
:workflows [(json-auth/json-login
:login-uri "/login"
:login-failure-handler json-auth/login-failed
:credential-fn auth/cred-fn)]})
(ring-session/wrap-session)))
我也尝试过不使用 auth-json-workflow,路由的实现看起来几乎相同,如果有帮助,我可以添加它,但我得到相同的结果。
然后我的测试看起来像这样(使用 ring-mock):
(defn post [url body]
(-> (mock/request :post url body)
(mock/content-type "application/json")
app))
(fact "login with incorrect username and password returns unauthenticated"
(:status (post "/login" invalid-auth-account-json)) => 401
(provided
(auth/cred-fn anything) => nil))
(fact "login with correct username and password returns success"
(:status (post "/login" auth-account-json)) => 200
(provided
(auth/cred-fn anything) => {:identity "root"}))
然后我得到以下运行测试的输出:
hey look I got called with {:password "admin_password", :username "not-a-user"}
FAIL at (handler.clj:66)
These calls were not made the right number of times:
(auth/cred-fn anything) [expected at least once, actually never called]
FAIL "routes - authenticated routes - login with incorrect username and password returns unauthenticated" at (handler.clj:64)
Expected: 401
Actual: java.lang.Exception
clojure_api_seed.authentication$cred_fn.invoke(authentication.clj:23)
hey look I got called with {:password "admin_password", :username "root"}
FAIL at (handler.clj:70)
These calls were not made the right number of times:
(auth/cred-fn anything) [expected at least once, actually never called]
FAIL "routes - authenticated routes - login with correct username and password returns success" at (handler.clj:68)
Expected: 200
Actual: java.lang.Exception
clojure_api_seed.authentication$cred_fn.invoke(authentication.clj:23)
所以从我可以看到提供的声明没有生效,我不知道为什么。有什么想法吗?
【问题讨论】:
-
也许您在 midje 应用替换时遇到了问题,参见。 stackoverflow.com/questions/21042577/… 我不知道您的 cred-fn 何时/何地被调用。
-
提供的工作正常,我找到了一个解决方法,我在下面发布了
-
Midje 不模拟宏,这可能是问题所在。