2.4 KiB · text History e569b6d
defmodule CartosnapAppWeb.UploadLiveTest do
  use CartosnapAppWeb.ConnCase, async: true
  use Oban.Testing, repo: CartosnapApp.Repo

  import Phoenix.LiveViewTest

  alias CartosnapApp.Photos
  alias CartosnapApp.Workers.ProcessImage

  setup :register_and_log_in_user

  setup do
    path =
      Path.join(System.tmp_dir!(), "cartosnap-upload-#{System.unique_integer([:positive])}.png")

    {_, 0} = System.cmd("magick", ["-size", "120x90", "gradient:teal-white", path])
    on_exit(fn -> File.rm(path) end)
    %{path: path}
  end

  test "uploads photos and queues them for resizing", %{conn: conn, scope: scope, path: path} do
    {:ok, view, _html} = live(conn, ~p"/upload")

    upload =
      file_input(view, "#upload-form", :photos, [
        %{name: "beach.png", content: File.read!(path), type: "image/png"}
      ])

    render_upload(upload, "beach.png")
    assert has_element?(view, "#upload-entries")

    view |> form("#upload-form") |> render_submit()

    assert [photo] = Photos.list_photos(scope)
    assert photo.filename == "beach.png"
    assert has_element?(view, "#uploaded-#{photo.id}")
    assert_enqueued(worker: ProcessImage, args: %{id: photo.id})
  end

  test "refuses files it can't take", %{conn: conn} do
    {:ok, view, _html} = live(conn, ~p"/upload")

    upload =
      file_input(view, "#upload-form", :photos, [
        %{name: "notes.txt", content: "hi", type: "text/plain"}
      ])

    assert {:error, [[_ref, :not_accepted]]} = render_upload(upload, "notes.txt")
  end

  test "uploads straight into a trip", %{conn: conn, scope: scope, path: path} do
    trip = CartosnapApp.PhotosFixtures.trip_fixture(scope, name: "Maine")
    {:ok, view, _html} = live(conn, ~p"/upload?#{[trip: trip.id]}")

    upload =
      file_input(view, "#upload-form", :photos, [
        %{name: "dock.png", content: File.read!(path), type: "image/png"}
      ])

    render_upload(upload, "dock.png")
    view |> form("#upload-form") |> render_submit()

    assert [photo] = CartosnapApp.Trips.list_album(trip)
    assert photo.filename == "dock.png"
    assert has_element?(view, "#see-trip", "Maine")
  end

  test "a trip that isn't yours isn't offered", %{conn: conn} do
    other = CartosnapApp.AccountsFixtures.user_scope_fixture()
    theirs = CartosnapApp.PhotosFixtures.trip_fixture(other)
    {:ok, view, _html} = live(conn, ~p"/upload?#{[trip: theirs.id]}")
    refute render(view) =~ theirs.id
  end
end