Best Python code snippet using assertpy_python
assertions.py
Source:assertions.py  
...110    def is_equal_to(self, other, **kwargs):111        """Asserts that val is equal to other."""112        if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \113                self._check_dict_like(other, check_values=False, return_as_bool=True):114            if self._dict_not_equal(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')):115                self._dict_err(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include'))116        else:117            if self.val != other:118                self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val, other))119        return self120    def is_not_equal_to(self, other):121        """Asserts that val is not equal to other."""122        if self.val == other:123            self._err('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other))124        return self125    def is_same_as(self, other):126        """Asserts that the val is identical to other, via 'is' compare."""127        if self.val is not other:128            self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other))129        return self130    def is_not_same_as(self, other):131        """Asserts that the val is not identical to other, via 'is' compare."""132        if self.val is other:133            self._err('Expected <%s> to be not identical to <%s>, but was.' % (self.val, other))134        return self135    def is_true(self):136        """Asserts that val is true."""137        if not self.val:138            self._err('Expected <True>, but was not.')139        return self140    def is_false(self):141        """Asserts that val is false."""142        if self.val:143            self._err('Expected <False>, but was not.')144        return self145    def is_none(self):146        """Asserts that val is none."""147        if self.val is not None:148            self._err('Expected <%s> to be <None>, but was not.' % self.val)149        return self150    def is_not_none(self):151        """Asserts that val is not none."""152        if self.val is None:153            self._err('Expected not <None>, but was.')154        return self155    def is_type_of(self, some_type):156        """Asserts that val is of the given type."""157        if type(some_type) is not type and \158                not issubclass(type(some_type), type):159            raise TypeError('given arg must be a type')160        if type(self.val) is not some_type:161            if hasattr(self.val, '__name__'):162                t = self.val.__name__163            elif hasattr(self.val, '__class__'):164                t = self.val.__class__.__name__165            else:166                t = 'unknown'167            self._err('Expected <%s:%s> to be of type <%s>, but was not.' % (self.val, t, some_type.__name__))168        return self169    def is_instance_of(self, some_class):170        """Asserts that val is an instance of the given class."""171        try:172            if not isinstance(self.val, some_class):173                if hasattr(self.val, '__name__'):174                    t = self.val.__name__175                elif hasattr(self.val, '__class__'):176                    t = self.val.__class__.__name__177                else:178                    t = 'unknown'179                self._err(180                    'Expected <%s:%s> to be instance of class <%s>, but was not.' % (self.val, t, some_class.__name__))181        except TypeError:182            raise TypeError('given arg must be a class')183        return self184    def is_length(self, length):185        """Asserts that val is the given length."""186        if type(length) is not int:187            raise TypeError('given arg must be an int')188        if length < 0:189            raise ValueError('given arg must be a positive int')190        if len(self.val) != length:191            self._err('Expected <%s> to be of length <%d>, but was <%d>.' % (self.val, length, len(self.val)))192        return self193    def contains(self, *items):194        """Asserts that val contains the given item or items."""195        if len(items) == 0:196            raise ValueError('one or more args must be given')197        elif len(items) == 1:198            if items[0] not in self.val:199                if self._check_dict_like(self.val, return_as_bool=True):200                    self._err('Expected <%s> to contain key <%s>, but did not.' % (self.val, items[0]))201                else:202                    self._err('Expected <%s> to contain item <%s>, but did not.' % (self.val, items[0]))203        else:204            missing = []205            for i in items:206                if i not in self.val: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 \...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!!
