Best Python code snippet using playwright-python
parser.py
Source:parser.py
1###################################################################2# Barbora Å mahlÃková3# 2020/20214# S1S formula parser5###################################################################6from automaton import Automaton7from intersection import *8from union import *9from atomic_automata import *10from complement import *11from tree import *12import math13import itertools14import re15from copy import deepcopy16def analyse_predicates(file_text):17 """Analyses user-defined predicates."""18 predicates={}19 # user-defined predicates20 lines = file_text.split('\n')21 error=False22 for line in lines:23 if len(line)!=0 and line.split()[0]=="#define": #line[0]=='#':24 my_predicate=""25 i=726 if not line[i].isspace():27 error=True28 break29 30 # skip spaces31 while i<len(line) and line[i].isspace():32 i+=133 if line[i]!='(':34 # wrong format35 error=True36 break37 # predicate in parentheses38 left=039 right=040 while i<len(line):41 if line[i]=='(':42 left+=143 elif line[i]==')':44 right+=145 my_predicate+=line[i]46 i+=147 if left==right and left!=0:48 break49 while i<len(line) and line[i].isspace():50 i+=151 if i==len(line):52 error=True53 54 # predicate definition55 definition=""56 while i<len(line):57 definition+=line[i]58 i+=159 60 new_pred=""61 i=162 while i<len(my_predicate):63 if my_predicate[i]=='(' or my_predicate[i].isspace():64 break65 new_pred+=my_predicate[i]66 i+=167 68 variables=[]69 while i<len(my_predicate):70 if my_predicate[i].isalpha():71 variables.append(my_predicate[i])72 i+=173 a = parse(definition, predicates)74 tmp = 175 for var in variables:76 for i in range(len(a.transitions)):77 a.transitions[i][1] = a.transitions[i][1].replace(var, "#"+str(tmp))78 new_alphabet = set()79 for symbol in a.alphabet:80 new = symbol.replace(var, "#"+str(tmp))81 new_alphabet.add(new)82 a.alphabet = deepcopy(new_alphabet)83 tmp += 184 if "--rabit" in sys.argv:85 a = rabit_reduction(a)86 87 predicates[new_pred]=[len(variables), a]88 89 else:90 break91 if error:92 raise SyntaxError("Wrong format of user-defined predicates!")93 return predicates94def parse(file_text, predicates):95 """Creates a list of elements from S1S formula."""96 # skip lines with user-defined predicates97 lines = file_text.split('\n')98 new_text=""99 for line in lines:100 if not(len(line)!=0 and line[0]=='#'):101 new_text+=line102 formula=[]103 element=""104 left=0 # number of parentheses105 right=0106 for c in new_text:107 # parentheses108 if c=='(' or c==')':109 if element!="":110 formula.append(element)111 element=""112 formula.append(c)113 if c=='(':114 left+=1115 if c==')':116 right+=1117 118 # skip spaces119 elif c.isspace() and element!="":120 formula.append(element)121 element=""122 123 # load whole element124 elif not c.isspace():125 element+=c126 if left!=right:127 raise SyntaxError("Invalid form of input formula (parentheses not matching).")128 129 #create_tree(formula, predicates)130 a = create_automaton(formula, predicates) 131 edit_transitions(a)132 return a 133 134 135def create_automaton(formula, predicates):136 """Creates Buchi automaton from S1S formula."""137 138 if "--spot" in sys.argv:139 spot = True140 else:141 spot = False142 if "--rabit" in sys.argv:143 rabit = True144 else:145 rabit = False146 147 stack=[]148 atom=[]149 first=True 150 for element in formula:151 if element!=")":152 stack.append(element)153 else:154 atom.append(element)155 # pop everything to '(' and add to atom156 while(stack[-1]!="("):157 atom.append(stack.pop())158 atom.append(stack.pop())159 atom.reverse()160 error=False161 # user-defined predicates162 if atom[1] in predicates.keys():163 a = deepcopy(predicates[atom[1]][1])164 for i in range(predicates[atom[1]][0]):165 for j in range(len(a.transitions)):166 a.transitions[j][1] = a.transitions[j][1].replace("#"+str(i+1), atom[i+2])167 new_alphabet = set()168 for symbol in a.alphabet:169 new = symbol.replace("#"+str(i+1), atom[i+2])170 new_alphabet.add(new)171 a.alphabet = deepcopy(new_alphabet)172 # operations with automata173 elif atom[1]=="exists":174 if not (isinstance(atom[3], Automaton)):175 error=True176 else:177 a=exists(atom[2],atom[3])178 elif atom[1]=="forall":179 if not (isinstance(atom[3], Automaton)):180 error=True181 else:182 a = atom[3]183 if spot:184 a = spot_complement(a)185 else:186 a=comp2(a)187 a = exists(atom[2], a)188 if rabit:189 a = rabit_reduction(a)190 if spot:191 a = spot_complement(a)192 else:193 a=comp2(a)194 elif atom[1]=="and":195 if not (isinstance(atom[2], Automaton) and isinstance(atom[3], Automaton)):196 error=True197 else:198 a=intersection(atom[2],atom[3])199 elif atom[1]=="or":200 if not (isinstance(atom[2], Automaton) and isinstance(atom[3], Automaton)):201 error=True202 else:203 a=union(atom[2],atom[3])204 elif atom[1]=="neg":205 if not (isinstance(atom[2], Automaton)):206 error=True207 else:208 a = atom[2]209 if spot:210 a = spot_complement(a)211 else:212 a=comp2(a)213 elif atom[1]=="implies":214 if not (isinstance(atom[2], Automaton) and isinstance(atom[3], Automaton)):215 error=True216 else:217 a = atom[2]218 if spot:219 a = spot_complement(a)220 else:221 a = comp2(a)222 if rabit:223 a = rabit_reduction(a)224 a=union(a, atom[3])225 # atomic automata226 elif atom[1]=="zeroin":227 a=zeroin(atom[2])228 elif atom[1]=="sing":229 a=sing(atom[2])230 elif atom[1]=="sub":231 a=sub(atom[2],atom[3])232 elif atom[1]=="succ":233 a=succ(atom[2],atom[3])234 elif atom[1]=="<":235 a=less(atom[2],atom[3])236 237 else:238 if (not first) or len(atom)!=4:239 raise SyntaxError('Invalid form of input formula near "{}".'.format(' '.join(map(str,atom))))240 if isinstance(atom[2], Automaton) or isinstance(atom[3], Automaton):241 raise SyntaxError('Invalid form of input formula near "{}".'.format(atom[1]))242 # arguments of succ or sub can be in parentheses243 atom.remove('(')244 atom.remove(')')245 atom.reverse()246 for i in range(len(atom)):247 stack.append(atom[len(atom)-i-1])248 atom=[]249 first=False250 continue251 if error:252 raise SyntaxError('Invalid form of input formula near "{}".'.format(atom[1]))253 stack.append(a)254 first=True255 atom=[]256 # reduction257 if rabit:258 a = rabit_reduction(a)259 return a260def rabit_reduction(a):261 "Using Rabit for reduction"262 alphabet = a.alphabet263 write_all_transitions(a)264 write_to_file(a, 'a.ba') # write to a.ba265 stream = os.popen('java -jar ../RABIT250/Reduce.jar a.ba 10')266 output = stream.read()267 #print(output)268 with open('reduced_10_a.ba') as f:269 a = load_data(f) # reduced automaton270 a.alphabet = alphabet271 272 return a273def myfunc():274 if not hasattr(myfunc, "counter"):275 myfunc.counter = 0276 myfunc.counter += 1277 return myfunc.counter278def spot_complement(a):279 "Using Spot for complement"280 281 a = rabit_reduction(a)282 alphabet = a.alphabet283 complete_automaton(a)284 285 # write to .ba file286 write_all_transitions(a)287 write_to_file(a, 'a.ba')288 stream = os.popen('cat a.ba')289 output = stream.read()290 291 # convert to .hoa292 with open('a.hoa', 'w+') as f:293 f.write('HOA: v1\n')294 f.write('States: {}\n'.format(len(a.states)))295 f.write('Start:')296 for state in a.start:297 f.write(" {}".format(state))298 f.write('\n')299 f.write('acc-name: Buchi\n')300 f.write('Acceptance: 1 Inf(0)\n')301 f.write('properties: explicit-labels state-acc trans-labels\n')302 f.write('AP: {}'.format(int(math.log(len(a.alphabet),2))))303 for c in a.alphabet:304 i=0305 symbol_count = 0306 symbols=list()307 while i<len(c):308 f.write(' "{}"'.format(c[i]))309 symbol_count += 1310 symbols.append(c[i])311 i+=4312 break313 f.write('\n')314 f.write('--BODY--\n')315 for state in a.states:316 f.write('State: {}'.format(state))317 if state in a.accept:318 f.write(' {0}')319 f.write('\n')320 for t in a.transitions:321 if t[0]==state:322 string=""323 i=0324 while i<symbol_count:325 if "{}:0".format(symbols[i]) in t[1]:326 word = "!{}".format(i)327 else:328 word = "{}".format(i)329 if i==0:330 string += word331 else:332 string += " & {}".format(word)333 i+=1334 f.write('[{}] {}\n'.format(string, t[2]))335 f.write('--END--\n')336 # export .hoa files337 #endFile = 'aut/'+sys.argv[-1]+'-'+str(myfunc())+'.hoa'338 #stream = subprocess.Popen('cp a.hoa ' + endFile, shell=True)339 #stream.wait()340 # complement using spot341 stream = subprocess.Popen('autfilt --complement --ba a.hoa >a_neg.hoa', shell=True)342 stream.wait()343 b = Automaton(set(), a.alphabet, list(), set(), set())344 with open('a_neg.hoa') as src:345 for line in src:346 if "States" in line:347 split = line.split()348 for state in split:349 if state.isdigit():350 for i in range(int(state)):351 b.states.add(str(i))352 elif "Start" in line:353 split = line.split()354 for state in split:355 if state.isdigit():356 b.start.add(state)357 elif "State:" in line:358 split = line.split()359 for s in split:360 if s.isdigit():361 current = s362 elif "{0}" in s:363 b.accept.add(current)364 elif "[" in line:365 split = line.split()366 for state in split:367 if state.isdigit():368 dst = state369 370 newline = re.search('\[(.+?)\]',line).group(1)371 newline = newline.replace('[','')372 newline = newline.replace(']','')373 newline = newline.replace('|','')374 split = newline.split()375 for option in split:376 string=""377 for i in range(symbol_count):378 if "!{}".format(i) in option:379 if i==0:380 string += "{}:0".format(symbols[i])381 else:382 string += "|{}:0".format(symbols[i])383 elif str(i) in option:384 if i==0:385 string += "{}:1".format(symbols[i])386 else:387 string += "|{}:1".format(symbols[i])388 else:389 if i==0:390 string += "{}:?".format(symbols[i])391 else:392 string += "|{}:?".format(symbols[i])393 if [current, string, dst] not in b.transitions:394 b.transitions.append([current, string, dst])395 396 write_all_transitions(b)397 write_to_file(b, 'a.ba')398 with open('a.ba') as f:399 a = load_data(f)400 a.alphabet = alphabet401 a = rabit_reduction(a)...
test_matchers.py
Source:test_matchers.py
...63 assert c == "act"64 assert "act" == c65 assert c is not a66def test_pretty_print_any_such_that():67 def my_predicate(x):68 return True69 a = Any()70 aa = a.such_that(my_predicate).such_that(lambda: True)71 assert repr(aa) == repr(a) + ".such_that(my_predicate).such_that(<lambda>)"72 assert str(aa) == str(a) + ".such_that(my_predicate).such_that(<lambda>)"73 class Predicate(object):74 @classmethod75 def __call__(cls, x):76 return True77 b = Any(str)78 bb = b.such_that(Predicate)79 assert repr(bb) == repr(b) + ".such_that(Predicate)"80 assert str(bb) == str(b) + ".such_that(Predicate)"81def test_contains_equality():...
validation_classes.py
Source:validation_classes.py
1import hashlib2class Md5sumValidator:3 def __init__(self, test_name, input_file, expected_md5sum, comment=None):4 self.test_name = test_name5 self.input_file = input_file6 self.expected_md5sum = expected_md5sum7 self.test_type = "md5sum"8 self.comment = comment9 def is_valid(self):10 return get_md5sum(self.input_file, self.comment) == self.expected_md5sum11 def __eq__(self, other):12 return (13 self.test_name == other.test_name14 and self.input_file == other.input_file15 and self.expected_md5sum == other.expected_md5sum16 and self.comment == other.comment17 )18def get_md5sum(filepath, comment=None):19 """20 Compute the md5 sum for a file.21 If `comment` is specified, ignore all lines of the file that start with22 this comment-character.23 :param filepath: a path to a file, a string.24 :param comment: the comment character for the file; all lines that start25 with this character will be disregarded.26 :return: the md5sum for the file, as a string27 """28 my_predicate = lambda x: True29 if comment is not None:30 my_predicate = lambda x: not x.startswith(comment)31 try:32 # We assume the file isn't binary33 my_hash = hashlib.md5()34 with open(filepath, "r") as f:35 for line in filter(my_predicate, f):36 my_hash.update(line.encode("utf-8"))37 except UnicodeDecodeError:38 # If there are any encoding errors, we try treating the file as if it's39 # binary40 my_hash = hashlib.md5()41 with open(filepath, "rb") as f:42 for chunk in iter(lambda: f.read(4096), b""):43 my_hash.update(chunk)44 except:45 raise...
decorator1.py
Source:decorator1.py
1#!/usr/bin/python2#https://www.jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/3def is_even(value):4 """Return True if *value* is even."""5 return (value % 2) == 06def count_occurrences(target_list, predicate):7 """Return the number of times applying the callable *predicate* to a8 list element returns True."""9 return sum([1 for e in target_list if predicate(e)])10my_predicate = is_even11my_list = [1, 2, 4, 6, 7, 8, 9, 11, 12]12result = count_occurrences(my_list, my_predicate)...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!