2.7 KiB · text History 9c0fc16
defmodule LambentExWeb.PlacesTest do
  use LambentExWeb.ConnCase

  import Phoenix.LiveViewTest

  alias LambentEx.Places

  @pubsub LambentEx.PubSub

  setup do
    clear_defaults()

    on_exit(fn ->
      clear_defaults()
      # once a place has a default its devices get adopted, and those links
      # would otherwise outlive the test
      for name <- ["page-hall-bb01", "page-hall-bb02"] do
        case Registry.lookup(:lambent_links, "link-#{name}") do
          [{pid, _}] -> LambentEx.LinkSupervisor.abort_child(pid)
          [] -> :ok
        end
      end
    end)

    :ok
  end

  defp clear_defaults do
    Places.defaults() |> Map.keys() |> Enum.each(&Places.set_default(&1, nil))
    Places.defaults()
  end

  test "the devices page links to it", %{conn: conn} do
    {:ok, _live, html} = live(conn, "/cfg/devices")
    assert html =~ "/cfg/devices/places"
  end

  test "a place can be pointed at a running machine", %{conn: conn} do
    {:ok, live, _html} = live(conn, "/cfg/devices/places")

    Phoenix.PubSub.broadcast(
      @pubsub,
      "scan-82667777",
      {:devices_pub,
       %{"bb:bb:bb:bb:bb:01" => %{"place" => "page-hall", "type" => "7777-flex", "sox" => 2}}}
    )

    Phoenix.PubSub.broadcast(
      @pubsub,
      "machines_idx",
      {:machines_pub,
       %{id: "SolidxPageMachine", name: "page-machine", persist: false, opts: [persist: false]}}
    )

    html = render(live)
    assert html =~ "page-hall"
    assert html =~ "page-machine"
    # nothing driving it yet
    assert html =~ "1 unlinked"

    live
    |> form("#place-default-page-hall", %{"place" => "page-hall", "machine" => "page-machine"})
    |> render_change()

    assert Places.defaults()["page-hall"] == "page-machine"
    assert render(live) =~ "pinned so it comes back"
  end

  test "the page offers to link what is sitting there unlinked", %{conn: conn} do
    {:ok, live, _html} = live(conn, "/cfg/devices/places")

    Phoenix.PubSub.broadcast(
      @pubsub,
      "scan-82667777",
      {:devices_pub,
       %{"bb:bb:bb:bb:bb:02" => %{"place" => "page-hall", "type" => "7777-flex", "sox" => 2}}}
    )

    # nothing to offer until the place has a default
    refute render(live) =~ "Link 1 now"

    Places.set_default("page-hall", "page-machine")
    Places.defaults()

    html = render(live)
    assert html =~ "Link 1 now"

    html = live |> element(~s(button[phx-click="adopt"])) |> render_click()
    assert html =~ "Linking 1 device(s) in page-hall"
  end

  test "a default pointing at something not running says so", %{conn: conn} do
    Places.set_default("page-hall", "long-gone")
    Places.defaults()

    {:ok, _live, html} = live(conn, "/cfg/devices/places")

    assert html =~ "long-gone"
    assert html =~ "not running"
  end
end