Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/bypass.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ defmodule Bypass do
|> String.split("<!-- MDOC !-->")
|> Enum.fetch!(1)

defstruct pid: nil, port: nil
defstruct pid: nil, port: nil, ip: nil

@typedoc """
Represents a Bypass server process.
Expand All @@ -25,6 +25,7 @@ defmodule Bypass do
## Options

- `port` - Optional TCP port to listen to requests.
- `ip` - Optional TCP IP to listen to requests. Default is `{127, 0, 0, 1}`

## Examples

Expand All @@ -43,8 +44,9 @@ defmodule Bypass do
def open(opts \\ []) do
pid = start_instance(opts)
port = Bypass.Instance.call(pid, :port)
ip = Bypass.Instance.call(pid, :ip)
debug_log("Did open connection #{inspect(pid)} on port #{inspect(port)}")
bypass = %Bypass{pid: pid, port: port}
bypass = %Bypass{pid: pid, port: port, ip: ip}
setup_framework_integration(test_framework(), bypass)
bypass
end
Expand Down
78 changes: 23 additions & 55 deletions lib/bypass/instance.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ defmodule Bypass.Instance do
use GenServer, restart: :transient

import Bypass.Utils
import Plug.Router.Utils, only: [build_path_match: 1]

def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, [opts])
Expand All @@ -25,16 +24,20 @@ defmodule Bypass.Instance do

def init([opts]) do
# Get a free port from the OS
case :ranch_tcp.listen(so_reuseport() ++ [ip: listen_ip(), port: Keyword.get(opts, :port, 0)]) do
case :ranch_tcp.listen(
so_reuseport() ++
[ip: Keyword.get(opts, :ip, listen_ip()), port: Keyword.get(opts, :port, 0)]
) do
{:ok, socket} ->
{:ok, port} = :inet.port(socket)
{:ok, {ip, port}} = :inet.sockname(socket)
:erlang.port_close(socket)

ref = make_ref()
socket = do_up(port, ref)
socket = do_up(ip, port, ref)

state = %{
expectations: %{},
ip: ip,
port: port,
ref: ref,
socket: socket,
Expand Down Expand Up @@ -76,8 +79,12 @@ defmodule Bypass.Instance do
{:reply, port, state}
end

defp do_handle_call(:up, _from, %{port: port, ref: ref, socket: nil} = state) do
socket = do_up(port, ref)
defp do_handle_call(:ip, _, %{ip: ip} = state) do
{:reply, ip, state}
end

defp do_handle_call(:up, _from, %{ip: ip, port: port, ref: ref, socket: nil} = state) do
socket = do_up(ip, port, ref)
{:reply, :ok, %{state | socket: socket}}
end

Expand Down Expand Up @@ -135,7 +142,6 @@ defmodule Bypass.Instance do
route,
new_route(
fun,
path,
case expect do
:expect -> :once_or_more
:expect_once -> :once
Expand Down Expand Up @@ -276,50 +282,21 @@ defmodule Bypass.Instance do
end

defp route_info(method, path, %{expectations: expectations} = _state) do
segments = build_path_match(path) |> elem(1)

route =
expectations
|> Enum.reduce_while(
{:any, :any, %{}},
fn
{{^method, path_pattern}, %{path_parts: path_parts}}, acc ->
case match_route(segments, path_parts) do
{true, params} -> {:halt, {method, path_pattern, params}}
{false, _} -> {:cont, acc}
end

_, acc ->
{:cont, acc}
end
)

{route, Map.get(expectations, route)}
end

defp match_route(path, route) when length(path) == length(route) do
path
|> Enum.zip(route)
|> Enum.reduce_while(
{true, %{}},
fn
{value, {param, _, _}}, {_, params} ->
{:cont, {true, Map.put(params, Atom.to_string(param), value)}}
case Map.get(expectations, {method, path}, :no_expectations) do
:no_expectations ->
{:any, :any}

{segment, segment}, acc ->
{:cont, acc}

_, _ ->
{:halt, {false, nil}}
_ ->
{method, path}
end
)
end

defp match_route(_, _), do: {false, nil}
{route, Map.get(expectations, route)}
end

defp do_up(port, ref) do
defp do_up(ip, port, ref) do
plug_opts = [self()]
{:ok, socket} = :ranch_tcp.listen(so_reuseport() ++ [ip: listen_ip(), port: port])
{:ok, socket} = :ranch_tcp.listen(so_reuseport() ++ [ip: ip, port: port])
cowboy_opts = cowboy_opts(port, ref, socket)
{:ok, _pid} = Plug.Cowboy.http(Bypass.Plug, plug_opts, cowboy_opts)
socket
Expand Down Expand Up @@ -398,25 +375,16 @@ defmodule Bypass.Instance do
|> length
end

defp new_route(fun, path_parts, expected) when is_list(path_parts) do
defp new_route(fun, expected) do
%{
fun: fun,
expected: expected,
path_parts: path_parts,
retained_plugs: %{},
results: [],
request_count: 0
}
end

defp new_route(fun, :any, expected) do
new_route(fun, [], expected)
end

defp new_route(fun, path, expected) do
new_route(fun, build_path_match(path) |> elem(1), expected)
end

defp cowboy_opts(port, ref, socket) do
[ref: ref, port: port, transport_options: [num_acceptors: 5, socket: socket]]
end
Expand Down
5 changes: 2 additions & 3 deletions lib/bypass/plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ defmodule Bypass.Plug do
def init([pid]), do: pid

def call(%{method: method, request_path: request_path} = conn, pid) do
{method, path, path_params} = Bypass.Instance.call(pid, {:get_route, method, request_path})
route = {method, path}
conn = Plug.Conn.fetch_query_params(%{conn | params: path_params})
route = Bypass.Instance.call(pid, {:get_route, method, request_path})
ref = make_ref()

case Bypass.Instance.call(pid, {:get_expect_fun, route}) do
{:ok, ref, fun} ->
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ defmodule Bypass.Mixfile do
[
{:plug_cowboy, "~> 2.0"},
{:plug, "~> 1.7"},
{:ranch, "~> 1.7.1"},
{:ranch, "~> 1.7"},
{:ex_doc, "> 0.0.0", only: :dev},
{:espec, "~> 1.6", only: [:dev, :test]},
{:mint, "~> 1.1", only: :test}
Expand Down
72 changes: 28 additions & 44 deletions test/bypass_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,32 @@ defmodule BypassTest do
assert(is_map(bypass2) and bypass2.__struct__ == Bypass)
end

test "Bypass.open can specify an ip to operate on with expect" do
specify_ip({127, 0, 0, 2}, :expect)
end

test "Bypass.open can specify an ip to operate on with expect_once" do
specify_ip({127, 1, 2, 3}, :expect_once)
end

defp specify_ip(ip, expect_fun) do
port = 9876
bypass = Bypass.open(ip: ip, port: port)
address = ip |> :inet.ntoa() |> to_string()

apply(Bypass, expect_fun, [
bypass,
fn conn ->
assert address == conn.host
Plug.Conn.send_resp(conn, 200, "")
end
])

assert {:ok, 200, ""} = request(port, "/", "GET", address)
bypass2 = Bypass.open(ip: ip, port: port)
assert(is_map(bypass2) and bypass2.__struct__ == Bypass)
end

test "Bypass.down takes down the socket with expect" do
:expect |> down_socket
end
Expand Down Expand Up @@ -346,48 +372,6 @@ defmodule BypassTest do
end)
end

test "Bypass.stub/4 does not raise if request with parameters is made" do
:stub |> specific_route_with_params
end

test "Bypass.expect/4 can be used to define a specific route with parameters" do
:expect |> specific_route_with_params
end

test "Bypass.expect_once/4 can be used to define a specific route with parameters" do
:expect_once |> specific_route_with_params
end

defp specific_route_with_params(expect_fun) do
bypass = Bypass.open()
method = "POST"
pattern = "/this/:resource/get/:id"
path = "/this/my_resource/get/1234"

apply(Bypass, expect_fun, [
bypass,
method,
pattern,
fn conn ->
assert conn.method == method
assert conn.request_path == path

assert conn.params == %{
"resource" => "my_resource",
"id" => "1234",
"q_param_1" => "a",
"q_param_2" => "b"
}

Plug.Conn.send_resp(conn, 200, "")
end
])

capture_log(fn ->
assert {:ok, 200, ""} = request(bypass.port, path <> "?q_param_1=a&q_param_2=b")
end)
end

test "All routes to a Bypass.expect/4 call must be called" do
:expect |> all_routes_must_be_called
end
Expand Down Expand Up @@ -430,8 +414,8 @@ defmodule BypassTest do
"high-level" HTTP client, since they do connection pooling and we will sometimes get a connection
closed error and not a failed to connect error, when we test Bypass.down.
"""
def request(port, path \\ "/example_path", method \\ "POST") do
with {:ok, conn} <- Mint.HTTP.connect(:http, "127.0.0.1", port, mode: :passive),
def request(port, path \\ "/example_path", method \\ "POST", ip \\ "127.0.0.1") do
with {:ok, conn} <- Mint.HTTP.connect(:http, ip, port, mode: :passive),
{:ok, conn, ref} <- Mint.HTTP.request(conn, method, path, [], "") do
receive_responses(conn, ref, 100, [])
end
Expand Down