Skip to content
This repository
branch: statem
Fetching contributors…

Cannot retrieve contributors at this time

file 481 lines (431 sloc) 20.813 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
%%% Copyright 2010-2011 Manolis Papadakis <manopapad@gmail.com>,
%%% Eirini Arvaniti <eirinibob@gmail.com>
%%% and Kostis Sagonas <kostis@cs.ntua.gr>
%%%
%%% This file is part of PropEr.
%%%
%%% PropEr is free software: you can redistribute it and/or modify
%%% it under the terms of the GNU General Public License as published by
%%% the Free Software Foundation, either version 3 of the License, or
%%% (at your option) any later version.
%%%
%%% PropEr is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
%%% You should have received a copy of the GNU General Public License
%%% along with PropEr. If not, see <http://www.gnu.org/licenses/>.

%%% @copyright 2010-2011 Manolis Papadakis <manopapad@gmail.com>,
%%% Eirini Arvaniti <eirinibob@gmail.com>
%%% and Kostis Sagonas <kostis@cs.ntua.gr>
%%% @version {@version}
%%% @author Eirini Arvaniti <eirinibob@gmail.com>

%%% @doc This module contains functions for testing stateful systems that
%%% can be modeled as a finite state machine. That is, a finite collection
%%% of named states and transitions between them. `{@module}' is closely related
%%% to {@link proper_statem} and, in fact, implemented in terms of that. Test
%%% cases generated using `{@module}' will be on precisely the same form as
%%% test cases generated using {@link proper_statem}. The difference lies
%%% in the way the callback modules are specified. On the whole, the relation
%%% between {@link proper_statem} and `{@module}' can be considered similar
%%% to the one between `gen_server' and `gen_fsm' in OTP libraries.
%%%
%%% Due to name conflicts with functions automatically imported from
%%% {@link proper_statem}, a fully qualified call is needed in order to
%%% use the <a href="#index">API functions </a> of `{@module}'.
%%%
%%% == State representation ==
%%% Following the convention used in `gen_fsm behaviour', the state is
%%% separated into a `StateName::'{@type state_name()} and some
%%% `StateData::'{@type state_data()}. `StateName' is used to denote a state
%%% of the finite state machine and `StateData' is any relevant information
%%% that has to be stored in the testcase state. States are fully
%%% represented as tuples `{StateName, StateData}'.
%%%
%%% `StateName' is usually an atom (i.e. the name of the state), but can also
%%% be a tuple. In the latter case, the first element of the tuple must be an
%%% atom specifying the name of the state, whereas the rest of the elements can
%%% be arbitrary terms specifying state attributes. For example, when
%%% implementing the fsm of an elevator which can reach N different floors, the
%%% `StateName' for each floor could be `{floor,K}, 1 <= K <= N'.<br/>
%%% `StateData' can be an arbitrary term, but is usually a record.
%%%
%%% == Transition represantation ==
%%% A transition ({@type transition()}) is represented as a tuple
%%% `{TargetState, {call,M,F,A}}'. This means that performing the specified
%%% symbolic call at the current state of the fsm will lead to `TargetState'.
%%% The atom `history' can be used as `TargetState' to denote that a transition
%%% does not change the current state of the fsm.
%%%
%%% == Callback functions ==
%%% The following functions must be exported from the callback module
%%% implementing the finite state machine:
%%% <ul>
%%% <li> `initial_state() ::' {@type state_name()}
%%% <p>Specifies the initial state of the finite state machine. As with
%%% `proper_statem:initial_state/0', its result should be deterministic.
%%% </p></li>
%%% <li> `initial_state_data() ::' {@type state_data()}
%%% <p>Specifies what the state data should initially contain. Its result
%%% should be deterministic.</p></li>
%%% <li> `StateName(S::'{@type state_data()}`) ::'
%%% `['{@type transition()}`]'
%%% <p>There should be one instance of this function for each reachable
%%% state `StateName' of the finite state machine. In case `StateName' is a
%%% tuple the function takes a different form, described just below. The
%%% function returns a list of possible transitions from the current state.
%%% At command generation time, the instance of this function with the same
%%% name as the current state's name is called to return the list of possible
%%% transitions. Then, PropEr will randomly choose a transition and,
%%% according to that, generate the next symbolic call to be included in the
%%% command sequence. However, before the call is actually included, a
%%% precondition that might impose constraints on `StateData' is checked.<br/>
%%% Note also that PropEr detects transitions that would raise an exception
%%% of class `<error>' at generation time (not earlier) and does not choose
%%% them. This feature can be used to include conditional transitions that
%%% depend on the `StateData'.</p></li>
%%% <li> `StateName(Attr1::term(), ..., AttrN::term(),
%%% S::'{@type state_data()}`) ::'
%%% `['{@type transition()}`]'
%%% <p>There should be one instance of this function for each reachable state
%%% `{StateName,Attr1,...,AttrN}' of the finite state machine. The function
%%% has similar beaviour to `StateName/1', described above.</p></li>
%%% <li> `weight(From::'{@type state_name()}`,
%%% Target::'{@type state_name()}`,
%%% Call::'{@type symb_call()}`) :: integer()'
%%% <p>This is an optional callback. When it is not defined (or not exported),
%%% transitions are chosen with equal probability. When it is defined, it
%%% assigns an integer weight to transitions from `From' to `Target'
%%% triggered by symbolic call `Call'. In this case, each transition is chosen
%%% with probability proportional to the weight assigned.</p></li>
%%% <li> `precondition(From::'{@type state_name()}`,
%%% Target::'{@type state_name()}`,
%%% StateData::'{@type state_data()}`,
%%% Call::'{@type symb_call()}`) :: boolean()'
%%% <p>Similar to `proper_statem:precondition/2'. Specifies the
%%% precondition that should hold about `StateData' so that `Call' can be
%%% included in the command sequence. In case precondition doesn't hold, a
%%% new transition is chosen using the appropriate `StateName/1' generator.
%%% It is possible for more than one transitions to be triggered by the same
%%% symbolic call and lead to different target states. In this case, at most
%%% one of the target states may have a true precondition. Otherwise, PropEr
%%% will not be able to detect which transition was chosen and an exception
%%% will be raised.<br/>
%%% Preconditions are also very important for the shrinking procedure. When
%%% shrinking command sequences, we try to eliminate commands that do not
%%% contribute to failure, ensuring that all preconditions still hold.</p>
%%% </li>
%%% <li> `postcondition(From::'{@type state_name()}`,
%%% Target::'{@type state_name()}`,
%%% StateData::'{@type state_data()}`,
%%% Call::'{@type symb_call()}`,
%%% Res::'{@type result()}`) :: boolean()'
%%% <p>Similar to `proper_statem:postcondition/3'. Specifies the
%%% postcondition that should hold about the result `Res' of the evaluation
%%% of `Call'.</p></li>
%%% <li> `next_state_data(From::'{@type state_name()}`,
%%% Target::'{@type state_name()}`,
%%% StateData::'{@type state_data()}`,
%%% Res::'{@type result()}`,
%%% Call::'{@type symb_call()}`) ::'
%%% {@type state_data()}
%%% <p>Similar to `proper_statem:next_state/3'. Specifies how the
%%% transition from `FromState' to `Target' triggered by `Call' affects the
%%% `StateData'. `Res' refers to the result of `Call' and can be either
%%% symbolic or dynamic.</p></li>
%%% </ul>
%%%
%%% == Property for testing finite state machines ==
%%% This is an example of a property to test an fsm specification:
%%%
%%% ```prop_fsm() ->
%%% ?FORALL(Cmds, proper_fsm:commands(?MODULE),
%%% begin
%%% {H,S,Res} = proper_fsm:run_commands(?MODULE, Cmds),
%%% cleanup(),
%%% ?WHENFAIL(io:format("History: ~w\nState: ~w\nRes: ~w\n",
%%% [H,S,Res]),
%%% aggregate(zip(proper_fsm:state_names(H),
%%% command_names(Cmds)),
%%% Res =:= ok))
%%% end).'''
%%% @end

-module(proper_fsm).
-export([commands/1, commands/2]).
-export([run_commands/2, run_commands/3]).
-export([state_names/1]).

-export([initial_state/1, command/1, precondition/2, next_state/3,
postcondition/3]).
-export([target_states/4]).

-include("proper_internal.hrl").


%% -----------------------------------------------------------------------------
%% Type declarations
%% -----------------------------------------------------------------------------

-type symb_var() :: proper_statem:symb_var().
-type symb_call() :: proper_statem:symb_call().
-type fsm_result() :: proper_statem:statem_result().

-type state_name() :: atom() | tuple().
-type state_data() :: term().
-type fsm_state() :: {state_name(),state_data()}.
-type transition() :: {state_name(),symb_call()}.
-type result() :: term().
-type command() :: {'init',fsm_state()}
| {'set',symb_var(),symb_call()}.
-type command_list() :: [command()].
-type history() :: [{fsm_state(),result()}].
-type tmp_command() :: {'init',state()}
| {'set',symb_var(),symb_call()}.

-record(state, {name :: state_name(),
data :: state_data(),
mod :: mod_name()}).
-type state() :: #state{}.


%% -----------------------------------------------------------------------------
%% API
%% -----------------------------------------------------------------------------

%% @spec commands(mod_name()) -> proper_types:type()
%% @doc A special PropEr type which generates random command sequences,
%% according to an finite state machine specification. The function takes as
%% input the name of a callback module, which contains the fsm specification.
%% The initial state is computed by <br/>
%% `{Mod:initial_state/0, Mod:initial_state_data/0}'.

-spec commands(mod_name()) -> proper_types:type().
commands(Mod) ->
    ?LET([_|Cmds],
proper_statem:commands(?MODULE, initial_state(Mod)),
Cmds).

%% @spec commands(mod_name(), fsm_state()) -> proper_types:type()
%% @doc Similar to {@link commands/1}, but generated command sequences always
%% start at a given state. In this case, the first command is always <br/>
%% `{init, InitialState = {Name,Data}}' and is used to correctly initialize the
%% state every time the command sequence is run (i.e. during normal execution,
%% while shrinking and when checking a counterexample).

-spec commands(mod_name(), fsm_state()) -> proper_types:type().
commands(Mod, {Name,Data} = InitialState) ->
    State = #state{name = Name, data = Data, mod = Mod},
    ?LET([_|Cmds],
proper_statem:commands(?MODULE, State),
[{init,InitialState}|Cmds]).

%% @spec run_commands(mod_name(), command_list()) ->
%% {history(),fsm_state(),fsm_result()}
%% @doc Evaluates a given symbolic command sequence `Cmds' according to the
%% finite state machine specified in `Mod'. The result is a triple of the
%% form<br/> `{History, FsmState, Result}', similar to
%% {@link proper_statem:run_commands/2}.

-spec run_commands(mod_name(), command_list()) ->
         {history(),fsm_state(),fsm_result()}.
run_commands(Mod, Cmds) ->
    run_commands(Mod, Cmds, []).

%% @spec run_commands(mod_name(), command_list(), proper_symb:var_values()) ->
%% {history(),fsm_state(),fsm_result()}
%% @doc Similar to {@link run_commands/2}, but also accepts an environment
%% used for symbolic variable evaluation, exactly as described in
%% {@link proper_statem:run_commands/3}.

-spec run_commands(mod_name(), command_list(), proper_symb:var_values()) ->
         {history(),fsm_state(),fsm_result()}.
run_commands(Mod, Cmds, Env) ->
    Cmds1 = tmp_commands(Mod, Cmds),
    {H,S,Res} = proper_statem:run_commands(?MODULE, Cmds1, Env),
    History = [{{Name,Data},R} || {#state{name = Name, data = Data},R} <- H],
    State = {S#state.name, S#state.data},
    {History, State, Res}.

%% @spec state_names(history()) -> [state_name()]
%% @doc Extracts the names of the states from a given command execution history.
%% It is useful in combination with functions such as {@link proper:aggregate/2}
%% in order to collect statistics about state transitions during command
%% execution.

-spec state_names(history()) -> [state_name()].
state_names(History) ->
    [SName || {{SName,_},_Res} <- History].


%% -----------------------------------------------------------------------------
%% State machine specification for fsm commands
%% -----------------------------------------------------------------------------

%% @private
-spec initial_state(mod_name()) -> state().
initial_state(Mod) ->
    S_name = Mod:initial_state(),
    S_data = Mod:initial_state_data(),
    #state{name = S_name, data = S_data, mod = Mod}.

%% @private
-spec command(state()) -> proper_types:type().
command(#state{name = From, data = Data, mod = Mod}) ->
    choose_transition(Mod, From, get_transitions(Mod, From, Data)).

%% @private
-spec precondition(state(), symb_call()) -> boolean().
precondition(#state{name = From, data = Data, mod = Mod}, Call) ->
    Targets = target_states(Mod, From, Data, Call),
    case [To || To <- Targets,
Mod:precondition(From, cook_history(From, To), Data, Call)] of
[] -> false;
[_T] -> true
    end.

%% @private
-spec next_state(state(), symb_var() | result(), symb_call()) -> state().
next_state(S = #state{name = From, data = Data, mod = Mod} , Var, Call) ->
    To = cook_history(From, transition_target(Mod, From, Data, Call)),
    S#state{name = To,
data = Mod:next_state_data(From, To, Data, Var, Call)}.

%% @private
-spec postcondition(state(), symb_call(), result()) -> boolean().
postcondition(#state{name = From, data = Data, mod = Mod}, Call, Res) ->
    To = cook_history(From, transition_target(Mod, From, Data, Call)),
    Mod:postcondition(From, To, Data, Call, Res).


%% -----------------------------------------------------------------------------
%% Utility functions
%% -----------------------------------------------------------------------------

-spec tmp_commands(mod_name(), command_list()) -> [tmp_command()].
tmp_commands(Mod, Cmds) ->
    case Cmds of
[{init, {Name,Data}}|Rest] ->
I = #state{name = Name, data = Data, mod = Mod},
[{init,I}|Rest];
Rest ->
I = initial_state(Mod),
[{init,I}|Rest]
    end.

-spec get_transitions(mod_name(), state_name(), state_data()) ->
         [transition()].
get_transitions(Mod, StateName, Data) ->
    case StateName of
From when is_atom(From) ->
Mod:From(Data);
From when is_tuple(From) ->
Fun = element(1, From),
Args = tl(tuple_to_list(From)),
apply(Mod, Fun, Args ++ [Data])
    end.

-spec choose_transition(mod_name(), state_name(), [transition()]) ->
         proper_types:type().
choose_transition(Mod, From, T_list) ->
    case is_exported(Mod, {weight,3}) of
false ->
choose_uniform_transition(T_list);
true ->
choose_weighted_transition(Mod, From, T_list)
    end.

-spec choose_uniform_transition([transition()]) -> proper_types:type().
choose_uniform_transition(T_list) ->
    List = [CallGen || {_,CallGen} <- T_list],
    safe_union(List).

-spec choose_weighted_transition(mod_name(), state_name(), [transition()]) ->
         proper_types:type().
choose_weighted_transition(Mod, From, T_list) ->
    List = [{Mod:weight(From, cook_history(From, To), CallGen), CallGen}
|| {To,CallGen} <- T_list],
    safe_weighted_union(List).

-spec cook_history(state_name(), state_name()) -> state_name().
cook_history(From, history) -> From;
cook_history(_, To) -> To.

-spec is_exported(mod_name(), {fun_name(),arity()}) -> boolean().
is_exported(Mod, Fun) ->
    lists:member(Fun, Mod:module_info(exports)).

-spec transition_target(mod_name(), state_name(), state_data(), symb_call()) ->
         state_name().
transition_target(Mod, From, Data, Call) ->
    Targets = target_states(Mod, From, Data, Call),
    hd([T || T <- Targets,
Mod:precondition(From, cook_history(From, T), Data, Call)]).

%% @private
-spec target_states(mod_name(), state_name(), state_data(), symb_call()) ->
         [state_name()].
target_states(Mod, From, StateData, Call) ->
    find_target(get_transitions(Mod, From, StateData), Call, []).

-spec find_target([transition()], symb_call(), [state_name()]) ->
         [state_name()].
find_target([], _, Accum) -> Accum;
find_target(Transitions, Call, Accum) ->
    [{Target,CallGen}|Rest] = Transitions,
    case is_compatible(Call, CallGen) of
true -> find_target(Rest, Call, [Target|Accum]);
false -> find_target(Rest, Call, Accum)
    end.

-spec is_compatible(symb_call(), symb_call()) -> boolean().
is_compatible({call,M,F,A1}, {call,M,F,A2})
  when length(A1) =:= length(A2) ->
    true;
is_compatible(_, _) ->
    false.


%% -----------------------------------------------------------------------------
%% Special types and generators
%% -----------------------------------------------------------------------------

%% @private
-spec safe_union([proper_types:raw_type(),...]) -> proper_types:type().
safe_union(RawChoices) ->
    Choices = [proper_types:cook_outer(C) || C <- RawChoices],
    proper_types:subtype(
      [{generator, fun() -> safe_union_gen(Choices) end}],
      proper_types:union(Choices)).

%% @private
-spec safe_weighted_union([{frequency(),proper_types:raw_type()},...]) ->
         proper_types:type().
safe_weighted_union(RawFreqChoices) ->
    CookFreqType = fun({Freq,RawType}) ->
{Freq,proper_types:cook_outer(RawType)} end,
    FreqChoices = lists:map(CookFreqType, RawFreqChoices),
    Choices = [T || {_F,T} <- FreqChoices],
    proper_types:subtype(
      [{generator, fun() -> safe_weighted_union_gen(FreqChoices) end}],
      proper_types:union(Choices)).

%% @private
-spec safe_union_gen([proper_types:type(),...]) -> proper_gen:imm_instance().
safe_union_gen(Choices) ->
    {Choice,Type} = proper_arith:rand_choose(Choices),
    try proper_gen:generate(Type)
    catch
error:_ ->
safe_union_gen(proper_arith:list_remove(Choice, Choices))
    end.

%% @private
-spec safe_weighted_union_gen([{frequency(),proper_types:type()},...]) ->
         proper_gen:imm_instance().
safe_weighted_union_gen(FreqChoices) ->
    {Choice,Type} = proper_arith:freq_choose(FreqChoices),
    try proper_gen:generate(Type)
    catch
error:_ ->
safe_weighted_union_gen(proper_arith:list_remove(Choice,
FreqChoices))
    end.


%% @type symb_var() = proper_statem:symb_var().
%% Symbolic term to which we bind the result of a command.
%% @type symb_call() = proper_statem:symb_call().
%% Symbolic term which will be evaluated to a function call.
%% @type fsm_result() = proper_statem:statem_result().
%% Specifies the overall result of command execution. It can be one of following:
%% <ul>
%% <li><b>ok</b>
%% <p>All commands were successfully run and all postconditions were true</p>
%% </li>
%% <li><b>initialization_error</b>
%% <p>There was an error while evaluating the initial state.</p>
%% </li>
%% <li><b>postcondition</b>
%% <p>A postcondition was false or raised an exception.</p>
%% </li>
%% <li><b>precondition</b>
%% <p>A precondition was false or raised an exception.</p>
%% </li>
%% <li><b>exception</b>
%% <p>An exception was raised while running a command.</p>
%% </li>
%% </ul>
%% @type state_name() = atom() | tuple().
%% A named state of the fsm.
%% @type state_data() = term().
%% Internal state of the fsm.
%% @type fsm_state() = {state_name(),state_data()}.
%% Full specification of fsm state.
%% @type transition() = {state_name(),symb_call()}.
%% The target state of a transition zipped with the call triggering it.
%% @type result() = term().
%% The actual result of executing a command.
%% @type command() = {'init',fsm_state()}
%% | {'set',symb_var(),symb_call()}.
%% Symbolic term used to bind the result of a symbolic call to a symbolic
%% variable or to initialize the state.
%% @type command_list() = [command()].
%% List of symbolic commands.
%% @type history() = [{fsm_state(),result()}].
%% History of command execution. Contains the dynamic state prior to command
%% execution and the actual result, for each command that was executed without
%% raising an exception.
Something went wrong with that request. Please try again.