testing - 如何为 Plug 错误处理编写测试
问题描述
我正在尝试使用-- with等Plug.Test
来测试错误处理。Plug.ErrorHandler
assert conn.status == 406
我有defp handle_errors
(包含一条send_resp
语句),它似乎被调用了,但是,我的测试仍然失败,但仍然有同样的异常(好像handle_errors
没有效果)。
对示例高级插件(不是 Phoenix)应用程序的引用也将不胜感激。
解决方案
尝试这样的事情(未经测试):
defmodule NotAcceptableError do
defexception plug_status: 406, message: "not_acceptable"
end
defmodule Router do
use Plug.Router
use Plug.ErrorHandler
plug :match
plug :dispatch
get "/hello" do
raise NotAcceptableError
send_resp(conn, 200, "world")
end
def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do
send_resp(conn, conn.status, reason.message)
end
end
test "error" do
conn = conn(:get, "/hello")
assert_raise Plug.Conn.WrapperError, "** (NotAcceptableError not_acceptable)", fn ->
Router.call(conn, [])
end
assert_received {:plug_conn, :sent}
assert {406, _headers, "not_acceptable"} = sent_resp(conn)
end
推荐阅读
- c# - 使用正则表达式查找所有带有撇号的单词
- python - 在 Python 中向 Raspi 上的 SimpleBGC 发送串行命令
- fullcalendar - 如果超过 2 个事件,更改单元格颜色
- constraints - gurobi 中的逻辑约束
- javascript - Javascript Switch Case语句问题
- vba - ExcelVBA-替换指定文件夹中所有文件名中的字符串
- regex - 如何在多个可选捕获分组正则表达式中不包含前导空格
- python - Python Maria 数据库语法
- c# - 从 Mongo C# 驱动程序执行硬编码命令
- php - 在我的 2018 18 核 iMac 上,Python 或 PHP 中的线程速度要慢 100 倍