bypass v2.1.0 Bypass View Source

Build Status Module Version Hex Docs Total Download License Last Updated

Bypass provides a quick way to create a custom plug that can be put in place instead of an actual HTTP server to return prebaked responses to client requests. This is most useful in tests, when you want to create a mock HTTP server and test how your HTTP client handles different types of responses from the server.

Bypass supports Elixir 1.7 and OTP 20 and up. It works with Cowboy 2.

Usage

To use Bypass in a test case, open a connection and use its port to connect your client to it.

If you want to test what happens when the HTTP server goes down, use Bypass.down/1 to close the TCP socket and Bypass.up/1 to start listening on the same port again. Both functions block until the socket updates its state.

Expect Functions

You can take any of the following approaches:

  • expect/2 or expect_once/2 to install a generic function that all calls to bypass will use
  • expect/4 and/or expect_once/4 to install specific routes (method and path)
  • stub/4 to install specific routes without expectations
  • a combination of the above, where the routes will be used first, and then the generic version will be used as default

Example

In the following example TwitterClient.start_link() takes the endpoint URL as its argument allowing us to make sure it will connect to the running instance of Bypass.

defmodule TwitterClientTest do
  use ExUnit.Case, async: true

  setup do
    bypass = Bypass.open()
    {:ok, bypass: bypass}
  end

  test "client can handle an error response", %{bypass: bypass} do
    Bypass.expect_once(bypass, "POST", "/1.1/statuses/update.json", fn conn ->
      Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
    end)

    {:ok, client} = TwitterClient.start_link(url: endpoint_url(bypass.port))
    assert {:error, :rate_limited} == TwitterClient.post_tweet(client, "Elixir is awesome!")
  end

  test "client can recover from server downtime", %{bypass: bypass} do
    Bypass.expect(bypass, fn conn ->
      # We don't care about `request_path` or `method` for this test.
      Plug.Conn.resp(conn, 200, "")
    end)

    {:ok, client} = TwitterClient.start_link(url: endpoint_url(bypass.port))

    assert :ok == TwitterClient.post_tweet(client, "Elixir is awesome!")

    # Blocks until the TCP socket is closed.
    Bypass.down(bypass)

    assert {:error, :noconnect} == TwitterClient.post_tweet(client, "Elixir is awesome!")

    Bypass.up(bypass)

    # When testing a real client that is using e.g. https://github.com/fishcakez/connection
    # with https://github.com/ferd/backoff to handle reconnecting, we'd have to loop for
    # a while until the client has reconnected.

    assert :ok == TwitterClient.post_tweet(client, "Elixir is awesome!")
  end

  defp endpoint_url(port), do: "http://localhost:#{port}/"
end

That's all you need to do. Bypass automatically sets up an on_exit hook to close its socket when the test finishes running.

Multiple concurrent Bypass instances are supported, all will have a different unique port. Concurrent requests are also supported on the same instance.

Note: Bypass.open/0 must not be called in a setup_all blocks due to the way Bypass verifies the expectations at the end of each test.

How to use with ESpec

While Bypass primarily targets ExUnit, the official Elixir builtin test framework, it can also be used with ESpec. The test configuration is basically the same, there are only two differences:

  1. In your Mix config file, you must declare which test framework Bypass is being used with (defaults to :ex_unit). This simply disables the automatic integration with some hooks provided by ExUnit.

    config :bypass, test_framework: :espec
  2. In your specs, you must explicitly verify the declared expectations. You can do it in the finally block.

    defmodule TwitterClientSpec do
      use ESpec, async: true
      before do
        bypass = Bypass.open()
        {:shared, bypass: bypass}
      end
      finally do
        Bypass.verify_expectations!(shared.bypass)
      end
      specify "the client can handle an error response" do
        Bypass.expect_once(shared.bypass, "POST", "/1.1/statuses/update.json", fn conn ->
          Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
        end)
        {:ok, client} = TwitterClient.start_link(url: endpoint_url(shared.bypass.port))
        assert {:error, :rate_limited} == TwitterClient.post_tweet(client, "Elixir is awesome!")
      end
      defp endpoint_url(port), do: "http://localhost:#{port}/"
    end

Configuration options

Set :enable_debug_log to true in the application environment to make Bypass log what it's doing:

config :bypass, enable_debug_log: true

Link to this section Summary

Types

t()

Represents a Bypass server process.

Functions

Closes the TCP socket. Blocks until the operation is complete.

Expects the passed function to be called at least once regardless of the route.

Expects the passed function to be called at least once for the specified route (method and path).

Expects the passed function to be called exactly once regardless of the route.

Expects the passed function to be called exactly once for the specified route (method and path).

Starts an Elixir process running a minimal Plug app. The process is a HTTP handler and listens to requests on a TCP port on localhost.

Makes an expectation to pass.

Allows the function to be invoked zero or many times for the specified route (method and path).

Re-opens the TCP socket on the same port. Blocks until the operation is complete.

Can be called to immediately verify if the declared request expectations have been met.

Link to this section Types

Specs

t() :: %Bypass{pid: pid(), port: non_neg_integer()}

Represents a Bypass server process.

Link to this section Functions

Specs

down(t()) :: :ok | {:error, :already_down}

Closes the TCP socket. Blocks until the operation is complete.

Bypass.down(bypass)

Specs

expect(t(), (Plug.Conn.t() -> Plug.Conn.t())) :: :ok

Expects the passed function to be called at least once regardless of the route.

Bypass.expect(bypass, fn conn ->
  assert "/1.1/statuses/update.json" == conn.request_path
  assert "POST" == conn.method
  Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
end)
Link to this function

expect(bypass, method, path, fun)

View Source

Specs

expect(t(), String.t(), String.t(), (Plug.Conn.t() -> Plug.Conn.t())) :: :ok

Expects the passed function to be called at least once for the specified route (method and path).

  • method is one of ["GET", "POST", "HEAD", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT"]

  • path is the endpoint.

Bypass.expect(bypass, "POST", "/1.1/statuses/update.json", fn conn ->
  Agent.get_and_update(AgentModule, fn step_no -> {step_no, step_no + 1} end)
  Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
end)
Link to this function

expect_once(bypass, fun)

View Source

Specs

expect_once(t(), (Plug.Conn.t() -> Plug.Conn.t())) :: :ok

Expects the passed function to be called exactly once regardless of the route.

Bypass.expect_once(bypass, fn conn ->
  assert "/1.1/statuses/update.json" == conn.request_path
  assert "POST" == conn.method
  Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
end)
Link to this function

expect_once(bypass, method, path, fun)

View Source

Specs

expect_once(t(), String.t(), String.t(), (Plug.Conn.t() -> Plug.Conn.t())) ::
  :ok

Expects the passed function to be called exactly once for the specified route (method and path).

  • method is one of ["GET", "POST", "HEAD", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT"]

  • path is the endpoint.

Bypass.expect_once(bypass, "POST", "/1.1/statuses/update.json", fn conn ->
  Agent.get_and_update(AgentModule, fn step_no -> {step_no, step_no + 1} end)
  Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
end)

Specs

open(Keyword.t()) :: t()

Starts an Elixir process running a minimal Plug app. The process is a HTTP handler and listens to requests on a TCP port on localhost.

Use the other functions in this module to declare which requests are handled and set expectations on the calls.

Options

  • port - Optional TCP port to listen to requests.

Examples

bypass = Bypass.open()

Assign a specific port to a Bypass instance to listen on:

bypass = Bypass.open(port: 1234)

Specs

pass(t()) :: :ok

Makes an expectation to pass.

Bypass.expect(bypass, fn _conn ->
  Bypass.pass(bypass)

  assert false
end)
Link to this function

stub(bypass, method, path, fun)

View Source

Specs

stub(t(), String.t(), String.t(), (Plug.Conn.t() -> Plug.Conn.t())) :: :ok

Allows the function to be invoked zero or many times for the specified route (method and path).

  • method is one of ["GET", "POST", "HEAD", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT"]

  • path is the endpoint.

Bypass.stub(bypass, "POST", "/1.1/statuses/update.json", fn conn ->
  Agent.get_and_update(AgentModule, fn step_no -> {step_no, step_no + 1} end)
  Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
end)

Specs

up(t()) :: :ok | {:error, :already_up}

Re-opens the TCP socket on the same port. Blocks until the operation is complete.

Bypass.up(bypass)
Link to this function

verify_expectations!(bypass)

View Source

Specs

verify_expectations!(t()) :: :ok | no_return()

Can be called to immediately verify if the declared request expectations have been met.

Returns :ok on success and raises an error on failure.