rakeshtripathy

rakeshtripathy

Exunit test error Ecto.Changeset.cast/4

I’m testing the test_controller and I’m getting this error:

** (FunctionClauseError) no function clause matching in Ecto.Changeset.cast/4
when attempting to create or update an object.

The following arguments were given to Ecto.Changeset.cast/4:

     # 1
     MyTest.Whatwasit.Version
 
     # 2
     %{action: "update", item_id: 730, item_type: "AdminUser", item_user_id: nil, object: %{admin_author_id: nil, availability_flag: false, email: "weren1930-1@gmail.com", failed_log_in_attempts: 0, full_name: "Petra fhghgf", groups: nil, id: 730, inserted_at: ~N[2023-06-09 10:46:47.691601], last_locked_at: nil, last_log_in_at: nil, last_log_in_remote_ip: nil, last_password_reset_at: nil, last_seen_at: nil, log_in_count: 0, reset_password_sent_at: nil, reset_password_token: nil, roles: ["admin"], updated_at: ~N[2023-06-09 10:46:47.692937], uuid: "df6789e9-f5a0-9876-80c4-0bgb72d777d2"}, whodoneit_admin_id: 729, whodoneit_admin_name: "test acc", whodoneit_id: nil, whodoneit_name: nil}
 
     # 3
     [:item_type, :item_id, :item_user_id, :object, :action, :whodoneit_id, :whodoneit_name, :whodoneit_admin_id, :whodoneit_admin_name]
 
     # 4
     []
 
 Attempted function clauses (showing 5 out of 5):
 
     def cast(_data, %{__struct__: _} = params, _permitted, _opts)
     def cast({data, types}, params, permitted, opts) when is_map(data)
     def cast(%Ecto.Changeset{types: nil}, _params, _permitted, _opts)
     def cast(%Ecto.Changeset{changes: changes, data: data, types: types, empty_values: empty_values} =
   changeset, params, permitted, opts)
     def cast(%{__struct__: module} = data, params, permitted, opts)
 
 code: patch(
 stacktrace:
   (ecto 3.3.4) Ecto.Changeset.cast/4
   (my_test 4.0.0) lib/my_test/shared/whatwasit_version.ex:42: MyTest.Whatwasit.Version.module_changeset/2
   (my_test 4.0.0) lib/my_test/shared/whatwasit_version.ex:117: MyTest.Whatwasit.Version.insert_version/3
   (ecto 3.3.4) lib/ecto/repo/schema.ex:528: anonymous fn/2 in Ecto.Repo.Schema.run_prepare/2
   (elixir 1.13.4) lib/enum.ex:2396: Enum."-reduce/3-lists^foldl/2-0-"/3
   (ecto 3.3.4) lib/ecto/repo/schema.ex:326: anonymous fn/15 in Ecto.Repo.Schema.do_update/4
   (ecto 3.3.4) lib/ecto/repo/schema.ex:919: anonymous fn/3 in Ecto.Repo.Schema.wrap_in_transaction/6
   (ecto_sql 3.3.3) lib/ecto/adapters/sql.ex:886: anonymous fn/3 in Ecto.Adapters.SQL.checkout_or_transaction/4
   (db_connection 2.2.1) lib/db_connection.ex:1427: DBConnection.run_transaction/4
   (my_test 4.0.0) lib/my_test_web/controllers/admin/test_controller.ex:97: MyTestWeb.Admin.TestController.update/3
   (my_test 4.0.0) lib/my_test_web/controllers/admin/test_controller.ex:1: MyTestWeb.Admin.TestController.action/2
   (my_test 4.0.0) lib/my_test_web/controllers/admin/test_controller.ex:1: MyTestWeb.Admin.TestController.phoenix_controller_pipeline/2
   (phoenix 1.5.14) lib/phoenix/router.ex:352: Phoenix.Router.__call__/2
   (my_test 4.0.0) lib/my_test_web/endpoint.ex:1: MyTestWeb.Endpoint.plug_builder_call/2
   (my_test 4.0.0) lib/my_test_web/endpoint.ex:1: MyTestWeb.Endpoint.call/2
   (phoenix 1.5.14) lib/phoenix/test/conn_test.ex:225: Phoenix.ConnTest.dispatch/5
   test/my_test_web/controllers/admin/test_controller_test.exs:72: (test)

test_controller.ex

def update(conn, %{“admin_user” => admin_params}, current_admin) do
changeset =
AdminUser.common_changeset(conn.assigns.admin_user, admin_params, whodoneit(current_admin))

case Repo.update(changeset) do
  {:ok, _admin} ->
    msg = gettext("user updated successfully")

    conn
    |> put_flash(:success, msg)
    |> redirect(to: Routes.test_user_path(conn, :index))

  {:error, changeset} ->
    render(conn, "edit.html", changeset: changeset)
end

end

test_controller_test.ex

test “Cannot add ‘root’ role to admin-user”, %{auth_conn: conn} do
admin = insert(:admin_user)

  patch(
    conn,
    Routes.test_user_path(conn, :update, admin),
    %{admin_user: %{roles: ~w[root admin]}}
  )
  
end

end

It seems like Elixir is matching a Ecto.Changeset.cast/3 into a Ecto.Changeset.cast/4 adding an empty array as the 4th parameter, and the error is throwing in Repo.update(changeset).

Note: This exunit test was running earlier, but after upgrading the elixir version to 1.13.4 and phoenix version to 1.5.14 similar unit tests are failing.

Please help to resolve this error.

Thanks,
Rakesh

Marked As Solved

jswanner

jswanner

Going back to your original stack trace:

We can see the error is raised when calling Ecto.Changeset.cast/4, which is called from MyTest.Whatwasit.Version.module_changeset/2 (not provided), which is called by MyTest.Whatwasit.Version.insert_version/3 (provided).

We can see the call to MyTest.Whatwasit.Version.module_changeset/2, the first argument is an atom (version_module):

We know from your original post that atom is being passed as the first argument to cast/4, but it should be a struct or a changeset. What we don’t yet know is where the struct is intended to be created from that atom.

If that module_changeset/2 function has code to create a struct in it, then you’ll need to figure out why it’s not happening. Otherwise, you could change the code in the version_changeset function to create a struct. Such as:

version_module.module_changeset(
  struct!(version_module),
  %{…}
)

Also Liked

ruslandoga

ruslandoga

:wave:

Could you please share your AdminUser.common_changeset and whodoneit implementations?

But judging just by the error, you are using an atom MyTest.Whatwasit.Version instead of a struct %MyTest.Whatwasit.Version{} for the first argument in Ecto.Changeset.cast and it causes the match error.

jswanner

jswanner

It looks like your problem is with

It’s making another call to Ecto.Changeset.cast/4, but instead of passing a struct or changeset as the first argument, it’s passing the atom MyTest.Whatwasit.Version.

rakeshtripathy

rakeshtripathy

Thank you @ruslandoga, Below are the details

In AdminUser.common_changeset :

def common_changeset(struct), do: common_changeset(struct, %{})

def common_changeset(struct, params) when is_map(params),
    do: common_changeset(struct, params, [])

def common_changeset(struct, opts) when is_list(opts), do: common_changeset(struct, %{}, opts)   
	   
def common_changeset(struct, params, opts) do
    max_length = Application.get_env(:my_test, :max_attribute_length) || 255
   
    struct
    |> email_changeset(params)
    |> cast(params, ~w[full_name roles groups availability_flag]a)
    |> validate_required(:full_name)
    |> validate_length(:full_name, max: max_length)
    |> put_roles
    |> put_groups
    |> prepare_version(opts)
end

whodoneit implementations :

def whodoneit(%User{} = user) do
    name =
      if user.first_name || user.last_name do
        [user.first_name, user.last_name]
        |> Enum.reject(&is_nil/1)
        |> Enum.join(" ")
      else
        user.email
      end

    [whodoneit: user, whodoneit_name: name]
  end

  def whodoneit(%AdminUser{} = admin) do
    [whodoneit_admin: admin, whodoneit_admin_name: admin.full_name]
  end

  def whodoneit(_), do: []
  def whodoneit, do: []

Also if I do inspect of Changeset, I am getting below result.

#Ecto.Changeset<
  action: nil,
  changes: %{roles: ["administrator"]},
  errors: [],
  data: #MyTest.AdminUser<>,
  valid?: true
>

Here Changeset valid is true, and I suspect issue is in Repo.update(changeset),
Please help to fix this issue.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

We're in Beta

About us Mission Statement