Now a working demo of FSM and DBC for the blog post.

main
Zed A. Shaw 3 months ago
parent 67264ca941
commit d498ae8d6a
  1. 1
      .gitignore
  2. 23
      python/dbc.py
  3. 26
      python/dbc_test.py
  4. 55
      python/fsm.py
  5. 8
      python/fsm_test.py
  6. 3
      status.txt

1
.gitignore vendored

@ -14,3 +14,4 @@ subprojects
*.dll
*~
[0-9]*
__pycache__

@ -0,0 +1,23 @@
import traceback
class DBCError(Exception): pass
class CheckError(DBCError): pass
class PreError(DBCError): pass
class PostError(DBCError): pass
class SentinelError(DBCError): pass
def check(test, msg, cls=CheckError):
print(">>> ", msg)
traceback.print_stack(limit=-1)
if not test:
raise cls(msg)
def pre(test, msg):
check(test, msg, PreError)
def post(test, msg):
check(test, msg, PostError)
def sentinel():
traceback.print_stack(limit=-1)
raise SentinelError()

@ -0,0 +1,26 @@
import dbc
import traceback
print("---- CHECK ---")
try:
dbc.check(1 == 2, "Check Failed!")
except dbc.CheckError as e:
print("Check failure:", e)
print("---- SENTINEL ---")
try:
dbc.sentinel()
except dbc.SentinelError as e:
print("Sentinel failure:", e)
print("---- PRECOND ---")
try:
dbc.pre(1 == 2, "Pre Failed!")
except dbc.PreError as e:
print("Pre condition failure: ", e)
print("---- POSTCOND ---")
try:
dbc.post(1 == 2, "Post Failed!")
except dbc.PostError as e:
print("Post condition failure:", e)

@ -0,0 +1,55 @@
def START():
return LISTENING
def LISTENING(event):
if event == "connect":
return CONNECTED
elif event == "error":
return LISTENING
else:
return ERROR
def CONNECTED(event):
if event == "accept":
return ACCEPTED
elif event == "close":
return CLOSED
else:
return ERROR
def ACCEPTED(event):
if event == "close":
return CLOSED
elif event == "read":
return READING(event)
elif event == "write":
return WRITING(event)
else:
return ERROR
def READING(event):
if event == "read":
return READING
elif event == "write":
return WRITING(event)
elif event == "close":
return CLOSED
else:
return ERROR
def WRITING(event):
if event == "read":
return READING(event)
elif event == "write":
return WRITING
elif event == "close":
return CLOSED
else:
return ERROR
def CLOSED(event):
return LISTENING(event)
def ERROR(event):
return ERROR

@ -0,0 +1,8 @@
import fsm
state = fsm.START()
script = ["connect", "accept", "read", "read", "write", "close", "connect"]
for event in script:
print(event, ">>>", state)
state = state(event)

@ -0,0 +1,3 @@
Welcome!
Working on a blog post about Finite State Machines and Design-by-Contract. Feel free to ask for advice about anything programming or art related.
Loading…
Cancel
Save