6.1 KiB · text History 3208487
defmodule VigilWeb.VglCliTest do
  @moduledoc """
  The `vgl` CLI (`cli/`), as built by `cargo build` in `cli/`, against a
  running server: login with the token on stdin, projects, keys, the
  `dsn` shortcut and issues. Builds nothing: skipped when
  `cli/target/debug/vgl` (or `VGL`) doesn't exist.
  """
  use VigilWeb.ConnCase, async: false

  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures
  import Vigil.ReleasesFixtures

  alias Vigil.{ApiTokens, Issues, Projects}
  alias Vigil.Organizations.Roles

  @vgl System.get_env("VGL") || Path.expand("../../cli/target/debug/vgl", __DIR__)

  setup :tmp_dir_for_config

  defp tmp_dir_for_config(_) do
    dir = Path.join(System.tmp_dir!(), "vgl-test-#{System.unique_integer([:positive])}")
    File.mkdir_p!(dir)
    on_exit(fn -> File.rm_rf!(dir) end)
    %{dir: dir}
  end

  setup %{dir: dir} do
    owner = user_fixture()
    org = organization_fixture(owner)
    scope = org_scope(owner, org)
    team = team_fixture(org, %{name: "Backend"})
    {:ok, token} = ApiTokens.create_token(owner, %{label: "vgl", scopes: Roles.all_scopes()})

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

    env = [
      {"VIGIL_CONFIG", Path.join(dir, "config.toml")},
      {"VIGIL_URL", nil},
      {"VIGIL_TOKEN", nil},
      {"VIGIL_ORG", nil},
      {"VIGIL_PROJECT", nil},
      {"NO_COLOR", "1"}
    ]

    %{
      env: env,
      url: "http://127.0.0.1:#{port}",
      token: token.token,
      org: org,
      scope: scope,
      team: team,
      dir: dir
    }
  end

  defp vgl(env, args) do
    {out, status} = System.cmd(@vgl, args, env: env, stderr_to_stdout: true)
    {status, out}
  end

  defp ok!(env, args) do
    {status, out} = vgl(env, args)
    assert status == 0, "vgl #{Enum.join(args, " ")} failed:\n#{out}"
    out
  end

  @tag :sdk
  test "login, projects, keys, dsn and issues", ctx do
    if File.exists?(@vgl) do
      %{env: env, org: org} = ctx

      # Login reads the token from stdin, checks it, and saves it 0600 with
      # the only organization as the default.
      {out, 0} =
        System.cmd(
          "sh",
          ["-c", ~s(printf '%s' "$TOKEN" | "$VGL" login --url "$URL" --token-stdin)],
          env: env ++ [{"TOKEN", ctx.token}, {"VGL", @vgl}, {"URL", ctx.url}],
          stderr_to_stdout: true
        )

      assert out =~ "Signed in"
      config = Path.join(ctx.dir, "config.toml")
      assert File.read!(config) =~ ~s(org = "#{org.slug}")
      assert %{mode: mode} = File.stat!(config)
      assert Bitwise.band(mode, 0o777) == 0o600

      # A bad token is refused, with the server's reason, and not saved.
      {out, status} =
        System.cmd(
          "sh",
          ["-c", ~s(echo nope | "$VGL" login --url "$URL" --token-stdin)],
          env: env ++ [{"VGL", @vgl}, {"URL", ctx.url}],
          stderr_to_stdout: true
        )

      assert status != 0
      assert out =~ "Invalid token (401)"
      assert File.read!(config) =~ ctx.token

      assert ok!(env, ["whoami"]) =~ "project:write"
      assert ok!(env, ["teams"]) =~ "backend"

      out =
        ok!(env, ["projects", "create", "Mobile App", "--team", "backend", "--platform", "java"])

      assert out =~ "Created project mobile-app"
      project = Projects.get_visible(ctx.scope, "mobile-app")
      [key] = Projects.list_keys(project)
      dsn = Projects.dsn(key, project)
      assert out =~ dsn

      list = ok!(env, ["projects", "list"])
      assert list =~ "mobile-app"
      assert list =~ "backend"

      assert [%{"slug" => "mobile-app", "platform" => "java"}] =
               env |> ok!(["projects", "list", "--json"]) |> Jason.decode!()

      assert ok!(env, ["projects", "show", "mobile-app"]) =~ "Mobile App (mobile-app)"

      env = env ++ [{"VIGIL_PROJECT", "mobile-app"}]
      assert ok!(env, ["keys", "list"]) =~ dsn
      assert ok!(env, ["dsn"]) == dsn <> "\n"

      assert ok!(env, ["projects", "edit", "--name", "Mobile"]) =~ "Updated project mobile-app"
      assert Projects.get_visible(ctx.scope, "mobile-app").name == "Mobile"

      a = issue_fixture(project, title: "NullPointerException in Checkout")
      b = issue_fixture(project, title: "Timeout talking to db")

      issues = ok!(env, ["issues", "list"])
      assert issues =~ "MOBILE-APP-#{a.short_id}"
      assert issues =~ "Timeout talking to db"
      refute ok!(env, ["issues", "list", "--query", "timeout"]) =~ "NullPointer"

      assert ok!(env, ["issues", "resolve", "MOBILE-APP-#{a.short_id}", "#{b.short_id}"]) =~
               "Resolved"

      assert %{status: :resolved} = Issues.get_issue(project.id, a.id)
      assert %{status: :resolved} = Issues.get_issue(project.id, b.id)
      assert ok!(env, ["issues", "list", "--status", "resolved"]) =~ "NullPointer"
      assert ok!(env, ["issues", "list"]) =~ "No issues match."

      assert ok!(env, ["issues", "ignore", "#{a.short_id}"]) =~ "Ignored"
      assert %{status: :ignored} = Issues.get_issue(project.id, a.id)

      # The read-only listings.
      release_fixture(ctx.scope, "mobile@1.0.0+7", [project])
      assert ok!(env, ["releases", "list"]) =~ "mobile@1.0.0+7"
      assert ok!(env, ["releases", "show", "mobile@1.0.0+7"]) =~ "released     not yet"
      assert ok!(env, ["monitors"]) =~ "No cron monitors."

      {:ok, _} =
        Vigil.Uptime.create_monitor(ctx.scope, project, %{
          "name" => "Checkout page",
          "type" => "get",
          "url" => "https://shop.test/checkout"
        })

      assert ok!(env, ["uptime", "list"]) =~ "Checkout page"

      # Errors print the server's detail and exit non-zero.
      assert {1, out} = vgl(env, ["projects", "show", "nope"])
      assert out =~ "Not found (404)"
      assert {1, out} = vgl(env, ["issues", "resolve", "999999999"])
      assert out =~ "no issue"

      # Deleting wants --yes off a terminal.
      assert {1, out} = vgl(env, ["projects", "delete"])
      assert out =~ "--yes"
      assert ok!(env, ["projects", "delete", "--yes"]) =~ "Deleted project"
      assert Projects.get_visible(ctx.scope, "mobile-app") == nil
    else
      IO.puts("skipping vgl: no #{@vgl} (cargo build in cli/)")
    end
  end
end