From 54938d30384ac3ca8cdc6dac32dc6e9963fb368e Mon Sep 17 00:00:00 2001 From: Josh Wien Date: Wed, 29 Mar 2023 17:05:41 -0700 Subject: [PATCH] Add request! function --- lib/finch.ex | 16 ++++++++++++++++ test/finch_test.exs | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/finch.ex b/lib/finch.ex index c0a89bcc..0bfd0a9f 100644 --- a/lib/finch.ex +++ b/lib/finch.ex @@ -332,6 +332,22 @@ defmodule Finch do end end + @doc """ + Sends an HTTP request and returns a `Finch.Response` struct + or raises an exception in case of failure. + + See `request/3` for more detailed information. + """ + @spec request!(Request.t(), name(), keyword()) :: + Response.t() + def request!(%Request{} = req, name, opts \\ []) do + with {:ok, resp} <- request(req, name, opts) do + resp + else + {:error, exception} -> raise exception + end + end + # Catch-all for backwards compatibility below def request(name, method, url) do request(name, method, url, []) diff --git a/test/finch_test.exs b/test/finch_test.exs index 71bfa7c3..c6b7ad56 100644 --- a/test/finch_test.exs +++ b/test/finch_test.exs @@ -530,6 +530,30 @@ defmodule FinchTest do end end + describe "request!/3" do + test "returns response on successful request", %{bypass: bypass, finch_name: finch_name} do + start_supervised!({Finch, name: finch_name}) + query_string = "query=value" + + Bypass.expect_once(bypass, "GET", "/", fn conn -> + assert conn.query_string == query_string + Plug.Conn.send_resp(conn, 200, "OK") + end) + + assert %{status: 200} = + Finch.build(:get, endpoint(bypass, "?" <> query_string)) + |> Finch.request(finch_name) + end + + test "raises exception on bad request", %{finch_name: finch_name} do + start_supervised!({Finch, name: finch_name}) + + assert_raise(Exception, fn -> + Finch.build(:get, "http://idontexist.wat") |> Finch.request(finch_name) + end) + end + end + describe "connection options" do test "are passed through to the conn", %{bypass: bypass} do expect_any(bypass)