【问题标题】:How to write a test for Plug error handling如何为 Plug 错误处理编写测试
【发布时间】:2020-04-29 23:21:07
【问题描述】:

我正在尝试使用Plug.Test 来测试使用Plug.ErrorHandler 实现的错误处理——使用assert conn.status == 406 等。

我有 defp handle_errors(包含单个 send_resp 语句),它似乎被调用了,但是,我的测试仍然失败并出现相同的异常(好像 handle_errors 没有效果)。

还可以参考高级 Plug(不是 Phoenix)应用示例。

【问题讨论】:

    标签: testing error-handling elixir plug


    【解决方案1】:

    尝试这样的事情(未测试):

    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
    

    【讨论】:

    • 这正是我在发布此问题之前尝试过的,但这不是解决方案。
    • 尝试覆盖handle_errors/2,并使用给定的reason。这对我来说通过了测试(见上文编辑)。
    • 感谢您的回复,但匹配格式化字符串对我来说不是解决方案。我期望能够匹配实际的错误类型或其他东西。
    【解决方案2】:

    使用assert_error_sent/2 断言您引发了错误,并且该错误已被包装并以特定状态发送。匹配其 {status, headers, body} 返回值,以断言 HTTP 响应的其余部分符合您的期望。

    response = assert_error_sent 404, fn ->
      get(build_conn(), "/users/not-found")
    end
    assert {404, [_h | _t], "Page not found"} = response
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多