How to use assertion method in apickli

Best JavaScript code snippet using apickli

alcq.py

Source:alcq.py Github

copy

Full Screen

1from alcqObj import *2from typing import Optional, Set, Tuple3from copy import copy, deepcopy4from functools import partial5import string6from itertools import combinations7def expand_formula(f: Formula) -> Formula:8 if isinstance(f, PrimitiveConcept):9 return f10 elif isinstance(f, DefinedConcept):11 return expand_formula(f.definition)12 if isinstance(f, And):13 return And(expand_formula(f.param1), expand_formula(f.param2))14 elif isinstance(f, Or):15 return Or(expand_formula(f.param1), expand_formula(f.param2))16 elif isinstance(f, Not):17 return Not(expand_formula(f.param))18 elif isinstance(f, ForAll):19 if isinstance(f.concept, PrimitiveConcept) or isinstance(f.concept,20 Relation):21 return ForAll(f.relation, f.concept)22 elif isinstance(f.concept, DefinedConcept):23 dc: DefinedConcept = f.concept24 return ForAll(f.relation, expand_formula(dc.definition))25 else:26 return ForAll(f.relation, expand_formula(f.concept))27 elif isinstance(f, Exists):28 if isinstance(f.concept, PrimitiveConcept) or isinstance(f.concept,29 Relation):30 return Exists(f.relation, f.concept)31 elif isinstance(f.concept, DefinedConcept):32 dc: DefinedConcept = f.concept33 return Exists(f.relation, expand_formula(dc.definition))34 else:35 return Exists(f.relation, expand_formula(f.concept))36 elif isinstance(f, AtMost):37 if isinstance(f.concept, PrimitiveConcept) or isinstance(f.concept, Relation):38 return AtMost(f.n, f.relation, f.concept)39 elif isinstance(f.concept, DefinedConcept):40 dc: DefinedConcept = f.concept41 return AtMost(f.n, f.relation, expand_formula(dc.definition))42 else:43 return AtMost(f.n, f.relation, expand_formula(f.concept))44 pass45 elif isinstance(f, AtLeast):46 if isinstance(f.concept, PrimitiveConcept) or isinstance(f.concept,47 Relation):48 return AtLeast(f.n, f.relation, f.concept)49 elif isinstance(f.concept, DefinedConcept):50 dc: DefinedConcept = f.concept51 return AtLeast(f.n, f.relation, expand_formula(dc.definition))52 else:53 return AtLeast(f.n, f.relation, expand_formula(f.concept))54 print(type(f), f)55 raise RuntimeError("should not be here")56def expand_concept(c: Concept) -> Formula:57 """58 expand all defined concept to primitive ones59 :param c: concept (defined or primitive)60 :param tbox:61 :return: expaned concept (most possibly a defined one)62 """63 if isinstance(c, PrimitiveConcept):64 return c65 if isinstance(c, DefinedConcept):66 defn: Formula = c.definition67 # pre_process68 # if isinstance(defn, ForAll) or isinstance(defn, Exists):69 # if isinstance(defn.concept, DCConstant):70 expanded: Formula = expand_formula(defn)71 return expanded72 print(type(c))73 raise RuntimeError("should not be here")74def push_in_not(f: Formula) -> Formula:75 """76 Push not into the deepest possible level77 :param f:78 :return:79 """80 if isinstance(f, PrimitiveConcept):81 return f82 elif isinstance(f, DefinedConcept):83 raise RuntimeError("should not happen")84 if isinstance(f, Not):85 if isinstance(f.param, And):86 return push_in_not(Or(Not(f.param.param1), Not(f.param.param2)))87 elif isinstance(f.param, Or):88 return push_in_not(And(Not(f.param.param1), Not(f.param.param2)))89 elif isinstance(f.param, Not):90 return push_in_not(f.param.param)91 elif isinstance(f.param, ForAll):92 return push_in_not(Exists(f.param.relation, Not(f.param.concept)))93 elif isinstance(f.param, Exists):94 return push_in_not(ForAll(f.param.relation, Not(f.param.concept)))95 elif isinstance(f.param, AtMost):96 return AtLeast(f.param.n + 1, f.param.relation, f.param.concept)97 elif isinstance(f.param, AtLeast):98 if f.param.n == 0:99 return Bottom100 else:101 return AtMost(f.param.n - 1, f.param.relation, f.param.concept)102 elif isinstance(f.param, PrimitiveConcept):103 return Not(push_in_not(f.param))104 if isinstance(f, And):105 return And(push_in_not(f.param1), push_in_not(f.param2))106 elif isinstance(f, Or):107 return Or(push_in_not(f.param1), push_in_not(f.param2))108 elif isinstance(f, ForAll):109 return ForAll(f.relation, push_in_not(f.concept))110 elif isinstance(f, Exists):111 return Exists(f.relation, push_in_not(f.concept))112 elif isinstance(f, AtMost):113 return AtMost(f.n, f.relation, push_in_not(f.concept))114 elif isinstance(f, AtLeast):115 return AtLeast(f.n, f.relation, push_in_not(f.concept))116 print(type(f))117 print(f)118 raise RuntimeError("should not be there")119def process_abox(abox: ABox) -> ABox:120 """121 ABox to NNF?122 :param abox:123 :return:124 """125 new_abox: ABox = set()126 for a in abox:127 new_a: Optional[Assertion] = None128 if isinstance(a, ConceptAssertion):129 c = a.concept130 processed_c = push_in_not(expand_concept(c))131 if isinstance(processed_c, PrimitiveConcept):132 new_a = ConceptAssertion(processed_c, a.obj)133 else:134 new_a = ComplexAssertion(processed_c, a.obj)135 elif isinstance(a, RelationAssertion):136 new_a = a137 elif isinstance(a, ComplexAssertion):138 f = a.formula139 processed_f = push_in_not(expand_formula(f))140 new_a = ComplexAssertion(processed_f, a.obj)141 elif isinstance(a, InequalityAssertion):142 new_a = a143 if new_a is not None:144 new_abox.add(new_a)145 else:146 print(type(a), a)147 raise RuntimeError("should not happen")148 return new_abox149# concept, formula150def get_cf_search_type(c: Union[Concept, Formula]):151 if isinstance(c, PrimitiveConcept):152 return ConceptAssertion153 elif isinstance(c, DefinedConcept):154 raise RuntimeError("should not happen")155 elif isinstance(c, Formula):156 return ComplexAssertion157def build_cf_query(c: Union[Concept, Formula], a: Constant):158 if isinstance(c, PrimitiveConcept):159 return ConceptAssertion(c, a)160 elif isinstance(c, DefinedConcept):161 raise RuntimeError("Should not happen")162 elif isinstance(c, Formula):163 return ComplexAssertion(c, a)164 else:165 print("eror: ", c)166 raise RuntimeError("Should not happen")167def and_both_exist(abox: ABox, c: Union[Concept, Formula], d: Union[Concept, Formula], a: Constant) -> bool:168 # note: here c&d has been splited, need to check in and_rule, before this invocation169 # if is_this_concept_top(c):170 # return True171 c_a_exist, d_a_exist = False, False172 c_query, d_query = build_cf_query(c, a), build_cf_query(d, a)173 for assertion in abox:174 if assertion == c_query:175 c_a_exist = True176 if assertion == d_query:177 d_a_exist = True178 return c_a_exist and d_a_exist179# check and apply?180def and_rule(abox: ABox) -> Tuple[bool, List[ABox]]:181 # deep copy?182 found_use_case = False183 found_idx = -1184 found_assertion: Optional[ComplexAssertion] = None185 found_formula: Optional[And] = None186 for idx, a in enumerate(abox):187 if isinstance(a, ComplexAssertion):188 f: Formula = a.formula189 if isinstance(f, And):190 if is_this_bottom_something(f):191 # no need to apply and on top192 continue193 # found And(C,D) (a)194 # need to check if C(a) and D(a) are already here195 # Abox should be a set...196 if not and_both_exist(abox, f.param1, f.param2, a.obj):197 found_use_case = True198 found_idx = idx199 found_assertion = a200 found_formula = f201 break202 if found_use_case:203 print("and found", found_assertion)204 # and don't change number205 new_abox = set(abox)206 # DONE: check all alike...207 for param in [found_formula.param1, found_formula.param2]:208 if isinstance(param, PrimitiveConcept):209 new_abox.add(ConceptAssertion(param, found_assertion.obj))210 elif isinstance(param, DefinedConcept):211 raise RuntimeError("should not happen")212 elif isinstance(param, Formula):213 new_abox.add(ComplexAssertion(param, found_assertion.obj))214 else:215 raise RuntimeError("should not happen")216 return True, [new_abox]217 else:218 return False, []219def exist_already_exist(abox: ABox, r: Relation, c: Concept, a: Constant) -> bool:220 # check if r(a,c), C(c) exists in current abox221 # first get all r(a,c), get all candidate c222 possible_2nd_set = set()223 for assertion in abox:224 if isinstance(assertion, RelationAssertion):225 if assertion.relation == r and assertion.obj1 == a:226 possible_2nd_set.add(assertion.obj2)227 # then check C(c)228 # remark: no need to handle top here, all constant are added top in preprocessing229 possible_query = {build_cf_query(c, p) for p in possible_2nd_set}230 for assertion in abox:231 if assertion in possible_query:232 return True233 return False234class ConstantStorage(object):235 def __init__(self):236 self.counter = 0237 def generate(self) -> Constant:238 self.counter += 1239 return Constant(f"${self.counter}")240 def __repr__(self):241 return f"ConstantStorage(counter={self.counter})"242def exist_rule(abox: ABox, cs: ConstantStorage) -> Tuple[bool, List[ABox]]:243 found_use_case = False244 found_idx = -1245 found_assertion: Optional[ComplexAssertion] = None246 found_exists: Optional[Exists] = None247 for idx, a in enumerate(abox):248 if isinstance(a, ComplexAssertion) and isinstance(a.formula, Exists):249 r: Relation = a.formula.relation250 c: Concept = a.formula.concept251 # now we have Exist r.C (a)252 # we need to check r(a,c), C(c)253 # check rest:254 if not exist_already_exist(abox, r, c, a.obj):255 found_use_case = True256 found_idx = idx257 found_assertion = a258 found_exists = a.formula259 break260 else:261 # ??262 pass263 if found_use_case:264 print("exist found", found_assertion)265 # and don't change number266 new_abox = set(abox)267 new_constant: Constant = cs.generate()268 new_abox.add(RelationAssertion(found_exists.relation, found_assertion.obj, new_constant))269 if isinstance(found_exists.concept, PrimitiveConcept):270 new_abox.add(ConceptAssertion(found_exists.concept, new_constant))271 elif isinstance(found_exists.concept, Formula):272 new_abox.add(ComplexAssertion(found_exists.concept, new_constant))273 else:274 raise RuntimeError("should not happen")275 return True, [new_abox]276 else:277 return False, []278def union_neither_exists(abox: ABox, C: Union[Concept, Formula], D: Union[Concept, Formula], a: Constant) -> bool:279 # if is_this_top_something(C):280 # return not True and not True281 c_a_exist, d_a_exist = False, False282 c_query, d_query = build_cf_query(C, a), build_cf_query(D, a)283 for assertion in abox:284 if assertion == c_query:285 c_a_exist = True286 if assertion == d_query:287 d_a_exist = True288 return not c_a_exist and not d_a_exist289def union_rule(abox: ABox) -> Tuple[bool, List[ABox]]:290 found_use_case = False291 found_idx = -1292 found_assertion: Optional[ComplexAssertion] = None293 found_or: Optional[Or] = None294 for idx, a in enumerate(abox):295 if isinstance(a, ComplexAssertion) and isinstance(a.formula, Or):296 # don't decompose top297 if is_this_top_something(a.formula):298 continue299 C: Formula = a.formula.param1300 D: Formula = a.formula.param2301 # now we have Or(C,D) (a)302 # we need to check either C(a) or D(a)303 # check rest:304 if union_neither_exists(abox, C, D, a.obj):305 found_use_case = True306 found_idx = idx307 found_assertion = a308 found_or = a.formula309 break310 else:311 # ??312 pass313 if found_use_case:314 print("union found", found_assertion)315 # and don't change number316 new_abox = set(abox)317 abox_c = set(new_abox)318 if isinstance(found_or.param1, PrimitiveConcept):319 abox_c.add(ConceptAssertion(found_or.param1, found_assertion.obj))320 else:321 abox_c.add(ComplexAssertion(found_or.param1, found_assertion.obj))322 abox_d = set(new_abox)323 if isinstance(found_or.param2, PrimitiveConcept):324 abox_d.add(ConceptAssertion(found_or.param2, found_assertion.obj))325 else:326 abox_d.add(ComplexAssertion(found_or.param2, found_assertion.obj))327 return True, [abox_c, abox_d]328 else:329 return False, []330def forall_apply_list(abox: ABox, r: Relation, C: Union[Concept, Formula], a: Constant) -> Tuple[bool, Set[Constant]]:331 # if Top, can let it add, will be handled by post processing332 # first find all possible b333 possible_2nd_set = set()334 for assertion in abox:335 if isinstance(assertion, RelationAssertion) and assertion.relation == r and assertion.obj1 == a:336 possible_2nd_set.add(assertion.obj2)337 # not C(b)338 should_be_added_set = set()339 for b in possible_2nd_set:340 b_query = build_cf_query(C, b)341 found_b = False342 for assertion in abox:343 if assertion == b_query:344 found_b = True345 break346 if not found_b:347 should_be_added_set.add(b)348 return len(should_be_added_set) != 0, should_be_added_set349def forall_rule(abox: ABox) -> Tuple[bool, List[ABox]]:350 found_use_case = False351 found_idx = -1352 found_assertion: Optional[ComplexAssertion] = None353 found_forall: Optional[ForAll] = None354 found_apply_list: Optional[Set[Constant]] = None355 for idx, a in enumerate(abox):356 if isinstance(a, ComplexAssertion) and isinstance(a.formula, ForAll):357 r: Relation = a.formula.relation358 c: Concept = a.formula.concept359 # now we have Or(C,D) (a)360 # we need to check either C(a) or D(a)361 # check rest:362 need_apply, apply_list = forall_apply_list(abox, r, c, a.obj)363 if need_apply:364 found_use_case = True365 found_idx = idx366 found_assertion = a367 found_forall = a.formula368 found_apply_list = apply_list369 break370 else:371 # ??372 pass373 if found_use_case:374 print("forall found", found_assertion)375 # and don't change number376 new_abox = set(abox)377 for b in found_apply_list:378 if isinstance(found_forall.concept, PrimitiveConcept):379 new_abox.add(ConceptAssertion(found_forall.concept, b))380 elif isinstance(found_forall.concept, DefinedConcept):381 raise RuntimeError("should not happen")382 elif isinstance(found_forall.concept, Formula):383 new_abox.add(ComplexAssertion(found_forall.concept, b))384 else:385 raise RuntimeError("should not happen")386 return True, [new_abox]387 else:388 return False, []389class ConstantBuilder:390 def __init__(self):391 self.counter = 0392 # DONE: prefix > 26393 self.prefix = 0394 # Excel column style A...Z,AA,AB...395 # https://stackoverflow.com/a/48984697396 def _divmod_excel(self, n):397 a, b = divmod(n, 26)398 if b == 0:399 return a - 1, b + 26400 return a, b401 def _to_excel(self, num):402 chars = []403 while num > 0:404 num, d = self._divmod_excel(num)405 chars.append(string.ascii_uppercase[d - 1])406 return ''.join(reversed(chars))407 def generate(self) -> Constant:408 self.counter += 1409 return Constant(f"${self._to_excel(self.prefix)}-{self.counter}")410 def new_prefix(self):411 self.prefix += 1412 def __repr__(self):413 return f"ConstantBuilder(prefix={self.prefix}, counter={self.counter})"414def at_least_should_apply(abox: ABox, n: int, r: Relation, c: Union[Concept, Formula], a: Constant) -> bool:415 can_apply = True416 # find all possible c_is417 all_c_li = []418 for assertion in abox:419 if isinstance(assertion, RelationAssertion) and assertion.relation == r and assertion.obj1 == a:420 all_c_li.append(assertion.obj2)421 # do a filter by C422 new_all_c_li = []423 for current_ci in all_c_li:424 # if success then add425 # special case426 if is_this_top_something(c):427 pass428 # DONE: always success429 new_all_c_li.append(current_ci)430 else:431 query = build_cf_query(c, current_ci)432 if query in abox:433 new_all_c_li.append(current_ci)434 all_c_li = new_all_c_li435 all_c_li = list(set(all_c_li))436 # early check437 if len(all_c_li) < n:438 return True439 # check with basic permutation?440 for comb in combinations(all_c_li, n):441 # now we have an tuple of size N442 current_comb_ok = True443 # goal: check if in "any" combination, "all" the inequality pair exists in abox444 # if such combination (a qualified one, all pair exists) is found, then no need to apply445 # otherwise need to apply446 for bi,bj in combinations(comb, 2):447 if ne(bi, bj) not in abox and ne(bj, bi) not in abox:448 # one inequality pair not exist449 # current combination is not qualified450 current_comb_ok = False451 break452 if current_comb_ok:453 # found one such (qualified) combination, no need to apply454 return False455 else:456 # this combination failed, just keep finding457 pass458 # all combination failed, need to apply459 # no more combination, just return false460 return True461def at_least_rule(abox: ABox, cb: ConstantBuilder) -> Tuple[bool, List[ABox]]:462 found_use_case = False463 found_idx = -1464 found_assertion: Optional[ComplexAssertion] = None465 found_at_least: Optional[AtLeast] = None466 for idx, a in enumerate(abox):467 if isinstance(a, ComplexAssertion) and isinstance(a.formula, AtLeast):468 n: int = a.formula.n469 r: Relation = a.formula.relation470 c: Concept = a.formula.concept471 if at_least_should_apply(abox, n, r,c,a.obj):472 found_use_case = True473 found_idx = idx474 found_assertion = a475 found_at_least = a.formula476 break477 else:478 # ??479 pass480 if found_use_case:481 print("at least found", found_assertion)482 # and don't change number483 new_abox = set(abox)484 cb.new_prefix()485 new_constant_li: List[Constant] = []486 for idx in range(found_at_least.n):487 new_constant: Constant = cb.generate()488 new_constant_li.append(new_constant)489 # add relation490 new_abox.add(RelationAssertion(found_at_least.relation, found_assertion.obj, new_constant))491 # add concept492 if isinstance(found_at_least.concept, PrimitiveConcept):493 new_abox.add(ConceptAssertion(found_at_least.concept, new_constant))494 elif isinstance(found_at_least.concept, Formula):495 new_abox.add(ComplexAssertion(found_at_least.concept, new_constant))496 else:497 # Top & Bottom?498 print(type(found_at_least.concept))499 raise RuntimeError("should not happen")500 # add inequality501 for bi, bj in combinations(new_constant_li, 2):502 new_abox.add(InequalityAssertion(bi, bj))503 return True, [new_abox]504 else:505 return False, []506def at_most_should_apply(abox: ABox, n: int, r: Relation, c: Union[Concept, Formula], a: Constant) -> Tuple[bool, List[Constant]]:507 # need to check: has more than expected508 # get initial list by relation509 possible_b_li = []510 for assertion in abox:511 if isinstance(assertion, RelationAssertion) and assertion.relation == r and assertion.obj1 == a:512 possible_b_li.append(assertion.obj2)513 # filter by concept514 new_possible_b_li = []515 for current_b in possible_b_li:516 if is_this_top_something(c):517 new_possible_b_li.append(current_b)518 else:519 b_query = build_cf_query(c, current_b)520 if b_query in abox:521 new_possible_b_li.append(current_b)522 possible_b_li = new_possible_b_li523 possible_b_li = list(set(possible_b_li))524 # early check525 if len(possible_b_li) <= n:526 # less then n, no need to apply527 return False, []528 # check inequality with permutation529 # need to choose n+1530 # check not all exist531 # as long as one equality don't exist, we can use532 for comb in combinations(possible_b_li, n+1):533 for bi, bj in combinations(comb, 2):534 if InequalityAssertion(bi, bj) not in abox and InequalityAssertion(bj,bi) not in abox:535 # we found one eq not in...536 return True, list(comb)537 # can not use by default538 return False, []539def make_substitution(abox: ABox, src: Constant, dst: Constant) -> ABox:540 new_abox = []541 for assertion in abox:542 new_assertion : Optional[Assertion] = None543 if isinstance(assertion, ConceptAssertion):544 new_assertion = assertion545 if assertion.obj == src:546 new_assertion = ConceptAssertion(assertion.concept, dst)547 elif isinstance(assertion, RelationAssertion):548 new_assertion = assertion549 obj1, obj2 = assertion.obj1, assertion.obj2550 found1, found2 = False, False551 if obj1 == src:552 obj1 = dst553 found1 = True554 if obj2 == src:555 obj2 = dst556 found2 = True557 if found1 or found2:558 new_assertion = RelationAssertion(assertion.relation, obj1, obj2)559 elif isinstance(assertion, ComplexAssertion):560 new_assertion = assertion561 if assertion.obj == src:562 new_assertion = ComplexAssertion(assertion.formula, dst)563 elif isinstance(assertion, InequalityAssertion):564 new_assertion = assertion565 obj1, obj2 = assertion.obj1, assertion.obj2566 found1, found2 = False, False567 if obj1 == src:568 obj1 = dst569 found1 = True570 if obj2 == src:571 obj2 = dst572 found2 = True573 if found1 or found2:574 new_assertion = InequalityAssertion(obj1, obj2)575 else:576 raise RuntimeError("should not be here")577 if new_assertion is not None:578 new_abox.append(new_assertion)579 else:580 raise RuntimeError("should not be here")581 return new_abox582def at_most_rule(abox: ABox) -> Tuple[bool, List[ABox]]:583 found_use_case = False584 found_idx = -1585 found_assertion: Optional[ComplexAssertion] = None586 found_at_most: Optional[AtMost] = None587 found_combination: Optional[List[Constant]] = None588 for idx, a in enumerate(abox):589 if isinstance(a, ComplexAssertion) and isinstance(a.formula, AtMost):590 n: int = a.formula.n591 r: Relation = a.formula.relation592 c: Concept = a.formula.concept593 should_apply, possible_comb = at_most_should_apply(abox, n, r, c, a.obj)594 if should_apply:595 found_use_case = True596 found_idx = idx597 found_assertion = a598 found_at_most = a.formula599 found_combination = possible_comb600 break601 else:602 # ??603 pass604 if found_use_case:605 print("at most found", found_assertion)606 # and don't change number607 new_abox_li: List[ABox] = []608 # do some kind of substitution?609 for bi, bj in combinations(found_combination, 2):610 bi: Constant611 bj: Constant612 if ne(bi,bj) not in abox and ne(bj,bi) not in abox:613 # DONE: choose one direction to substitute?614 abox_copy = set(abox)615 # fix 4 child has at most 2 problem616 bi_names = bi.name.split("~")617 bj_names = bj.name.split("~")618 bi_names += bj_names619 all_names = sorted(bi_names)620 new_constant = Constant("~".join(all_names))621 new_abox = make_substitution(abox_copy, bi, new_constant)622 new_abox = make_substitution(new_abox, bj, new_constant)623 new_abox_li.append(new_abox)624 return True, new_abox_li625 else:626 return False, []627def choose_rule_can_apply(abox: ABox, r: Relation, c: Concept, a: Constant) -> Tuple[bool, Optional[Constant]]:628 # don't apply if C is top629 # if is_this_top_something(c):630 # return False, None631 # check all possible b632 possible_b_list: List[Constant] = []633 for assertion in abox:634 if isinstance(assertion, RelationAssertion) and assertion.relation == r and assertion.obj1 == a:635 possible_b_list.append(assertion.obj2)636 # check all C(b)637 # DONE: add check for not c(b)638 for current_b in possible_b_list:639 b_query = build_cf_query(c, current_b)640 # inside it's all XA641 # if isinstance(b_query, ConceptAssertion):642 # b_query = ComplexAssertion(b_query.concept, current_b)643 not_b_query: Assertion = None644 if isinstance(b_query, ConceptAssertion) and isinstance(b_query.concept, PrimitiveConcept):645 not_b_query = ComplexAssertion(Not(b_query.concept), current_b)646 elif isinstance(b_query, ComplexAssertion):647 inside = push_in_not(Not(b_query.formula))648 if isinstance(inside, Concept):649 not_b_query = ConceptAssertion(inside, current_b)650 else:651 not_b_query = ComplexAssertion(push_in_not(Not(b_query.formula)), current_b)652 # c itself is a not?: should not happen, should use (Not(concept))(constant)653 else:654 raise RuntimeError("should not be here")655 if not_b_query is None:656 raise RuntimeError("should not happen")657 if b_query not in abox and not_b_query not in abox:658 # neither C(b) nor NOT(C(b)) exists659 print("choose rule: chosen", current_b, "with C:",c)660 return True, current_b661 return False, None662def choose_rule(abox: ABox) -> Tuple[bool, List[ABox]]:663 found_use_case = False664 found_idx = -1665 found_assertion: Optional[ComplexAssertion] = None666 found_at_most: Optional[AtMost] = None667 found_constant : Optional[Constant] = None668 for idx, a in enumerate(abox):669 if isinstance(a, ComplexAssertion) and isinstance(a.formula, AtMost):670 n: int = a.formula.n671 r: Relation = a.formula.relation672 c: Concept = a.formula.concept673 can_apply, b = choose_rule_can_apply(abox, r,c,a.obj)674 if can_apply:675 found_use_case = True676 found_idx = idx677 found_assertion = a678 found_at_most = a.formula679 found_constant = b680 break681 else:682 # ??683 pass684 if found_use_case:685 print("choose found", found_assertion)686 # and don't change number687 new_abox_list = []688 new_assertion: Optional[Assertion] = None689 if isinstance(found_at_most.concept, PrimitiveConcept):690 new_assertion = ConceptAssertion(found_at_most.concept, found_constant)691 elif isinstance(found_at_most.concept, DefinedConcept):692 raise RuntimeError("should not happen")693 elif isinstance(found_at_most.concept, Formula):694 new_assertion = ComplexAssertion(found_at_most.concept, found_constant)695 else:696 print(type(found_at_most.concept))697 raise RuntimeError("should not happen")698 # add positive699 pos_abox = set(abox)700 neg_abox = set(abox)701 neg_assertion : Assertion = None702 # DONE: push into...703 if isinstance(new_assertion, ConceptAssertion) and isinstance(new_assertion.concept, PrimitiveConcept):704 inside = push_in_not(expand_concept(new_assertion.concept))705 if isinstance(inside, PrimitiveConcept):706 neg_assertion = ConceptAssertion(inside, found_constant)707 else:708 neg_assertion = ComplexAssertion(inside, found_constant)709 elif isinstance(new_assertion, ComplexAssertion):710 inside = push_in_not(expand_formula(new_assertion.formula))711 if isinstance(inside, PrimitiveConcept):712 neg_assertion = ConceptAssertion(inside, found_constant)713 else:714 neg_assertion = ComplexAssertion(inside, found_constant)715 else:716 raise RuntimeError("should not be here")717 pos_abox.add(new_assertion)718 neg_abox.add(neg_assertion)719 return True, [pos_abox, neg_abox]720 else:721 return False, []722def exist_same_inequality(abox: ABox) -> bool:723 for assertion in abox:724 if isinstance(assertion, InequalityAssertion) and assertion.obj1 == assertion.obj2:725 return True726 return False727def exist_certain_at_most_violation(abox: ABox, source: Assertion):728 if not isinstance(source, ComplexAssertion) or not isinstance(source.formula, AtMost):729 raise ValueError("parameter not at most assertion")730 # just check one given abox731 n = source.formula.n732 # first get all b_i by relations733 all_b_list = []734 for assertion in abox:735 if isinstance(assertion, RelationAssertion) and assertion.relation == source.formula.relation and assertion.obj1 == source.obj:736 all_b_list.append(assertion.obj2)737 # then filter by C738 filtered_all_b_list = []739 for b in all_b_list:740 if is_this_top_something(source.formula.concept):741 filtered_all_b_list.append(b)742 continue743 b_query = build_cf_query(source.formula.concept, b)744 if b_query in abox:745 filtered_all_b_list.append(b)746 all_b_list = filtered_all_b_list747 # quick test748 if len(all_b_list) <= n:749 return False750 # finally check inequality751 # by default no violation, unless one such violation is found752 for comb in combinations(all_b_list, n+1):753 # for each combination754 all_have_inequality = True755 for bi, bj in combinations(comb, 2):756 if ne(bi,bj) not in abox and ne(bj,bi) not in abox:757 all_have_inequality = False758 break759 if all_have_inequality:760 # find one violation761 return True762 # if nothing is found, then safe763 return False764def exist_at_most_violation(abox: ABox) -> bool:765 # get all <= nr.C(a)766 all_at_most_list = []767 for assertion in abox:768 if isinstance(assertion, ComplexAssertion) and isinstance(assertion.formula, AtMost):769 all_at_most_list.append(assertion)770 # check one by one771 for atmost in all_at_most_list:772 if exist_certain_at_most_violation(abox, atmost):773 return True774 # should be safe by default775 return False776def is_abox_open(abox: ABox) -> bool:777 # DONE: add support for TOP/BOTTOM778 if exist_same_inequality(abox):779 print("is_abox_open: exist same inequality")780 return False781 # DONE: another contradiction782 if exist_at_most_violation(abox):783 print("is_abox_open: exist at most violation")784 return False785 not_set: Set[Assertion] = set()786 for assertion in abox:787 if isinstance(assertion, ConceptAssertion) and isinstance(assertion.concept, PrimitiveConcept):788 not_set.add(ComplexAssertion(Not(assertion.concept), assertion.obj))789 elif isinstance(assertion, RelationAssertion):790 # should not do anything791 pass792 elif isinstance(assertion, ComplexAssertion):793 not_set.add(ComplexAssertion(push_in_not(Not(assertion.formula)), assertion.obj))794 elif isinstance(assertion, InequalityAssertion):795 # checked before796 pass797 else:798 raise RuntimeError("should not happen")799 for assertion in abox:800 if assertion in not_set:801 return False802 return True803def is_this_top_something(c: Union[DefinedConcept, ComplexAssertion, Formula, Concept]):804 return c == Top \805 or (c == Top.definition or c == push_in_not(Not(Bottom.definition))) \806 or (isinstance(c, DefinedConcept) and (c.definition == Top.definition or c == push_in_not(Not(Bottom.definition)))) \807 or (isinstance(c, ComplexAssertion) and (c.formula == Top.definition or c == push_in_not(Not(Bottom.definition)))) \808 or (isinstance(c, Formula) and (c == Top.definition or c == push_in_not(Not(Bottom.definition))))809def is_this_bottom_something(c: Union[DefinedConcept, ComplexAssertion, Formula, Concept]):810 return c == Bottom \811 or (c == Bottom.definition or c == push_in_not(Not(Top.definition))) \812 or (isinstance(c, DefinedConcept) and (813 c.definition == Bottom.definition or c == push_in_not(Not(Top.definition)))) \814 or (isinstance(c, ComplexAssertion) and (815 c.formula == Bottom.definition or c == push_in_not(Not(Top.definition)))) \816 or (isinstance(c, Formula) and (c == Bottom.definition or c == push_in_not(Not(Top.definition))))817def is_this_assertion_top(ca: ComplexAssertion) -> bool:818 if not isinstance(ca, ComplexAssertion):819 raise ValueError820 obj: Constant = ca.obj821 return is_this_top_something(ca.formula) or build_cf_query(Top.definition, obj) == ca822def is_this_assertion_bottom(ca: ComplexAssertion) -> bool:823 if not isinstance(ca, ComplexAssertion):824 raise ValueError825 obj: Constant = ca.obj826 return is_this_bottom_something(ca.formula) or build_cf_query(Bottom.definition, obj) == ca827def pre_process_top(abox: ABox):828 # directly edit in place829 new_tops : Set[Assertion] = set()830 for assertion in abox:831 if isinstance(assertion, ConceptAssertion):832 new_tops.add(Top(assertion.obj))833 elif isinstance(assertion, RelationAssertion):834 new_tops.add(Top(assertion.obj1))835 new_tops.add(Top(assertion.obj2))836 elif isinstance(assertion, ComplexAssertion):837 new_tops.add(Top(assertion.obj))838 elif isinstance(assertion, InequalityAssertion):839 new_tops.add(Top(assertion.obj1))840 new_tops.add(Top(assertion.obj2))841 new_tops = process_abox(new_tops)842 # just an add all843 abox.update(new_tops)844def post_process_bottom(abox: ABox) -> Optional[ABox]:845 # this clears abox containing bottom, so they can later be deleted846 # and removes top from existing abox847 new_abox = set()848 for assertion in abox:849 if isinstance(assertion, ComplexAssertion):850 # print("checking:", assertion)851 if is_this_assertion_bottom(assertion):852 print("bottom found", assertion)853 return None854 elif is_this_assertion_top(assertion):855 # in fact need to add all top, don't remove...856 pass857 # print("top found", assertion)858 # don't add859 # continue860 else:861 # print("neither")862 new_abox.add(assertion)863 else:864 new_abox.add(assertion)865 return new_abox866def run_tableau_algo(abox: ABox, verbose=False):867 # hash?868 # duplicate abox?869 worlds: List[ABox] = [abox]870 if verbose:871 print("---initial----")872 print("Current Worlds: ", len(worlds))873 for idx, w in enumerate(worlds):874 print(idx, "len", len(w), "----")875 for idx2, l in enumerate(w):876 print("world", idx, "line", idx2, l)877 found_one_apply = False878 cs = ConstantStorage()879 cb = ConstantBuilder()880 while True:881 # pre process882 for world in worlds:883 pre_process_top(world)884 current_idx = -1885 replace_new_list = None886 rules = [and_rule, union_rule, forall_rule, choose_rule, partial(at_least_rule, cb=cb), at_most_rule, partial(exist_rule, cs=cs),]887 # rules = [and_rule, forall_rule ,partial(exist_rule, cs=cs)]888 for rule in rules:889 for idx, w in enumerate(worlds):890 found, new_list = rule(w)891 if found:892 print("apply on world ", idx)893 # print("found! on world", idx)894 print("rule!", rule)895 found_one_apply = True896 current_idx = idx897 replace_new_list = new_list898 break899 if current_idx != -1:900 break901 if current_idx != -1 and replace_new_list is not None:902 worlds.pop(current_idx)903 worlds += replace_new_list904 # process top/bottom905 post_processed_world_list = []906 for world in worlds:907 new_world: Optional[ABox] = post_process_bottom(world)908 if new_world is not None:909 post_processed_world_list.append(new_world)910 else:911 if verbose:912 print("BOTTOM FOUND: world eliminated!")913 print("eliminated world: ")914 for idx, assertion in enumerate(world):915 print(idx, assertion)916 worlds = post_processed_world_list917 # post process 2: remove same world918 # simulate a set of aboxes919 if verbose:920 print("--dedupe world--")921 print("before dedupe len=", len(worlds))922 frozen_worlds = {frozenset(world) for world in worlds}923 worlds = [set(world) for world in frozen_worlds]924 print("after dedupe len=", len(worlds))925 # print world926 print("-------intermediate-----------")927 print("Current Worlds: ", len(worlds))928 for idx, w in enumerate(worlds):929 print(idx, "len", len(w), "----")930 for idx2, l in enumerate(w):931 print("world", idx, "line", idx2, l)932 print("------------------")933 # jump out if no more rules can be applied934 if not found_one_apply:935 break936 # reset937 found_one_apply = False938 # while: no more rules can be applied939 # rule has priority940 #941 # remove with index?942 # check if has an open world943 print("-------final-----------")944 print("Worlds: ", len(worlds))945 world_open_list: List[bool] = []946 for idx, w in enumerate(worlds):947 if verbose:948 print(idx, w)949 for idx2, l in enumerate(w):950 print("world", idx, "line", idx2, l)951 world_open_bool: bool = is_abox_open(w)952 print(idx, "open?", world_open_bool)953 world_open_list.append(world_open_bool)954 print("world overview: ", len(world_open_list), world_open_list)955 print("final (consistency, true=open) verdict: ", any(world_open_list))956 return any(world_open_list)957def is_subsumption_of(c1: Concept, c2: Concept) -> bool:958 """959 C ⊑T D960 :param c1: C961 :param c2: D962 :return:963 """964 anded = push_in_not(And(expand_concept(c1),Not(expand_concept(c2))))965 a = Constant("$a")966 abox = {(anded)(a)}967 is_consistent = run_tableau_algo(process_abox(abox))968 return not is_consistent969if __name__ == '__main__':970 Smart = PrimitiveConcept("Smart")971 Studious = PrimitiveConcept("Studious")972 GoodStudent = DefinedConcept("GoodStudent", And(Smart, Studious))973 attendBy = Relation("attendBy")974 topic = Relation("topic")975 Course = DefinedConcept("Course", Exists(topic, Top))976 Good = PrimitiveConcept("Good")977 GoodCourse = DefinedConcept("GoodCourse", And(Good, Course))978 # print(expand_concept(GoodCourse))979 s1 = Constant("Student 1")980 c1 = Constant("Course 1")981 # print(GoodStudent(a))982 # print(attendBy(c1, s1))983 a = Constant("a")984 assertion = And(Exists(attendBy, Smart), And(Exists(attendBy, Studious), Not(Exists(attendBy, GoodStudent))))(a)985 abox = {assertion}986 run_tableau_algo(process_abox(abox))987 c1 = DefinedConcept("c1", And(Exists(attendBy, Smart), Exists(attendBy, Studious)))988 c2 = DefinedConcept("c2", Exists(attendBy, GoodStudent))989 # should be false...

Full Screen

Full Screen

mod_state_assertion_commands.py

Source:mod_state_assertion_commands.py Github

copy

Full Screen

1from cli import *2from sim_commands import conf_object_expander3import os4import sys5try:6 temp_filename = "/tmp/state-assertion-" + os.environ['USER'] + ".gz"7except:8 temp_filename = "/tmp/state-assertion.gz"9def get_sa_name(name):10 if not name:11 name = "sa0"12 seq = 013 try:14 while 1:15 SIM_get_object(name)16 seq = seq + 117 name = "sa%d" % seq18 except:19 pass20 return name21compr_strings = ["guess", "none", "bz2", "gz"]22def compr_expander(string):23 return get_completions(string, compr_strings)24def get_sa_compr(compression):25 if compression == "guess":26 return 027 elif compression == "no" or compression == "none":28 return 129 elif compression == "bz2":30 return 231 elif compression == "gz":32 return 333 else:34 print "Unknown compression: %s" % compression35 return 036def get_compr_from_filename(file):37 if (file[-3:] == ".gz"):38 return 339 elif (file[-4:] == ".bz2"):40 return 241 else:42 return 143def state_assertion_cf_common(file, compression, name, align, postev):44 name = get_sa_name(name)45 compr_nb = get_sa_compr(compression)46 if (compr_nb == 0):47 compr_nb = get_compr_from_filename(file)48 sa = SIM_new_object("state-assertion", name)49 print "Creating file '%s' with compression '%s'"%(file, compr_strings[compr_nb])50 sa.create = [file, compr_nb, "", -1, align, postev]51 return sa52# create a new assertion object53def state_assertion_create_file(file, compression, name, align, postev):54 sa = state_assertion_cf_common(file, compression, name, align, postev)55 print sa.name, "created. You probably want to add some objects or memory space now with 'add' and 'add-mem-lis', then run 'start' to begin the assertion process."56new_command("state-assertion-create-file", state_assertion_create_file,57 [arg(filename_t(), "file"),58 arg(str_t, "compression", "?", "guess", expander = compr_expander),59 arg(str_t, "name", "?", ""),60 arg(int_t, "align", "?", 8L),61 arg(int_t, "post_events", "?", 1L)],62 type = "state-assertion commands",63 short = "record a state assertion file",64 doc = """65 This command creates a state assertion file.<br/>66 - <i>file</i> is the name of the file to be created<br/>67 - <i>compression</i> is the compression used (none, bz2, gz)<br/>68 - <i>name</i> is the name of the object to be created. Default is saX where X is a number.69 - <i>align</i> is the alignment of the structures inside the file. It can be useful to set it so that objects saving their state are sure to get correctly aligned structures. Default is 8 which is sufficient for most hosts.70 - <i>post_events</i> tells state-assertion to post events by itself for recording and comparing. Default is true.71 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="66")72# connect a server to drive a state-assertion73def state_assertion_connect(server, port, compression, align, postev, name):74 name = get_sa_name(name)75 compr_nb = get_sa_compr(compression)76 # no way to guess here, so we just patch77 if (compr_nb == 0):78 compr_nb = 179 sa = SIM_new_object("state-assertion", name)80 sa.create = ["", compr_nb, server, port, align, postev]81 print name, "connected. You probably want to add some objects or memory space now with 'add' and 'add-mem-lis', then run 'start' to begin the assertion process."82 return sa83new_command("state-assertion-connect", state_assertion_connect,84 [arg(str_t, "server", "?", "localhost"),85 arg(int_t, "port", "?", 6666L),86 arg(str_t, "compression", "?", "none", expander = compr_expander),87 arg(int_t, "align", "?", 8L),88 arg(int_t, "post_events", "?", 1L),89 arg(str_t, "name", "?", "")],90 type = "state-assertion commands",91 short = "connect to a state-assertion receiver",92 doc = """93 This command connects to a state-assertion receiver so that all data94 gathered during the state recording will be sent over to the95 receiver.<br/>96 - <i>server</i> receiver host waiting for the connection<br/>97 - <i>port</i> port number on which the receiver is waiting for a connection<br/>98 - <i>compression</i> is the compression used (none, bz2, gz)<br/>99 - <i>name</i> is the name of the object to be created. Default is saX where X is a number.100 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="96")101def state_assertion_of_common(file, compression, name, postev):102 name = get_sa_name(name)103 compr_nb = get_sa_compr(compression)104 if (compr_nb == 0):105 compr_nb = get_compr_from_filename(file)106 sa = SIM_new_object("state-assertion", name)107 print "Opening file '%s' with compression '%s'"%(file, compr_strings[compr_nb])108 sa.open = [file, compr_nb, -1, postev]109 return sa110# open a state assertion file111def state_assertion_open_file(file, compression, name, postev):112 sa = state_assertion_of_common(file, compression, name, postev)113 print sa.name, "opened. You should run 'start' to begin the assertion process."114new_command("state-assertion-open-file", state_assertion_open_file,115 [arg(filename_t(exist = 1), "file"),116 arg(str_t, "compression", "?", "guess", expander = compr_expander),117 arg(str_t, "name", "?", ""),118 arg(int_t, "post_events", "?", 1L)],119 type = "state-assertion commands",120 short = "open a state assertion file for comparing",121 doc = """122 Open a state assertion file to compare it to the current execution.<br/>123 - <i>name</i> is the name of the object. A default name in saX is provided if none is given.<br/>124 - <i>file</i> is the name of the state assertion file<br/>125 - <i>compression</i> is the compression used on the file (none, bz2, gz)126 - <i>post_events</i>127 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="131")128def state_assertion_open_server(port, compression, name, postev):129 name = get_sa_name(name)130 compr_nb = get_sa_compr(compression)131 if compr_nb == 0:132 compr_nb = 1133 sa = SIM_new_object("state-assertion", name)134 sa.open = ["", compr_nb, port, postev]135 print name, "connected. You should run start to begin the assertion process."136new_command("state-assertion-receive", state_assertion_open_server,137 [arg(int_t, "port", "?", 6666L),138 arg(str_t, "compression", "?", "none", expander = compr_expander),139 arg(str_t, "name", "?", ""),140 arg(int_t, "post_events", "?", 1L)],141 type = "state-assertion commands",142 short = "wait for a connection from a state assertion sender",143 doc = """144 Wait for a connection (state-assertion-connect) from a sender. The data received from the sender will be compared against the current execution.<br/>145 - <i>port</i> indicates where simics should wait for the connection<br/>146 - <i>compression</i> is the compression used on the file (none, bz2, gz)147 - <i>name</i> is the name of the object. A default name in saX is provided if none is given.<br/>148 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="156")149# add an conf object for assertion150def state_assertion_add_cmd(sa, obj, steps, type, attr):151 sa.add = [obj, steps, type, attr];152new_command("add", state_assertion_add_cmd,153 [arg(str_t, "object-name", expander = conf_object_expander),154 arg(int_t, "steps"),155 arg(int_t, "type", "?", 1),156 arg(str_t, "attribute", "?", "")],157 type = "state-assertion commands",158 short = "add an object to be asserted",159 namespace = "state-assertion",160 doc = """161 Add an object to a state assertion file so its state will be recorded.<br/>162 - <i>obj</i> is the name of the object to be added.<br/>163 - <i>steps</i> is the number of steps between each save.<br/>164 - <i>type</i> is the type of state saved in the file (for devices that provide several, the most complete state is saved by default). IA64 cpus have two states, 1 is system-level, 2 is user-level (without CR, PSR, RR)<br/>165 - <i>attribute</i> is the attribute to save. If specified, the save_state interface is not used and the attribute is saved instead. This is useful for object having no save_state interface.166 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="174")167# add an conf object for assertion168def state_assertion_add_mem_lis_cmd(sa, memory_space):169 sa.addmemlis = [memory_space]170new_command("add-mem-lis", state_assertion_add_mem_lis_cmd,171 [arg(str_t, "memory_space")],172 type = "state-assertion commands",173 short = "add a memory listener on the specified memory space",174 namespace = "state-assertion",175 doc = """176 Add a memory listener to a memory space so that all memory transactions will be recorded in the file.<br/>177 - <i>memory_space</i> is the name of the memory space to listen to.<br/>178 - <i>-o</i> allows state-assertion to take over an existing memory hierarchy.<br/>179 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="194")180# fforward an assertion file181def state_assertion_ff_cmd(sa, obj, steps):182 sa.fforward = [obj, steps];183new_command("fforward", state_assertion_ff_cmd,184 [arg(str_t, "object-name", expander = conf_object_expander),185 arg(int_t, "steps")],186 type = "state-assertion commands",187 short = "fast-forward a state assertion file when comparing",188 namespace = "state-assertion",189 doc = """190 Fast-forward a state assertion file. The contents of the file are ignored until the object <i>obj</i> has skipped <i>steps</i> steps. The simulation is not fast-forwarded. Other objects in the file are fast-forwarded along.191 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="213")192# start trace assertion193def state_assertion_start_cmd(sa):194 sa.start = 1195new_command("start", state_assertion_start_cmd,196 [],197 type = "state-assertion commands",198 short = "start trace asserting/comparing",199 namespace = "state-assertion",200 doc = """201 Start the recording/comparison.202 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="227")203# stop trace assertion204def state_assertion_stop_cmd(sa):205 sa.stop = 1206new_command("stop", state_assertion_stop_cmd,207 [],208 type = "state-assertion commands",209 short = "stop trace asserting/comparing and close the file",210 namespace = "state-assertion",211 doc = """212 Stop the recording/comparison, flush the buffers and close the file.213 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="240")214# stop trace assertion215def state_assertion_info_cmd(sa):216 sa.info = 1217new_command("info", state_assertion_info_cmd,218 [],219 type = "state-assertion commands",220 short = "provide information about the state assertion",221 namespace = "state-assertion",222 doc = """223 Describe the state assertion performed by the current object.224 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="253")225# stop trace assertion226def state_assertion_status_cmd(sa):227 sa.status = 1228new_command("status", state_assertion_status_cmd,229 [],230 type = "state-assertion commands",231 short = "provide the status of the current state assertion",232 namespace = "state-assertion",233 doc = """234 Describe the status of the state assertion performed by the235 current object.236 """, filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="267")237# simple record238def state_assertion_record(file, compression, object, steps, type):239 sa = state_assertion_cf_common(file, compression, "", 8, 1)240 state_assertion_add_cmd(sa, object, steps, type, "")241 state_assertion_start_cmd(sa)242new_command("state-assertion-simple-record", state_assertion_record,243 [arg(str_t, "file", "?", temp_filename),244 arg(str_t, "compression", "?", "guess", expander = compr_expander),245 arg(str_t, "object-name", "?", "cpu0",246 expander = conf_object_expander),247 arg(int_t, "steps", "?", 1),248 arg(int_t, "type", "?", 1)], 249 type = "state-assertion commands",250 short = "record the state of an object every x steps",251 doc = """252Create a file (by default /tmp/state-assertion-$USER.gz) and save the state253of <i>object</i> every <i>steps</i> steps. You just have to run 'c' afterwards254to begin the recording.<br/> <i>object</i> is the simics object whose state255will be recorded. <i>steps</i> is the number of steps256between each state recording (default is 1).""", filename="/mp/simics-3.0/src/extensions/state-assertion/commands.py", linenumber="283")257# simple assert258def state_assertion_assert(file, compression, post):259 sa = state_assertion_of_common(file, compression, "", post)260 state_assertion_start_cmd(sa)261new_command("state-assertion-simple-assert", state_assertion_assert,262 [arg(filename_t(), "file", "?", temp_filename),263 arg(str_t, "compression", "?", "guess", expander = compr_expander),264 arg(int_t, "post_event", "?", 1)],265 type = "state-assertion commands",266 short = "assert the file",267 doc = """268 This command asserts the current run against the file. You just have to run 'c' afterwards to begin the assertion process....

Full Screen

Full Screen

file.py

Source:file.py Github

copy

Full Screen

1# Copyright (C) 2014 The Android Open Source Project2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14from collections import namedtuple15from common.immutables import ImmutableDict16from common.logger import Logger17from file_format.c1visualizer.struct import C1visualizerFile, C1visualizerPass18from file_format.checker.struct import CheckerFile, TestCase, TestAssertion19from match.line import MatchLines, EvaluateLine20MatchScope = namedtuple("MatchScope", ["start", "end"])21MatchInfo = namedtuple("MatchInfo", ["scope", "variables"])22class MatchFailedException(Exception):23 def __init__(self, assertion, lineNo, variables):24 self.assertion = assertion25 self.lineNo = lineNo26 self.variables = variables27def splitIntoGroups(assertions):28 """ Breaks up a list of assertions, grouping instructions which should be29 tested in the same scope (consecutive DAG and NOT instructions).30 """31 splitAssertions = []32 lastVariant = None33 for assertion in assertions:34 if (assertion.variant == lastVariant and35 assertion.variant in [TestAssertion.Variant.DAG, TestAssertion.Variant.Not]):36 splitAssertions[-1].append(assertion)37 else:38 splitAssertions.append([assertion])39 lastVariant = assertion.variant40 return splitAssertions41def findMatchingLine(assertion, c1Pass, scope, variables, excludeLines=[]):42 """ Finds the first line in `c1Pass` which matches `assertion`.43 Scan only lines numbered between `scope.start` and `scope.end` and not on the44 `excludeLines` list.45 Returns the index of the `c1Pass` line matching the assertion and variables46 values after the match.47 Raises MatchFailedException if no such `c1Pass` line can be found.48 """49 for i in range(scope.start, scope.end):50 if i in excludeLines: continue51 newVariables = MatchLines(assertion, c1Pass.body[i], variables)52 if newVariables is not None:53 return MatchInfo(MatchScope(i, i), newVariables)54 raise MatchFailedException(assertion, scope.start, variables)55def matchDagGroup(assertions, c1Pass, scope, variables):56 """ Attempts to find matching `c1Pass` lines for a group of DAG assertions.57 Assertions are matched in the list order and variable values propagated. Only58 lines in `scope` are scanned and each line can only match one assertion.59 Returns the range of `c1Pass` lines covered by this group (min/max of matching60 line numbers) and the variable values after the match of the last assertion.61 Raises MatchFailedException when an assertion cannot be satisfied.62 """63 matchedLines = []64 for assertion in assertions:65 assert assertion.variant == TestAssertion.Variant.DAG66 match = findMatchingLine(assertion, c1Pass, scope, variables, matchedLines)67 variables = match.variables68 assert match.scope.start == match.scope.end69 assert match.scope.start not in matchedLines70 matchedLines.append(match.scope.start)71 return MatchInfo(MatchScope(min(matchedLines), max(matchedLines)), variables)72def testNotGroup(assertions, c1Pass, scope, variables):73 """ Verifies that none of the given NOT assertions matches a line inside74 the given `scope` of `c1Pass` lines.75 Raises MatchFailedException if an assertion matches a line in the scope.76 """77 for i in range(scope.start, scope.end):78 line = c1Pass.body[i]79 for assertion in assertions:80 assert assertion.variant == TestAssertion.Variant.Not81 if MatchLines(assertion, line, variables) is not None:82 raise MatchFailedException(assertion, i, variables)83def testEvalGroup(assertions, scope, variables):84 for assertion in assertions:85 if not EvaluateLine(assertion, variables):86 raise MatchFailedException(assertion, scope.start, variables)87def MatchTestCase(testCase, c1Pass):88 """ Runs a test case against a C1visualizer graph dump.89 Raises MatchFailedException when an assertion cannot be satisfied.90 """91 assert testCase.name == c1Pass.name92 matchFrom = 093 variables = ImmutableDict()94 c1Length = len(c1Pass.body)95 # NOT assertions are verified retrospectively, once the scope is known.96 pendingNotAssertions = None97 # Prepare assertions by grouping those that are verified in the same scope.98 # We also add None as an EOF assertion that will set scope for NOTs.99 assertionGroups = splitIntoGroups(testCase.assertions)100 assertionGroups.append(None)101 for assertionGroup in assertionGroups:102 if assertionGroup is None:103 # EOF marker always matches the last+1 line of c1Pass.104 match = MatchInfo(MatchScope(c1Length, c1Length), None)105 elif assertionGroup[0].variant == TestAssertion.Variant.Not:106 # NOT assertions will be tested together with the next group.107 assert not pendingNotAssertions108 pendingNotAssertions = assertionGroup109 continue110 elif assertionGroup[0].variant == TestAssertion.Variant.InOrder:111 # Single in-order assertion. Find the first line that matches.112 assert len(assertionGroup) == 1113 scope = MatchScope(matchFrom, c1Length)114 match = findMatchingLine(assertionGroup[0], c1Pass, scope, variables)115 elif assertionGroup[0].variant == TestAssertion.Variant.NextLine:116 # Single next-line assertion. Test if the current line matches.117 assert len(assertionGroup) == 1118 scope = MatchScope(matchFrom, matchFrom + 1)119 match = findMatchingLine(assertionGroup[0], c1Pass, scope, variables)120 elif assertionGroup[0].variant == TestAssertion.Variant.DAG:121 # A group of DAG assertions. Match them all starting from the same point.122 scope = MatchScope(matchFrom, c1Length)123 match = matchDagGroup(assertionGroup, c1Pass, scope, variables)124 else:125 assert assertionGroup[0].variant == TestAssertion.Variant.Eval126 scope = MatchScope(matchFrom, c1Length)127 testEvalGroup(assertionGroup, scope, variables)128 continue129 if pendingNotAssertions:130 # Previous group were NOT assertions. Make sure they don't match any lines131 # in the [matchFrom, match.start) scope.132 scope = MatchScope(matchFrom, match.scope.start)133 testNotGroup(pendingNotAssertions, c1Pass, scope, variables)134 pendingNotAssertions = None135 # Update state.136 assert matchFrom <= match.scope.end137 matchFrom = match.scope.end + 1138 variables = match.variables139def MatchFiles(checkerFile, c1File, targetArch, debuggableMode):140 for testCase in checkerFile.testCases:141 if testCase.testArch not in [None, targetArch]:142 continue143 if testCase.forDebuggable != debuggableMode:144 continue145 # TODO: Currently does not handle multiple occurrences of the same group146 # name, e.g. when a pass is run multiple times. It will always try to147 # match a check group against the first output group of the same name.148 c1Pass = c1File.findPass(testCase.name)149 if c1Pass is None:150 Logger.fail("Test case not found in the CFG file",151 testCase.fileName, testCase.startLineNo, testCase.name)152 Logger.startTest(testCase.name)153 try:154 MatchTestCase(testCase, c1Pass)155 Logger.testPassed()156 except MatchFailedException as e:157 lineNo = c1Pass.startLineNo + e.lineNo158 if e.assertion.variant == TestAssertion.Variant.Not:159 msg = "NOT assertion matched line {}"160 else:161 msg = "Assertion could not be matched starting from line {}"162 msg = msg.format(lineNo)...

Full Screen

Full Screen

badge_assertion.py

Source:badge_assertion.py Github

copy

Full Screen

1# coding: utf-82from datetime import date, datetime3from typing import List, Dict, Type4from openapi_server.models.base_model_ import Model5from openapi_server.models.badge_assertion_recipient import BadgeAssertionRecipient6from openapi_server import util7class BadgeAssertion(Model):8 """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).9 Do not edit the class manually.10 """11 def __init__(self, open_badge_id: str=None, created_at: datetime=None, created_by: str=None, badge_class: str=None, issuer: str=None, image: str=None, recipient: BadgeAssertionRecipient=None, issued_on: datetime=None):12 """BadgeAssertion - a model defined in OpenAPI13 :param open_badge_id: The open_badge_id of this BadgeAssertion.14 :param created_at: The created_at of this BadgeAssertion.15 :param created_by: The created_by of this BadgeAssertion.16 :param badge_class: The badge_class of this BadgeAssertion.17 :param issuer: The issuer of this BadgeAssertion.18 :param image: The image of this BadgeAssertion.19 :param recipient: The recipient of this BadgeAssertion.20 :param issued_on: The issued_on of this BadgeAssertion.21 """22 self.openapi_types = {23 'open_badge_id': str,24 'created_at': datetime,25 'created_by': str,26 'badge_class': str,27 'issuer': str,28 'image': str,29 'recipient': BadgeAssertionRecipient,30 'issued_on': datetime31 }32 self.attribute_map = {33 'open_badge_id': 'openBadgeID',34 'created_at': 'createdAt',35 'created_by': 'createdBy',36 'badge_class': 'badgeClass',37 'issuer': 'issuer',38 'image': 'image',39 'recipient': 'recipient',40 'issued_on': 'issuedOn'41 }42 self._open_badge_id = open_badge_id43 self._created_at = created_at44 self._created_by = created_by45 self._badge_class = badge_class46 self._issuer = issuer47 self._image = image48 self._recipient = recipient49 self._issued_on = issued_on50 @classmethod51 def from_dict(cls, dikt: dict) -> 'BadgeAssertion':52 """Returns the dict as a model53 :param dikt: A dict.54 :return: The BadgeAssertion of this BadgeAssertion.55 """56 return util.deserialize_model(dikt, cls)57 @property58 def open_badge_id(self):59 """Gets the open_badge_id of this BadgeAssertion.60 :return: The open_badge_id of this BadgeAssertion.61 :rtype: str62 """63 return self._open_badge_id64 @open_badge_id.setter65 def open_badge_id(self, open_badge_id):66 """Sets the open_badge_id of this BadgeAssertion.67 :param open_badge_id: The open_badge_id of this BadgeAssertion.68 :type open_badge_id: str69 """70 self._open_badge_id = open_badge_id71 @property72 def created_at(self):73 """Gets the created_at of this BadgeAssertion.74 :return: The created_at of this BadgeAssertion.75 :rtype: datetime76 """77 return self._created_at78 @created_at.setter79 def created_at(self, created_at):80 """Sets the created_at of this BadgeAssertion.81 :param created_at: The created_at of this BadgeAssertion.82 :type created_at: datetime83 """84 self._created_at = created_at85 @property86 def created_by(self):87 """Gets the created_by of this BadgeAssertion.88 :return: The created_by of this BadgeAssertion.89 :rtype: str90 """91 return self._created_by92 @created_by.setter93 def created_by(self, created_by):94 """Sets the created_by of this BadgeAssertion.95 :param created_by: The created_by of this BadgeAssertion.96 :type created_by: str97 """98 self._created_by = created_by99 @property100 def badge_class(self):101 """Gets the badge_class of this BadgeAssertion.102 :return: The badge_class of this BadgeAssertion.103 :rtype: str104 """105 return self._badge_class106 @badge_class.setter107 def badge_class(self, badge_class):108 """Sets the badge_class of this BadgeAssertion.109 :param badge_class: The badge_class of this BadgeAssertion.110 :type badge_class: str111 """112 self._badge_class = badge_class113 @property114 def issuer(self):115 """Gets the issuer of this BadgeAssertion.116 :return: The issuer of this BadgeAssertion.117 :rtype: str118 """119 return self._issuer120 @issuer.setter121 def issuer(self, issuer):122 """Sets the issuer of this BadgeAssertion.123 :param issuer: The issuer of this BadgeAssertion.124 :type issuer: str125 """126 self._issuer = issuer127 @property128 def image(self):129 """Gets the image of this BadgeAssertion.130 :return: The image of this BadgeAssertion.131 :rtype: str132 """133 return self._image134 @image.setter135 def image(self, image):136 """Sets the image of this BadgeAssertion.137 :param image: The image of this BadgeAssertion.138 :type image: str139 """140 self._image = image141 @property142 def recipient(self):143 """Gets the recipient of this BadgeAssertion.144 :return: The recipient of this BadgeAssertion.145 :rtype: BadgeAssertionRecipient146 """147 return self._recipient148 @recipient.setter149 def recipient(self, recipient):150 """Sets the recipient of this BadgeAssertion.151 :param recipient: The recipient of this BadgeAssertion.152 :type recipient: BadgeAssertionRecipient153 """154 self._recipient = recipient155 @property156 def issued_on(self):157 """Gets the issued_on of this BadgeAssertion.158 :return: The issued_on of this BadgeAssertion.159 :rtype: datetime160 """161 return self._issued_on162 @issued_on.setter163 def issued_on(self, issued_on):164 """Sets the issued_on of this BadgeAssertion.165 :param issued_on: The issued_on of this BadgeAssertion.166 :type issued_on: datetime167 """...

Full Screen

Full Screen

test_tap.py

Source:test_tap.py Github

copy

Full Screen

1from django.utils import unittest2from djangojs.tap import TapParser, TapTest, TapModule, TapAssertion3class TapAssertionTest(unittest.TestCase):4 def test_parse_ok(self):5 '''Should parse a simple OK assertion'''6 assertion = TapAssertion.parse('ok 1')7 self.assertIsNotNone(assertion)8 self.assertEqual(assertion.num, 1)9 self.assertEqual(assertion.success, True)10 self.assertEqual(assertion.parsed_indent, '')11 self.assertEqual(assertion.message, None)12 self.assertEqual(assertion.expected, None)13 self.assertEqual(assertion.got, None)14 self.assertListEqual(assertion.stack, [])15 def test_parse_not_ok(self):16 '''Should parse a simple NOT OK assertion'''17 assertion = TapAssertion.parse('not ok 2')18 self.assertIsNotNone(assertion)19 self.assertEqual(assertion.num, 2)20 self.assertEqual(assertion.success, False)21 self.assertEqual(assertion.parsed_indent, '')22 self.assertEqual(assertion.message, None)23 self.assertEqual(assertion.expected, None)24 self.assertEqual(assertion.got, None)25 self.assertListEqual(assertion.stack, [])26 def test_parse_ok_with_message(self):27 '''Should parse an OK assertion with message'''28 assertion = TapAssertion.parse('ok 284 - I should be equal to me.')29 self.assertIsNotNone(assertion)30 self.assertEqual(assertion.num, 284)31 self.assertEqual(assertion.success, True)32 self.assertEqual(assertion.parsed_indent, '')33 self.assertEqual(assertion.message, 'I should be equal to me.')34 self.assertEqual(assertion.expected, None)35 self.assertEqual(assertion.got, None)36 self.assertListEqual(assertion.stack, [])37 def test_parse_not_ok_with_message(self):38 '''Should parse a NOT OK assertion with message'''39 assertion = TapAssertion.parse('not ok 284 - I should be equal to me.')40 self.assertIsNotNone(assertion)41 self.assertEqual(assertion.num, 284)42 self.assertEqual(assertion.success, False)43 self.assertEqual(assertion.parsed_indent, '')44 self.assertEqual(assertion.message, 'I should be equal to me.')45 self.assertEqual(assertion.expected, None)46 self.assertEqual(assertion.got, None)47 self.assertListEqual(assertion.stack, [])48 def test_parse_not_ok_with_source(self):49 '''Should parse a NOT OK assertion with message and source'''50 line = (51 'not ok 298 - reset should not modify test status, '52 'source: at http://localhost:8000/static/js/test/libs/qunit.js:435'53 )54 assertion = TapAssertion.parse(line)55 self.assertIsNotNone(assertion)56 self.assertEqual(assertion.num, 298)57 self.assertEqual(assertion.success, False)58 self.assertEqual(assertion.parsed_indent, '')59 self.assertEqual(assertion.message, 'reset should not modify test status')60 self.assertEqual(assertion.expected, None)61 self.assertEqual(assertion.got, None)62 self.assertListEqual(assertion.stack, ['http://localhost:8000/static/js/test/libs/qunit.js:435'])63 def test_parse_not_ok_with_expectations(self):64 '''Should parse a NOT OK assertion with expectations'''65 line = "not ok 42 - expected: 'something', got: 'something else'"66 assertion = TapAssertion.parse(line)67 self.assertIsNotNone(assertion)68 self.assertEqual(assertion.num, 42)69 self.assertEqual(assertion.success, False)70 self.assertEqual(assertion.parsed_indent, '')71 self.assertEqual(assertion.message, None)72 self.assertEqual(assertion.expected, 'something')73 self.assertEqual(assertion.got, 'something else')74 self.assertListEqual(assertion.stack, [])75 def test_parse_not_ok_with_all(self):76 '''Should parse a NOT OK assertion with all extras'''77 line = (78 "not ok 42 - reset should not modify test status, "79 "expected: 'something', got: 'something else', "80 "source: at http://localhost:8000/static/js/test/libs/qunit.js:435"81 )82 assertion = TapAssertion.parse(line)83 self.assertIsNotNone(assertion)84 self.assertEqual(assertion.num, 42)85 self.assertEqual(assertion.success, False)86 self.assertEqual(assertion.parsed_indent, '')87 self.assertEqual(assertion.message, 'reset should not modify test status')88 self.assertEqual(assertion.expected, 'something')89 self.assertEqual(assertion.got, 'something else')90 self.assertListEqual(assertion.stack, ['http://localhost:8000/static/js/test/libs/qunit.js:435'])91class TapTestTest(unittest.TestCase):92 def test_parse_test(self):93 '''Should parse a test statement'''94 line = '# test: This is a test'95 test = TapTest.parse(line)96 self.assertEqual(test.name, 'This is a test')97 self.assertEqual(test.parsed_indent, '')98class TapModuleTest(unittest.TestCase):99 def test_parse_module(self):100 '''Should parse a module statement'''101 line = '# module: This is a module'102 module = TapModule.parse(line)103 self.assertEqual(module.name, 'This is a module')104 self.assertEqual(module.parsed_indent, '')105class TapParserTest(unittest.TestCase):106 def test_single_test(self):107 '''Should parse a test and its children'''108 # import ipdb; ipdb.set_trace()109 parser = TapParser(TapAssertion)110 output = '''111# test: should be defined112ok 1113not ok 2114 '''115 items = list(parser.parse(output.splitlines()))116 self.assertIsInstance(items[0], TapTest)117 self.assertIsInstance(items[1], TapAssertion)118 self.assertIsInstance(items[2], TapAssertion)119 def test_single_module(self):120 '''Should parse a module and its children'''121 parser = TapParser(TapAssertion)122 output = '''123# module: This is a module124# test: should be defined125ok 1126 '''127 items = list(parser.parse(output.splitlines()))128 self.assertIsInstance(items[0], TapModule)129 self.assertIsInstance(items[1], TapTest)...

Full Screen

Full Screen

test_bulk_assertions.py

Source:test_bulk_assertions.py Github

copy

Full Screen

...43class TestBulkAssertionTestCase(BulkAssertionTest):44 # We have to use assertion methods from the base UnitTest class,45 # so we make a number of super calls that skip BulkAssertionTest.46 # pylint: disable=bad-super-call47 def _run_assertion(self, assertion_tuple):48 """49 Run the supplied tuple of (assertion, *args) as a method on this class.50 """51 assertion, args = assertion_tuple[0], assertion_tuple[1:]52 getattr(self, assertion)(*args)53 def _raw_assert(self, assertion_name, *args, **kwargs):54 """55 Run an un-modified assertion.56 """57 # Use super(BulkAssertionTest) to make sure we get un-adulturated assertions58 return getattr(super(BulkAssertionTest, self), 'assert' + assertion_name)(*args, **kwargs)59 @ddt.data(*(STATIC_PASSING_ASSERTIONS + CONTEXT_PASSING_ASSERTIONS))60 def test_passing_asserts_passthrough(self, assertion_tuple):61 self._run_assertion(assertion_tuple)62 @ddt.data(*(STATIC_FAILING_ASSERTIONS + CONTEXT_FAILING_ASSERTIONS))63 def test_failing_asserts_passthrough(self, assertion_tuple):64 with self._raw_assert('Raises', AssertionError) as context:65 self._run_assertion(assertion_tuple)66 self._raw_assert('NotIsInstance', context.exception, BulkAssertionError)67 @ddt.data(*CONTEXT_PASSING_ASSERTIONS)68 @ddt.unpack69 def test_passing_context_assertion_passthrough(self, assertion, *args):70 assertion_args = []71 args = list(args)72 exception = args.pop(0)73 while not callable(args[0]):74 assertion_args.append(args.pop(0))75 function = args.pop(0)76 with getattr(self, assertion)(exception, *assertion_args):77 function(*args)78 @ddt.data(*CONTEXT_FAILING_ASSERTIONS)79 @ddt.unpack80 def test_failing_context_assertion_passthrough(self, assertion, *args):81 assertion_args = []82 args = list(args)83 exception = args.pop(0)84 while not callable(args[0]):85 assertion_args.append(args.pop(0))86 function = args.pop(0)87 with self._raw_assert('Raises', AssertionError) as context:88 with getattr(self, assertion)(exception, *assertion_args):89 function(*args)90 self._raw_assert('NotIsInstance', context.exception, BulkAssertionError)91 @ddt.data(*list(itertools.product(92 CONTEXT_PASSING_ASSERTIONS,93 CONTEXT_FAILING_ASSERTIONS,94 CONTEXT_FAILING_ASSERTIONS95 )))96 @ddt.unpack97 def test_bulk_assert(self, passing_assertion, failing_assertion1, failing_assertion2):98 contextmanager = self.bulk_assertions()99 contextmanager.__enter__()100 self._run_assertion(passing_assertion)101 self._run_assertion(failing_assertion1)102 self._run_assertion(failing_assertion2)103 with self._raw_assert('Raises', BulkAssertionError) as context:104 contextmanager.__exit__(None, None, None)105 self._raw_assert('Equals', len(context.exception.errors), 2)106 @ddt.data(*list(itertools.product(107 CONTEXT_FAILING_ASSERTIONS108 )))109 @ddt.unpack110 def test_nested_bulk_asserts(self, failing_assertion):111 with self._raw_assert('Raises', BulkAssertionError) as context:112 with self.bulk_assertions():113 self._run_assertion(failing_assertion)114 with self.bulk_assertions():115 self._run_assertion(failing_assertion)116 self._run_assertion(failing_assertion)117 self._raw_assert('Equal', len(context.exception.errors), 3)118 @ddt.data(*list(itertools.product(119 CONTEXT_PASSING_ASSERTIONS,120 CONTEXT_FAILING_ASSERTIONS,121 CONTEXT_FAILING_ASSERTIONS122 )))123 @ddt.unpack124 def test_bulk_assert_closed(self, passing_assertion, failing_assertion1, failing_assertion2):125 with self._raw_assert('Raises', BulkAssertionError) as context:126 with self.bulk_assertions():127 self._run_assertion(passing_assertion)128 self._run_assertion(failing_assertion1)129 self._raw_assert('Equals', len(context.exception.errors), 1)130 with self._raw_assert('Raises', AssertionError) as context:131 self._run_assertion(failing_assertion2)...

Full Screen

Full Screen

simple.py

Source:simple.py Github

copy

Full Screen

1from veripy.assertions.support import AssertionCounter, AssertionFailedError2def assertEqual(expected, actual, message=''):3 AssertionCounter.incr()4 if expected != actual:5 raise AssertionFailedError(message == '' and 'expected ' + str(expected) + ' got ' + str(actual) or message)6 else:7 return True8def assertNotEqual(expected, actual, message=''):9 AssertionCounter.incr()10 11 if expected == actual:12 raise AssertionFailedError(message == '' and 'expected not ' + str(expected) + ' got ' + str(actual) or message)13 else:14 return True15def assertGreaterThan(expected, actual, message=''):16 AssertionCounter.incr()17 18 if expected >= actual:19 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be greater than ' + str(expected) or message)20 else:21 return True22def assertGreaterThanOrEqualTo(expected, actual, message=''):23 AssertionCounter.incr()24 if expected > actual:25 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be greater than or equal to ' + str(expected) or message)26 else:27 return True28def assertLessThan(expected, actual, message=''):29 AssertionCounter.incr()30 31 if expected <= actual:32 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be less than ' + str(expected) or message)33 else:34 return True35def assertLessThanOrEqualTo(expected, actual, message=''):36 AssertionCounter.incr()37 38 if expected < actual:39 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be less than or equal to ' + str(expected) or message)40 else:41 return True42def assertNone(actual, message=''):43 AssertionCounter.incr()44 45 if not actual == None:46 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be None' or message)47 else:48 return True49def assertNotNone(actual, message=''):50 AssertionCounter.incr()51 if not actual != None:52 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to not be None' or message)53 else:54 return True55def assertTrue(actual, message=''):56 AssertionCounter.incr()57 58 if actual != True:59 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be True' or message)60 else:61 return True62def assertFalse(actual, message=''):63 AssertionCounter.incr()64 if actual != False:65 raise AssertionFailedError(message == '' and 'expected ' + str(actual) + ' to be False' or message)66 else:67 return True68def fail(message=''):69 AssertionCounter.incr()...

Full Screen

Full Screen

test_assertions.py

Source:test_assertions.py Github

copy

Full Screen

...3class Response(object):4 def __init__(self, content):5 self.content = content6class TestAssertions(unittest.TestCase):7 def test_empty_assertion(self):8 self.assertFalse(check_assertion('empty', 'AA'))9 self.assertFalse(check_assertion('empty', '12'))10 self.assertFalse(check_assertion('empty', '1'))11 self.assertFalse(check_assertion('empty', '0'))12 self.assertFalse(check_assertion('empty', 0))13 self.assertTrue(check_assertion('empty', ''))14 self.assertTrue(check_assertion('empty', None))15 def test_notempty_assertion(self):16 self.assertTrue(check_assertion('notempty', 'AA'))17 self.assertTrue(check_assertion('notempty', '12'))18 self.assertTrue(check_assertion('notempty', '1'))19 self.assertTrue(check_assertion('notempty', '0'))20 self.assertTrue(check_assertion('notempty', 0))21 self.assertFalse(check_assertion('notempty', ''))22 self.assertFalse(check_assertion('notempty', None))23 def test_in_assertion(self):24 self.assertTrue(check_assertion('in 1,2,3,4', 1))25 self.assertTrue(check_assertion('in 1,2,3,4', 2))26 self.assertTrue(check_assertion('in 1,2,3,4', 3))27 self.assertTrue(check_assertion('in 1,2,3,4', 4))28 self.assertTrue(check_assertion('in 1,2,3,4', '4'))29 self.assertFalse(check_assertion('in 1,2,3,4', 6))30 self.assertFalse(check_assertion('in 1,2,3,4', '6'))31 def test_notin_assertion(self):32 self.assertFalse(check_assertion('notin 1,2,3,4', 1))33 self.assertFalse(check_assertion('notin 1,2,3,4', 2))34 self.assertFalse(check_assertion('notin 1,2,3,4', 3))35 self.assertFalse(check_assertion('notin 1,2,3,4', 4))36 self.assertFalse(check_assertion('notin 1,2,3,4', '4'))37 self.assertTrue(check_assertion('notin 1,2,3,4', 6))38 self.assertTrue(check_assertion('notin 1,2,3,4', '6'))39if __name__ == '__main__':...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3defineSupportCode(function({Before}) {4 Before(function() {5 this.apickli = new Apickli.Apickli('http', 'localhost:8000');6 });7});8var {defineSupportCode} = require('cucumber');9defineSupportCode(function({Given, Then}) {10 Given('I have a request', function(callback) {11 this.apickli.get('/test', function(err, res) {12 if (err) {13 callback(err);14 } else {15 callback();16 }17 });18 });19 Then('I expect status code to be {int}', function(statusCode, callback) {20 this.apickli.assertResponseCode(statusCode);21 callback();22 });23});241 scenario (1 passed)253 steps (3 passed)261 scenario (1 passed)273 steps (3 passed)

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var apickli = require('apickli');3var {defineSupportCode} = require('cucumber');4var apickli = new apickli.Apickli('http', 'localhost:8000');5defineSupportCode(function({Given,When,Then}) {6 Given('I set header Accept to application/json', function (callback) {7 this.apickli.addRequestHeader('Accept', 'application/json');8 callback();9 });10 When('I GET /test', function (callback) {11 this.apickli.get('/test', callback);12 });13 Then('I should get HTTP response code 200', function (callback) {14 assert.equal(this.apickli.getResponseObject().statusCode, 200);15 callback();16 });17});18var apickli = require('apickli');19var {defineSupportCode} = require('cucumber');20var apickli = new apickli.Apickli('http', 'localhost:8000');21defineSupportCode(function({Given,When,Then}) {22 Given('I set header Accept to application/json', function (callback) {23 this.apickli.addRequestHeader('Accept', 'application/json');24 callback();25 });26 When('I GET /test', function (callback) {27 this.apickli.get('/test', callback);28 });29 Then('I should get HTTP response code 200', function (callback) {30 this.apickli.assertResponseCode(200);31 callback();32 });33});

Full Screen

Using AI Code Generation

copy

Full Screen

1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3defineSupportCode(function({Given, When, Then}) {4 Given('I set header Accept to application/json', function(callback) {5 this.apickli.addRequestHeader('Accept', 'application/json');6 callback();7 });8 When('I GET /api/1', function(callback) {9 });10 Then('the response code is 200', function(callback) {11 this.apickli.assertResponseCode(200);12 callback();13 });14});151 scenario (1 passed)163 steps (3 passed)

Full Screen

Using AI Code Generation

copy

Full Screen

1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3var assert = require('assert');4defineSupportCode(function({Given, When, Then}) {5 Given('I have a variable set to {int}', function (number, callback) {6 this.apickli.setGlobalVariable('number', number);7 callback();8 });9 When('I increment the variable by {int}', function (number, callback) {10 this.apickli.setGlobalVariable('number', this.apickli.getGlobalVariable('number') + number);11 callback();12 });13 Then('the variable should contain {int}', function (number, callback) {14 assert.equal(this.apickli.getGlobalVariable('number'), number);15 callback();16 });17});

Full Screen

Using AI Code Generation

copy

Full Screen

1var Apickli = require('apickli');2var apickli = new Apickli();3var assert = require('assert');4module.exports = function () {5 this.Given(/^I set header (.*) to (.*)$/, function (headerName, headerValue, callback) {6 apickli.addRequestHeader(headerName, headerValue);7 callback();8 });9 this.When(/^I send (.*) request to (.*)$/, function (method, path, callback) {10 apickli.httpRequest(method, path, callback);11 });12 this.Then(/^response code should be (.*)$/, function (statusCode, callback) {13 assert.equal(apickli.getResponseObject().statusCode, statusCode);14 callback();15 });16};

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 apickli 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