fredmcgroarty

fredmcgroarty

"(EXIT) already started:" when testing parts of application

I am trying to write a test that covers the behavior more or less of the entire application - technically these are more integrative tests than strictly unit tests - and I feel as though there is something missing in my understanding of how processes are started and named that is stopping me from being able to test the application the way I want.

How do I instruct the application code of the names assigned to the associated processes it calls on during the run of a test? I have seen similar questions relating to this issue/error but I am too inexperienced to see the answer for my particular context.

I have the following Supervisor, which starts 3 custom written workers and another from this library

defmodule Krown.Supervisor do          
  use Supervisor                       
  # code omitted for brevity  
                                                                                                                                                                                                 
  def start_link(init_arg \\ []) do                                   
    Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)     
  end                                                                 

  def init(args \\ []) do                                                                            
                                                                                                   
    children = [                                                                                     
      {FileSystem.Worker,                                                                            
       [                                                                                             
         name: Keyword.get(args, :file_event_name, FileEventNotify),                                 
         recursive: true,                                                                            
         dirs: [Application.fetch_env!(:my_app, :event_dir)]                                          
       ]},                                                                                           
      {Dispatcher, [name: Keyword.get(args, :dispatcher_name, Dispatcher)]},  
      {Converter, [name: Keyword.get(args, :converter_name, Converter)]},
      {Uploader, [name: Keyword.get(args, :uploader_name, Uploader)]},           
    ]                                                                                                
                                                                                                   
    Supervisor.init(children, strategy: :one_for_one)                                                
  end                                                                                                
end

The Dispatcher, which monitors messages in FileSystem.Worker, looks like this:

defmodule Krown.Dispatcher do
  use GenServer                                                                                                                     
  # code omitted for brevity                                                                                                                                                                                                                                                                      
                                                                                                                                                                                                                                             
  def init(_) do                                                                                                                    
    FileEventNotify                                                                                                                 
    |> Process.whereis()                                                                                                            
    |> FileSystem.subscribe()                                                                                                       
                                                                                                                                    
    {:ok, nil}                                                                                                                      
  end                                                                                                                               
                                                                                                                                    
  def handle_info({:file_event, _watcher_pid, {fpath, events}}, _state) do                                                                                                                                                                                                                                                                                                                                                                                                                                                          
    Path.dirname(fpath)                                                                                                             
    |> Path.split()                                                                                                                 
    |> List.last()                                                                                                                  
    |> case do                                                                                                                      
      "raw" ->                                                                                                           
        Converter                                                                                                                     
      "wav" ->                                                                                                         
        Uploader                                                                                                      
     end                                                                                                                             
     |> case Process.whereis() do                                                                                             
        nil ->                                                                                                                      
          Logger.warn("Unable to locate pid with name: #{pid_name}")                                                                
          raise "#{pid_name} PID NOT FOUND"                                                                                                                                                                                                                
        pid ->                                                                                                                      
          GenServer.cast(pid, {:perform, fpath})                                                                                    
      end                                                                                                                           
                                                                                                                                    
    {:noreply, nil}                                                                                                                 
  end                                                                                                                               

And a basic test for illustrative purposes:


  test "something contrived "                           
    spec = %{                                                                         
      id: __MODULE__,                                                                    
      start: {                                                                           
        DescribedModule,                                                                 
        :start_link,                                                                     
        [[uploader_name: Test.Uploader,                                                  
          converter_name: Test.Converter,                                                
          file_event_name: Test.FileEventNotify,                                         
          event_dispatcher_name: Test.Dispatcher]]                                       
      }                                                                                  
    }                                                                                    
    pid = start_supervised!(spec, restart: :temporary)                                
             
    # create a file that will trigger FileEventNotify and Dispatcher 
    File.touch("some_fpath")                                                                            
    assert Process.alive?(pid)     

   # Uploader will remove the file once it has completed #perform
    refute File.exists?("some_fpath")
                                                                                                                      
  end                                                                                    

Declaring names for each GenServer in the test avoids the ** (EXIT) already started: #PID<0.284.0> type error, but it effectively breaks my application in the Dispatcher, since the dispatcher relies on there being static names for the two processes it sends messages to in #perform/2.

So I think to myself, “maybe I am missing something, possibly the use of a Registry?”. But I played with that and it took me back to my first problem whereby the application code has no way of knowing what the dynamically named Registry is.

I noticed that if I comment out mod: {Krown, []} from mix.exs, then I could run the tests successfully - but obviously this is not something I can use successfully in the real world, so what’s the point?

Maybe I am thinking about this all wrong. I feel I am stuck in my understanding. I guess I am writing more integration tests vs unit tests? If so, should I structure them differently?
I also have doubts the vocabulary I am using to express the issue I am having, so any feedback on that is also welcome.

First Post!

eksperimental

eksperimental

I’m not 100% this is what you may need, but you can pattern match on the context of the test.

test "something contrived ", %{test: test_name} = _context do
  # test_name is a unique string that you can use to identify your GenServers.
end

you can also use setup/2 to create a genserver automatically, and pass it through the context, but in this case you will have to randomly generate the name as the test name won’t be available.

Where Next?

Popular in Questions 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
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
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
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
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
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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 41989 114
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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
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

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement