Joe Half Face
Joe Half Face

Reputation: 2333

How do I define function dynamically in Erlang/Elixir

I have GenServer which basically only handles cast.

So I don't have any functions which track state of server (as I don't need it).

The problem: while I don't need it in production, I need some testing.

I can define handle_call just to track server state in test suit, however, this feels wrong.

I thought of adding this handle_call function at runtime before my test suit, so I can track server state in certain cases of casts sequences.

Tried to find some useful data googling, but didn't find anything.

Upvotes: 2

Views: 275

Answers (2)

Derek Brown
Derek Brown

Reputation: 521

Do you mean that you don't want the compiled module to contain the given handle_call function to appear in production? In eunit, for example, you can surround functions you only want to exist for testing with ifdef(TEST)./endif.. If you're using rebar3, and run eunit tests with rebar3 eunit, rebar3 defines TEST for you automatically, so that's all you have to do (as well as include the eunit.hrl). Otherwise, you can define it manually at compile-time.

See http://erlang.org/doc/apps/eunit/chapter.html for more information.

Upvotes: 0

michalmuskala
michalmuskala

Reputation: 11288

Since GenServer is an OTP special process, you can use tools from the :sys module to introspect it's state and behaviour. One of those functions is :sys.get_state/1 that allows you to access the state of the process without defining any specific callbacks in the server.

Upvotes: 4

Related Questions