Is it enough testing the endpoint for a file upload or should we test the context function which does the parsing/inserting stuff from the uploaded file into the DB?

I’ve got a function/action called upload_file in my controller. Inside that function I call parse_and_insert_from_file context function which does inserting stuff into the DB from the file.

# file_upload_controller.ex

def upload_file(...) do
  ...
  UploadContext.parse_and_insert_from_file(...)
end

Is it enough to test the upload_file action or should I also test parse_and_insert_from_file function in my context test?
For example is it enough testing upload_file in file_upload_controller_test.exs or should I also test save_file function in upload_context_test.exs by mocking the contents of the file?

I am just not really experienced enough to tell what to test where yet but what I would do is to only test the action upload_file and I would say that’s enough since that action is already using that function.

What would be your opinion?

Hi!

The biggest challenge with testing file upload is to have a file to upload and if that upload goes to the third party (eg S3). In the case of a third party, you should mock in test automation.
If there is not the third party, a mock is not needed.

This function helps a lot for file generation:

https://hexdocs.pm/plug/Plug.Upload.html#random_file/1

Regarding the layers, it is always easier to mock closer to the save_file function.

What to test? Just cover all code paths (Elixir conditions, error codes) in your test files, starting from lower layers (closer to the database) towards the controller layer. So for example, if you have case statement in save_file, then write a test for that in upload_context_test

Regards, Karlo.

1 Like

So what you’re saying is basically I need to test both, right? For example if I’ve got that case statement and I test it in upload_context_test, since an action like upload_file in file_upload_controller will be using that function. Should I also test the same thing (or error to be specific) for my action in file_upload_controller_test.exs?

In controller layer, just test for errors that are pattern matched in the controller. If you only pattern match errors in upload_file then just test in that context.

I found that developers in Phoenix code only pattern match errros in controller, not in layer that uses Ecto library. I found this good approach, because doing that you do not duplicate error pattern matching.

Regards, Karlo.