Hello guys I’m trying mock a function that is executed when I call my endpoint (In the middle of all code).
But when I call my endpoint all is working but th mock not is called and upload the file to s3. Can someone give me a help with this?
Thanks!
This is the error
1) test upload user image when the user is logged (DirectHomeApiWeb.UserControllerTest)
test/direct_home_api_web/controllers/user_controller_test.exs:165
** (Mox.VerificationError) error while verifying mocks for #PID<0.534.0>:
* expected DirectHomeApi.Aws.MockS3.upload_files/1 to be invoked once but it was invoked 0 times
stacktrace:
(mox 1.0.0) lib/mox.ex:692: Mox.verify_mock_or_all!/3
(ex_unit 1.11.3) lib/ex_unit/on_exit_handler.ex:143: ExUnit.OnExitHandler.exec_callback/1
(ex_unit 1.11.3) lib/ex_unit/on_exit_handler.ex:129: ExUnit.OnExitHandler.on_exit_runner_loop/0
user_controller_test.ex
defmodule DirectHomeApiWeb.UserControllerTest do
use DirectHomeApiWeb.ConnCase
use ExUnit.Case, async: true
import Mox
alias DirectHomeApi.Model.User
alias DirectHomeApi.Repo
doctest DirectHomeApi.Aws.S3
setup :verify_on_exit!
describe "upload user image" do
test "when the user is logged", %{conn: conn} do
DirectHomeApi.Aws.MockS3
|> expect(:upload_files, fn _image -> {:ok, %{}} end)
image = %Plug.Upload{
content_type: "image/jpeg",
filename: "test.jpeg",
path: "test/images/some_image.jpeg"
}
user = create_user()
conn =
sigin_and_put_token(conn, user)
|> post(Routes.user_path(conn, :upload_image), %{"id" => user.id, "photo" => image})
assert 200 = conn.status
assert {:ok, %{"sucess" => "The image could be saved sucessfully"}} = Jason.decode(conn.resp_body)
#%{"error" => "The image not could be storage in s3"}
end
end
end
s3.ex
defmodule DirectHomeApi.Aws.S3 do
@callback upload_files(arg :: any) :: {:ok, map()} | {:ok, map()}
def upload_files(image) do
content_type = image.content_type
format_file = String.split(content_type, "/") |> List.last()
file_name = "#{Ecto.UUID.generate()}.#{format_file}"
file_path = image.path
bucket = System.get_env("BUCKET_NAME")
ExAws.S3.put_object(bucket, file_name, File.read!(file_path), [
{:content_type, content_type}
])
|> ExAws.request()
|> case do
{:ok, _} -> {:ok, file_name}
{:error, error} -> {:error, error}
end
end
end
test_helper.ex
ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(DirectHomeApi.Repo, :manual)
Mox.defmock(DirectHomeApi.Aws.MockS3, for: DirectHomeApi.Aws.S3)