Fl4m3Ph03n1x

Fl4m3Ph03n1x

Wrong unused warnings in Elixir

Background

I have a test that defines modules which use a behaviour. To save some typing I am using an alias for the behaviour module when I use it in my tests. However the compiler doesn’t see it and plasters my screen with unused warnings.

Code


defmodule MyApp.DispatcherTest do
  use ExUnit.Case

  # Contract 
  alias MyApp.Dispatcher.Backend
  
  # SUT
  alias MyApp.Dispatcher

  test "calls request_fn with the correct parameters" do

    defmodule MyApp.Dispatcher.Backend.MissTest do
      @behaviour Backend

      @impl Backend
      def match(_params), do: false

      @impl Backend
      def url(_params), do: "/bfg_division"
    end

    defmodule MyApp.Dispatcher.Backend.HitTest do
      @behaviour Backend

      @impl Backend
      def match(_params), do: true

      @impl Backend
      def url(_params), do: "/family_jules"
    end

    defmodule MyApp.Dispatcher.Backend.HitTest2 do
      @behaviour Backend

      @impl Backend
      def match(_params), do: true

      @impl Backend
      def url(_params), do: "/comatose"
    end

    params = %{}
    test_pid = self()
    deps = [
      backends: [
        MyApp.Dispatcher.Backend.HitTest,
        MyApp.Dispatcher.Backend.HitTest2,
        MyApp.Dispatcher.Backend.MissTest
      ],
      request: fn(name, url) ->
        send(test_pid, {:fire, {name, url}})
        {:ok, :received}
      end
    ]

    Dispatcher.send(params, deps)

    expected_name = :hit_test
    expected_url = "/family_jules"
    assert_receive {:fire, {^expected_name, ^expected_url}}

    expected_name2 = :hit_test2
    expected_url2 = "/comatose"
    assert_receive {:fire, {^expected_name2, ^expected_url2}}
  end

end

Inside the test I have 3 test modules (MissTest, HitTest, HitTest2), which implement the behaviour Backend. Each module implements 2 functions to comply with the contract of the behaviour.

Problem

The problem is that every time I run mix test I get this warning plastered onto my screen:

warning: unused alias Backend
  test/myapp/dispatcher_test.exs:4

Which is not true. To prove it, if I actually remove the line alias MyApp.Dispatcher.Backend then I get even more warnings, stating that behaviour Backend doens’t exist or is not specified.

Questions

  1. Why am I getting this warning?
  2. How can I fix it?

Marked As Solved

josevalim

josevalim

Creator of Elixir

This is a (non-solvable) limitation in how the compiler detects that aliases are used. Once that file is compiled, the Backend has indeed not been used, because the other modules are only defined (and their contents only executed) when the test runs.

You have two options:

  1. Pass warn: false to the alias
  2. Move your module definition outside of the test and inside the module body

Also Liked

zwippie

zwippie

I guess this is what’s happening:

You are defining your test backend modules within MyApp.DispatcherTest, so their final name is something like MyApp.DispatcherTest.MyApp.Dispatcher.Backend.MissTest, not MyApp.Dispatcher.Backend.MissTest.

Fl4m3Ph03n1x

Fl4m3Ph03n1x

Thank you so much for your reply.
One final question.

Does this mean, in your opinion, that I am using a anti-pattern in my tests? Am I structuring my code so bad that I am hitting a compiler limitation? (Does this raise any flags to you?)

josevalim

josevalim

Creator of Elixir

I personally don’t think it is a bad flag, it is fine. But you can also move the modules out and the behaviour should be the same, so I would rather do that rather than use the warn: false flag, if that makes any sense.

Ninigi

Ninigi

It was late in the day for me, and I honestly didn’t want to spend any time on thinking about your problem in depth, so I just threw in what I thought at that moment in the form of a question. I didn’t even think about defining the modules in your tests - should have been obvious :slightly_smiling_face: - but what jumped out to me was the fact that you did not really care about where the logic for the return value you needed was defined, as long as the return values satisfies your test case. That looked like the perfect example for a mock to me, and you already defined the behaviour, so why not go for Mox.

The way I thought you might want to use it is define one or two mock modules in your test helper, and call the same module(s) multiple times with different return values. That way, the return value would be obvious from the tests and you wouldn’t have to define the modules over and over again.

However, my experience with Mox is limited to communication layers of an app - mainly in the actual implementation of the communication, think HTTP connectors that implement get, post, put, patch and delete - so my suggestion might not be suitable for you at all.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
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
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement