Best Python code snippet using assertpy_python
assertions.py
Source:assertions.py
...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')...
numeric.py
Source:numeric.py
...349 AssertionBuilder: returns this instance to chain to the next assertion350 Raises:351 AssertionError: if val is **not** close to other within tolerance352 """353 self._validate_close_to_args(self.val, other, tolerance)354 if self.val < (other-tolerance) or self.val > (other+tolerance):355 if type(self.val) is datetime.datetime:356 tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000357 h, rem = divmod(tolerance_seconds, 3600)358 m, s = divmod(rem, 60)359 return self.error('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % (360 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))361 else:362 return self.error('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (self.val, other, tolerance))363 return self364 def is_not_close_to(self, other, tolerance):365 """Asserts that val is numeric and is *not* close to other within tolerance.366 Args:367 other: the other value368 tolerance: the tolerance369 Examples:370 Usage::371 assert_that(123).is_not_close_to(100, 22)372 assert_that(123.4).is_not_close_to(123, 0.1)373 Returns:374 AssertionBuilder: returns this instance to chain to the next assertion375 Raises:376 AssertionError: if val **is** close to other within tolerance377 """378 self._validate_close_to_args(self.val, other, tolerance)379 if self.val >= (other-tolerance) and self.val <= (other+tolerance):380 if type(self.val) is datetime.datetime:381 tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000382 h, rem = divmod(tolerance_seconds, 3600)383 m, s = divmod(rem, 60)384 return self.error('Expected <%s> to not be close to <%s> within tolerance <%d:%02d:%02d>, but was.' % (385 self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))386 else:387 return self.error('Expected <%s> to not be close to <%s> within tolerance <%s>, but was.' % (self.val, other, tolerance))...
helpers.py
Source:helpers.py
...78 else:79 raise TypeError('ordering is not defined for type <%s>' % val_type.__name__)80 if low > high:81 raise ValueError('given low arg must be less than given high arg')82 def _validate_close_to_args(self, val, other, tolerance):83 """Helper for validate given arg and delta."""84 if type(val) is complex or type(other) is complex or type(tolerance) is complex:85 raise TypeError('ordering is not defined for complex numbers')86 if isinstance(val, numbers.Number) is False and type(val) is not datetime.datetime:87 raise TypeError('val is not numeric or datetime')88 if type(val) is datetime.datetime:89 if type(other) is not datetime.datetime:90 raise TypeError('given arg must be datetime, but was <%s>' % type(other).__name__)91 if type(tolerance) is not datetime.timedelta:92 raise TypeError('given tolerance arg must be timedelta, but was <%s>' % type(tolerance).__name__)93 else:94 if isinstance(other, numbers.Number) is False:95 raise TypeError('given arg must be numeric')96 if isinstance(tolerance, numbers.Number) is False:...
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!!