Best JavaScript code snippet using chai
alcq.py
Source:alcq.py
...128 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)))) \...
mod_state_assertion_commands.py
Source:mod_state_assertion_commands.py
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....
file.py
Source:file.py
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)...
badge_assertion.py
Source:badge_assertion.py
...3from 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 """...
test_tap.py
Source:test_tap.py
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)...
test_bulk_assertions.py
Source:test_bulk_assertions.py
1import ddt2import itertools3from xmodule.tests import BulkAssertionTest, BulkAssertionError4STATIC_PASSING_ASSERTIONS = (5 ('assertTrue', True),6 ('assertFalse', False),7 ('assertIs', 1, 1),8 ('assertEqual', 1, 1),9 ('assertEquals', 1, 1),10 ('assertIsNot', 1, 2),11 ('assertIsNone', None),12 ('assertIsNotNone', 1),13 ('assertIn', 1, (1, 2, 3)),14 ('assertNotIn', 5, (1, 2, 3)),15 ('assertIsInstance', 1, int),16 ('assertNotIsInstance', '1', int),17 ('assertItemsEqual', [1, 2, 3], [3, 2, 1])18)19STATIC_FAILING_ASSERTIONS = (20 ('assertTrue', False),21 ('assertFalse', True),22 ('assertIs', 1, 2),23 ('assertEqual', 1, 2),24 ('assertEquals', 1, 2),25 ('assertIsNot', 1, 1),26 ('assertIsNone', 1),27 ('assertIsNotNone', None),28 ('assertIn', 5, (1, 2, 3)),29 ('assertNotIn', 1, (1, 2, 3)),30 ('assertIsInstance', '1', int),31 ('assertNotIsInstance', 1, int),32 ('assertItemsEqual', [1, 1, 1], [1, 1])33)34CONTEXT_PASSING_ASSERTIONS = (35 ('assertRaises', KeyError, {}.__getitem__, '1'),36 ('assertRaisesRegexp', KeyError, "1", {}.__getitem__, '1'),37)38CONTEXT_FAILING_ASSERTIONS = (39 ('assertRaises', ValueError, lambda: None),40 ('assertRaisesRegexp', KeyError, "2", {}.__getitem__, '1'),41)42@ddt.ddt43class 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)...
simple.py
Source:simple.py
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()...
test_assertions.py
Source:test_assertions.py
1import unittest2from ejpiaj.core import check_assertion3class 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__':...
Using AI Code Generation
1const assert = require('chai').assert;2const expect = require('chai').expect;3const should = require('chai').should();4const add = require('../myMath').add;5const sub = require('../myMath').sub;6const mul = require('../myMath').mul;7const div = require('../myMath').div;8describe('test for add function', function () {9 it('add two positive numbers', function () {10 assert.equal(add(2, 3), 5);11 });12 it('add two negative numbers', function () {13 assert.equal(add(-2, -3), -5);14 });15 it('add one positive and one negative number', function () {16 assert.equal(add(2, -3), -1);17 });18 it('add two floating numbers', function () {19 assert.equal(add(1.2, 2.3), 3.5);20 });21});22describe('test for sub function', function () {23 it('sub two positive numbers', function () {24 assert.equal(sub(2, 3), -1);25 });26 it('sub two negative numbers', function () {27 assert.equal(sub(-2, -3), 1);28 });29 it('sub one positive and one negative number', function () {30 assert.equal(sub(2, -3), 5);31 });32 it('sub two floating numbers', function () {33 assert.equal(sub(1.2, 2.3), -1.1);34 });35});36describe('test for mul function', function () {37 it('mul two positive numbers', function () {
Using AI Code Generation
1var assert = require('chai').assert;2var expect = require('chai').expect;3var should = require('chai').should();4var supertest = require('supertest');5var app = require('../app');6var request = supertest(app);7var mocha = require('mocha');8var describe = mocha.describe;9var it = mocha.it;10describe('Test for the app', function () {11 it('should return status 200', function (done) {12 request.get('/').expect(200, done);13 });14});
Using AI Code Generation
1var assert = require('chai').assert;2var should = require('chai').should();3var expect = require('chai').expect;4var supertest = require('supertest');5var app = require('../app');6describe('Test', function() {7 it('should return 200', function(done) {8 api.get('/').expect(200, done);9 });10});11describe('Test', function() {12 it('should return 200', function(done) {13 api.get('/').expect(200, done);14 });15});16describe('Test', function() {17 it('should return 200', function(done) {18 api.get('/').expect(200, done);19 });20});21describe('Test', function() {22 it('should return 200', function(done) {23 api.get('/').expect(200, done);24 });25});26describe('Test', function() {27 it('should return 200', function(done) {28 api.get('/').expect(200, done);29 });30});31describe('Test', function() {32 it('should return 200', function(done) {33 api.get('/').expect(200, done);34 });35});36describe('Test', function() {37 it('should return 200', function(done) {38 api.get('/').expect(200, done);39 });40});41describe('Test', function() {42 it('should return 200', function(done) {43 api.get('/').expect(200, done);44 });45});46describe('Test', function() {47 it('should return 200', function(done) {48 api.get('/').expect(200, done);49 });50});
Using AI Code Generation
1const assert = require('chai').assert;2const app = require('../app');3sayHelloResult = app.sayHello();4addNumbersResult = app.addNumbers(5,5);5describe('App', function(){6 describe('sayHello()', function(){7 it('sayHello should return hello', function(){8 assert.equal(sayHelloResult, 'hello');9 });10 it('sayHello should return type string', function(){11 assert.typeOf(sayHelloResult, 'string');12 });13 });14 describe('addNumbers()', function(){15 it('addNumbers should be above 5', function(){16 assert.isAbove(addNumbersResult, 5);17 });18 it('addNumbers should return type number', function(){19 assert.typeOf(addNumbersResult, 'number');20 });21 });22});
Using AI Code Generation
1var assert = require('chai').assert;2var expect = require('chai').expect;3var should = require('chai').should();4var add = require('../app.js').add;5var sub = require('../app.js').sub;6var mul = require('../app.js').mul;7var div = require('../app.js').div;8describe('Addition', function() {9 it('should return 5 when 2 and 3 are passed', function() {10 assert.equal(add(2, 3), 5);11 });12 it('should return 0 when -2 and 2 are passed', function() {13 assert.equal(add(-2, 2), 0);14 });15 it('should return 10 when 5 and 5 are passed', function() {16 assert.equal(add(5, 5), 10);17 });18 it('should return 0 when 0 and 0 are passed', function() {19 assert.equal(add(0, 0), 0);20 });21 it('should return 0 when 0 and 0 are passed', function() {22 expect(add(0, 0)).to.equal(0);23 });24 it('should return 0 when 0 and 0 are passed', function() {25 add(0, 0).should.equal(0);26 });27});28describe('Subtraction', function() {29 it('should return 1 when 2 and 3 are passed', function() {30 assert.equal(sub(2, 3), 1);31 });32 it('should return 0 when -2 and -2 are passed', function() {33 assert.equal(sub(-2, -2), 0);34 });35 it('should return 0 when 5 and 5 are passed', function() {36 assert.equal(sub(5, 5), 0);37 });38 it('should return 0 when 0 and 0 are passed', function() {39 assert.equal(sub(0, 0), 0);40 });41 it('should return 0 when 0 and 0 are passed', function() {42 expect(sub(0, 0)).to.equal(0);43 });44 it('should return 0 when 0 and 0 are passed', function() {
Using AI Code Generation
1const assert = require('chai').assert;2const expect = require('chai').expect;3const should = require('chai').should();4describe('This is our first test', function(){5 it('should return true', function(){6 assert.equal(true, true);7 });8 it('should return true', function(){9 expect(true).to.be.true;10 });11 it('should return true', function(){12 true.should.be.true;13 });14});15![mocha test](
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const assert = chai.assert;4const should = chai.should();5const chai = require('chai');6const expect = chai.expect;7const assert = chai.assert;8const should = chai.should();9const chai = require('chai');10const expect = chai.expect;11const assert = chai.assert;12const should = chai.should();13const chai = require('chai');14const expect = chai.expect;15const assert = chai.assert;16const should = chai.should();17const chai = require('chai');18const expect = chai.expect;19const assert = chai.assert;20const should = chai.should();21const chai = require('chai');22const expect = chai.expect;23const assert = chai.assert;24const should = chai.should();25const chai = require('chai');26const expect = chai.expect;27const assert = chai.assert;28const should = chai.should();29const chai = require('chai');30const expect = chai.expect;31const assert = chai.assert;32const should = chai.should();33const chai = require('chai');34const expect = chai.expect;35const assert = chai.assert;36const should = chai.should();37const chai = require('chai');38const expect = chai.expect;39const assert = chai.assert;40const should = chai.should();41const chai = require('chai');42const expect = chai.expect;43const assert = chai.assert;44const should = chai.should();45const chai = require('chai');46const expect = chai.expect;47const assert = chai.assert;48const should = chai.should();49const chai = require('chai');50const expect = chai.expect;51const assert = chai.assert;52const should = chai.should();53const chai = require('chai');54const expect = chai.expect;55const assert = chai.assert;56const should = chai.should();
Using AI Code Generation
1const assert = require('chai').assert;2const head = require('../head');3describe("#head", () => {4 it("returns 1 for [1, 2, 3]", () => {5 assert.strictEqual(head([1, 2, 3]), 1);6 });7 it("returns '5' for ['5']", () => {8 assert.strictEqual(head(['5']), '5'); 9 });10 it("returns 5 for [5,6,7]", () => {11 assert.strictEqual(head([5,6,7]), 5); 12 });13 it("returns 5 for [5]", () => {14 assert.strictEqual(head([5]), 5); 15 });16 it("returns 'Hello' for ['Hello', 'Lighthouse', 'Labs']", () => {17 assert.strictEqual(head(["Hello", "Lighthouse", "Labs"]), "Hello"); 18 });19 it("returns undefined for []", () => {20 assert.strictEqual(head([]), undefined); 21 });22});23const expect = chai.expect;24const assert = chai.assert;25const should = chai.should();26const chai = require('chai');27const expect = chai.expect;28const assert = chai.assert;29const should = chai.should();30const chai = require('chai');31const expect = chai.expect;32const assert = chai.assert;33const should = chai.should();34const chai = require('chai');35const expect = chai.expect;36const assert = chai.assert;37const should = chai.should();38const chai = require('chai');39const expect = chai.expect;40const assert = chai.assert;41const should = chai.should();42const chai = require('chai');43const expect = chai.expect;44const assert = chai.assert;45const should = chai.should();46const chai = require('chai');47const expect = chai.expect;48const assert = chai.assert;49const should = chai.should );50const chai = require('chai');51const expect = chai.expect;52const assert = chai.assert;53const should = chai.should();54const chai = require('chai');55const expect = chai.expect;56const assert = chai.assert;57const should = chai.should();58const chai = require('chai');59const expect = chai.expect;60const assert = chai.assert;61const should = chai.should();62const expect = require('chai').expect;63const should = require('chai').should();64describe('This is our first test', function(){65 it('should return true', function(){66 assert.equal(true, true);67 });68 it('should return true', function(){69 expect(true).to.be.true;70 });71 it('should return true', function(){72 true.should.be.true;73 });74});75![mocha test](
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const assert = chai.assert;4const should = chai.should();5const chai = require('chai');6const expect = chai.expect;7const assert = chai.assert;8const should = chai.should();9const chai = require('chai');10const expect = chai.expect;11const assert = chai.assert;12const should = chai.should();13const chai = require('chai');14const expect = chai.expect;15const assert = chai.assert;16const should = chai.should();17const chai = require('chai');18const expect = chai.expect;19const assert = chai.assert;20const should = chai.should();21const chai = require('chai');22const expect = chai.expect;23const assert = chai.assert;24const should = chai.should();25const chai = require('chai');26const expect = chai.expect;27const assert = chai.assert;28const should = chai.should();29const chai = require('chai');30const expect = chai.expect;31const assert = chai.assert;32const should = chai.should();33const chai = require('chai');34const expect = chai.expect;35const assert = chai.assert;36const should = chai.should();37const chai = require('chai');38const expect = chai.expect;39const assert = chai.assert;40const should = chai.should();41const chai = require('chai');42const expect = chai.expect;43const assert = chai.assert;44const should = chai.should();45const chai = require('chai');46const expect = chai.expect;47const assert = chai.assert;48const should = chai.should();49const chai = require('chai');50const expect = chai.expect;51const assert = chai.assert;52const should = chai.should();53const chai = require('chai');54const expect = chai.expect;55const assert = chai.assert;56const should = chai.should();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!