2.6 KiB · text History 9c0fc16
defmodule LambentExWeb.CronosTest do
  use LambentExWeb.ConnCase

  import Phoenix.LiveViewTest

  alias LambentEx.Meta

  setup do
    on_exit(fn -> Meta.get_cronos() |> Enum.each(fn {k, _v} -> Meta.del_cronos(k) end) end)
    :ok
  end

  test "the schedule form renders", %{conn: conn} do
    {:ok, _live, html} = live(conn, "/cfg/services/cronos")

    assert html =~ "New Schedule"
    assert html =~ "cronos-form"
    # a link action has nothing to set, so the arg select stays out of the way
    refute html =~ "Set to"
  end

  test "picking a brightness action asks what to set it to", %{conn: conn} do
    {:ok, live, _html} = live(conn, "/cfg/services/cronos")

    html =
      live
      |> form("#cronos-form", cronos: %{action: "global_bright"})
      |> render_change()

    assert html =~ "Set to"
    assert html =~ "QUARTER"
    # the global clamp is the one thing that has no targets
    refute html =~ "cronos[targets][]"
  end

  test "a schedule is saved in the shape cronos reads", %{conn: conn} do
    {:ok, live, _html} = live(conn, "/cfg/services/cronos")

    # what the action is picked to do only appears once the action is chosen
    live |> form("#cronos-form", cronos: %{action: "global_bright"}) |> render_change()

    live
    |> form("#cronos-form",
      cronos: %{name: "sched-test", time: "23:30", action: "global_bright", arg: "63"}
    )
    |> render_submit()

    assert {"sched-test", cfg} =
             Meta.get_cronos() |> Enum.find(fn {k, _v} -> k == "sched-test" end)

    assert cfg.time == ~T[23:30:00]
    assert cfg.action == :global_bright
    assert cfg.arg == 63
    assert cfg.targets == []
  end

  test "a name is only scheduled once, however many times it is saved", %{conn: conn} do
    for arg <- ["63", "127"] do
      {:ok, live, _html} = live(conn, "/cfg/services/cronos")
      live |> form("#cronos-form", cronos: %{action: "global_bright"}) |> render_change()

      live
      |> form("#cronos-form",
        cronos: %{name: "sched-twice", time: "23:30", action: "global_bright", arg: arg}
      )
      |> render_submit()
    end

    entries = Meta.get_cronos() |> Enum.filter(fn {k, _v} -> k == "sched-twice" end)

    assert [{_name, cfg}] = entries
    assert cfg.arg == 127
  end

  test "a schedule missing its targets is not saved", %{conn: conn} do
    {:ok, live, _html} = live(conn, "/cfg/services/cronos")

    html =
      live
      |> form("#cronos-form", cronos: %{name: "sched-empty", time: "23:30", action: "link_on"})
      |> render_submit()

    assert html =~ "pick at least one"
    assert Meta.get_cronos() |> Enum.find(fn {k, _v} -> k == "sched-empty" end) == nil
  end
end