Created
April 5, 2016 02:55
-
-
Save andrewshatnyy/fa99d4a643df520e5385e06c66365bdb to your computer and use it in GitHub Desktop.
Gen FSM in elixir example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule SipsMatcher do | |
require :gen_fsm | |
def consume_s(fsm) do | |
:gen_fsm.sync_send_event(fsm, :s) | |
end | |
def consume_not_s(fsm) do | |
:gen_fsm.sync_send_event(fsm, :not_s) | |
end | |
def consume_i(fsm) do | |
:gen_fsm.sync_send_event(fsm, :i) | |
end | |
def consume_p(fsm) do | |
:gen_fsm.sync_send_event(fsm, :p) | |
end | |
def start_link do | |
{:ok, fsm} = :gen_fsm.start_link(__MODULE__, [], []) | |
fsm | |
end | |
def init(_) do | |
{:ok, :starting, []} | |
end | |
def got_s(:i, _from, state) do | |
{:reply, :got_si, :got_si, state} | |
end | |
def got_si(:p, _from, state) do | |
{:reply, :got_sip, :got_sip, state} | |
end | |
def got_sip(:s, _from, state) do | |
{:reply, :got_sips, :got_sips, state} | |
end | |
def got_sip(:not_s, _from, state) do | |
{:reply, :got_sips, :got_sips, state} | |
end | |
def got_sips(_, _from, state) do | |
{:reply, :got_sips, :got_sips, state} | |
end | |
def starting(:s, _from, state_data) do | |
{:reply, :got_s, :got_s, state_data} | |
end | |
def starting(:not_s, _from, state_data) do | |
{:reply, :starting, :starting, state_data} | |
end | |
def starting(:not_s, _from, state_data) do | |
{:reply, :starting, :starting, state_data} | |
end | |
end | |
defmodule SipsMatcherTest do | |
use ExUnit.Case | |
test "[:starting] it takes 's' " do | |
fsm = SipsMatcher.start_link | |
assert SipsMatcher.consume_s(fsm) == :got_s | |
end | |
test "[:starting] it takes 'not_s' " do | |
fsm = SipsMatcher.start_link | |
assert SipsMatcher.consume_not_s(fsm) == :starting | |
end | |
test "takes all right chars" do | |
fsm = SipsMatcher.start_link | |
SipsMatcher.consume_s(fsm) | |
SipsMatcher.consume_i(fsm) | |
SipsMatcher.consume_p(fsm) | |
SipsMatcher.consume_s(fsm) == :got_sips | |
end | |
test "comes back to initial state" do | |
fsm = SipsMatcher.start_link | |
SipsMatcher.consume_s(fsm) | |
SipsMatcher.consume_i(fsm) | |
SipsMatcher.consume_p(fsm) | |
assert SipsMatcher.consume_not_s(fsm) == :starting | |
end | |
test "stays with the same state" do | |
fsm = SipsMatcher.start_link | |
SipsMatcher.consume_s(fsm) | |
SipsMatcher.consume_i(fsm) | |
SipsMatcher.consume_p(fsm) | |
SipsMatcher.consume_s(fsm) | |
SipsMatcher.consume_not_s(fsm) == :got_sips | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment