Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save garthk/068987a03ae152ebd9f66c99c1168951 to your computer and use it in GitHub Desktop.
Save garthk/068987a03ae152ebd9f66c99c1168951 to your computer and use it in GitHub Desktop.
Now-successful attempt at a Phoenix integration test
defmodule Opencensus.Honeycomb.PhoenixIntegrationTest do
use ExUnit.Case, async: false
use Phoenix.ConnTest
alias Jason
alias Opencensus.Honeycomb.Event
alias Opencensus.Honeycomb.Sampler
defmodule HelloWeb.OpencensusTracePlug do
use Opencensus.Plug.Trace, attributes: [:release]
def release(_conn) do
%{
branch: "master",
commit: "ae9e6d8"
}
end
end
defmodule HelloWeb.Router do
use Plug.Router
plug(:match)
plug(:dispatch)
Plug.Router.get "/ctx" do
{:span_ctx, trace_id, span_id, _, _} = :ocp.current_span_ctx()
body = Jason.encode!(%{"trace_id" => trace_id, "span_id" => span_id})
conn
|> Plug.Conn.put_resp_header("content-type", "application/json")
|> send_resp(200, body)
end
match _ do
send_resp(conn, 404, "oops")
end
end
defmodule HelloWeb.Endpoint do
# We need an OTP app to host Phoenix, and ours has strong opinions about its configuration, so:
use Phoenix.Endpoint, otp_app: :opencensus
def init(_), do: {:ok, []}
plug(HelloWeb.OpencensusTracePlug)
# ... your usual chain...
# plug(Plug.Static)
# plug(Phoenix.CodeReloader)
# ...
plug(HelloWeb.Router)
end
setup _ do
:ok = Application.ensure_started(:mime)
:ok = Application.ensure_started(:plug_crypto)
:ok = Application.ensure_started(:plug)
:ok = Application.ensure_started(:opencensus_honeycomb)
start_supervised!(HelloWeb.Endpoint, [])
handle_event = fn n, measure, meta, _ -> IO.inspect({n, measure, meta}) end
:telemetry.attach_many("test", Sender.telemetry_events(), handle_event, nil)
{:ok, []}
end
test "Phoenix integration" do
conn =
Phoenix.ConnTest.build_conn(:get, "/ctx")
|> HelloWeb.Endpoint.call([])
assert %{
"span_id" => span_id,
"trace_id" => trace_id
} = json_response(conn, 200)
assert is_integer(trace_id)
assert is_integer(span_id)
end
end
@garthk
Copy link
Author

garthk commented Jun 2, 2019

I'd love to know how to start Phoenix and simulate a request without having to set up a Phoenix app. Feel free to delete TestWeb.OpencensusTracePlug.

@garthk
Copy link
Author

garthk commented Jun 2, 2019

Solved. Also requires this config snippet:

if Mix.env() == :test do
  # We need an OTP app to host Phoenix, and ours has strong opinions about its configuration, so:
  config :opencensus, Opencensus.Honeycomb.PhoenixIntegrationTest.HelloWeb.Endpoint,
    debug_errors: true,
    secret_key_base: 30 |> :crypto.strong_rand_bytes() |> Base.encode32(),
    json_library: Jason,
    url: [host: "localhost"]

  config :opencensus,
    reporters: [{Opencensus.Honeycomb.Reporter, []}],
    send_interval_ms: 5
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment