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.

First Post!

bobbypriambodo

bobbypriambodo

Extract that function to its own module and make it public?

You can even test the implementation of encrypt_token function that way if you want.

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.

Last Post!

polypush135

polypush135

this was informative, thank you very much :smile:

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
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

Other popular topics Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
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 42716 114
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement