How to use set_actionnames method in fMBT

Best Python code snippet using fMBT_python

lsts.py

Source:lsts.py Github

copy

Full Screen

...34***35Example I: write a three-state LSTS to file out.lsts:36import lsts37w = lsts.writer( file("out.lsts","w") )38w.set_actionnames( ["tau","action1","action2"] )39w.set_transitions( [ [(1,0),(0,0)], [(0,2),(2,1)], [] ] )40w.write()41***42Example II: read lsts from stdin, rename the first non-tau action and43write the lsts to stdout.44import sys45import lsts46r = lsts.reader(sys.stdin)47r.get_actionnames()[1]="new name"48lsts.writer(sys.stdout,r)49***50Example III: list action names used in the transitions51import lsts52r = lsts.reader(sys.stdin)53used_actions=[]54for source_state, transition_list in enumerate(r.get_transitions()):55 for dest_state, action_number in transition_list:56 if not action_number in used_actions:57 used_actions.append( action_number )58 print r.get_actionnames()[ action_number ]59***60Helper classes and functions61class fakefile can be used to create a file-like object from a62string. The object can be used for reading and writing LSTSs. For63example, if string s contains an LSTS64r=lsts.reader(fakefile(s))65r.read()66reads the LSTS in s.67props_by_states(lsts_object) returns table indexed with state68numbers. The table includes lists of state proposition numbers. For69example,70props_by_states(r)[42]71returns list of numbers of propositions true in state 42. To convert72the number of a state proposition to a name, index alphabetically73ordered list of state proposition keys with it:74stateproplist=r.get_stateprops().keys()75stateproplist.sort()76name_of_prop=stateproplist[num_of_a_stateprop]77"""78version="0.522 svn"79# 0.490 -> 0.522 support for dos lines (carriage returns are removed)80# 0.110 -> 0.490 support for multirow action names81# 0.55 -> 0.110 lsts file objects can be read and written already in82# the constructor.83# 0.53 -> 0.55 stateprops numbered in the order of occurence in the lsts file84# (alphabetical order). Documentation changed accordingly.85# 0.52 -> 0.53 bugfix: state props numbered off-by-one86# 0.52 -> 0.53 bugfix: reading multi-line transitions and state props87# 0.52 -> 0.53 props_by_states-helper function88# 0.52 -> 0.53 psyco is used if possible89# 0.50 -> 0.52 added support for state prop ranges "x..y"90from sys import stderr91class fakefile:92 """93 fakefile(string) is a file-like object that contains the94 string. It implements readline and write methods and nothing else.95 This class can be used as input and output file of the reader and96 the writer classes. The contents of the file are in attribute s.97 """98 def __init__(self,lstscontents):99 self.s=lstscontents100 def readline(self):101 l=self.s[:self.s.find("\n")+1]102 self.s=self.s[self.s.find("\n")+1:]103 return l104 def write(self,s):105 self.s+=s106def props_by_states(lsts_object):107 """props_by_states(lsts_object) -> state_table108 If propositions x and y (and no other propositions) are true in109 state s, then state_table[s]==[x,y]. s, x and y are natural110 numbers. To obtain the name of the proposition x, use111 stateproplist=r.get_stateprops().keys()112 stateproplist.sort()113 name_of_prop=stateproplist[num_of_a_stateprop]114 """115 statetbl=[ [] for x in xrange(lsts_object.get_header().state_cnt)]116 propdict=lsts_object.get_stateprops()117 propkeys = propdict.keys()118 propkeys.sort()119 for propindex,prop in enumerate(propkeys):120 for state in propdict[prop]:121 statetbl[state].append(propindex)122 return statetbl123class _header:124 pass125class lsts:126 def __init__(self):127 self._history=[]128 self._header=_header()129 self._header.state_cnt=0130 self._header.action_cnt=0131 self._header.transition_cnt=0132 self._header.initial_states=0133 self._actionnames=[]134 self._transitions=[]135 self._stateprops={} # state prop name -> list of states136 self._layout=[]137 def set_actionnames(self,actionnames):138 """139 Parameters:140 - actionnames is a list of strings141 Notes:142 This method modifies Action_cnt field in the header.143 """144 if len(actionnames) > 0 and actionnames[0]=="tau":145 self._actionnames=actionnames146 else:147 stderr.write('LSTS.PY: warning: set_actionnames did not receive "tau".\n')148 self._actionnames=["tau"]+actionnames149 self._header.action_cnt=len(self._actionnames)-1150 def set_transitions(self,transitions):151 """152 Parameters:153 - transitions should be a list of list of pairs, where154 transitions[i] is a list of pairs (dest_state, action_index)155 that describe leaving transitions from state i. If there are156 no transitions from state i, then transitions[i] is empty157 list.158 dest_state and action_index are indexes to transitions and159 actionnames lists. That is, they may have values from 0 to160 len(list)-1.161 Notes:162 This method modifies State_cnt and Transition_cnt fields in163 the header.164 """165 self._transitions=transitions166 self._header.state_cnt=len(transitions)167 self._header.transition_cnt=0168 for s in transitions:169 self._header.transition_cnt+=len(s)170 def set_stateprops(self,stateprops):171 """172 Parameters:173 - stateprops should be a dictionary whose keys are state174 proposition names and values are lists of state numbers.175 Notes:176 This method modifies State_prop_cnt field in the header.177 """178 self._stateprops=stateprops179 self._header.state_prop_cnt=len(self._stateprops)180 def set_layout(self,layout):181 """182 Parameters:183 - layout should be a list of pairs (xcoord, ycoord), indexed184 with state numbers.185 """186 self._layout=layout187 def get_actionnames(self):188 return self._actionnames189 def get_transitions(self):190 return self._transitions191 def get_stateprops(self):192 return self._stateprops193 def get_layout(self):194 return self._layout195 def get_history(self):196 return self._history197 def get_header(self):198 return self._header199class writer(lsts):200 """201 LSTS writer class202 """203 def __init__(self,file=None,lsts_object=None):204 """205 Parameters:206 - Optional parameter 'file' should provide method207 'write'. Output will be written to this object. Valid objects208 are, for example, files opened for writing and sys.stdout.209 - Optional parameter lsts_object should be an instance of lsts210 (or reader or writer) class. New header will be automatically211 generated based on action names and transitions of the lsts212 object.213 - If both optional arguments are provided, the lsts object is214 immediately written to the file. In this case, for backward215 compatibility, the first call of write method will not do216 anything the writing target is the same file object.217 """218 self._written_in_constructor=None # this file has been written219 lsts.__init__(self)220 self.__file=file221 if isinstance(lsts_object,lsts):222 self.set_actionnames( lsts_object.get_actionnames() )223 self.set_transitions( lsts_object.get_transitions() )224 self.set_stateprops( lsts_object.get_stateprops() )225 self.set_layout( lsts_object.get_layout() )226 self._header.initial_states=lsts_object.get_header().initial_states227 if file!=None and lsts_object!=None: # write immediately228 self.write()229 self._written_in_constructor=file230 def write(self,file=None,stateprop_order=None):231 """232 Parameters:233 - optional parameter file is the same as in __init__.234 Notes:235 Writes all lsts information to the given file object.236 """237 if not file:238 file=self.__file239 if self._written_in_constructor==file:240 self._written_in_constructor=None241 return242 file.write("Begin Lsts\n\n")243 file.write("Begin History\n")244 for num,s in enumerate(self._history):245 file.write("\t"+str(num+1)+"\n")246 file.write("\t\""+s+"\"\n")247 file.write("End History\n\n")248 file.write("Begin Header\n")249 file.write(" State_cnt = " + str(self._header.state_cnt) + "\n")250 file.write(" Action_cnt = " + str(self._header.action_cnt) + "\n")251 file.write(" Transition_cnt = " + str(self._header.transition_cnt) + "\n")252 if self._stateprops:253 file.write(" State_prop_cnt = " + str(self._header.state_prop_cnt) + "\n")254 file.write(" Initial_states = " + str(self._header.initial_states+1) + ";\n")255 file.write("End Header\n\n")256 file.write("Begin Action_names\n")257 for ai,a in enumerate(self._actionnames[1:]):258 file.write(" "+str(ai+1)+' = "'+a.replace('"','\\"')+'"\n')259 file.write("End Action_names\n\n")260 if self._stateprops:261 file.write("Begin State_props\n")262 if stateprop_order == None:263 propnames=self._stateprops.keys()264 propnames.sort()265 else:266 propnames = stateprop_order267 for key in propnames:268 file.write(' "%s" :' % key.replace('"','\\"'))269 for v in self._stateprops[key]:270 file.write(' %s' % (v+1))271 file.write(';\n')272 file.write("End State_props\n\n")273 file.write("Begin Transitions\n")274 for si,s in enumerate(self._transitions):275 file.write(" "+str(si+1)+":")276 for (dest_state,action_index) in s:277 file.write(" "+str(dest_state+1)+","+str(action_index))278 file.write(";\n")279 file.write("End Transitions\n\n")280 if self._layout:281 file.write("Begin Layout\n")282 for statenum, xcoor, ycoord in [(num, val[0], val[1])283 for num, val in enumerate(self._layout)284 if val!=None]:285 file.write(' %s %s %s\n' % (statenum+1, xcoor, ycoord))286 file.write("End Layout\n")287 file.write("End Lsts\n")288class reader(lsts):289 def __init__(self,file=None):290 """291 Parameters:292 - Optional parameter file should provide method 'read'. Valid293 objects are, for example, files opened for reading and294 sys.stdin. If file_object is given, the file is immediately295 read, so there is no need to call read method afterwards."""296 lsts.__init__(self)297 self.__already_read=0298 self.__file=file299 self.__sections=["begin lsts",300 "begin history","end history",301 "begin header","end header",302 "begin action_names", "end action_names",303 "begin transitions", "end transitions",304 "begin state_props", "end state_props",305 "begin layout", "end layout",306 "end lsts"]307 import re308 self.__headerrow=re.compile('\s*(\S+)\s*=\s*([0-9]+)[^0-9]')309 self.__actionnamerow=re.compile('\s*([0-9]+)\s*=\s*"(([^"]|\\")*)"')310 self.__actionnamemultirow_start1=re.compile('\s*([0-9]+)\s*=\s*"([^\\\\]*)\\\\\^\s*$')311 self.__actionnamemultirow_start2=re.compile('\s*([0-9]+)\s*=\s*$')312 self.__actionnamemultirow_cont=re.compile('\s*\^([^\\\\]*)\\\\\^')313 self.__actionnamemultirow_end=re.compile('\s*\^([^"]*)"')314 self.__transitionrow=re.compile('\s*([0-9]+)[:\s]+(.*)\s*;')315 trowc1=re.compile('{[^}]*}|"[^"]*"') # transition row cleaner 1316 trowc2=re.compile(',')317 self.__cleanrow=lambda s:trowc2.sub(' ',trowc1.sub(' ',s))318 self.__stateproprow=re.compile('\s*"(([^"]|\\")*)"\s*:\s*([.0-9\s]*);')319 if file:320 self.read()321 self.__already_read=1322 def read(self,file=None):323 """324 """325 if self.__already_read:326 self.__already_read=0327 return328 if not file:329 file=self.__file330 sidx=0 # index of section that we expect to read next331 secs=self.__sections332 layout_rows=[]333 l=file.readline()334 while l:335 l=l.replace(chr(0x0d),'')336 if l.strip().lower() in secs: # move to the next section337 sidx=secs.index(l.strip().lower())338 elif secs[sidx]=="begin history":339 self._history.append(l.strip())340 elif secs[sidx]=="begin header": # parse a header row341 res=self.__headerrow.search(l)342 if res and int(res.group(2))>0:343 if res.group(1).lower()=="action_cnt":344 self._actionnames=["tau"] + ['N/A' for i in xrange(0,int(res.group(2)))]345 self._header.action_cnt=int(res.group(2))346 actionname_in_multirow=-1347 elif res.group(1).lower()=="state_cnt":348 self._header.state_cnt=int(res.group(2))349 self._transitions=[ [] for _ in xrange(0,self._header.state_cnt) ]350 self._layout=[None for _ in xrange(self._header.state_cnt)]351 elif res.group(1).lower()=="transition_cnt":352 self._header.transition_cnt=int(res.group(2))353 elif res.group(1).lower()=="state_prop_cnt":354 self._header.state_prop_cnt=int(res.group(2))355 elif res.group(1).lower()=="initial_states":356 self._header.initial_states=int(res.group(2))-1 # only one allowed (BAD)357 elif secs[sidx]=="begin action_names": # parse an action name row358 res=self.__actionnamerow.search(l)359 if res and int(res.group(1))>0:360 self._actionnames[int(res.group(1))]=res.group(2).replace('\\"', '"')361 actionname_in_multirow=-1362 else:363 if actionname_in_multirow==-1:364 res=self.__actionnamemultirow_start1.search(l)365 if res:366 # store the number of the action whose name367 # is given in multiple rows368 actionname_in_multirow=int(res.group(1))369 self._actionnames[actionname_in_multirow]=res.group(2)370 else: # real hack. parse 'number = \n "action name"'371 res=self.__actionnamemultirow_start2.search(l)372 if res:373 nextline=file.readline()374 while nextline.strip()=="": nextline=file.readline()375 self._actionnames[int(res.group(1))]=\376 nextline.split('"',1)[1].rsplit('"',1)[0]377 else:378 res=self.__actionnamemultirow_cont.search(l)379 if res:380 self._actionnames[actionname_in_multirow]+=res.group(1)381 else:382 res=self.__actionnamemultirow_end.search(l)383 if res:384 self._actionnames[actionname_in_multirow]+=res.group(1)385 actionname_in_multirow=-1386 elif secs[sidx]=="begin transitions": # parse a transition row387 res=self.__transitionrow.search(l)388 if res and int(res.group(1))>0:389 starting_state=int(res.group(1))-1390 l=self.__cleanrow(res.group(2)).split()391 for (dest_state,action_index) in \392 [ (l[i],l[i+1]) for i in range(0,len(l))[::2] ]:393 self._transitions[starting_state].append(394 (int(dest_state)-1,int(action_index)) )395 elif secs[sidx]=="begin state_props": # parse state proposition row396 res=self.__stateproprow.search(l)397 if res:398 propname=res.group(1).replace('\\"', '"')399 proplist=[]400 for propitem in res.group(3).split():401 try:402 # single number403 propnum=int(propitem)-1 # off-by-one404 proplist.append(propnum)405 except ValueError:406 # range of numbers: x..y407 try:408 proprange=[int(x) for x in propitem.split("..")]409 except ValueError:410 print propitem411 proprange[0]-=1 # off-by-one412 proplist.extend(range(*proprange))413 proplist.sort()414 self._stateprops[propname]=proplist415 elif secs[sidx]=="begin layout":416 layout_numbers=l.strip().split()417 try:418 statenum, xcoord, ycoord = [int(x) for x in layout_numbers]419 except ValueError:420 raise ValueError("Layout section has an illegal row: '%s'" % l.strip())421 statenum-=1422 try:423 self._layout[statenum]=(xcoord,ycoord)424 except IndexError:425 raise IndexError("Illegal state number in layout section: %s" % statenum)426 if sidx == len(secs): # we are ready427 break428 else:429 l=file.readline()430 while l.strip()=="":431 if not l: break432 l=file.readline()433 if secs[sidx]=="begin state_props" or secs[sidx]=="begin transitions":434 while (not l.lower().strip() in secs) and (not ";" in l):435 newline=file.readline()436 if not newline: break437 # if there is only one white space in the front of the new row,438 # delete it... it may be that there should not be white space439 if l[-3:-1]==".." or newline[:3]==" ..":440 newline=newline.lstrip()441 l=l.rstrip()+newline442try:443 import psyco444 psyco.profile()445except: pass446# Compatibility to Python 2.1 requires enumerate:447try:448 enumerate([1])449except:450 def enumerate(list_of_anything):451 i = 0452 result = []453 for a in list_of_anything:454 result.append((i,a))455 i += 1456 return result457if __name__=="__main__":458 """ Testiohjelma """459 class filu:460 def __init__(self):461 self.s=""462 def write(self,s):463 self.s+=s464 def readline(self):465 l=self.s[:self.s.find("\n")+1]466 self.s=self.s[self.s.find("\n")+1:]467 return l468 outf1=filu()469 w=writer(outf1)470 w.set_actionnames(["tau","a","b","c"])471 w.set_transitions([[(0,0),(1,2)],[(0,1),(1,1),(2,3)],[]])472 w.write()473 inf=filu()474 inf.s=outf1.s475 r=reader(inf)476 r.read()477 outf2=filu()478 ww=writer(file=outf2,lsts_object=r)479 # r.__class__=writer480 ww.write(outf2)481 test="Write - read written - rewrite (the written LSTSs should be the same)"482 if outf1.s==outf2.s:483 print "PASS",test484 else:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful