Testing gen_fsm – Part 6 ATG engine – Implementation


Finally, after all this thinking and all the discussing with ourselves, the moment of implementation is here. Of course, I have been writing this up during the ever so minimal spare time, and will present the final result for your pleasure, and also walk you through the interesting bits and pieces while commenting it. Enjoy!

Overview

The ATG machine consists of 2 application modules and 2 user-supplied modules

  • atg_parsetrans.erl
  • atg_machine.erl
  • test module
  • gen_fsm implementation module

The general idea is that the test module will include the atg_parsetrans as a parse transformation, and the state representation of the gen_fsm (often a record). The test module will then define a set of 3-tuples which act as a kind of Hoare-triples. The atg_machine is then used for using the test module-defined rules and auxiliary functions to randomly test sequences of transitions through the gen_fsm.

In detail – atg_parsetrans.erl

The atg_parsetrans module is the parse_transform library that your test-module should import (for your convenience).  atg_parsetrans will convert the kind-of Hoare Triples to an atg_machine friendly format. The transformation of your test module will then be roughly

  • Encase all expressions in fun’s
  • Store a string representation of the original expression, used for failure reports
  • Put the fun encased Expr and the String representation  into internal atg record
  • Drop the ‘$RULES’ tuple and replace with a list of all the records

The code follows

%%% @author Gianfranco <zenon@zen.home>
%%% @copyright (C) 2010, Gianfranco
%%% The Automated Test Generator (ATG) parse transformer
%%% Transforms the 3-tuples in the list as second elements of
%%% {'$RULES',[RULES]} into funs() -> RULE end, and creates accessors
%%% for state etc.
%%% Created : 20 Oct 2010 by Gianfranco <zenon@zen.home>
-module(atg_parsetrans).
-export([parse_transform/2]).

%% t(X)        = transformation of X
%% t('$ID')   => erlang:get('$ID')
%% t('$STATE')=> (fun......end)()
%% t('$PROGRAM_RESULT') => erlang:get('$PROGRAM_RESULT')
%% t({'$RULES',[RULE]})=> [t(R) || R <- [RULE]]
parse_transform([File,Module|Rest],_Options) ->
%% Transform with sneaked in rule_fun record
    transform([File,Module,abstr_rule_fun_record()|Rest]).

%% For inserting the used record into the file :)
abstr_rule_fun_record() ->
    {attribute,1,record,
      {rule_fun,
       [{record_field,1,{atom,1,function}},
        {record_field,1,{atom,1,string}}]}}.

%% All occurrences of '$STATE' must be replaced with this
%% call.
% ((fun() ->
%    {status,_,_,[_,_,_,_,Misc]} = sys:get_status(erlang:get('$ID')),
%    AllDatas = lists:flatten([ X || {data,X} <- Misc]),
%    proplists:get_value("StateData",AllData)
%  end)())
transform({atom,_Line,'$STATE'}) ->
    StrFunExp =
        "((fun() ->
            {status,_,_,[_,_,_,_,Misc]} = sys:get_status(erlang:get('$ID')),
            AllDatas = lists:flatten([ X || {data,X} <- Misc]),
            proplists:get_value(\"StateData\",AllDatas)
        end)()).",
    {ok,FunTkns,_} = erl_scan:string(StrFunExp),
    {ok,[FunForm]} = erl_parse:parse_exprs(FunTkns),
    FunForm;
%% All calls to use the other atoms acting as variables need to be changed to
%% proper erlang:get/1 from the process dictionary
transform({atom,_Line,'$PROGRAM_RESULT'}) ->
    StrFunExp = "erlang:get('$PROGRAM_RESULT').",
    {ok,FunTkns,_} = erl_scan:string(StrFunExp),
    {ok,[FunForm]} = erl_parse:parse_exprs(FunTkns),
    FunForm;
transform({atom,_Line,'$ID'}) ->
    StrFunExp = "erlang:get('$ID').",
    {ok,FunTkns,_} = erl_scan:string(StrFunExp),
    {ok,[FunForm]} = erl_parse:parse_exprs(FunTkns),
    FunForm;
transform({tuple,_,[{atom,_,'$RULES'},RuleList]}) ->
    rule_transform(RuleList);
transform(X) when is_tuple(X) ->
    list_to_tuple(lists:map(fun transform/1,tuple_to_list(X)));
transform(X) when is_list(X) ->
    lists:map(fun transform/1,X);
transform(X) -> X.

rule_transform({cons,L1,{tuple,L2,[A,B,C]},Rest}) ->
    {cons,L1,
     {tuple,L2,
      lists:map(
      fun({Expr,OrigExpr}) ->
              ExprStr   = erl_prettypr:format(Expr),
              OrigExprSt= erl_prettypr:format(OrigExpr),
              StructStr = "#rule_fun{function = fun()-> "++ExprStr++" end, "
                          "string = \""++OrigExprSt++"\"}.",
              {ok,Tkns,_} = erl_scan:string(StructStr),
              {ok,[Form]} = erl_parse:parse_exprs(Tkns),
              Form
      end,[{transform(A),A},{transform(B),B},{transform(C),C}])},
     rule_transform(Rest)};
rule_transform(X) -> X.


In order to fully understand this, the prerequisite knowledge is ‘The Abstract Format’. The key parts to know is that the entry-point of this module is the exported one (of course) and that it works on a list of abstract format terms. I then let each function clause of my transform/1 function take care of each specific thing that interests me.

transform({atom,_Line,'$STATE'}) ->
transform({atom,_Line,'$PROGRAM_RESULT'}) ->
transform({atom,_Line,'$ID'}) ->
transform({tuple,_,[{atom,_,'$RULES'},RuleList]}) ->

Besides this, the last three clauses work for traversing the Abstract Format

transform(X) when is_tuple(X) ->
    list_to_tuple(lists:map(fun transform/1,tuple_to_list(X)));
transform(X) when is_list(X) ->
    lists:map(fun transform/1,X);

and identity for let-through on the stuff that is not interesting.

transform(X) -> X.

Also, there is a specific function for traversing the list of 3-tuples holding the rules.  That function is interesting as it shows how I rewrite the code to be fun()-encapsulated and stringified. For this, I use erl_prettypr a very handy Abstract Form to String library, erl_scan the Erlang tokenizer (I hope you understand parsers and programming languages), and the erl_parse for generating replacement Abstract Form code.

Away we go

rule_transform({cons,L1,{tuple,L2,[A,B,C]},Rest}) ->
    {cons,L1,
     {tuple,L2,
      lists:map(
      fun({Expr,OrigExpr}) ->
              ExprStr   = erl_prettypr:format(Expr),
              OrigExprSt= erl_prettypr:format(OrigExpr),
              StructStr = "#rule_fun{function = fun()-> "++ExprStr++" end, "
                          "string = \""++OrigExprSt++"\"}.",
              {ok,Tkns,_} = erl_scan:string(StructStr),
              {ok,[Form]} = erl_parse:parse_exprs(Tkns),
              Form
      end,[{transform(A),A},{transform(B),B},{transform(C),C}])},
     rule_transform(Rest)};
rule_transform(X) -> X.

As can be seen, this function replaces each tuple element Expr with a #rule_fun record where the function field is bound to a fun encasing a parse-transformed version of the original Expr, and the string field is bound to the original un-parse-transformed Expr.

In detail – atg_machine.erl

The atg_machine is the whole .. yeah, machinery. Pumping through the different #rule_fun records, finding the matching ones, selecting one at random and executing.  The coarse steps of the atg_machine are

  • Check if end condition is met
  • Check if maximum iterations are met
  • Find matching set of accessible Rules
  • Pick one Rule at random from accessible rules
  • Execute the program of the picked Rule
  • Check postcondition of the picked Rule

One specially interesting thing is that if no rule can be applied before any endcondition is met, it will be considered a failure.

%%% @author Gianfranco <zenon@zen.home>
%%% @copyright (C) 2010, Gianfranco
%%% The Automated Test Generator (ATG) machinery, which handles
%%% rule execution and selecetion.
%%% Created : 20 Oct 2010 by Gianfranco <zenon@zen.home>
-module(atg_machine).
-export([run/3]).
-define(MAX_RUNS,100).

-record(rule_fun,{function :: fun() ,
               string   :: string() }).

-record(atg_triple,{pre  :: #rule_fun{},
                prog :: #rule_fun{},
                post :: #rule_fun{}}).

-record(atg_state,{remaining :: integer(),
               passed    :: integer(),
               log       :: [#atg_triple{}],
               state_log :: [any()],
               rules     :: [{#rule_fun{},#rule_fun{},#rule_fun{}}],
               stop_pred :: fun()}).

%------------------------------------------------------------------------------
-spec run([#rule_fun{}],fun(),fun()) -> ok | {error,any()} | true.
run(BaseSetOfRules, GenFsm_Setup,StopPred) ->
    case (catch GenFsm_Setup()) of
        {'EXIT',Reason} -> exit({setup,Reason});
        Result ->
            {A,B,C} = now(),
            random:seed(A,B,C),
            bind_to_id(Result),
            run_until(#atg_state{remaining = ?MAX_RUNS,
                                 passed    = 0,
                                 log       = [],
                                 state_log = [],
                                 rules     = BaseSetOfRules,
                                 stop_pred = StopPred})
    end.

%------------------------------------------------------------------------------
run_until(#atg_state{remaining=0}) -> report_success();
run_until(State) -> check_stopcondition(State).

check_stopcondition(#atg_state{stop_pred = StopPred} = State) ->
    case (catch StopPred()) of
        {'EXIT',Reason} -> exit({stop_predicate,Reason});
        true -> report_success();
        false -> check_hitset(State)
    end.

check_hitset(#atg_state{rules = RuleSet} = State) ->
    HitSet = [ X || X={P,_,_} <- RuleSet, (P#rule_fun.function)() ],
    case HitSet of
        [] -> exit({empty_hitset,fsm_state()});
        _ -> pick_rule(HitSet,State)
    end.

pick_rule(HitSet,State) ->
    {X,Y,Z} = lists:nth(random:uniform(length(HitSet)),HitSet),
    Triple = #atg_triple{pre=X, prog=Y, post=Z},
    use_rule(Triple,State).

use_rule(Triple = #atg_triple{prog=Y},State) ->
    io:format(".",[]),
    case (catch (Y#rule_fun.function)()) of
        {'EXIT',Reason} -> report_error(program,{Reason,Triple},State);
        Result ->
            bind_to_program_result(Result),
            test_postcondition(Triple,State)
    end.

test_postcondition(Triple = #atg_triple{post=Z},
                   #atg_state{remaining = Remaining,
                              passed = Passed,
                              log = Log,
                              state_log = SLog}=State) ->
    case (catch (Z#rule_fun.function)()) of
        {'EXIT',Reason} -> report_error(postcondition,{Reason,Triple},State);
        false-> report_error(postcondition,{postcondition_false,Triple},State);
        true -> run_until(State#atg_state{remaining=Remaining-1,
                                          passed=Passed+1,
                                          log=[Triple|Log],
                                          state_log=[fsm_state()|SLog]})
    end.

%------------------------------------------------------------------------------
bind_to_id(Value) -> erlang:put('$ID',Value).
bind_to_program_result(Value) -> erlang:put('$PROGRAM_RESULT',Value).    

report_success() ->
    io:format("~n~n*** Automated Testing Successfull ***~n~n",[]),
    ok.

report_error(Phase,{Cause,Triple},#atg_state{passed=Passed,
                                             log=Log,
                                             state_log=SLog}) ->
    io:format("~n~n*** ERROR: Automated Testing Failure ***~n"
              " Failed after: ~p ~n"
              " Failure phase: ~p~n"
              " Cause: ~p~n"
              " Rule: ~p~n"
              " State: ~p~n"
              " Log: ~p~n"
              " States: ~p~n"
              " $ID: ~p~n"
              " $PROGRAM_RESULT: ~p~n",
              [Passed,Phase,Cause,triple_to_str(Triple),
               fsm_state(),[triple_to_str(T) || T <- Log],SLog,
               erlang:get('$ID'),
               erlang:get('$PROGRAM_RESULT')]),
    % Kill the gen_fsm?
    exit(erlang:get('$ID'),kill),
    {error,Cause}.

fsm_state() ->
    ((fun() ->
              {status,_,_,[_,_,_,_,Misc]} = sys:get_status(erlang:get('$ID')),
              AllDatas = lists:flatten([ X || {data,X} <- Misc]),
              proplists:get_value("StateData",AllDatas)
      end)()).   

triple_to_str(#atg_triple{pre=#rule_fun{string=PreStr},
                          prog=#rule_fun{string=ProgStr},
                          post=#rule_fun{string=PostStr}}) ->
    {PreStr,ProgStr,PostStr}.

Some interesting things to discuss could be that this machinery does not need parse_transforming and never needs to know the internal format of the gen_fsm. So, it’s gen_fsm implementation agnostic. It will run until the first thing happens of [condition failure, end condition success, 100 iterations passed].

Other than that, I believe the code is fairly self explanatory. Of course, be welcome to ask in the comments.

A test module

A user supplied test module (call it what you want, for example: demo.erl) should define that parse-transformation is to be done with the atg_parsetrans module.

-compile({parse_transform, atg_parsetrans}).

The test module must also define the internally used state record of the gen_fsm if such a record is used and it will be very handy if the following functions are exported from the test module

-export([rules/0,is_done/0,start/0]).

why are these functions so handy, and what should they contain?

The rules() function is an obvious way to pass the Rule-list to the machinery, thus, this function is defined to return {‘$RULES’,  [....]} where the dots ‘.’ in the list are the 3-tuples. Something like this

rules() ->
  {'$RULES',
    [
     { not reg(seller), do_reg(seller), reg(seller,'$PROGRAM_RESULT')},
     { not reg(buyer), do_reg(buyer),reg(buyer,'$PROGRAM_RESULT')}
    ]}.

The is_done/0 function will serve as the end predicate for the machinery, so it will know when it’s “done”, can be set to return false if MAX_ITERATIONS of tests are wanted.
Example could be

is_done() -> '$STATE'#state.deal_done == true.

And the final export start/0 will serve as the function that return the value that will be bound for the gen_fsm accessing.
Example

start() ->
    {ok,Pid} = tradepost:start_link(),
    Pid.

Thus, we understand, that the majority of the work lies in writing the rules/0 function and all the 3-tuples defining the rules. The programmer will have to tip in some extra work into the predicates.  Now for the example test module.

Usage examples

My own test module (demo.erl) will be posted below, together with the success output and some error examples when we do some bad modifications to the tradepost.erl code.
First the demo.erl code

-module(demo).
-export([rules/0,is_done/0,start/0]).
-compile({parse_transform, atg_parsetrans}).

%% Must be included for gen_fsm
-record(state,{item,cash,seller,buyer,seller_accept,buyer_accept,deal_done}).

start() ->
    {ok,Pid} = tradepost:start_link(),
    Pid.

% ------------------------------------------------------------------------------
% List of all rules - mock code!
% ------------------------------------------------------------------------------
rules() ->
    {'$RULES',
     [
      % Seller and buyer registration,
      { not reg(seller), do_reg(seller), reg(seller,'$PROGRAM_RESULT')},
      { not reg(buyer),  do_reg(buyer),  reg(buyer,'$PROGRAM_RESULT')},
      { reg(seller), insert(item), item_is('$PROGRAM_RESULT')},
      { reg(buyer),  insert(cash),  cash_is('$PROGRAM_RESULT')},
      { tradepost_has(cash), remove(cash), not tradepost_has(cash) },
      { tradepost_has(item), remove(item), not tradepost_has(item) },
      { tradepost_has(cash) andalso
        tradepost_has(item), closedeal(), return_value_is([item,100])}
     ]
    }.

% Deal is done when deal_done is true
is_done() -> '$STATE'#state.deal_done == true.

reg(seller) -> '$STATE'#state.seller =/= undefined;
reg(buyer) ->  '$STATE'#state.buyer =/= undefined.

reg(seller,Passwd) -> '$STATE'#state.seller == Passwd;
reg(buyer,Passwd) -> '$STATE'#state.buyer == Passwd.

% The identifier of the gen_fsm is accessed through '$ID'
do_reg(buyer) ->
    Password = generate_passwd(buyer),
    tradepost:buyer_identify('$ID',Password),
    Password;
do_reg(seller) ->
    Password = generate_passwd(seller),
    tradepost:seller_identify('$ID',Password),
    Password. % This line ensures that '$PROGRAM_RESULT' is bound to
              % the generated password, for the Postcondition to access.

insert(item) ->
    Password = '$STATE'#state.seller,
    Item = generate_item(),
    tradepost:seller_insert('$ID',Item,Password),
    Item; % Ensure '$PROGRAM_RESULT is Item
insert(cash) ->
    Password = '$STATE'#state.buyer,
    Cash = generate_cash(),
    tradepost:buyer_insert('$ID',Cash,Password),
    Cash. % Ensure '$PROGRAM_RESULT is Cash

% Check that item is the specified item (argument).
item_is(GivenItem) -> '$STATE'#state.item == GivenItem.

% Check that cash is specified amount (argument)
cash_is(GivenAmount) -> '$STATE'#state.cash == GivenAmount.

% Testing state to contain cash xor item
tradepost_has(cash) -> '$STATE'#state.cash =/= undefined;
tradepost_has(item) -> '$STATE'#state.item =/= undefined.

remove(cash) ->
    Passwd = '$STATE'#state.buyer,
    tradepost:buyer_withdraw('$ID',Passwd);
remove(item) ->
    Passwd = '$STATE'#state.seller,
    tradepost:seller_withdraw('$ID',Passwd).

% Deal closing, is a parallelized action.
% therefore I have to bind the value of '$ID' to the atom '$ID' in the
% new process without writing '$ID' as an atom when doing so! o<:D
closedeal() ->
    ID   = '$ID',
    Self = self(),
    spawn_link(fun() ->
                       erlang:put(list_to_atom("$ID"),ID),
                       Passwd = '$STATE'#state.buyer,
                       ItemAndCash = tradepost:get_contents('$ID',Passwd),
                       Self ! tradepost:buyer_deal('$ID',Passwd,ItemAndCash)
               end),
    spawn_link(fun() ->
                       erlang:put(list_to_atom("$ID"),ID),
                       Passwd = '$STATE'#state.seller,
                       ItemAndCash = tradepost:get_contents('$ID',Passwd),
                       Self ! tradepost:seller_deal('$ID',Passwd,ItemAndCash)
               end),
    [receive X -> X end,receive Y -> Y end].                            

return_value_is(X)-> lists:sort(X) == lists:sort('$PROGRAM_RESULT').

generate_passwd(buyer) -> buyer;
generate_passwd(seller) -> seller.

generate_item() -> item.
generate_cash() -> 100.

There, this is the test module I have for the tradepost.erl module, and here comes the compilation and running. I have already compile atg_parsetrans and atg_machine to ebin/ and therefore add ebin/ to the path when compiling demo.erl

zen:EUnitFSM zenon$ erlc -o ebin/ src/demo.erl -pa ebin/
zen:EUnitFSM zenon$ erl -pa ebin/
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> atg_machine:run(demo:rules(),fun demo:start/0, fun demo:is_done/0).
...........

*** Automated Testing Successfull ***

ok
2>

The 11 dots seen show that 11 cycles where run before the is_done/0 predicate returned true. Now, if we wish to see some errors, let’s make a small modification (that actually was a bug I discovered thanks to my own tool) in tradepost.erl

On line 118, change the last don’t care to undefined.

{cash_received,item,Pwd,_,_,_} -> {ok, cash_received, undef(item,LoopD)};

like this, and save + recompile

{cash_received,item,Pwd,_,_,undefined} -> {ok, cash_received, undef(item,LoopD)};

now, running should produce the nice error output format

16> atg_machine:run(demo:rules(),fun demo:start/0, fun demo:is_done/0).
........

*** ERROR: Automated Testing Failure ***
 Failed after: 7
 Failure phase: postcondition
 Cause: postcondition_false
 Rule: {"tradepost_has(item)","remove(item)","not tradepost_has(item)"}
 State: {state,item,100,seller,buyer,undefined,undefined,false}
 Log: [{"reg(buyer)","insert(cash)","cash_is('$PROGRAM_RESULT')"},
       {"tradepost_has(cash)","remove(cash)","not tradepost_has(cash)"},
       {"reg(buyer)","insert(cash)","cash_is('$PROGRAM_RESULT')"},
       {"reg(seller)","insert(item)","item_is('$PROGRAM_RESULT')"},
       {"not reg(buyer)","do_reg(buyer)","reg(buyer, '$PROGRAM_RESULT')"},
       {"reg(seller)","insert(item)","item_is('$PROGRAM_RESULT')"},
       {"not reg(seller)","do_reg(seller)","reg(seller, '$PROGRAM_RESULT')"}]
 States: [{state,item,100,seller,buyer,undefined,undefined,false},
          {state,item,undefined,seller,buyer,undefined,undefined,false},
          {state,item,100,seller,buyer,undefined,undefined,false},
          {state,item,undefined,seller,buyer,undefined,undefined,false},
          {state,item,undefined,seller,buyer,undefined,undefined,false},
          {state,item,undefined,seller,undefined,undefined,undefined,false},
          {state,undefined,undefined,seller,undefined,undefined,undefined,
                 false}]
 $ID: <0.88.0>
 $PROGRAM_RESULT: error
** exception exit: killed
17>

Now, first of, the 8 dots say that 8 cycles where performed, and the Error output says that we failed on the 8th cycle, that is, after 7 completed. The phase of the error was the postcondition of the selected rule. The selected rule is shown on the “Rule:” line. The current state in which we failed is shown after “State:”.

The “Log:” shows a list of all the processed and passed rules, most recent nearest the top of the screen. This is also true for the “States:” output, which serves as a log for us. The internal process dictionary bindings for ‘$ID’ and ‘$PROGRAM_RESULT’ are also shown.
In short, almost everything we need for debugging is here.

Now for a really terrifyingly delicious comment! I had to run this several (6 times) before this error was shown.

Why? Because the testing is randomised. And some of the corner cases will thus not be triggered easily during short runs.  Let us undo the faulty change and introduce an easier one into the program. Let’s forget that buyer inserts cash and not item. (Line 42, change cash  to item : and recompile!)

4> atg_machine:run(demo:rules(),fun demo:start/0, fun demo:is_done/0).
...

*** ERROR: Automated Testing Failure ***
 Failed after: 2
 Failure phase: postcondition
 Cause: postcondition_false
 Rule: {"reg(buyer)","insert(cash)","cash_is('$PROGRAM_RESULT')"}
 State: {state,undefined,undefined,seller,buyer,undefined,undefined,false}
 Log: [{"not reg(buyer)","do_reg(buyer)","reg(buyer, '$PROGRAM_RESULT')"},
       {"not reg(seller)","do_reg(seller)","reg(seller, '$PROGRAM_RESULT')"}]
 States: [{state,undefined,undefined,seller,buyer,undefined,undefined,false},
          {state,undefined,undefined,seller,undefined,undefined,undefined,
                 false}]
 $ID: <0.43.0>
 $PROGRAM_RESULT: 100
** exception exit: killed
5>

Bam! Reading the error reason, it becomes apparent that something is not working in the cash insertion! the cash in the state does not match ‘$PROGRAM_RESULT’ which was 100! Looking at the State, it’s undefined. Bummer! :)

This was the final part of the home-written ATG, I will presumably put in on git if the demand is high enough.

Cheers

/G

Testing gen_fsm – Part 5 ATG Engine


The first post on the Automatest Test Generator for gen_fsm testing gave us a good idea on Rule basis, what we should brainstorm on now, is how the internal machinery should be for this to work as expected. By now this seems to take on a form outside of EUnit, and I shall therefore drop the EUnit prefix on the titles (for now). Without further ado, let us start writing some free-style mock code of our machine, firs off, a basic skeleton.

Second Iteration – Machinery Brainstorming

%------------------------------------------------------------------------------
% Minimal for now, there is a lot of bells and whistles that can be added.
%------------------------------------------------------------------------------
run(BaseSetOfRules, GenFsm_Setup) ->
    case (catch GenFsm_Setup()) of
        {'EXIT',Reason} -> report_error(setup,Reason);
        Result ->
            bind_to_id(Result),
            run_until(BaseSetOfRules,100)
    end.

%------------------------------------------------------------------------------
% No more iterations to run, and no crashes, all is okay
run_until(_RulesSet, 0) -> report_success();
% An iteration: Find valid rules (== positive precondition) and run one of them
run_until(RuleSet,Iterations) when Iterations > 0 ->
    HitSet = [ X || X={Precond,_,_} <- RuleSet, Precond() ],
    {_,Program,PostCondition} = lists:nth(random:uniform(length(HitSet)),HitSet),
    case (catch Program()) of
        {'EXIT',Reason} -> report_error(program,Reason);
        Result ->
            bind_to_program_result(Result),
            % Test postcondition
            case (catch PostCondition()) of
                {'EXIT',Reason2} -> report_error(postcondition,Reason2);
                true -> run_until(RuleSet,Iterations-1);
                false-> report_error(postcondition,postcondition_false)
            end
    end.

In the code seen above, the BaseSetOfRules would be the result of the previously written rule() function, a list of rules. The second argument GenFsm_Setup would correspond to some kind of setup function to run before starting (think in {setup,fun setup/0,fun cleanup/0} terms). This function call should give a result which can be used to bind with ‘$ID’.

A very important detail is that the predicates PostCondition and PreCondition must not change the State of the gen_fsm!

Given the code above, we kind of have an idea of the machinery and it’s syntax. The natural question is then, how do we put this together through parse_transforming? The special parts that need consideration is the binding of values  to

  • ‘$ID’
  • ‘$PROGRAM_RESULT’
  • ‘$STATE’

And also the accessing of these values. Of course, another detail worth mentioning is the fact that the machinery seems to treat the Precondition, Program and Postcondition as they where all function objects. This brain-storm design implies that all Expressions given in the previous Rule post are encapsulated into a fun during the parse_transforming (aha!).

Let this discussion of value binding and accessing be the focus for the next iteration.

Third Iteration – Binding and Accessing

For the binding of values, the erlang process dictionary fits perfectly. But before going further, let me light up the usual warning lamps about using the process dictionary and tell you how bad it is and how you should never do it, and give you the link to the info about it. Now that we got that out of the way, here is the simple implementation the machinery needs to pull this of.

% Use the process dictionary of the machinery for these special values
bind_to_id(Value) -> erlang:put('$ID',Value).
bind_to_program_result(Value) -> erlang:put('$PROGRAM_RESULT',Value).

Great, but what about the ‘$STATE’ binding, do we need the process dictionary for it?The answer is: No. The gen_fsm state is a fresh info value that needs to be  requests each time the ‘$STATE’ atom is seen in the user (rule) code,  thus we would expect the parse_transform to exchange the  ‘$STATE’ atom with a special function call.

What about accessing the values bound to these atoms? Well, for the process dictionary bound ones, just let the parse_transform exchange all occurrences with process dictionary lookups. Looking at the first brainstorm syntax, and how it evolves:

 % Old brain-storm syntax
   { not reg(seller), do_reg(seller), reg(seller,generated_pwd)},

 % Updated brain-storm syntax
   { not reg(seller), do_reg(seller), reg(seller,'$PROGRAM_RESULT')},

 % Parse_transform ed
   { fun() -> not reg(seller) end ,
     fun() -> do_reg(seller) end,
     fun() -> reg(seller,erlang:get('$PROGRAM_RESULT') end },

As for the ‘$STATE’ atom, we would expect the parse_transform to replace it with something roughly similar to this “do not try this at home kids – I am a professional“.

% Old brain-storm syntax
 reg(seller) -> '$STATE'#state.seller =/= undefined;

% Parse_transform:d into this
 reg(seller) ->
   ((fun() ->
      {status,_,_,[_,_,_,_,Misc]} = sys:get_status(erlang:get('$ID')),
      AllDatas = lists:flatten([ X || {data,X} <- Misc]),
      proplists:get_value("StateData",AllData)
     end)())#state.seller =/= undefined;

Let me guide you through it in case you need it. According to our manual pages, the sys:get_status will return a nifty status tuple where the last element is a list which in turn has a last element which is a proplist. That proplist contains the state representation which can be accessed through the Key “StateData”. For our purposes, this is great. Please note: “… Callback modules for gen_server and gen_fsm can also customise the value of Misc by exporting a format_status/2 function that contributes module-specific information…“.

This state accessing might have to be done in several places with close proximity, thus I encase it into an instantly executed functional object (fun), which is parenthesised in order to make it usable by any type accessing method of choice.

Now we have a kind of good idea on how we would like the Rules to be written. Also we kind of know how we would like the machinery to work, thus, the next iteration should be the start of the  actual implementation.

Cheers

/G

EUnit Testing gen_fsm – Part 4 Automated Test Machinery


Using the idea from the last post, we have a machinery which takes a set of Rules as input, a gen_fsm, setup and cleanup. To develop this, there is once again a big question, will this be done with parse transforms or using macros and functions? To try and answer this question along with how it should work, let’s write some mock-code. This will be the first iteration of the ATG (Automated Test Generator).

First Iteration – Brainstorm

For this first iteration, it gets easier if we break it down into some use-cases, first off, the battery of Rules,

% ------------------------------------------------------------------------------
% List of all rules - mock code!
% ------------------------------------------------------------------------------
rules() ->
    [
     % Seller and buyer registration,
     % The postcondition needs to access the password which was generated in
     % the program so that we can verify that the tradepost holds the correct
     % registration.
     { not reg(seller), do_reg(seller), reg(seller,generated_pwd)},
     { not reg(buyer),  do_reg(buyer),  reg(buyer,generated_pwd)},

     % Insert item / cash, should insert random amount of cash and random
     % items. The PostCond must be able to test the existence of that item / cash
     % and thus must have access to the generated item / cash.
     { reg(seller), insert(item), item_is(inserted_item)},
     { reg(buyer),  insert(cash),   cash_is(inserted_amount)},

     % Removal of cash or item, remove needs to use the password which
     % the tradepost currently has.
     { tradepost_has(cash), remove(cash), not tradepost_has(cash) },
     { tradepost_has(item), remove(item), not tradepost_has(item) },

     % Close a deal, we must check that the _returned value_ is the correct one.
     % We must pass on the returned value to the postcond. The Postcond must
     % then also have access to the original item and cash.
     { tradepost_has(cash)
       andalso tradepost_has(item), closedeal(), return_value_is(??)}
    ].

As can be seen, I added some comments on thoughts that deserve discussion. It will often be the case that the postcondition needs to refer to a value which is the result of the Program. Such an example can be the test for correct registration. For that case, we do not only need access to the state, but also the generated password which was used. How to fix it? Bind the Program result to a special atom ‘$PROGRAM_RESULT’, also, bind the state to a special atom ‘$STATE’. Problem solved. Please note that such a solution , is leaning towards parse-transforms.

% The State is accessed through the special  atom
% '$STATE', and the module must include the state record.
reg(seller) -> '$STATE'#state.seller =/= undefined;
reg(buyer) ->  '$STATE'#state.buyer =/= undefined.

% Passwd can be result from Program, thus the call in
% the Rule may then be { ..... , reg(seller,'$PROGRAM_RESULT')}
reg(seller,Passwd) -> '$STATE'#state.seller == Passwd;
reg(buyer,Passwd) -> '$STATE'#state.buyer == Passwd.

Another special binding added to this machinery, is the identifier for the gen_fsm, this could be a registered name or a Pid. The usage of this is shown below, where a registration is performed, and the password is returned for the Postcondition.

% The identifier of the gen_fsm is accessed through '$ID'
do_reg(seller) ->
    Password = generate_passwd(),
    tradepost:seller_identify('$ID',Password),
    Password. % This line ensures that '$PROGRAM_RESULT' is bound to
             % the generated password, for the Postcondition to access.

How the ‘$ID’ is bound, is unclear for now, but that can be taken care of later, remember that we are just writing mock code to get an idea of what we possibly want. Going from the top to bottom, how would we love to see the insertion?

% This of course also uses the $ID, but also the state to access the password.
% seems only fair to return the inserted item for this function as that
% probably is what we wish, ... always.
insert(item) ->
    Password = '$STATE'#state.seller,
    Item = generate_item(),
    tradepost:seller_insert('$ID',Item,Password),
    Item; % Ensure '$PROGRAM_RESULT is Item
insert(cash) ->
    Password = '$STATE'#state.buyer,
    Cash = generate_cash(),
    tradepost:buyer_insert('$ID',Cash,Password),
    Cash; % Ensure '$PROGRAM_RESULT is Cash

Coupled to this, Now, how to test that the cash is the amount we wish, and that the item is the sought one?

% Check that item is the specified item (argument).
item_is(GivenItem) -> '$STATE'#state.item == GivenItem.

% Check that cash is specified amount (argument)
cash_is(GivenAmount) -> '$STATE'#state.cash == GivenAmount.

Or simpler, just test existence?

% Testing state to contain cash xor item
tradepost_has(cash) -> '$STATE'#state.cash =/= undefined;
tradepost_has(item) -> '$STATE'#state.item =/= undefined.

Likewise, removal should be easy with the help of ‘$ID’ and ‘$STATE’

% Utilizing both state and id, but nice thing is that result
% of withdraw function will be bound to $PROGRAM_RESULT in this mockup.
remove(cash) ->
    Passwd = '$STATE'#state.buyer,
    tradepost:buyer_withdraw('$ID',Passwd);
remove(item) ->
    Passwd = '$STATE'#state.seller,
    tradepost:seller_withdraw('$ID',Passwd);

Nearing the end of the first iteration brainstorming, what remains is a way to program the deal closing and a way to test the return value of this (a way to test the return value of the deal closing), ‘$PROGRAM_RESULT’ is still our friend, but it would be good to have some kind of parallelism. Once again, how would we like to see this written?

% Deal closing, is a parallelized action.
% Return value should still be bound to '$PROGRAM_RESULT'
% Could be bound in the form [ A , B ] for this example.
% Inspiration from the parallel keyword in EUnit.
closedeal() ->
    {'$PARALLEL',
     [ begin
           Pass = '$STATE'#state.buyer,
           ItemAndCash = tradepost:get_contents('$ID',Pass),
           tradepost:buyer_deal('$ID',Pass,ItemAndCash)
       end,
       begin
           Pass = '$STATE'#state.seller,
           ItemAndCash = tradepost:get_contents('$ID',Pass),
           tradepost:seller_deal('$ID',Pass,ItemAndCash)
       end]}.

This seems to do the trick,  the idea is to pass a list of  functions which are executed in parallel, the result of each one is bound to an element in the generated list which is bound to ‘$PROGRAM_RESULT’. As this seems that this covers the first iteration of brainstorming, it could be nice to sum it up.

Summary of First Brainstorming session

The Automated Test Generator machinery has a set of Rules, each Rule is modeled as a 3-tuple, The first element in the 3-tuple is the Precondition that has to be met for the Rule to possibly take action. The second element is a Program which is executed, iff the Precondition holds and the Rule is chosen. The third element is a Postcondition that must hold once the Program of the Rule is executed.

The different special syntax elements which have been identified now are

  • ‘$STATE’,  the internal state of the gen_fsm being tested.
  • ‘$ID’,  identifier of the gen_fsm, can be a registered name, a registered name on a node or a Pid.
  • ‘$PROGRAM_RESULT’, the result of the Program (middle element in the Rule)
  • ‘$PARALLEL’, keyword for marking that functions are to be executed in parallel, and the joint result is bound to ‘$PROGRAM_RESULT’

Besides these special syntactical elements, we should try structuring the thoughts a bit more.

rule() = { precondition(), program(), postcondition() }

precondition() = expr() -> true | false.
program()    = expr() -> any().
postcondition()= expr() -> true | false.

Maybe this definition feels a bit weak and lame, but as for now, it captures what we wish, next brainstorming session should focus on the machinery of our automated test generator.

Cheers

EUnit Testing gen_fsm – Part 2


Last post we saw the symbolic (somewhat DSL) for the gen_fsm testing, using that as help we shall continue with the Buyer API. Technically, we are now doing the fourth iteration.

Fourth Iteration – Buyer API

The buyer wishes to be identified like the seller, to deposit cash and to withdraw cash. Thus his/her usage is similar. By good TDD, we will write the tests first, adding them to tradepost_tests.erl

The new added instantiators

% This is the main point of "entry" for my EUnit testing.
% A generator which forces setup and cleanup for each test in the testset
main_test_() ->
    {foreach,
     fun setup/0,
     fun cleanup/1,
     % Note that this must be a List of TestSet or Instantiator
     [
      % First Iteration
      fun started_properly/1,
      % Second Iteration
      fun identify_seller/1,
      fun insert_item/1,
      fun withdraw_item/1,
      % Fourth iteration
      fun identify_buyer/1,
      fun insert_cash/1,
      fun withdraw_cash/1
     ]}.

And their implementations

identify_buyer(Pid) ->
    ?fsm_test(Pid,"Identify Buyer Test",
       [{state,is,pending},
        {call,tradepost,buyer_identify,[Pid,buyer_password],ok},
        {state,is,pending},
        {loopdata,is,[undefined,undefined,undefined,buyer_password,undefined]}
      ]).

insert_cash(Pid) ->
    ?fsm_test(Pid,"Insert Cash Test",
       [{state,is,pending},
        {call,tradepost,buyer_identify,[Pid,buyer_password],ok},
        {call,tradepost,buyer_insertcash,[Pid,100,buyer_password],ok},
        {state,is,cash_received},
        {loopdata,is,[undefined,100,undefined,buyer_password,undefined]}
       ]).

withdraw_cash(Pid) ->
    ?fsm_test(Pid,"Withdraw Cash Test",
       [{state,is,pending},
        {call,tradepost,buyer_identify,[Pid,buyer_password],ok},
        {call,tradepost,buyer_insertcash,[Pid,100,buyer_password],ok},
        {call,tradepost,buyer_withdrawcash,[Pid,buyer_password],ok},
        {loopdata,is,[undefined,undefined,undefined,buyer_password,undefined]}
       ]).

The changes in tradepost.erl

%% API
-export([start_link/0,stop/1,seller_identify/2,seller_insertitem/3,
         seller_withdraw_item/2,buyer_identify/2,buyer_insertcash/3,
         buyer_withdrawcash/2]).
%% States
-export([pending/2,pending/3,item_received/3,cash_received/3]).

buyer_identify(TradePost,Password) ->
    gen_fsm:sync_send_event(TradePost,{identify_buyer,Password}).
buyer_insertcash(TradePost,Amount,Password) ->
    gen_fsm:sync_send_event(TradePost,{insert_cash,Amount,Password}).
buyer_withdrawcash(TradePost,Password) ->
    gen_fsm:sync_send_event(TradePost,{withdraw_cash,Password}).    

pending({identify_buyer,Password},_Frm,LoopD = #state{buyer=Password}) ->
    {reply,ok,pending,LoopD};
pending({identify_buyer,Password},_Frm,LoopD = #state{buyer=undefined}) ->
    {reply,ok,pending,LoopD#state{buyer=Password}};
pending({identify_buyer,_},_,LoopD) ->
    {reply,error,pending,LoopD};

pending({insert_cash,Amount,Password},_Frm,LoopD = #state{buyer=Password}) ->
    {reply,ok,cash_received,LoopD#state{cash=Amount}};
pending({insert_cash,_,_},_Frm,LoopD) ->
    {reply,error,pending,LoopD}.

cash_received({withdraw_cash,Password},_From,LoopD = #state{buyer=Password}) ->
    {reply,ok,pending,LoopD#state{cash=undefined}};
cash_received({withdraw_cash,_},_From,LoopD) ->
    {reply,error,cas_received,LoopD}.

Compiling and running

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/ -eval 'eunit:test(tradepost,[verbose]).'
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> ======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly (Started Properly Test)...ok
    tradepost_tests: identify_seller (Identify Seller Test)...ok
    tradepost_tests: insert_item (Insert Item Test)...[0.001 s] ok
    tradepost_tests: withdraw_item (Withdraw Item Test)...[0.001 s] ok
    tradepost_tests: identify_buyer (Identify Buyer Test)...ok
    tradepost_tests: insert_cash (Insert Cash Test)...[0.001 s] ok
    tradepost_tests: withdraw_cash (Withdraw Cash Test)...ok
    [done in 0.024 s]
  [done in 0.024 s]
=======================================================
  All 7 tests passed.

1>

Wow. Great. So the buyer and the seller can now deposit and retract their respective parts. Awesome. However, there are some intentionally left out parts (and yes, I assume more than one of you has been thinking and cringing about it) – the interleaving of the actions. That is left for the fifth iteration.

Fifth Iteration – Interleaving of Actions

Much straight forward  – what if the buyer identifies and inserts the item, and the buyer wishes to identify after this?

Why, let’s write a test scenario for it (and of course it will fail).

interleaving1(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Inserts Item, then Buyer Identiefies",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,a],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,a],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok}
              ]).

And just as we knew, it would blow

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/ -eval 'eunit:test(tradepost,[verbose]).'
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]Eshell V5.7.5  (abort with ^G)
1> ======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly (Started Properly Test)...[0.001 s] ok
    tradepost_tests: identify_seller (Identify Seller Test)...ok
    tradepost_tests: insert_item (Insert Item Test)...ok
    tradepost_tests: withdraw_item (Withdraw Item Test)...ok
    tradepost_tests: identify_buyer (Identify Buyer Test)...ok
    tradepost_tests: insert_cash (Insert Cash Test)...ok
    tradepost_tests: withdraw_cash (Withdraw Cash Test)...ok
    tradepost_tests: interleaving1 (Seller Identifies, Inserts Item, then Buyer Identiefies)...*skipped*
undefined
*unexpected termination of test process*
::{function_clause,[{tradepost,item_received,
                               [{identify_buyer,b},
                                {<0.69.0>,#Ref<0.0.0.113>},
                                {state,ring,undefined,a,undefined,...}]},
                    {gen_fsm,handle_msg,7},
                    {proc_lib,init_p_do_apply,3}]}

The issue is of course that it is not possible to identify oneself in any other state than the pending one. Do we consider this a flaw or as part of the system design?  For this example, we shall regard it to be a flaw. And the true design should be that either buyer or seller must be able to identify themselves once before inserting their part and closing the deal.

Let’s add some more tests that we know should pass, like reversing the roles, and adding more interleaving of actions. As will be seen, this causes a lot of code, and we discover the need for some Automated Test Generation.

interleaving1(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Inserts Item, then Buyer Identiefies",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {loopdata,is,[ring,undefined,s,b]}
              ]).

interleaving2(Pid) ->
    ?fsm_test(Pid,"Buyer Identifies, Inserts Item, then Seller Identiefies",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {loopdata,is,[undefined,100,s,b]}
              ]).

interleaving3(Pid) ->
    ?fsm_test(Pid,"Buyer Identifies, Seller Identifies, buyer inserts cash",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {loopdata,is,[undefined,100,s,b]}
              ]).

interleaving4(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Buyer Identifies, Seller inserts item",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {loopdata,is,[ring,undefined,s,b]}
              ]).

interleaving5(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Seller inserts item, Buyer Identifies,"
              "Buyer Inserts Cash",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {loopdata,is,[ring,100,s,b]}
              ]).

These are not all the tests (some 6 more are hidden). For the future (for some future iteration), we would like to specify which state transitions are legal, which functions cause these transitions, and ultimately let the machine generate them for us, run the sequences and test whether all is good.

Also, while failing, it would be tremenduously nice if the automatic test generation would show us a trace of the failing run.

Fixing up the problem with identification, a lot of the tests run through, however a new problem is evident.

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/ -eval 'eunit:test(tradepost,[verbose]).'
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> ======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly (Started Properly Test)...ok
    tradepost_tests: identify_seller (Identify Seller Test)...ok
    tradepost_tests: insert_item (Insert Item Test)...ok
    tradepost_tests: withdraw_item (Withdraw Item Test)...ok
    tradepost_tests: identify_buyer (Identify Buyer Test)...ok
    tradepost_tests: insert_cash (Insert Cash Test)...ok
    tradepost_tests: withdraw_cash (Withdraw Cash Test)...ok
    tradepost_tests: interleaving1 (Seller Identifies, Inserts Item, then Buyer Identiefies)...ok
    tradepost_tests: interleaving2 (Buyer Identifies, Inserts Item, then Seller Identiefies)...ok
    tradepost_tests: interleaving3 (Buyer Identifies, Seller Identifies, buyer inserts cash)...ok
    tradepost_tests: interleaving4 (Seller Identifies, Buyer Identifies, Seller inserts item)...ok
    tradepost_tests: interleaving5 (Seller Identifies, Seller inserts item, Buyer Identifies,Buyer Inserts Cash)...*skipped*
undefined
*unexpected termination of test process*
::{function_clause,[{tradepost,item_received,
                               [{insert_cash,100,a},
                                {<0.85.0>,#Ref<0.0.0.153>},
                                {state,ring,undefined,a,a,...}]},
                    {gen_fsm,handle_msg,7},
                    {proc_lib,init_p_do_apply,3}]}

=ERROR REPORT==== 5-Sep-2010::22:33:23 ===
** State machine <0.83.0> terminating
** Last message in was {'$gen_sync_event',
                           {<0.85.0>,#Ref<0.0.0.153>},
                           {insert_cash,100,a}}
** When State == item_received
**      Data  == {state,ring,undefined,a,a,undefined}
** Reason for termination =
** {function_clause,[{tradepost,item_received,
                                [{insert_cash,100,a},
                                 {<0.85.0>,#Ref<0.0.0.153>},
                                 {state,ring,undefined,a,a,undefined}]},
                     {gen_fsm,handle_msg,7},
                     {proc_lib,init_p_do_apply,3}]}
=======================================================
  Failed: 0.  Skipped: 0.  Passed: 11.
One or more tests were cancelled.

1>

It is not possible to insert the cash after the item has been inserted!(?) Clearly, there is an interleaving problem between item insertion and cash insertion. The true design  should be that either buyer or seller must be able to insert xor withdraw their item / cash before closing the deal, irrespective of the other parts item / cash.

An interesting thing to note is that we got this failing tests because this test was longer. It triggered more transitions, and was in a sense, more complex. This is another thing we wish to get for free from an automated test generating engine.

Wishing to test what we just discussed, we add a longer test that should serve as a green light once it goes through.

interleaving6(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Seller inserts item, Buyer Identifies,"
              "Seller Withdraws Item, Buyer Inserts Cash, Seller Inserts Item"
              "Buyer Withdraws Cash, Seller Withdraws Item"
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,seller_withdraw_item,[Pid,s],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {call,tradepost,seller_insertitem[Pid,ring,s],ok},
               {call,tradepost,buyer_withdrawcash,[Pid,b],ok},
               {call,tradepost,seller_withdraw_item,[Pid,s],ok},
               {loopdata,is,[undefined,undefined,s,b]}
              ]).

A little later …

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/ -eval 'eunit:test(tradepost,[verbose]).'
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> ======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly (Started Properly Test)...ok
    tradepost_tests: identify_seller (Identify Seller Test)...ok
    tradepost_tests: insert_item (Insert Item Test)...[0.001 s] ok
    tradepost_tests: withdraw_item (Withdraw Item Test)...[0.001 s] ok
    tradepost_tests: identify_buyer (Identify Buyer Test)...[0.001 s] ok
    tradepost_tests: insert_cash (Insert Cash Test)...[0.001 s] ok
    tradepost_tests: withdraw_cash (Withdraw Cash Test)...[0.001 s] ok
    tradepost_tests: interleaving1 (Seller Identifies, Inserts Item, then Buyer Identiefies)...ok
    tradepost_tests: interleaving2 (Buyer Identifies, Inserts Item, then Seller Identiefies)...ok
    tradepost_tests: interleaving3 (Buyer Identifies, Seller Identifies, buyer inserts cash)...[0.001 s] ok
    tradepost_tests: interleaving4 (Seller Identifies, Buyer Identifies, Seller inserts item)...ok
    tradepost_tests: interleaving5 (Seller Identifies, Seller inserts item, Buyer Identifies,Buyer Inserts Cash)...[0.001 s] ok
    tradepost_tests: interleaving6 (Seller Identifies, Seller inserts item, Buyer Identifies,Seller Withdraws Item, Buyer Inserts Cash, Seller Inserts ItemBuyer Withdraws Cash, Seller Withdraws Item)...[0.001 s] ok
    [done in 0.041 s]
  [done in 0.041 s]
=======================================================
  All 13 tests passed.

1>

That done, the code of tradepost.erl is now

%%%-------------------------------------------------------------------
%%% @author Gianfranco <zenon@zen.home>
%%% @copyright (C) 2010, Gianfranco
%%% Created :  2 Sep 2010 by Gianfranco <zenon@zen.home>
%%%-------------------------------------------------------------------
-module(tradepost).
-behaviour(gen_fsm).

%% API
-export([start_link/0,stop/1,seller_identify/2,seller_insertitem/3,
         seller_withdraw_item/2,buyer_identify/2,buyer_insertcash/3,
         buyer_withdrawcash/2]).

%% States
-export([pending/3,item_received/3,cash_received/3]).

%% gen_fsm callbacks
-export([init/1, handle_event/3, handle_sync_event/4, handle_info/3,
         terminate/3, code_change/4]).
-record(state, {object,cash,seller,buyer}).

%%%===================================================================
%%% API
start_link() -> gen_fsm:start_link(?MODULE, [], []).

stop(Pid) -> gen_fsm:sync_send_all_state_event(Pid,stop).

seller_identify(TradePost,Password) ->
    gen_fsm:sync_send_all_state_event(TradePost,{identify_seller,Password}).
seller_insertitem(TradePost,Item,Password) ->
    gen_fsm:sync_send_event(TradePost,{insert,Item,Password}).
seller_withdraw_item(TradePost,Password) ->
    gen_fsm:sync_send_event(TradePost,{withdraw,Password}).

buyer_identify(TradePost,Password) ->
    gen_fsm:sync_send_all_state_event(TradePost,{identify_buyer,Password}).
buyer_insertcash(TradePost,Amount,Password) ->
    gen_fsm:sync_send_event(TradePost,{insert_cash,Amount,Password}).
buyer_withdrawcash(TradePost,Password) ->
    gen_fsm:sync_send_event(TradePost,{withdraw_cash,Password}).    

%%--------------------------------------------------------------------
pending({insert,Item,Password},_Frm,LoopD = #state{seller=Password}) ->
    {reply,ok,item_received,LoopD#state{object=Item}};
pending({insert_cash,Amount,Password},_Frm,LoopD = #state{buyer=Password}) ->
    {reply,ok,cash_received,LoopD#state{cash=Amount}};
pending(_E,_From,LoopD) ->
    {reply,error,pending,LoopD}.

item_received({withdraw,Password},_Frm,LoopD = #state{seller=Password}) ->
    NewState = case LoopD#state.cash of
                   undefined -> pending;
                   _ -> cash_received
               end,
    {reply,ok,NewState,LoopD#state{object=undefined}};
item_received({withdraw_cash,Password},_Frm,LoopD = #state{buyer=Password}) ->
    NewState = case LoopD#state.object of
                   undefined -> pending;
                   _ -> item_received
               end,
    {reply,ok,NewState,LoopD#state{cash=undefined}};
item_received({insert_cash,Amount,Password},_Frm,LoopD = #state{buyer=Password})->
    {reply,ok,cash_received,LoopD#state{cash=Amount}};
item_received({insert,Item,Password},_Frm,LoopD = #state{seller=Password})->
    {reply,ok,item_received,LoopD#state{object=Item}};
item_received(_E,_From,LoopD) ->
    {reply,error,item_received,LoopD}.

cash_received({withdraw_cash,Password},_From,LoopD = #state{buyer=Password}) ->
    NewState = case LoopD#state.object of
                   undefined -> pending;
                   _ -> item_received
               end,
    {reply,ok,NewState,LoopD#state{cash=undefined}};
cash_received({withdraw,Password},_Frm,LoopD = #state{seller=Password}) ->
    NewState = case LoopD#state.cash of
                   undefined -> pending;
                   _ -> cash_received
               end,
    {reply,ok,NewState,LoopD#state{object=undefined}};
cash_received({insert_cash,Amount,Password},_Frm,LoopD = #state{buyer=Password})->
    {reply,ok,cash_received,LoopD#state{cash=Amount}};
cash_received({insert,Item,Password},_Frm,LoopD = #state{seller=Password})->
    {reply,ok,item_received,LoopD#state{object=Item}};
cash_received(_E,_From,LoopD) ->
    {reply,error,cash_received,LoopD}.

%%--------------------------------------------------------------------
handle_sync_event({identify_seller,Pass},_From,StateName,
                  LoopData=#state{seller=undefined}) ->
    {reply,ok,StateName,LoopData#state{seller=Pass}};
handle_sync_event({identify_buyer,Pass},_From,StateName,
                  LoopData=#state{buyer=undefined}) ->
    {reply,ok,StateName,LoopData#state{buyer=Pass}};
handle_sync_event(stop,_From,_StateName,LoopData) ->
    {stop,normal,ok,LoopData};
handle_sync_event(_E,_From,StateName,LoopData) ->
    {reply,error,StateName,LoopData}.

%%--------------------------------------------------------------------
init([]) -> {ok, pending, #state{}}.
handle_event(_Event, StateName, State) ->{next_state, StateName, State}.
handle_info(_Info, StateName, State) -> {next_state, StateName, State}.
terminate(_Reason, _StateName, _State) -> ok.
code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}.

And the time has inevitably come for the deal closure API (next up – in the third part), and for your convenience, the full tradepost_tests.erl

%%% @author Gianfranco <zenon@zen.home>
%%% @copyright (C) 2010, Gianfranco
%%% Created :  6 Sep 2010 by Gianfranco <zenon@zen.home>
-module(tradepost_tests).
-include_lib("eunit/include/eunit.hrl").
-include("include/eunit_fsm.hrl").

% This is the main point of "entry" for my EUnit testing.
% A generator which forces setup and cleanup for each test in the testset
main_test_() ->
    {foreach,
     fun setup/0,
     fun cleanup/1,
     % Note that this must be a List of TestSet or Instantiator
     [
      % First Iteration
      fun started_properly/1,
      % Second Iteration
      fun identify_seller/1,
      fun insert_item/1,
      fun withdraw_item/1,
      % Fourth iteration
      fun identify_buyer/1,
      fun insert_cash/1,
      fun withdraw_cash/1,
      % Fifth iteration
      fun interleaving1/1,
      fun interleaving2/1,
      fun interleaving3/1,
      fun interleaving4/1,
      fun interleaving5/1,
      fun interleaving6/1
     ]}.

% Setup and Cleanup
setup()      -> {ok,Pid} = tradepost:start_link(), Pid.
cleanup(Pid) -> tradepost:stop(Pid).

% Pure tests below
% ------------------------------------------------------------------------------
% Let's start simple, I want it to start and check that it is okay.
% I will use the introspective function for this
started_properly(Pid) ->
    ?fsm_test(Pid,"Started Properly Test",
              [{state,is,pending},
               {loopdata,is,[undefined,undefined,undefined,undefined]}
              ]).

% Now, we are adding the Seller API tests
identify_seller(Pid) ->
    ?fsm_test(Pid,"Identify Seller Test",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,seller_password],ok},
               {state,is,pending},
               {loopdata,is,[undefined,undefined,seller_password,undefined]}
              ]).

insert_item(Pid) ->
    ?fsm_test(Pid,"Insert Item Test",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,seller_password],ok},
               {call,tradepost,seller_insertitem,[Pid,playstation,seller_password],ok},
               {state,is,item_received},
               {loopdata,is,[playstation,undefined,seller_password,undefined]}
              ]).

withdraw_item(Pid) ->
    ?fsm_test(Pid,"Withdraw Item Test",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,seller_password],ok},
               {call,tradepost,seller_insertitem,[Pid,button,seller_password],ok},
               {state,is,item_received},
               {call,tradepost,seller_withdraw_item,[Pid,seller_password],ok},
               {state,is,pending},
               {loopdata,is,[undefined,undefined,seller_password,undefined]}
              ]).

identify_buyer(Pid) ->
    ?fsm_test(Pid,"Identify Buyer Test",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,buyer_password],ok},
               {state,is,pending},
               {loopdata,is,[undefined,undefined,undefined,buyer_password]}
              ]).

insert_cash(Pid) ->
    ?fsm_test(Pid,"Insert Cash Test",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,buyer_password],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,buyer_password],ok},
               {state,is,cash_received},
               {loopdata,is,[undefined,100,undefined,buyer_password]}
              ]).

withdraw_cash(Pid) ->
    ?fsm_test(Pid,"Withdraw Cash Test",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,buyer_password],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,buyer_password],ok},
               {call,tradepost,buyer_withdrawcash,[Pid,buyer_password],ok},
               {loopdata,is,[undefined,undefined,undefined,buyer_password]}
              ]).

interleaving1(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Inserts Item, then Buyer Identiefies",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {loopdata,is,[ring,undefined,s,b]}
              ]).

interleaving2(Pid) ->
    ?fsm_test(Pid,"Buyer Identifies, Inserts Item, then Seller Identiefies",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {loopdata,is,[undefined,100,s,b]}
              ]).

interleaving3(Pid) ->
    ?fsm_test(Pid,"Buyer Identifies, Seller Identifies, buyer inserts cash",
              [{state,is,pending},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {loopdata,is,[undefined,100,s,b]}
              ]).

interleaving4(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Buyer Identifies, Seller inserts item",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {loopdata,is,[ring,undefined,s,b]}
              ]).

interleaving5(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Seller inserts item, Buyer Identifies,"
              "Buyer Inserts Cash",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {loopdata,is,[ring,100,s,b]}
              ]).

interleaving6(Pid) ->
    ?fsm_test(Pid,"Seller Identifies, Seller inserts item, Buyer Identifies,"
              "Seller Withdraws Item, Buyer Inserts Cash, Seller Inserts Item"
              "Buyer Withdraws Cash, Seller Withdraws Item",
              [{state,is,pending},
               {call,tradepost,seller_identify,[Pid,s],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_identify,[Pid,b],ok},
               {call,tradepost,seller_withdraw_item,[Pid,s],ok},
               {call,tradepost,buyer_insertcash,[Pid,100,b],ok},
               {call,tradepost,seller_insertitem,[Pid,ring,s],ok},
               {call,tradepost,buyer_withdrawcash,[Pid,b],ok},
               {call,tradepost,seller_withdraw_item,[Pid,s],ok},
               {loopdata,is,[undefined,undefined,s,b]}
              ]).

EUnit Testing gen_fsm – Part 1


This post will be TDD based and shows how the Tradepost program is developed and is tested.

First iteration – Start and Stop

I start writing the test! This gives me the opportunity to crystallize my thoughts about the program.

The module implementing the tests of the Tradepost

-module(tradepost_tests).
-include_lib("eunit/include/eunit.hrl").
% This is the main point of "entry" for my EUnit testing.
% A generator which forces setup and cleanup for each test in the testset
main_test_() ->
    {foreach,
     fun setup/0,
     fun cleanup/1,
     % Note that this must be a List of TestSet or Instantiator
     % (I have instantiators == functions generating tests)
     [
      % First Iteration
      fun started_properly/1,
     ]}.

% Setup and Cleanup
setup()      -> {ok,Pid} = tradepost:start_link(), Pid.
cleanup(Pid) -> tradepost:stop(Pid).

% Pure tests below
% ------------------------------------------------------------------------------
% Let's start simple, I want it to start and check that it is okay.
% I will use the introspective function for this
started_properly(Pid) ->
    fun() ->
            ?assertEqual(pending,tradepost:introspection_statename(Pid)),
            ?assertEqual([undefined,undefined,undefined,undefined,undefined],
                         tradepost:introspection_loopdata(Pid))
    end.

Compilation and running should fail as the gen_fsm module is barely minimal

zen:EUnitFSM zenon$ tree .
.
├── ebin
├── include
├── src
│   └── tradepost.erl
└── test
    └── tradepost_tests.erl

4 directories, 2 files
zen:EUnitFSM zenon$ 

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> eunit:test(tradepost).
tradepost_tests: started_properly...*failed*
::error:{assertEqual_failed,
          [{module,tradepost_tests},
           {line,33},
           {expression,"tradepost : introspection_statename ( Pid )"},
           {expected,pending},
           {value,ok}]}
  in function tradepost_tests:'-started_properly/1-fun-0-'/2
  in call from tradepost_tests:'-started_properly/1-fun-2-'/1

module 'tradepost_tests'
*** context cleanup failed ***
::error:undef
  in function tradepost:stop/1
    called as stop(<0.39.0>)

=======================================================
  Failed: 1.  Skipped: 0.  Passed: 0.
One or more tests were cancelled.
error
2>

Clearly the tradepost does not handle the introspective functions and stop, let’s write them first.

The interface

introspection_statename(TradePost) ->
    gen_fsm:sync_send_all_state_event(TradePost,which_statename).
introspection_loopdata(TradePost) ->
    gen_fsm:sync_send_all_state_event(TradePost,which_loopdata).
stop(Pid) -> gen_fsm:sync_send_all_state_event(Pid,stop).

And the handling

handle_sync_event(which_statename, _From, StateName, LoopData) ->
    {reply, StateName, StateName, LoopData};
handle_sync_event(which_loopdata, _From, StateName, LoopData) ->
    {reply,tl(tuple_to_list(LoopData)),StateName,LoopData};
handle_sync_event(stop,_From,_StateName,LoopData) ->
    {stop,normal,ok,LoopData}.

Running

zen:EUnitFSM zenon$ erl -pa ebin/
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> eunit:test(tradepost,[verbose]).
======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly...ok
    [done in 0.004 s]
  [done in 0.005 s]
=======================================================
  Test passed.
ok
2>


Wow, I’m glad we got that sorted out. Now,  as we have set the first nail in the mountain and hooked us to it, the climb begins in a series of cycles. Next up, the Seller API.

Second Iteration – Seller API

What the seller needs, is a way to insert an item, and a way to remove an item. Also to identify him/her self with a naive password approach. Once identified, the seller (and only the seller) should be able to add and retract items.

The main_test_() has now been expanded to

% This is the main point of "entry" for my EUnit testing.
% A generator which forces setup and cleanup for each test in the testset
main_test_() ->
    {foreach,
     fun setup/0,
     fun cleanup/1,
     % Note that this must be a List of TestSet or Instantiator
     % (I have instantiators)
     [
      % First Iteration
      fun started_properly/1,
      % Second Iteration
      fun identify_seller/1,
      fun insert_item/1,
      fun withdraw_item/1
     ]}.

And the definition of the tests themselves

% Now, we are adding the Seller API tests
identify_seller(Pid) ->
    fun() ->
            % From Pending, identify seller, then state should be pending
            % loopdata should now contain seller_password
            ?assertEqual(pending,tradepost:introspection_statename(Pid)),
            ?assertEqual(ok,tradepost:seller_identify(Pid,seller_password)),
            ?assertEqual(pending,tradepost:introspection_statename(Pid)),
            ?assertEqual([undefined,undefined,seller_password,undefined,
                       undefined],tradepost:introspection_loopdata(Pid))
    end.

insert_item(Pid) ->
    fun() ->
            % From pending and identified seller, insert item
            % state should now be item_received, loopdata should now contain itm
            tradepost:introspection_statename(Pid),
            tradepost:seller_identify(Pid,seller_password),
            ?assertEqual(ok,tradepost:seller_insertitem(Pid,playstation,
                                                  seller_password)),
            ?assertEqual(item_received,tradepost:introspection_statename(Pid)),
            ?assertEqual([playstation,undefined,seller_password,undefined,
                       undefined],tradepost:introspection_loopdata(Pid))
    end.

withdraw_item(Pid) ->
    fun() ->
            % identified seller and inserted item, withdraw item
            % state should now be pending, loopdata should now contain only password
            tradepost:seller_identify(Pid,seller_password),
            tradepost:seller_insertitem(Pid,playstation,seller_password),
            ?assertEqual(ok,tradepost:withdraw_item(Pid,seller_password)),
            ?assertEqual(pending,tradepost:introspection_statename(Pid)),
            ?assertEqual([undefined,undefined,seller_password,undefined,
                       undefined],tradepost:introspection_loopdata(Pid))
    end.

Now, this is a lot of code duplication per test, and  I shall start rewriting the code into something more wieldy, but first: the failed compilation and the code making it pass.

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> eunit:test(tradepost).
tradepost_tests: identify_seller...*failed*
::error:undef
  in function tradepost:seller_identify/2
    called as seller_identify(<0.39.0>,seller_password)
  in call from tradepost_tests:'-identify_seller/1-fun-1-'/2
  in call from tradepost_tests:'-identify_seller/1-fun-4-'/1

tradepost_tests: insert_item...*failed*
::error:undef
  in function tradepost:seller_identify/2
    called as seller_identify(<0.39.0>,seller_password)
  in call from tradepost_tests:'-insert_item/1-fun-3-'/1

tradepost_tests: withdraw_item...*failed*
::error:undef
  in function tradepost:seller_identify/2
    called as seller_identify(<0.39.0>,seller_password)
  in call from tradepost_tests:'-withdraw_item/1-fun-3-'/1

=======================================================
  Failed: 3.  Skipped: 0.  Passed: 1.
error
2>

Some writing and enjoying later, the module

%%%-------------------------------------------------------------------
%%% @author Gianfranco <zenon@zen.home>
%%% @copyright (C) 2010, Gianfranco
%%% Created :  2 Sep 2010 by Gianfranco <zenon@zen.home>
%%%-------------------------------------------------------------------
-module(tradepost).
-behaviour(gen_fsm).

%% API
-export([start_link/0,introspection_statename/1,introspection_loopdata/1,
         stop/1,seller_identify/2,seller_insertitem/3,withdraw_item/2]).

%% States
-export([pending/2,pending/3,item_received/3]).

%% gen_fsm callbacks
-export([init/1, handle_event/3, handle_sync_event/4, handle_info/3,
         terminate/3, code_change/4]).
-record(state, {object,cash,seller,buyer,time}).

%%% API
start_link() -> gen_fsm:start_link(?MODULE, [], []).

introspection_statename(TradePost) ->
    gen_fsm:sync_send_all_state_event(TradePost,which_statename).
introspection_loopdata(TradePost) ->
    gen_fsm:sync_send_all_state_event(TradePost,which_loopdata).
stop(Pid) -> gen_fsm:sync_send_all_state_event(Pid,stop).

seller_identify(TradePost,Password) ->
    gen_fsm:sync_send_event(TradePost,{identify_seller,Password}).
seller_insertitem(TradePost,Item,Password) ->
    gen_fsm:sync_send_event(TradePost,{insert,Item,Password}).

withdraw_item(TradePost,Password) ->
    gen_fsm:sync_send_event(TradePost,{withdraw,Password}).

%%--------------------------------------------------------------------
pending(_Event,LoopData) -> {next_state,pending,LoopData}.

pending({identify_seller,Password},_Frm,LoopD = #state{seller=Password}) ->
    {reply,ok,pending,LoopD};
pending({identify_seller,Password},_Frm,LoopD = #state{seller=undefined}) ->
    {reply,ok,pending,LoopD#state{seller=Password}};
pending({identify_seller,_},_,LoopD) ->
    {reply,error,pending,LoopD};

pending({insert,Item,Password},_Frm,LoopD = #state{seller=Password}) ->
    {reply,ok,item_received,LoopD#state{object=Item}};
pending({insert,_,_},_Frm,LoopD) ->
    {reply,error,pending,LoopD}.

item_received({withdraw,Password},_Frm,LoopD = #state{seller=Password}) ->
    {reply,ok,pending,LoopD#state{object=undefined}};
item_received({withdraw,_},_Frm,LoopD) ->
    {reply,error,item_received,LoopD}.

%%--------------------------------------------------------------------
handle_sync_event(which_statename, _From, StateName, LoopData) ->
    {reply, StateName, StateName, LoopData};
handle_sync_event(which_loopdata, _From, StateName, LoopData) ->
    {reply,tl(tuple_to_list(LoopData)),StateName,LoopData};
handle_sync_event(stop,_From,_StateName,LoopData) ->
    {stop,normal,ok,LoopData};
handle_sync_event(_E,_From,StateName,LoopData) ->
    {reply,ok,StateName,LoopData}.

%%--------------------------------------------------------------------
init([]) -> {ok, pending, #state{}}.
handle_event(_Event, StateName, State) ->{next_state, StateName, State}.
handle_info(_Info, StateName, State) -> {next_state, StateName, State}.
terminate(_Reason, _StateName, _State) -> ok.
code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}.

And proof for the functioning of it.

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/ -eval 'eunit:test(tradepost,[verbose]).'
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> ======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly...ok
    tradepost_tests: identify_seller...ok
    tradepost_tests: insert_item...ok
    tradepost_tests: withdraw_item...ok
    [done in 0.015 s]
  [done in 0.015 s]
=======================================================
  All 4 tests passed.
1>

Awesome! And we got a bonus as well: how to run eunit directly from the command line with the -eval command. Cool, oneliners always make you feel more “1337”.

It all looks very good so far, but I will use the third iteration to fixing up the eunit module, it has way to much duplication and could be made more declarative (specifying what should be computed – not how [ which is kind of more abstract <of course someone will oppose>]).

Third Iteration –  Eunit GenFSM DSL (do not worry)

Testing gen_fsm’s should ideally be all about testing state transitions, in-state computations and variables. For this purpose, I would like to have my DSL that handles all of the pesky details for me.

To exemplify, I would like to write the first test

started_properly(Pid) ->
    fun() ->
            ?assertEqual(pending,tradepost:introspection_statename(Pid)),
            ?assertEqual([undefined,undefined,undefined,undefined,undefined],
                         tradepost:introspection_loopdata(Pid))
    end.

as something along these lines

started_properly(Pid) ->
    {"Proper startup test",
     [{statename,is,pending},
      {loopdata,is,[undefined,undefined,undefined,undefined,undefined]}
      ]}.

And, this test

insert_item(Pid) ->
    fun() ->
        % From pending and identified seller, insert item
        % state should now be item_received, loopdata should now contain itm
        tradepost:introspection_statename(Pid),
        tradepost:seller_identify(Pid,seller_password),
        ?assertEqual(ok,tradepost:seller_insertitem(Pid,playstation,
                                              seller_password)),
        ?assertEqual(item_received,tradepost:introspection_statename(Pid)),
        ?assertEqual([playstation,undefined,seller_password,undefined,
                   undefined],tradepost:introspection_loopdata(Pid))
    end.

as something along these lines

insert_item(Pid) ->
    {"Insert Item Test",
      [{state,is,pending},
       {call,tradepost,seller_identify,[Pid,seller_password],ok},
       {call,tradepost,seller_insertitem,[Pid,playstation,seller_password]},
       {state,is,item_received},
       {loopdata,is,[playstation,undefined,seller_password,undefined,undefined]}
      ]}.

This is a symbolic method that defines our DSL in a yet readable way, hiding the logic. For this to work, we need a translation from our DSL to actual EUnit syntax without losing the EUnit machinery. We will also drop the intrusive introspective functions for the usage of the better sys:get_status/1 (thank you Ulf).

Thus, let the journey begin, first with the translation of the Test. This can be done in two ways, either at runtime or at compile time with parse-transforms. I choose the runtime one with translation functions and macros. Ulf Wiger has a neat library for cooler parse transforms, but I shall not use this for now, (the code will probably be revised many times)

The test module has now been changed to

-module(tradepost_tests).
-include_lib("eunit/include/eunit.hrl").
-include("include/eunit_fsm.hrl").

% This is the main point of "entry" for my EUnit testing.
% A generator which forces setup and cleanup for each test in the testset
main_test_() ->
    {foreach,
     fun setup/0,
     fun cleanup/1,
     % Note that this must be a List of TestSet or Instantiator
     [
      % First Iteration
      fun started_properly/1,
      % Second Iteration
      fun identify_seller/1,
      fun insert_item/1,
      fun withdraw_item/1
     ]}.

% Setup and Cleanup
setup()      -> {ok,Pid} = tradepost:start_link(), Pid.
cleanup(Pid) -> tradepost:stop(Pid).

% Pure tests below
% ------------------------------------------------------------------------------
% Let's start simple, I want it to start and check that it is okay.
% I will use the introspective function for this
started_properly(Pid) ->
    ?fsm_test(tradepost,Pid,"Started Properly Test",
      [{state,is,pending},
       {loopdata,is,[undefined,undefined,undefined,undefined,undefined]}
     ]).

% Now, we are adding the Seller API tests
identify_seller(Pid) ->
    ?fsm_test(Pid,"Identify Seller Test",
      [{state,is,pending},
       {call,tradepost,seller_identify,[Pid,seller_password],ok},
       {state,is,pending},
       {loopdata,is,[undefined,undefined,seller_password,undefined,undefined]}
      ]).

insert_item(Pid) ->
    ?fsm_test(Pid,"Insert Item Test",
       [{state,is,pending},
        {call,tradepost,seller_identify,[Pid,seller_password],ok},
        {call,tradepost,seller_insertitem,[Pid,playstation,seller_password],ok},
        {state,is,item_received},
        {loopdata,is,[playstation,undefined,seller_password,undefined,undefined]}
       ]).

withdraw_item(Pid) ->
    ?fsm_test(Pid,"Withdraw Item Test",
       [{state,is,pending},
        {call,tradepost,seller_identify,[Pid,seller_password],ok},
        {call,tradepost,seller_insertitem,[Pid,button,seller_password],ok},
        {state,is,item_received},
        {call,tradepost,seller_withdraw_item,[Pid,seller_password],ok},
        {state,is,pending},
        {loopdata,is,[undefined,undefined,seller_password,undefined,undefined]}
       ]).

And the supporting logic is found in eunit_fsm.hrl

-define(fsm_test(Id,Title,CmdList),
  {Title,fun() -> [ eunit_fsm:translateCmd(Id,Cmd) || Cmd <- CmdList] end}).

together with eunit_fsm.erl

-module(eunit_fsm).
-export([translateCmd/2,get/2]).
-define(Expr(X),??X).
translateCmd(Id,{state,is,X}) ->
    case get(Id,"StateName") of
        X -> true;
        _V ->  .erlang:error({statename_match_failed,
                              [{module, ?MODULE},
                               {line, ?LINE},
                               {expected, X},
                               {value, _V}]})
    end;
translateCmd(_Id,{call,M,F,A,X}) ->
    case apply(M,F,A) of
        X -> ok;
        _V ->  .erlang:error({function_call_match_failed,
                              [{module, ?MODULE},
                               {line, ?LINE},
                               {expression, ?Expr(apply(M,F,A))},
                               {expected, X},
                               {value, _V}]})
    end;
translateCmd(Id,{loopdata,is,X}) ->
    case tl(tuple_to_list(get(Id,"StateData"))) of
        X    -> true;
        _V ->    .erlang:error({loopdata_match_failed,
                                [{module, ?MODULE},
                                 {line, ?LINE},
                                 {expected, X},
                                 {value, _V}]})
    end.

% StateName or StateData
get(Id,Which) ->
    {status,_Pid,_ModTpl, List} = sys:get_status(Id),
    AllData = lists:flatten([ X || {data,X} <- lists:last(List) ]),
    proplists:get_value(Which,AllData).

Now, we have a method of expressing the tests more clearly, next up is the buyer API. Testing if of the essence!

zen:EUnitFSM zenon$ tree .
.
├── ebin
├── include
│   └── eunit_fsm.hrl
├── src
│   └── tradepost.erl
└── test
    ├── eunit_fsm.erl
    └── tradepost_tests.erl

4 directories, 4 files
zen:EUnitFSM zenon$ 

Compile and run

zen:EUnitFSM zenon$ erlc -o ebin/ src/*.erl test/*.erl
zen:EUnitFSM zenon$ erl -pa ebin/ -eval 'eunit:test(tradepost,[verbose]).'
Erlang R13B04 (erts-5.7.5) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> ======================== EUnit ========================
module 'tradepost'
  module 'tradepost_tests'
    tradepost_tests: started_properly (Started Properly Test)...[0.001 s] ok
    tradepost_tests: identify_seller (Identify Seller Test)...ok
    tradepost_tests: insert_item (Insert Item Test)...ok
    tradepost_tests: withdraw_item (Withdraw Item Test)...ok
    [done in 0.014 s]
  [done in 0.014 s]
=======================================================
  All 4 tests passed.

1>

And so, it works. Next part is adding buyer API and extending the DSL where needed, also maybe rewriting it with Ulf’s awesome parse transform libs.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: