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.

josevalim

josevalim

Creator of Elixir

@eahanson already pointed out that you can now have bugs that won’t be caught in tests. It is worth mentioning that @compile :export_all emits warnings from OTP 20 on:

warning: export_all flag enabled - all functions will be exported
  lib/elixir/test/elixir/code_formatter/general_test.exs:3

FWIW, the warning and functionality comes from the Erlang compiler, Elixir has nothing to do with it.

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.

Where Next?

Popular in Questions Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
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
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement