action.test.exs (2573B)
1 # Zenflows is designed to implement the Valueflows vocabulary, 2 # written and maintained by srfsh <info@dyne.org>. 3 # Copyright (C) 2021-2023 Dyne.org foundation <foundation@dyne.org>. 4 # 5 # This program is free software: you can redistribute it and/or modify 6 # it under the terms of the GNU Affero General Public License as published by 7 # the Free Software Foundation, either version 3 of the License, or 8 # (at your option) any later version. 9 # 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU Affero General Public License for more details. 14 # 15 # You should have received a copy of the GNU Affero General Public License 16 # along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 defmodule ZenflowsTest.VF.Action do 19 use ZenflowsTest.Help.EctoCase, async: true 20 21 alias Ecto.Changeset 22 alias Zenflows.VF.Action 23 24 defmodule Dummy do 25 use Ecto.Schema 26 27 alias Ecto.Changeset 28 alias Zenflows.VF.Action 29 30 embedded_schema do 31 field :action_id, Action.ID 32 field :action, :map, virtual: true 33 end 34 35 def changeset(params) do 36 %__MODULE__{} 37 |> common(params) 38 |> Map.put(:action, :insert) 39 end 40 41 def changeset(schema, params) do 42 schema 43 |> common(params) 44 |> Map.put(:action, :update) 45 end 46 47 defp common(schema, params) do 48 Changeset.cast(schema, params, [:action_id]) 49 end 50 end 51 52 setup do 53 %{inserted: %Dummy{action_id: Factory.build(:action_id)}} 54 end 55 56 test "insert" do 57 # doesn't work with invalid ids 58 assert %Changeset{valid?: false, changes: %{}, errors: errs} 59 = Dummy.changeset(%{action_id: "doesn't exists"}) 60 assert Keyword.has_key?(errs, :action_id) 61 62 # works with all valid ids 63 Enum.each(Action.ID.values(), fn x -> 64 assert %Changeset{valid?: true, changes: %{action_id: ^x}, errors: []} 65 = Dummy.changeset(%{action_id: x}) 66 end) 67 end 68 69 test "update", %{inserted: schema} do 70 # doesn't work with invalid ids 71 assert %Changeset{valid?: false, changes: %{}, errors: errs} 72 = Dummy.changeset(schema, %{action_id: "doesn't exists"}) 73 assert Keyword.has_key?(errs, :action_id) 74 75 # because if the values are the same, there won't be any change 76 all = Enum.reject(Action.ID.values(), &(&1 == schema.action_id)) 77 # works with all valid ids 78 Enum.each(all, fn x -> 79 assert %Changeset{valid?: true, changes: %{action_id: ^x}, errors: []} 80 = Dummy.changeset(schema, %{action_id: x}) 81 end) 82 end 83 84 test "preload", %{inserted: %{action_id: id} = schema} do 85 assert %{action: %Action{id: ^id}} = Action.preload(schema, :action) 86 end 87 end