From b5baf20aaa7b3ed4150c0772ec449a8447c60d23 Mon Sep 17 00:00:00 2001 From: nelsonic Date: Wed, 30 Sep 2020 17:14:35 +0100 Subject: [PATCH] create test/app/person_test.exs to test basic Person CRUD #65 --- lib/app/person.ex | 45 ++++++++++++++++++++++++++++++++++++++++ test/app/person_test.exs | 33 +++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 lib/app/person.ex create mode 100644 test/app/person_test.exs diff --git a/lib/app/person.ex b/lib/app/person.ex new file mode 100644 index 00000000..92fca020 --- /dev/null +++ b/lib/app/person.ex @@ -0,0 +1,45 @@ +defmodule App.Person do + use Ecto.Schema + import Ecto.Changeset + alias App.Repo + # https://stackoverflow.com/a/47501059/1148249 + alias __MODULE__ + + schema "people" do + field :status, :id + field :tag, :id + timestamps() + end + + @doc """ + Default attributes validation for Person + """ + def changeset(person, attrs) do + person + |> cast(attrs, [:id, :status, :tag]) + end + + def create_person(attrs) do + changeset(%Person{}, attrs) + |> Repo.insert!() + end + + def get_person!(id) do + __MODULE__ + |> Repo.get_by!(id: id) + end + + def upsert_person(person) do + case get_person!(person.id) do + nil -> + create_person(person) + + # existing person + ep -> + merged = Map.merge(AuthPlug.Helpers.strip_struct_metadata(ep), person) + {:ok, person} = Repo.update(changeset(%Person{id: ep.id}, merged)) + # ensure that the preloads are returned: + person + end + end +end diff --git a/test/app/person_test.exs b/test/app/person_test.exs new file mode 100644 index 00000000..11184877 --- /dev/null +++ b/test/app/person_test.exs @@ -0,0 +1,33 @@ +defmodule App.CtxTest do + use App.DataCase + alias App.Person + + describe "people" do + @valid_attrs %{ + status: 1, + } + @update_attrs %{ + status: 2 + } + + test "create_person/1 with valid data creates a person" do + person = Person.create_person(@valid_attrs) + assert person.status == 1 + end + + test "get_person!/1 returns the person with given id" do + person = create_person() + got_person = Person.get_person!(person.id) + + assert got_person.id == person.id + end + + test "usert_person/1 with valid data updates the person" do + person = create_person() + update_data = Map.merge(@update_attrs, %{id: person.id}) + updated_person = Person.upsert_person(update_data) + + assert updated_person.status == @update_attrs.status + end + end +end