5.1 KiB · text History 1a4b866
defmodule VigilWeb.SdkConformanceTest do
  @moduledoc """
  The real SDKs against a running server: sentry-python straight from the
  reference checkout (`~/Development/local/sentry_oss_2019/sentry-python`,
  or `SENTRY_PYTHON_PATH`), which sends brotli when the `brotli` module is
  installed, as in production; and sentry-elixir the same way
  (`SENTRY_ELIXIR_PATH`), through `test/support/sdk/sentry_elixir_send.exs`.
  Each is skipped when its checkout is missing.
  """
  # A live server, and the sandbox shared with its request processes.
  use VigilWeb.ConnCase, async: false

  import Ecto.Query
  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.Ingest.BufferedItem
  alias Vigil.{Projects, Repo}

  @elixir_sdk System.get_env(
                "SENTRY_ELIXIR_PATH",
                Path.expand("~/Development/local/sentry_oss_2019/sentry-elixir")
              )

  @python_sdk System.get_env(
                "SENTRY_PYTHON_PATH",
                Path.expand("~/Development/local/sentry_oss_2019/sentry-python")
              )

  setup do
    owner = user_fixture()
    org = organization_fixture(owner)
    project = project_fixture(org_scope(owner, org))
    [key] = Projects.list_keys(project)

    server = start_supervised!({Bandit, plug: VigilWeb.Endpoint, port: 0, ip: :loopback})
    {:ok, {_ip, port}} = ThousandIsland.listener_info(server)

    hex = String.replace(key.public_key, "-", "")
    %{project: project, dsn: "http://#{hex}@127.0.0.1:#{port}/#{project.dsn_id}"}
  end

  @tag :sdk
  test "sentry-python sends an error and a message, and is told it worked", %{
    dsn: dsn,
    project: project
  } do
    if File.dir?(Path.join(@python_sdk, "sentry_sdk")) and System.find_executable("python3") do
      script = """
      import sentry_sdk
      sentry_sdk.init(dsn=#{inspect(dsn)}, release="vigil-test@1.0", environment="test", debug=True)
      try:
          1 / 0
      except ZeroDivisionError:
          sentry_sdk.capture_exception()
      sentry_sdk.capture_message("hello from python")
      sentry_sdk.flush(timeout=10)
      """

      {out, status} =
        System.cmd("python3", ["-c", script],
          env: [{"PYTHONPATH", @python_sdk}],
          stderr_to_stdout: true
        )

      assert status == 0, out
      # The SDK logs any status it didn't like; none here.
      refute out =~ ~r/Unexpected status code|HTTP Error|Rate-limited|connection refused/i, out

      items =
        Repo.all(from i in BufferedItem, where: i.project_id == ^project.id and i.type == "event")

      assert length(items) == 2, out

      payloads = Enum.map(items, &Jason.decode!(&1.payload))

      assert Enum.any?(
               payloads,
               &match?(
                 %{"exception" => %{"values" => [%{"type" => "ZeroDivisionError"} | _]}},
                 &1
               )
             )

      assert Enum.any?(payloads, &(&1["message"] == "hello from python"))
      assert Enum.all?(items, &(&1.event_id =~ ~r/^[0-9a-f]{32}$/))

      # And on into issues (slice 2).
      Vigil.Ingest.Drain.drain(project.id)
      titles = project.id |> Vigil.Issues.list_issues() |> Enum.map(& &1.title) |> Enum.sort()
      assert ["ZeroDivisionError: division by zero", "hello from python"] = titles
    else
      IO.puts("skipping sentry-python conformance: no checkout at #{@python_sdk} or no python3")
    end
  end

  @tag :sdk
  test "sentry-elixir gets back the id it sent, for errors, messages and check-ins",
       %{dsn: dsn, project: project} do
    if File.exists?(Path.join(@elixir_sdk, "mix.exs")) do
      script = Path.expand("../support/sdk/sentry_elixir_send.exs", __DIR__)

      {out, status} =
        System.cmd("elixir", [script],
          env: [{"SENTRY_DSN", dsn}, {"SENTRY_ELIXIR_PATH", @elixir_sdk}, {"MIX_ENV", "prod"}],
          stderr_to_stdout: true
        )

      assert status == 0, out

      # `result: :sync` returns the `id` from our response: sentry-elixir
      # accepts only a 200 with a JSON object, and retries anything else.
      # (A check-in's id is the SDK's own; it is queued, and flushed at the
      # end of the script.)
      for label <- ~w(exception message check_in) do
        assert out =~ ~r/#{label}: \{:ok, "[0-9a-f]{32}"\}/, out
      end

      types =
        Repo.all(from i in BufferedItem, where: i.project_id == ^project.id, select: i.type)
        |> Enum.frequencies()

      assert types["event"] == 2, out
      assert types["check_in"] == 1, out

      [check_in] =
        Repo.all(
          from i in BufferedItem, where: i.project_id == ^project.id and i.type == "check_in"
        )

      assert %{"monitor_slug" => "vigil-nightly", "status" => "ok"} =
               Jason.decode!(check_in.payload)

      # And on into issues (slice 2); the check-in waits for slice 7.
      Vigil.Ingest.Drain.drain(project.id)
      issues = project.id |> Vigil.Issues.list_issues() |> Enum.sort_by(& &1.title)

      assert [
               %{type: :error, title: "ArgumentError: boom from elixir"},
               %{type: :default, title: "hello from elixir"}
             ] = issues
    else
      IO.puts("skipping sentry-elixir conformance: no checkout at #{@elixir_sdk}")
    end
  end
end