How to use _fmt_items method in assertpy

Best Python code snippet using assertpy_python

assertions.py

Source:assertions.py Github

copy

Full Screen

...207 missing.append(i)208 if missing:209 if self._check_dict_like(self.val, return_as_bool=True):210 self._err('Expected <%s> to contain keys %s, but did not contain key%s %s.' % (211 self.val, self._fmt_items(items), '' if len(missing) == 0 else 's', self._fmt_items(missing)))212 else:213 self._err('Expected <%s> to contain items %s, but did not contain %s.' % (214 self.val, self._fmt_items(items), self._fmt_items(missing)))215 return self216 def does_not_contain(self, *items):217 """Asserts that val does not contain the given item or items."""218 if len(items) == 0:219 raise ValueError('one or more args must be given')220 elif len(items) == 1:221 if items[0] in self.val:222 self._err('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0]))223 else:224 found = []225 for i in items:226 if i in self.val:227 found.append(i)228 if found:229 self._err('Expected <%s> to not contain items %s, but did contain %s.' % (230 self.val, self._fmt_items(items), self._fmt_items(found)))231 return self232 def contains_only(self, *items):233 """Asserts that val contains only the given item or items."""234 if len(items) == 0:235 raise ValueError('one or more args must be given')236 else:237 extra = []238 for i in self.val:239 if i not in items:240 extra.append(i)241 if extra:242 self._err('Expected <%s> to contain only %s, but did contain %s.' % (243 self.val, self._fmt_items(items), self._fmt_items(extra)))244 missing = []245 for i in items:246 if i not in self.val:247 missing.append(i)248 if missing:249 self._err('Expected <%s> to contain only %s, but did not contain %s.' % (250 self.val, self._fmt_items(items), self._fmt_items(missing)))251 return self252 def contains_sequence(self, *items):253 """Asserts that val contains the given sequence of items in order."""254 if len(items) == 0:255 raise ValueError('one or more args must be given')256 else:257 try:258 for i in xrange(len(self.val) - len(items) + 1):259 for j in xrange(len(items)):260 if self.val[i + j] != items[j]:261 break262 else:263 return self264 except TypeError:265 raise TypeError('val is not iterable')266 self._err('Expected <%s> to contain sequence %s, but did not.' % (self.val, self._fmt_items(items)))267 def contains_duplicates(self):268 """Asserts that val is iterable and contains duplicate items."""269 try:270 if len(self.val) != len(set(self.val)):271 return self272 except TypeError:273 raise TypeError('val is not iterable')274 self._err('Expected <%s> to contain duplicates, but did not.' % self.val)275 def does_not_contain_duplicates(self):276 """Asserts that val is iterable and does not contain any duplicate items."""277 try:278 if len(self.val) == len(set(self.val)):279 return self280 except TypeError:281 raise TypeError('val is not iterable')282 self._err('Expected <%s> to not contain duplicates, but did.' % self.val)283 def is_empty(self):284 """Asserts that val is empty."""285 if len(self.val) != 0:286 if isinstance(self.val, str_types):287 self._err('Expected <%s> to be empty string, but was not.' % self.val)288 else:289 self._err('Expected <%s> to be empty, but was not.' % self.val)290 return self291 def is_not_empty(self):292 """Asserts that val is not empty."""293 if len(self.val) == 0:294 if isinstance(self.val, str_types):295 self._err('Expected not empty string, but was empty.')296 else:297 self._err('Expected not empty, but was empty.')298 return self299 def is_in(self, *items):300 """Asserts that val is equal to one of the given items."""301 if len(items) == 0:302 raise ValueError('one or more args must be given')303 else:304 for i in items:305 if self.val == i:306 return self307 self._err('Expected <%s> to be in %s, but was not.' % (self.val, self._fmt_items(items)))308 def is_not_in(self, *items):309 """Asserts that val is not equal to one of the given items."""310 if len(items) == 0:311 raise ValueError('one or more args must be given')312 else:313 for i in items:314 if self.val == i:315 self._err('Expected <%s> to not be in %s, but was.' % (self.val, self._fmt_items(items)))316 return self317 ### numeric assertions ###318 COMPAREABLE_TYPES = set([datetime.datetime, datetime.timedelta, datetime.date, datetime.time])319 NON_COMPAREABLE_TYPES = set([complex])320 def _validate_compareable(self, other):321 self_type = type(self.val)322 other_type = type(other)323 if self_type in self.NON_COMPAREABLE_TYPES:324 raise TypeError('ordering is not defined for type <%s>' % self_type.__name__)325 if self_type in self.COMPAREABLE_TYPES:326 if other_type is not self_type:327 raise TypeError('given arg must be <%s>, but was <%s>' % (self_type.__name__, other_type.__name__))328 return329 if isinstance(self.val, numbers.Number):330 if not isinstance(other, numbers.Number):331 raise TypeError('given arg must be a number, but was <%s>' % other_type.__name__)332 return333 raise TypeError('ordering is not defined for type <%s>' % self_type.__name__)334 def _validate_number(self):335 """Raise TypeError if val is not numeric."""336 if isinstance(self.val, numbers.Number) is False:337 raise TypeError('val is not numeric')338 def _validate_real(self):339 """Raise TypeError if val is not real number."""340 if isinstance(self.val, numbers.Real) is False:341 raise TypeError('val is not real number')342 def is_zero(self):343 """Asserts that val is numeric and equal to zero."""344 self._validate_number()345 return self.is_equal_to(0)346 def is_not_zero(self):347 """Asserts that val is numeric and not equal to zero."""348 self._validate_number()349 return self.is_not_equal_to(0)350 def is_nan(self):351 """Asserts that val is real number and NaN (not a number)."""352 self._validate_number()353 self._validate_real()354 if not math.isnan(self.val):355 self._err('Expected <%s> to be <NaN>, but was not.' % self.val)356 return self357 def is_not_nan(self):358 """Asserts that val is real number and not NaN (not a number)."""359 self._validate_number()360 self._validate_real()361 if math.isnan(self.val):362 self._err('Expected not <NaN>, but was.')363 return self364 def is_inf(self):365 """Asserts that val is real number and Inf (infinity)."""366 self._validate_number()367 self._validate_real()368 if not math.isinf(self.val):369 self._err('Expected <%s> to be <Inf>, but was not.' % self.val)370 return self371 def is_not_inf(self):372 """Asserts that val is real number and not Inf (infinity)."""373 self._validate_number()374 self._validate_real()375 if math.isinf(self.val):376 self._err('Expected not <Inf>, but was.')377 return self378 def is_greater_than(self, other):379 """Asserts that val is numeric and is greater than other."""380 self._validate_compareable(other)381 if self.val <= other:382 if type(self.val) is datetime.datetime:383 self._err('Expected <%s> to be greater than <%s>, but was not.' % (384 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))385 else:386 self._err('Expected <%s> to be greater than <%s>, but was not.' % (self.val, other))387 return self388 def is_greater_than_or_equal_to(self, other):389 """Asserts that val is numeric and is greater than or equal to other."""390 self._validate_compareable(other)391 if self.val < other:392 if type(self.val) is datetime.datetime:393 self._err('Expected <%s> to be greater than or equal to <%s>, but was not.' % (394 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))395 else:396 self._err('Expected <%s> to be greater than or equal to <%s>, but was not.' % (self.val, other))397 return self398 def is_less_than(self, other):399 """Asserts that val is numeric and is less than other."""400 self._validate_compareable(other)401 if self.val >= other:402 if type(self.val) is datetime.datetime:403 self._err('Expected <%s> to be less than <%s>, but was not.' % (404 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))405 else:406 self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val, other))407 return self408 def is_less_than_or_equal_to(self, other):409 """Asserts that val is numeric and is less than or equal to other."""410 self._validate_compareable(other)411 if self.val > other:412 if type(self.val) is datetime.datetime:413 self._err('Expected <%s> to be less than or equal to <%s>, but was not.' % (414 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))415 else:416 self._err('Expected <%s> to be less than or equal to <%s>, but was not.' % (self.val, other))417 return self418 def is_positive(self):419 """Asserts that val is numeric and greater than zero."""420 return self.is_greater_than(0)421 def is_negative(self):422 """Asserts that val is numeric and less than zero."""423 return self.is_less_than(0)424 def is_between(self, low, high):425 """Asserts that val is numeric and is between low and high."""426 val_type = type(self.val)427 self._validate_between_args(val_type, low, high)428 if self.val < low or self.val > high:429 if val_type is datetime.datetime:430 self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (431 self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'),432 high.strftime('%Y-%m-%d %H:%M:%S')))433 else:434 self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val, low, high))435 return self436 def is_not_between(self, low, high):437 """Asserts that val is numeric and is between low and high."""438 val_type = type(self.val)439 self._validate_between_args(val_type, low, high)440 if self.val >= low and self.val <= high:441 if val_type is datetime.datetime:442 self._err('Expected <%s> to not be between <%s> and <%s>, but was.' % (443 self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'),444 high.strftime('%Y-%m-%d %H:%M:%S')))445 else:446 self._err('Expected <%s> to not be between <%s> and <%s>, but was.' % (self.val, low, high))447 return self448 def is_close_to(self, other, tolerance):449 """Asserts that val is numeric and is close to other within tolerance."""450 self._validate_close_to_args(self.val, other, tolerance)451 if self.val < (other - tolerance) or self.val > (other + tolerance):452 if type(self.val) is datetime.datetime:453 tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000454 h, rem = divmod(tolerance_seconds, 3600)455 m, s = divmod(rem, 60)456 self._err('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % (457 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))458 else:459 self._err('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (460 self.val, other, tolerance))461 return self462 def is_not_close_to(self, other, tolerance):463 """Asserts that val is numeric and is not close to other within tolerance."""464 self._validate_close_to_args(self.val, other, tolerance)465 if self.val >= (other - tolerance) and self.val <= (other + tolerance):466 if type(self.val) is datetime.datetime:467 tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000468 h, rem = divmod(tolerance_seconds, 3600)469 m, s = divmod(rem, 60)470 self._err('Expected <%s> to not be close to <%s> within tolerance <%d:%02d:%02d>, but was.' % (471 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))472 else:473 self._err('Expected <%s> to not be close to <%s> within tolerance <%s>, but was.' % (474 self.val, other, tolerance))475 return self476 ### string assertions ###477 def is_equal_to_ignoring_case(self, other):478 """Asserts that val is case-insensitive equal to other."""479 if not isinstance(self.val, str_types):480 raise TypeError('val is not a string')481 if not isinstance(other, str_types):482 raise TypeError('given arg must be a string')483 if self.val.lower() != other.lower():484 self._err('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other))485 return self486 def contains_ignoring_case(self, *items):487 """Asserts that val is string and contains the given item or items."""488 if len(items) == 0:489 raise ValueError('one or more args must be given')490 if isinstance(self.val, str_types):491 if len(items) == 1:492 if not isinstance(items[0], str_types):493 raise TypeError('given arg must be a string')494 if items[0].lower() not in self.val.lower():495 self._err(496 'Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0]))497 else:498 missing = []499 for i in items:500 if not isinstance(i, str_types):501 raise TypeError('given args must all be strings')502 if i.lower() not in self.val.lower():503 missing.append(i)504 if missing:505 self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (506 self.val, self._fmt_items(items), self._fmt_items(missing)))507 elif isinstance(self.val, Iterable):508 missing = []509 for i in items:510 if not isinstance(i, str_types):511 raise TypeError('given args must all be strings')512 found = False513 for v in self.val:514 if not isinstance(v, str_types):515 raise TypeError('val items must all be strings')516 if i.lower() == v.lower():517 found = True518 break519 if not found:520 missing.append(i)521 if missing:522 self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (523 self.val, self._fmt_items(items), self._fmt_items(missing)))524 else:525 raise TypeError('val is not a string or iterable')526 return self527 def starts_with(self, prefix):528 """Asserts that val is string or iterable and starts with prefix."""529 if prefix is None:530 raise TypeError('given prefix arg must not be none')531 if isinstance(self.val, str_types):532 if not isinstance(prefix, str_types):533 raise TypeError('given prefix arg must be a string')534 if len(prefix) == 0:535 raise ValueError('given prefix arg must not be empty')536 if not self.val.startswith(prefix):537 self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix))538 elif isinstance(self.val, Iterable):539 if len(self.val) == 0:540 raise ValueError('val must not be empty')541 first = next(iter(self.val))542 if first != prefix:543 self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix))544 else:545 raise TypeError('val is not a string or iterable')546 return self547 def ends_with(self, suffix):548 """Asserts that val is string or iterable and ends with suffix."""549 if suffix is None:550 raise TypeError('given suffix arg must not be none')551 if isinstance(self.val, str_types):552 if not isinstance(suffix, str_types):553 raise TypeError('given suffix arg must be a string')554 if len(suffix) == 0:555 raise ValueError('given suffix arg must not be empty')556 if not self.val.endswith(suffix):557 self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix))558 elif isinstance(self.val, Iterable):559 if len(self.val) == 0:560 raise ValueError('val must not be empty')561 last = None562 for last in self.val:563 pass564 if last != suffix:565 self._err('Expected %s to end with <%s>, but did not.' % (self.val, suffix))566 else:567 raise TypeError('val is not a string or iterable')568 return self569 def matches(self, pattern):570 """Asserts that val is string and matches regex pattern."""571 if not isinstance(self.val, str_types):572 raise TypeError('val is not a string')573 if not isinstance(pattern, str_types):574 raise TypeError('given pattern arg must be a string')575 if len(pattern) == 0:576 raise ValueError('given pattern arg must not be empty')577 if re.search(pattern, self.val) is None:578 self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern))579 return self580 def does_not_match(self, pattern):581 """Asserts that val is string and does not match regex pattern."""582 if not isinstance(self.val, str_types):583 raise TypeError('val is not a string')584 if not isinstance(pattern, str_types):585 raise TypeError('given pattern arg must be a string')586 if len(pattern) == 0:587 raise ValueError('given pattern arg must not be empty')588 if re.search(pattern, self.val) is not None:589 self._err('Expected <%s> to not match pattern <%s>, but did.' % (self.val, pattern))590 return self591 def is_alpha(self):592 """Asserts that val is non-empty string and all characters are alphabetic."""593 if not isinstance(self.val, str_types):594 raise TypeError('val is not a string')595 if len(self.val) == 0:596 raise ValueError('val is empty')597 if not self.val.isalpha():598 self._err('Expected <%s> to contain only alphabetic chars, but did not.' % self.val)599 return self600 def is_digit(self):601 """Asserts that val is non-empty string and all characters are digits."""602 if not isinstance(self.val, str_types):603 raise TypeError('val is not a string')604 if len(self.val) == 0:605 raise ValueError('val is empty')606 if not self.val.isdigit():607 self._err('Expected <%s> to contain only digits, but did not.' % self.val)608 return self609 def is_lower(self):610 """Asserts that val is non-empty string and all characters are lowercase."""611 if not isinstance(self.val, str_types):612 raise TypeError('val is not a string')613 if len(self.val) == 0:614 raise ValueError('val is empty')615 if self.val != self.val.lower():616 self._err('Expected <%s> to contain only lowercase chars, but did not.' % self.val)617 return self618 def is_upper(self):619 """Asserts that val is non-empty string and all characters are uppercase."""620 if not isinstance(self.val, str_types):621 raise TypeError('val is not a string')622 if len(self.val) == 0:623 raise ValueError('val is empty')624 if self.val != self.val.upper():625 self._err('Expected <%s> to contain only uppercase chars, but did not.' % self.val)626 return self627 def is_unicode(self):628 """Asserts that val is a unicode string."""629 if type(self.val) is not unicode:630 self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__))631 return self632 ### collection assertions ###633 def is_iterable(self):634 """Asserts that val is iterable collection."""635 if not isinstance(self.val, Iterable):636 self._err('Expected iterable, but was not.')637 return self638 def is_not_iterable(self):639 """Asserts that val is not iterable collection."""640 if isinstance(self.val, Iterable):641 self._err('Expected not iterable, but was.')642 return self643 def is_subset_of(self, *supersets):644 """Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given."""645 if not isinstance(self.val, Iterable):646 raise TypeError('val is not iterable')647 if len(supersets) == 0:648 raise ValueError('one or more superset args must be given')649 missing = []650 if hasattr(self.val, 'keys') and callable(getattr(self.val, 'keys')) and hasattr(self.val, '__getitem__'):651 # flatten superset dicts652 superdict = {}653 for l, j in enumerate(supersets):654 self._check_dict_like(j, check_values=False, name='arg #%d' % (l + 1))655 for k in j.keys():656 superdict.update({k: j[k]})657 for i in self.val.keys():658 if i not in superdict:659 missing.append({i: self.val[i]}) # bad key660 elif self.val[i] != superdict[i]:661 missing.append({i: self.val[i]}) # bad val662 if missing:663 self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (664 self.val, self._fmt_items(superdict), self._fmt_items(missing),665 'was' if len(missing) == 1 else 'were'))666 else:667 # flatten supersets668 superset = set()669 for j in supersets:670 try:671 for k in j:672 superset.add(k)673 except Exception:674 superset.add(j)675 for i in self.val:676 if i not in superset:677 missing.append(i)678 if missing:679 self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (680 self.val, self._fmt_items(superset), self._fmt_items(missing),681 'was' if len(missing) == 1 else 'were'))682 return self683 ### dict assertions ###684 def contains_key(self, *keys):685 """Asserts the val is a dict and contains the given key or keys. Alias for contains()."""686 self._check_dict_like(self.val, check_values=False, check_getitem=False)687 return self.contains(*keys)688 def does_not_contain_key(self, *keys):689 """Asserts the val is a dict and does not contain the given key or keys. Alias for does_not_contain()."""690 self._check_dict_like(self.val, check_values=False, check_getitem=False)691 return self.does_not_contain(*keys)692 def contains_value(self, *values):693 """Asserts that val is a dict and contains the given value or values."""694 self._check_dict_like(self.val, check_getitem=False)695 if len(values) == 0:696 raise ValueError('one or more value args must be given')697 missing = []698 for v in values:699 if v not in self.val.values():700 missing.append(v)701 if missing:702 self._err('Expected <%s> to contain values %s, but did not contain %s.' % (703 self.val, self._fmt_items(values), self._fmt_items(missing)))704 return self705 def does_not_contain_value(self, *values):706 """Asserts that val is a dict and does not contain the given value or values."""707 self._check_dict_like(self.val, check_getitem=False)708 if len(values) == 0:709 raise ValueError('one or more value args must be given')710 else:711 found = []712 for v in values:713 if v in self.val.values():714 found.append(v)715 if found:716 self._err('Expected <%s> to not contain values %s, but did contain %s.' % (717 self.val, self._fmt_items(values), self._fmt_items(found)))718 return self719 def contains_entry(self, *args, **kwargs):720 """Asserts that val is a dict and contains the given entry or entries."""721 self._check_dict_like(self.val, check_values=False)722 entries = list(args) + [{k: v} for k, v in kwargs.items()]723 if len(entries) == 0:724 raise ValueError('one or more entry args must be given')725 missing = []726 for e in entries:727 if type(e) is not dict:728 raise TypeError('given entry arg must be a dict')729 if len(e) != 1:730 raise ValueError('given entry args must contain exactly one key-value pair')731 k = next(iter(e))732 if k not in self.val:733 missing.append(e) # bad key734 elif self.val[k] != e[k]:735 missing.append(e) # bad val736 if missing:737 self._err('Expected <%s> to contain entries %s, but did not contain %s.' % (738 self.val, self._fmt_items(entries), self._fmt_items(missing)))739 return self740 def does_not_contain_entry(self, *args, **kwargs):741 """Asserts that val is a dict and does not contain the given entry or entries."""742 self._check_dict_like(self.val, check_values=False)743 entries = list(args) + [{k: v} for k, v in kwargs.items()]744 if len(entries) == 0:745 raise ValueError('one or more entry args must be given')746 found = []747 for e in entries:748 if type(e) is not dict:749 raise TypeError('given entry arg must be a dict')750 if len(e) != 1:751 raise ValueError('given entry args must contain exactly one key-value pair')752 k = next(iter(e))753 if k in self.val and e[k] == self.val[k]:754 found.append(e)755 if found:756 self._err('Expected <%s> to not contain entries %s, but did contain %s.' % (757 self.val, self._fmt_items(entries), self._fmt_items(found)))758 return self759 ### datetime assertions ###760 def is_before(self, other):761 """Asserts that val is a date and is before other date."""762 if type(self.val) is not datetime.datetime:763 raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)764 if type(other) is not datetime.datetime:765 raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)766 if self.val >= other:767 self._err('Expected <%s> to be before <%s>, but was not.' % (768 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))769 return self770 def is_after(self, other):771 """Asserts that val is a date and is after other date."""772 if type(self.val) is not datetime.datetime:773 raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)774 if type(other) is not datetime.datetime:775 raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)776 if self.val <= other:777 self._err('Expected <%s> to be after <%s>, but was not.' % (778 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))779 return self780 def is_equal_to_ignoring_milliseconds(self, other):781 if type(self.val) is not datetime.datetime:782 raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)783 if type(other) is not datetime.datetime:784 raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)785 if self.val.date() != other.date() or self.val.hour != other.hour or self.val.minute != other.minute or self.val.second != other.second:786 self._err('Expected <%s> to be equal to <%s>, but was not.' % (787 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))788 return self789 def is_equal_to_ignoring_seconds(self, other):790 if type(self.val) is not datetime.datetime:791 raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)792 if type(other) is not datetime.datetime:793 raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)794 if self.val.date() != other.date() or self.val.hour != other.hour or self.val.minute != other.minute:795 self._err('Expected <%s> to be equal to <%s>, but was not.' % (796 self.val.strftime('%Y-%m-%d %H:%M'), other.strftime('%Y-%m-%d %H:%M')))797 return self798 def is_equal_to_ignoring_time(self, other):799 if type(self.val) is not datetime.datetime:800 raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)801 if type(other) is not datetime.datetime:802 raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)803 if self.val.date() != other.date():804 self._err('Expected <%s> to be equal to <%s>, but was not.' % (805 self.val.strftime('%Y-%m-%d'), other.strftime('%Y-%m-%d')))806 return self807 ### file assertions ###808 def exists(self):809 """Asserts that val is a path and that it exists."""810 if not isinstance(self.val, str_types):811 raise TypeError('val is not a path')812 if not os.path.exists(self.val):813 self._err('Expected <%s> to exist, but was not found.' % self.val)814 return self815 def does_not_exist(self):816 """Asserts that val is a path and that it does not exist."""817 if not isinstance(self.val, str_types):818 raise TypeError('val is not a path')819 if os.path.exists(self.val):820 self._err('Expected <%s> to not exist, but was found.' % self.val)821 return self822 def is_file(self):823 """Asserts that val is an existing path to a file."""824 self.exists()825 if not os.path.isfile(self.val):826 self._err('Expected <%s> to be a file, but was not.' % self.val)827 return self828 def is_directory(self):829 """Asserts that val is an existing path to a directory."""830 self.exists()831 if not os.path.isdir(self.val):832 self._err('Expected <%s> to be a directory, but was not.' % self.val)833 return self834 def is_named(self, filename):835 """Asserts that val is an existing path to a file and that file is named filename."""836 self.is_file()837 if not isinstance(filename, str_types):838 raise TypeError('given filename arg must be a path')839 val_filename = os.path.basename(os.path.abspath(self.val))840 if val_filename != filename:841 self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename))842 return self843 def is_child_of(self, parent):844 """Asserts that val is an existing path to a file and that file is a child of parent."""845 self.is_file()846 if not isinstance(parent, str_types):847 raise TypeError('given parent directory arg must be a path')848 val_abspath = os.path.abspath(self.val)849 parent_abspath = os.path.abspath(parent)850 if not val_abspath.startswith(parent_abspath):851 self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath))852 return self853 ### collection of objects assertions ###854 def extracting(self, *names, **kwargs):855 """Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given)."""856 if not isinstance(self.val, Iterable):857 raise TypeError('val is not iterable')858 if isinstance(self.val, str_types):859 raise TypeError('val must not be string')860 if len(names) == 0:861 raise ValueError('one or more name args must be given')862 def _extract(x, name):863 if self._check_dict_like(x, check_values=False, return_as_bool=True):864 if name in x:865 return x[name]866 else:867 raise ValueError('item keys %s did not contain key <%s>' % (list(x.keys()), name))868 elif isinstance(x, Iterable):869 self._check_iterable(x, name='item')870 return x[name]871 elif hasattr(x, name):872 attr = getattr(x, name)873 if callable(attr):874 try:875 return attr()876 except TypeError:877 raise ValueError('val method <%s()> exists, but is not zero-arg method' % name)878 else:879 return attr880 else:881 raise ValueError('val does not have property or zero-arg method <%s>' % name)882 def _filter(x):883 if 'filter' in kwargs:884 if isinstance(kwargs['filter'], str_types):885 return bool(_extract(x, kwargs['filter']))886 elif self._check_dict_like(kwargs['filter'], check_values=False, return_as_bool=True):887 for k in kwargs['filter']:888 if isinstance(k, str_types):889 if _extract(x, k) != kwargs['filter'][k]:890 return False891 return True892 elif callable(kwargs['filter']):893 return kwargs['filter'](x)894 return False895 return True896 def _sort(x):897 if 'sort' in kwargs:898 if isinstance(kwargs['sort'], str_types):899 return _extract(x, kwargs['sort'])900 elif isinstance(kwargs['sort'], Iterable):901 items = []902 for k in kwargs['sort']:903 if isinstance(k, str_types):904 items.append(_extract(x, k))905 return tuple(items)906 elif callable(kwargs['sort']):907 return kwargs['sort'](x)908 return 0909 extracted = []910 for i in sorted(self.val, key=lambda x: _sort(x)):911 if _filter(i):912 items = [_extract(i, name) for name in names]913 extracted.append(tuple(items) if len(items) > 1 else items[0])914 return AssertionBuilder(extracted, self.description, self.kind)915 ### dynamic assertions ###916 def __getattr__(self, attr):917 """Asserts that val has attribute attr and that attribute's value is equal to other via a dynamic assertion of the form: has_<attr>()."""918 if not attr.startswith('has_'):919 raise AttributeError('assertpy has no assertion <%s()>' % attr)920 attr_name = attr[4:]921 err_msg = False922 is_dict = isinstance(self.val, Iterable) and hasattr(self.val, '__getitem__')923 if not hasattr(self.val, attr_name):924 if is_dict:925 if attr_name not in self.val:926 err_msg = 'Expected key <%s>, but val has no key <%s>.' % (attr_name, attr_name)927 else:928 err_msg = 'Expected attribute <%s>, but val has no attribute <%s>.' % (attr_name, attr_name)929 def _wrapper(*args, **kwargs):930 if err_msg:931 self._err(err_msg) # ok to raise AssertionError now that we are inside wrapper932 else:933 if len(args) != 1:934 raise TypeError('assertion <%s()> takes exactly 1 argument (%d given)' % (attr, len(args)))935 try:936 val_attr = getattr(self.val, attr_name)937 except AttributeError:938 val_attr = self.val[attr_name]939 if callable(val_attr):940 try:941 actual = val_attr()942 except TypeError:943 raise TypeError('val does not have zero-arg method <%s()>' % attr_name)944 else:945 actual = val_attr946 expected = args[0]947 if actual != expected:948 self._err('Expected <%s> to be equal to <%s> on %s <%s>, but was not.' % (949 actual, expected, 'key' if is_dict else 'attribute', attr_name))950 return self951 return _wrapper952 ### expected exceptions ###953 def raises(self, ex):954 """Asserts that val is callable and that when called raises the given error."""955 if not callable(self.val):956 raise TypeError('val must be callable')957 if not issubclass(ex, BaseException):958 raise TypeError('given arg must be exception')959 return AssertionBuilder(self.val, self.description, self.kind, ex)960 def when_called_with(self, *some_args, **some_kwargs):961 """Asserts the val callable when invoked with the given args and kwargs raises the expected exception."""962 if not self.expected:963 raise TypeError('expected exception not set, raises() must be called first')964 try:965 self.val(*some_args, **some_kwargs)966 except BaseException as e:967 if issubclass(type(e), self.expected):968 # chain on with exception message as val969 return AssertionBuilder(str(e), self.description, self.kind)970 else:971 # got exception, but wrong type, so raise972 self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % (973 self.val.__name__,974 self.expected.__name__,975 self._fmt_args_kwargs(*some_args, **some_kwargs),976 type(e).__name__))977 # didn't fail as expected, so raise978 self._err('Expected <%s> to raise <%s> when called with (%s).' % (979 self.val.__name__,980 self.expected.__name__,981 self._fmt_args_kwargs(*some_args, **some_kwargs)))982 ### helpers ###983 def _err(self, msg):984 """Helper to raise an AssertionError, and optionally prepend custom description."""985 out = '%s%s' % ('[%s] ' % self.description if len(self.description) > 0 else '', msg)986 if self.kind == 'warn':987 print(out)988 return self989 elif self.kind == 'soft':990 global _soft_err991 _soft_err.append(out)992 return self993 else:994 raise AssertionError(out)995 def _fmt_items(self, i):996 if len(i) == 0:997 return '<>'998 elif len(i) == 1:999 return '<%s>' % i[0]1000 else:1001 return '<%s>' % str(i).lstrip('([').rstrip(',])')1002 def _fmt_args_kwargs(self, *some_args, **some_kwargs):1003 """Helper to convert the given args and kwargs into a string."""1004 if some_args:1005 out_args = str(some_args).lstrip('(').rstrip(',)')1006 if some_kwargs:1007 out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ', ': ') for i in [1008 (k, some_kwargs[k]) for k in sorted(some_kwargs.keys())]])1009 if some_args and some_kwargs:1010 return out_args + ', ' + out_kwargs1011 elif some_args:1012 return out_args1013 elif some_kwargs:1014 return out_kwargs1015 else:1016 return ''1017 def _validate_between_args(self, val_type, low, high):1018 low_type = type(low)1019 high_type = type(high)1020 if val_type in self.NON_COMPAREABLE_TYPES:1021 raise TypeError('ordering is not defined for type <%s>' % val_type.__name__)1022 if val_type in self.COMPAREABLE_TYPES:1023 if low_type is not val_type:1024 raise TypeError('given low arg must be <%s>, but was <%s>' % (val_type.__name__, low_type.__name__))1025 if high_type is not val_type:1026 raise TypeError('given high arg must be <%s>, but was <%s>' % (val_type.__name__, low_type.__name__))1027 elif isinstance(self.val, numbers.Number):1028 if isinstance(low, numbers.Number) is False:1029 raise TypeError('given low arg must be numeric, but was <%s>' % low_type.__name__)1030 if isinstance(high, numbers.Number) is False:1031 raise TypeError('given high arg must be numeric, but was <%s>' % high_type.__name__)1032 else:1033 raise TypeError('ordering is not defined for type <%s>' % val_type.__name__)1034 if low > high:1035 raise ValueError('given low arg must be less than given high arg')1036 def _validate_close_to_args(self, val, other, tolerance):1037 if type(val) is complex or type(other) is complex or type(tolerance) is complex:1038 raise TypeError('ordering is not defined for complex numbers')1039 if isinstance(val, numbers.Number) is False and type(val) is not datetime.datetime:1040 raise TypeError('val is not numeric or datetime')1041 if type(val) is datetime.datetime:1042 if type(other) is not datetime.datetime:1043 raise TypeError('given arg must be datetime, but was <%s>' % type(other).__name__)1044 if type(tolerance) is not datetime.timedelta:1045 raise TypeError('given tolerance arg must be timedelta, but was <%s>' % type(tolerance).__name__)1046 else:1047 if isinstance(other, numbers.Number) is False:1048 raise TypeError('given arg must be numeric')1049 if isinstance(tolerance, numbers.Number) is False:1050 raise TypeError('given tolerance arg must be numeric')1051 if tolerance < 0:1052 raise ValueError('given tolerance arg must be positive')1053 def _check_dict_like(self, d, check_keys=True, check_values=True, check_getitem=True, name='val',1054 return_as_bool=False):1055 if not isinstance(d, Iterable):1056 if return_as_bool:1057 return False1058 else:1059 raise TypeError('%s <%s> is not dict-like: not iterable' % (name, type(d).__name__))1060 if check_keys:1061 if not hasattr(d, 'keys') or not callable(getattr(d, 'keys')):1062 if return_as_bool:1063 return False1064 else:1065 raise TypeError('%s <%s> is not dict-like: missing keys()' % (name, type(d).__name__))1066 if check_values:1067 if not hasattr(d, 'values') or not callable(getattr(d, 'values')):1068 if return_as_bool:1069 return False1070 else:1071 raise TypeError('%s <%s> is not dict-like: missing values()' % (name, type(d).__name__))1072 if check_getitem:1073 if not hasattr(d, '__getitem__'):1074 if return_as_bool:1075 return False1076 else:1077 raise TypeError('%s <%s> is not dict-like: missing [] accessor' % (name, type(d).__name__))1078 if return_as_bool:1079 return True1080 def _check_iterable(self, l, check_getitem=True, name='val'):1081 if not isinstance(l, Iterable):1082 raise TypeError('%s <%s> is not iterable' % (name, type(l).__name__))1083 if check_getitem:1084 if not hasattr(l, '__getitem__'):1085 raise TypeError('%s <%s> does not have [] accessor' % (name, type(l).__name__))1086 def _dict_not_equal(self, val, other, ignore=None, include=None):1087 if ignore or include:1088 ignores = self._dict_ignore(ignore)1089 includes = self._dict_include(include)1090 # guarantee include keys are in val1091 if include:1092 missing = []1093 for i in includes:1094 if i not in val:1095 missing.append(i)1096 if missing:1097 self._err('Expected <%s> to include key%s %s, but did not include key%s %s.' % (1098 val,1099 '' if len(includes) == 1 else 's',1100 self._fmt_items(['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in includes]),1101 '' if len(missing) == 1 else 's',1102 self._fmt_items(missing)))1103 if ignore and include:1104 k1 = set([k for k in val if k not in ignores and k in includes])1105 elif ignore:1106 k1 = set([k for k in val if k not in ignores])1107 else: # include1108 k1 = set([k for k in val if k in includes])1109 if ignore and include:1110 k2 = set([k for k in other if k not in ignores and k in includes])1111 elif ignore:1112 k2 = set([k for k in other if k not in ignores])1113 else: # include1114 k2 = set([k for k in other if k in includes])1115 if k1 != k2:1116 return True1117 else:1118 for k in k1:1119 if self._check_dict_like(val[k], check_values=False, return_as_bool=True) and self._check_dict_like(1120 other[k], check_values=False, return_as_bool=True):1121 return self._dict_not_equal(val[k], other[k],1122 ignore=[i[1:] for i in ignores if1123 type(i) is tuple and i[0] == k] if ignore else None,1124 include=[i[1:] for i in self._dict_ignore(include) if1125 type(i) is tuple and i[0] == k] if include else None)1126 elif val[k] != other[k]:1127 return True1128 return False1129 else:1130 return val != other1131 def _dict_ignore(self, ignore):1132 return [i[0] if type(i) is tuple and len(i) == 1 else i \1133 for i in (ignore if type(ignore) is list else [ignore])]1134 def _dict_include(self, include):1135 return [i[0] if type(i) is tuple else i \1136 for i in (include if type(include) is list else [include])]1137 def _dict_err(self, val, other, ignore=None, include=None):1138 def _dict_repr(d, other):1139 out = ''1140 ellip = False1141 for k, v in d.items():1142 if k not in other:1143 out += '%s%s: %s' % (', ' if len(out) > 0 else '', repr(k), repr(v))1144 elif v != other[k]:1145 out += '%s%s: %s' % (', ' if len(out) > 0 else '', repr(k),1146 _dict_repr(v, other[k]) if self._check_dict_like(v, check_values=False,1147 return_as_bool=True) and self._check_dict_like(1148 other[k], check_values=False, return_as_bool=True) else repr(v)1149 )1150 else:1151 ellip = True1152 return '{%s%s}' % ('..' if ellip and len(out) == 0 else '.., ' if ellip else '', out)1153 if ignore:1154 ignores = self._dict_ignore(ignore)1155 ignore_err = ' ignoring keys %s' % self._fmt_items(1156 ['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in ignores])1157 if include:1158 includes = self._dict_ignore(include)1159 include_err = ' including keys %s' % self._fmt_items(1160 ['.'.join([str(s) for s in i]) if type(i) is tuple else i for i in includes])1161 self._err('Expected <%s> to be equal to <%s>%s%s, but was not.' % (1162 _dict_repr(val, other),1163 _dict_repr(other, val),1164 ignore_err if ignore else '',1165 include_err if include else ''1166 ))1167 ### snapshot testing ###1168 def snapshot(self, id=None, path='__snapshots'):1169 if sys.version_info[0] < 3:1170 raise NotImplementedError('snapshot testing requires Python 3')1171 class _Encoder(json.JSONEncoder):1172 def default(self, o):1173 if isinstance(o, set):...

Full Screen

Full Screen

contains.py

Source:contains.py Github

copy

Full Screen

...74 missing.append(i)75 if missing:76 if self._check_dict_like(self.val, return_as_bool=True):77 return self.error('Expected <%s> to contain keys %s, but did not contain key%s %s.' % (78 self.val, self._fmt_items(items), '' if len(missing) == 0 else 's', self._fmt_items(missing)))79 else:80 return self.error('Expected <%s> to contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))81 return self82 def does_not_contain(self, *items):83 """Asserts that val does not contain the given item or items.84 Checks if the collection excludes the given item or items using ``in`` operator.85 Args:86 *items: the item or items expected to be excluded87 Examples:88 Usage::89 assert_that('foo').does_not_contain('x')90 assert_that(['a', 'b']).does_not_contain('x', 'y')91 assert_that((1, 2, 3)).does_not_contain(4, 5)92 assert_that({'a': 1, 'b': 2}).does_not_contain('x', 'y') # checks keys93 assert_that({'a', 'b'}).does_not_contain('x', 'y')94 assert_that([1, 2, 3]).is_type_of(list).contains(1, 2).does_not_contain(4, 5)95 Returns:96 AssertionBuilder: returns this instance to chain to the next assertion97 Raises:98 AssertionError: if val **does** contain the item or items99 Tip:100 Use the :meth:`~assertpy.dict.DictMixin.does_not_contain_key` alias when working with101 *dict-like* objects to be self-documenting.102 """103 if len(items) == 0:104 raise ValueError('one or more args must be given')105 elif len(items) == 1:106 if items[0] in self.val:107 return self.error('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0]))108 else:109 found = []110 for i in items:111 if i in self.val:112 found.append(i)113 if found:114 return self.error('Expected <%s> to not contain items %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(found)))115 return self116 def contains_only(self, *items):117 """Asserts that val contains *only* the given item or items.118 Checks if the collection contains only the given item or items using ``in`` operator.119 Args:120 *items: the *only* item or items expected to be contained121 Examples:122 Usage::123 assert_that('foo').contains_only('f', 'o')124 assert_that(['a', 'a', 'b']).contains_only('a', 'b')125 assert_that((1, 1, 2)).contains_only(1, 2)126 assert_that({'a': 1, 'a': 2, 'b': 3}).contains_only('a', 'b')127 assert_that({'a', 'a', 'b'}).contains_only('a', 'b')128 Returns:129 AssertionBuilder: returns this instance to chain to the next assertion130 Raises:131 AssertionError: if val contains anything **not** item or items132 """133 if len(items) == 0:134 raise ValueError('one or more args must be given')135 else:136 extra = []137 for i in self.val:138 if i not in items:139 extra.append(i)140 if extra:141 return self.error('Expected <%s> to contain only %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(extra)))142 missing = []143 for i in items:144 if i not in self.val:145 missing.append(i)146 if missing:147 return self.error('Expected <%s> to contain only %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))148 return self149 def contains_sequence(self, *items):150 """Asserts that val contains the given ordered sequence of items.151 Checks if the collection contains the given sequence of items using ``in`` operator.152 Args:153 *items: the sequence of items expected to be contained154 Examples:155 Usage::156 assert_that('foo').contains_sequence('f', 'o')157 assert_that('foo').contains_sequence('o', 'o')158 assert_that(['a', 'b', 'c']).contains_sequence('b', 'c')159 assert_that((1, 2, 3)).contains_sequence(1, 2)160 Returns:161 AssertionBuilder: returns this instance to chain to the next assertion162 Raises:163 AssertionError: if val does **not** contains the given sequence of items164 """165 if len(items) == 0:166 raise ValueError('one or more args must be given')167 else:168 try:169 for i in xrange(len(self.val) - len(items) + 1):170 for j in xrange(len(items)):171 if self.val[i+j] != items[j]:172 break173 else:174 return self175 except TypeError:176 raise TypeError('val is not iterable')177 return self.error('Expected <%s> to contain sequence %s, but did not.' % (self.val, self._fmt_items(items)))178 def contains_duplicates(self):179 """Asserts that val is iterable and *does* contain duplicates.180 Examples:181 Usage::182 assert_that('foo').contains_duplicates()183 assert_that(['a', 'a', 'b']).contains_duplicates()184 assert_that((1, 1, 2)).contains_duplicates()185 Returns:186 AssertionBuilder: returns this instance to chain to the next assertion187 Raises:188 AssertionError: if val does **not** contain any duplicates189 """190 try:191 if len(self.val) != len(set(self.val)):192 return self193 except TypeError:194 raise TypeError('val is not iterable')195 return self.error('Expected <%s> to contain duplicates, but did not.' % self.val)196 def does_not_contain_duplicates(self):197 """Asserts that val is iterable and *does not* contain any duplicates.198 Examples:199 Usage::200 assert_that('fox').does_not_contain_duplicates()201 assert_that(['a', 'b', 'c']).does_not_contain_duplicates()202 assert_that((1, 2, 3)).does_not_contain_duplicates()203 Returns:204 AssertionBuilder: returns this instance to chain to the next assertion205 Raises:206 AssertionError: if val **does** contain duplicates207 """208 try:209 if len(self.val) == len(set(self.val)):210 return self211 except TypeError:212 raise TypeError('val is not iterable')213 return self.error('Expected <%s> to not contain duplicates, but did.' % self.val)214 def is_empty(self):215 """Asserts that val is empty.216 Examples:217 Usage::218 assert_that('').is_empty()219 assert_that([]).is_empty()220 assert_that(()).is_empty()221 assert_that({}).is_empty()222 assert_that(set()).is_empty()223 Returns:224 AssertionBuilder: returns this instance to chain to the next assertion225 Raises:226 AssertionError: if val is **not** empty227 """228 if len(self.val) != 0:229 if isinstance(self.val, str_types):230 return self.error('Expected <%s> to be empty string, but was not.' % self.val)231 else:232 return self.error('Expected <%s> to be empty, but was not.' % self.val)233 return self234 def is_not_empty(self):235 """Asserts that val is *not* empty.236 Examples:237 Usage::238 assert_that('foo').is_not_empty()239 assert_that(['a', 'b']).is_not_empty()240 assert_that((1, 2, 3)).is_not_empty()241 assert_that({'a': 1, 'b': 2}).is_not_empty()242 assert_that({'a', 'b'}).is_not_empty()243 Returns:244 AssertionBuilder: returns this instance to chain to the next assertion245 Raises:246 AssertionError: if val **is** empty247 """248 if len(self.val) == 0:249 if isinstance(self.val, str_types):250 return self.error('Expected not empty string, but was empty.')251 else:252 return self.error('Expected not empty, but was empty.')253 return self254 def is_in(self, *items):255 """Asserts that val is equal to one of the given items.256 Args:257 *items: the items expected to contain val258 Examples:259 Usage::260 assert_that('foo').is_in('foo', 'bar', 'baz')261 assert_that(1).is_in(0, 1, 2, 3)262 Returns:263 AssertionBuilder: returns this instance to chain to the next assertion264 Raises:265 AssertionError: if val is **not** in the given items266 """267 if len(items) == 0:268 raise ValueError('one or more args must be given')269 else:270 for i in items:271 if self.val == i:272 return self273 return self.error('Expected <%s> to be in %s, but was not.' % (self.val, self._fmt_items(items)))274 def is_not_in(self, *items):275 """Asserts that val is not equal to one of the given items.276 Args:277 *items: the items expected to exclude val278 Examples:279 Usage::280 assert_that('foo').is_not_in('bar', 'baz', 'box')281 assert_that(1).is_not_in(-1, -2, -3)282 Returns:283 AssertionBuilder: returns this instance to chain to the next assertion284 Raises:285 AssertionError: if val **is** in the given items286 """287 if len(items) == 0:288 raise ValueError('one or more args must be given')289 else:290 for i in items:291 if self.val == i:292 return self.error('Expected <%s> to not be in %s, but was.' % (self.val, self._fmt_items(items)))...

Full Screen

Full Screen

test_core.py

Source:test_core.py Github

copy

Full Screen

...27# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.28from assertpy import assert_that29def test_fmt_items_empty():30 ab = assert_that(None)31 assert_that(ab._fmt_items([])).is_equal_to('<>')32def test_fmt_items_single():33 ab = assert_that(None)34 assert_that(ab._fmt_items([1])).is_equal_to('<1>')35 assert_that(ab._fmt_items(['foo'])).is_equal_to('<foo>')36def test_fmt_items_multiple():37 ab = assert_that(None)38 assert_that(ab._fmt_items([1,2,3])).is_equal_to('<1, 2, 3>')39 assert_that(ab._fmt_items(['a','b','c'])).is_equal_to("<'a', 'b', 'c'>")40def test_fmt_args_kwargs_empty():41 ab = assert_that(None)42 assert_that(ab._fmt_args_kwargs()).is_equal_to('')43def test_fmt_args_kwargs_single_arg():44 ab = assert_that(None)45 assert_that(ab._fmt_args_kwargs(1)).is_equal_to('1')46 assert_that(ab._fmt_args_kwargs('foo')).is_equal_to("'foo'")47def test_fmt_args_kwargs_multiple_args():48 ab = assert_that(None)49 assert_that(ab._fmt_args_kwargs(1,2,3)).is_equal_to('1, 2, 3')50 assert_that(ab._fmt_args_kwargs('a','b','c')).is_equal_to("'a', 'b', 'c'")51def test_fmt_args_kwargs_single_kwarg():52 ab = assert_that(None)53 assert_that(ab._fmt_args_kwargs(a=1)).is_equal_to("'a': 1")...

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run assertpy 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