polypush135

polypush135

Tests that rely on private methods

So I have a module that has a private method.

  defp encrypt_token(token) do
    :crypto.hmac(:sha256, BeffectWeb.Endpoint.config(:secret_key_base), token)
    |> Base.encode16(case: :lower)
  end

its used in a method that I would like to write a test for.

  def find_invite!(invite_token) do
    Repo.get_by!(User, invite_token: encrypt_token(invite_token))
  end

My test would need to create a fake user who has a invite_token that was encrypted the same way the private encrypt_token/1 encodes

test "find_invite!/1 returns a user with a given invite_token" do
  token = "SHOULD_BE_HMAC" 
  
  # token needs to be encrypted the same way as the encrypt_token
  # when passing it to the fixture, but I can't invoke the private method encrypt_token/1
  user = user_fixture(invite_token: token) # invite_token: encrypt_token(token)
  
  assert Accounts.find_invite!(token) == user
end

My question is what is the best pattern for this since I don’t want to test private functions but I do want to make sure my test uses the same methods as the real method so that way my tests don’t become brittle.

Most Liked

josevalim

josevalim

Creator of Elixir

Most of the dissonance in these discussions come with the disagreement of what a private function means. To me, a private function is an implementation detail. I don’t care how it is named, I don’t care about the argument it receives. If I refactor my private functions and a test breaks, I have a bad test. This is also how the compiler is designed. A private function may not exist at all after the code is compiled.

That’s also why Elixir makes a distinction between code comments and documentation. Code comments are for those reading the source code.

In any case, if a private function has complexity to the point you feel you need to test it and/or document it, then it is most likely worth its own module. And you can still do so while keeping it private and using doctests. To provide an actual example, let’s see how the code above could be rewritten.

Let’s assume @polypush135’s code looks like this:

  defmodule User.Invitation do
    def find_invite!(invite_token) do
      Repo.get_by!(User, invite_token: encrypt_token(invite_token))
    end

    defp encrypt_token(token) do
      :crypto.hmac(:sha256, BeffectWeb.Endpoint.config(:secret_key_base), token)
      |> Base.encode16(case: :lower)
    end
  end

I would rewrite it to:

defmodule User.Invitation do
  defmodule Token do
    @moduledoc false

    @doc """
    Now I can doctest this too!
    """
    def encrypt(token) do
      :crypto.hmac(:sha256, BeffectWeb.Endpoint.config(:secret_key_base), token)
      |> Base.encode16(case: :lower)
    end
  end

  def find_invite!(invite_token) do
    Repo.get_by!(User, invite_token: Token.encrypt(invite_token))
  end
end

This way you keep everything in the same file, you provide a logical place for grouping all of the token functionality, you can write tests and doctests and you still don’t expose it to your “final” users.

PS: Note ex_doc now allows custom groups, so you can even have modules targeting different audiences and you can use the grouping functionality to break those apart in the UI.

sasajuric

sasajuric

Author of Elixir In Action

I mostly disagree with this. In my experience private functions are mostly internal details of the implementation, and the main reason of their existence is to organize the module internal code and make it easier to follow.

The API of the module is what the module guarantees, and this is IMO the only thing that should be tested.

In such cases, I find that there’s usually potential to split the module, and move complex internal functions as public functions of the new module, so they can be properly documented and tested.

Occasionally I do see the need to explain some private function, in which case I simply use a comment.

Finally, it’s worth noting that in Elixir, functions which are public but not meant to be invoked directly, should be marked with @doc false. This should indicate that a function is internal (even though marked public), and the clients should not depend on it directly. Such function will not appear in the generated doc, and the users will be unaware of its existence. People who read the code will see the function, but they will also see that it is marked with @doc false, and hence not meant to be invoked directly.

LostKobrakai

LostKobrakai

It’s less about private vs public but also about separating dependencies. Having a own module to do the encoding does allow you to test the encoding in isolation as well as being able to inject an mock for the encryption module on your user handling. In other words find_invite should not really be concerned with how your token is created, it just needs to be able to match tokens.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
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
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
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
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement