Best Python code snippet using avocado_python
version.py
Source:version.py  
1"""A module containing a core representation of IATI Version Numbers, plus how they are handled and compared.2Todo:3    Check whether there is any other version-related functionality to bring into this module.4    Ensure that everything in this module should be here.5"""6from decimal import Decimal7import re8import semantic_version9import iati.utilities10class Version(semantic_version.Version):11    """Representation of an IATI Standard Version Number."""12    def __init__(self, version):13        """Initialise a Version Number.14        Args:15            version (str / Decimal): A representation of an IATI version number.16        Raises:17            TypeError: If an attempt to pass something that is not a string or Decimal is made.18            ValueError: If a provided value is not a permitted version number.19        """20        if not isinstance(version, str) and not isinstance(version, Decimal):21            raise TypeError('A Version object must be created from a string or Decimal, not a {0}'.format(type(version)))22        # check to see if IATIver23        try:24            if self._is_iatidecimal(version):25                integer = str(int(version))26                decimal = str(int(version * 100) - 101)27                super(Version, self).__init__('.'.join([integer, decimal, '0']), True)28            elif self._is_iativer(version):29                integer = version.split('.')[0]30                decimal = str(int(version.split('.')[1]) - 1)31                super(Version, self).__init__('.'.join([integer, decimal, '0']), True)32            elif self._is_semver(version):33                super(Version, self).__init__(version, True)34            else:35                raise ValueError36        except (TypeError, ValueError):37            raise ValueError('A valid version number must be specified.')38    @property39    def integer(self):40        """int: The IATIver Integer Component of the Version."""41        return self.major42    @integer.setter43    def integer(self, value):44        self.major = value45    @property46    def decimal(self):47        """int: The IATIver Decimal Component of the Version.48        This differs from the minor component since it starts at .01 (1) rather than .0 (0).49        """50        return self.minor + 151    @decimal.setter52    def decimal(self, value):53        self.minor = value54    @property55    def iativer_str(self):56        """string: An IATIver-format string representation of the Version Number.57        Note:58            The name of this property may change.59        """60        return str(self.integer) + '.0' + str(self.decimal)61    @property62    def semver_str(self):63        """string: A SemVer-format string representation of the Version Number.64        Note:65            The name of this property may change.66        """67        return '.'.join([str(self.major), str(self.minor), str(self.patch)])68    def __repr__(self):69        """str: A representation of the Version Number that will allow a copy of this object to be instantiated."""70        return "iati.Version('" + self.semver_str + "')"71    def __str__(self):72        """str: A representation of the Version Number as would exist on the Version Codelist.73        Warning:74            At present this always results in an IATIver string. This may change should SemVer be adopted.75            The helper methods must be used if a specific format is required.76        """77        return self.iativer_str78    def _is_iatidecimal(self, version):79        """Determine whether a version string is a Decimal and is a permitted value.80        Args:81            version (string or Decimal): The string for which to check conformance.82        Returns:83            bool: True if the provided string is a permitted IATIver-format version number. False if not.84        """85        if not isinstance(version, Decimal):86            return False87        valid_values = [Decimal('1.0' + str(val)) for val in range(1, 10)]88        return version in valid_values89    def _is_iativer(self, version_string):90        """Determine whether a version string is in an IATIver format and is a permitted value.91        Args:92            version_string (string): The string for which to check conformance.93        Returns:94            bool: True if the provided string is a permitted IATIver-format version number. False if not.95        """96        # a regex for what makes a valid IATIver Version Number format string97        iativer_re = re.compile(r'^((1\.0[1-9])|(((1\d+)|([2-9](\d+)?))\.0[1-9](\d+)?))$')98        return iativer_re.match(version_string)99    def _is_semver(self, version_string):100        """Determine whether a version string is in a SemVer format and is a permitted value.101        Args:102            version_string (string): The string for which to check conformance.103        Returns:104            bool: True if the provided string is a permitted in SemVer-format version number. False if not.105        """106        is_semver_format = semantic_version.validate(version_string)107        try:108            is_permitted_value = semantic_version.Version(version_string).major != 0109        except ValueError:110            return False111        return is_semver_format and is_permitted_value112    def next_major(self):113        """Obtain a Version object that represents the next version after a Major Upgrade.114        Returns:115            iati.Version: A Version object that represents the next version after a Major Upgrade.116        """117        next_major = super(Version, self).next_major()118        return Version(str(next_major))119    def next_minor(self):120        """Obtain a Version object that represents the next version after a Minor Upgrade.121        Returns:122            iati.Version: A Version object that represents the next version after a Minor Upgrade.123        """124        next_minor = super(Version, self).next_minor()125        return Version(str(next_minor))126    def next_integer(self):127        """Obtain a Version object that represents the next version after an Integer Upgrade.128        Returns:129            iati.Version: A Version object that represents the next version after an Integer Upgrade.130        """131        return self.next_major()132    def next_decimal(self):133        """Obtain a Version object that represents the next version after a Decimal Upgrade.134        Returns:135            iati.Version: A Version object that represents the next version after a Decimal Upgrade.136        """137        return self.next_minor()138    next_patch = property()139    """Override the parent class's function to provide the next Patch Version.140    Implementation based on https://stackoverflow.com/a/235657141    Note:142        The Error that is raised has a slightly different message than if the attribute had never existed.143    Raises:144        AttributeError: An error that indicates that this attribute does not exist.145    """146STANDARD_VERSIONS_SUPPORTED = [Version(version_iativer) for version_iativer in ['1.04', '1.05', '2.01', '2.02', '2.03']]147"""Define all versions of the Standard fully supported by pyIATI."""148STANDARD_VERSIONS = [Version(version_iativer) for version_iativer in ['1.01', '1.02', '1.03']] + STANDARD_VERSIONS_SUPPORTED149"""Define all versions of the Standard.150Todo:151    This constant to be populated by the values in the Version codelist, rather than hard-coded.152    Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).153"""154STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)155"""The latest version of the IATI Standard."""156STANDARD_VERSIONS_MAJOR = list(set([157    minor_version.major for minor_version in STANDARD_VERSIONS158]))159"""The major versions of the IATI Standard.160Todo:161    Change from being ints to being Version()s.162"""163STANDARD_VERSIONS_MINOR = STANDARD_VERSIONS164"""The minor versions of the IATI Standard."""165STANDARD_VERSION_ANY = '*'166"""A value to represent that something is applicable to all versions of the IATI Standard - it is version independent.167Warning:168    Assumptions should not be made as to the value of this constant other than it: `is not None`169"""170def allow_fully_supported_version(input_func):171    """Decorate function by ensuring versions are fully supported by pyIATI.172    In terms of value:173    * Valid Decimal Versions will remain unchanged.174    * Invalid Decimal Versions will cause an error to be raised.175    * Other values will cause an error to be raised.176    Args:177        input_func (function): The function to decorate. Takes the `version` argument as its first argument.178    Returns:179        function: The input function, wrapped such that it is called with a fully supported iati.Version representing a Decimal Version.180    """181    def wrap_allow_fully_supported_version(*args, **kwargs):182        """Act as a wrapper to ensure a version number is a Decimal that is fully supported by pyIATI.183        Raises:184            ValueError: If the input version is not a Decimal iati.Version that pyIATI fully supports.185        """186        version = _extract_version_arg(args)187        if not _is_fully_supported(version):188            raise ValueError('{0} is not a fully supported version of the IATI Standard in a normalised representation.'.format(repr(version)))189        return input_func(*args, **kwargs)190    return wrap_allow_fully_supported_version191def allow_known_version(input_func):192    """Decorate function by ensuring versions are Decimal Versions of IATI that pyIATI knows exists.193    In terms of value:194    * Valid Decimal Versions will remain unchanged.195    * Invalid Decimal Versions will cause an error to be raised.196    * Other values will cause an error to be raised.197    Args:198        input_func (function): The function to decorate. Takes the `version` argument as its first argument.199    Returns:200        function: The input function, wrapped such that it is called with an iati.Version representing a real Decimal Version.201    """202    def wrap_allow_known_version(*args, **kwargs):203        """Act as a wrapper to ensure a version number is a Decimal that exists.204        Raises:205            ValueError: If the input version is not a known Decimal iati.Version.206        """207        version = _extract_version_arg(args)208        if not _is_known(version):209            raise ValueError('{0} is not a known version of the IATI Standard in a normalised representation.'.format(repr(version)))210        return input_func(*args, **kwargs)211    return wrap_allow_known_version212def allow_possible_version(input_func):213    """Decorate function by ensuring values specified to represent a Version can actually do so.214    In terms of value:215    * Permitted values representing an Integer or Decimal Version in a known format will remain unchanged.216    * STANDARD_VERSION_ANY will remain unchanged, as a way of representing all versions.217    * strings, integers and Decimals with values that cannot represent a Version will cause a ValueError.218    * Values of types other than string, Decimal, integer and iati.Version will cause a TypeError.219    Args:220        input_func (function): The function to decorate. Takes the `version` argument as its first argument.221    Returns:222        function: The input function, wrapped such that the return value is known to represent some IATI Version Number.223    """224    def wrap_allow_possible_version(*args, **kwargs):225        """Act as a wrapper to ensure a value represents a possible version number.226        Raises:227            TypeError: If the input version is not an iati.Version, string, Decimal or integer.228            ValueError: If the input version is a string, Decimal or Integer, but the value cannot represent a Version Number.229        """230        version = _extract_version_arg(args)231        _prevent_non_version_representations(version)232        return input_func(*args, **kwargs)233    return wrap_allow_possible_version234def decimalise_integer(input_func):235    """Decorate function by converting input version numbers to a normalised format Decimal Version.236    In terms of value:237    * Decimal Versions will remain unchanged.238    * Integer Versions will return the latest Decimal Version within the Integer.239    In terms of type:240    * strings and Decimals will become iati.Versions.241    * iati.Versions will remain unchanged.242    Args:243        input_func (function): The function to decorate. Takes the `version` argument as its first argument.244    Returns:245        function: The input function, wrapped such that it is called with a iati.Version representing a Decimal Version.246    """247    def wrap_decimalise_integer(*args, **kwargs):248        """Act as a wrapper to convert input Integer Version numbers to a normalised format Decimal Version."""249        version = _extract_version_arg(args)250        version = _decimalise_integer(version)251        return input_func(version, *args[1:], **kwargs)252    return wrap_decimalise_integer253def normalise_decimals(input_func):254    """Decorate function by converting an input version into an iati.Version if a value is specified that is a permitted way to represent a Decimal Version.255    Args:256        input_func (function): The function to decorate. Takes the `version` argument as its first argument.257    Returns:258        function: The input function, wrapped such that it is called with an iati.Version if a Decimal version is provided.259    """260    def wrap_normalise_decimals(*args, **kwargs):261        """Act as a wrapper to ensure a version number is an iati.Version if a Decimal version is specified."""262        version = _extract_version_arg(args)263        version = _normalise_decimal_version(version)264        return input_func(version, *args[1:], **kwargs)265    return wrap_normalise_decimals266def versions_for_integer(integer):267    """Return a list containing the supported versions for the input integer version.268    Args:269        integer (int): The integer version to find the supported version for.270    Returns:271        list of iati.Version: Containing the supported versions for the input integer.272    """273    return [version for version in iati.version.STANDARD_VERSIONS if version.major == int(integer)]274def _decimalise_integer(version):275    """Convert a version number into the most appropriate Decimal Version.276    * Integer Versions will return the latest Decimal Version within the Integer. If the Integer is invalid, returns the first Decimal that would exist in the Integer.277    * All other inputs will remain unchanged.278    Args:279        version (Any): The value to convert to a Decimal Version if it represents an Integer Version.280    Returns:281        Any: The Decimal Version of the Standard that the input version relates to, or the input unchanged.282    """283    # handle major versions284    try:285        if not isinstance(version, (int, str)) or isinstance(version, bool):286            raise TypeError287        elif isinstance(version, str) and str(int(version)) != version:  # detect strings containing numbers and whitespace288            raise ValueError289        major_version = int(version)290        if major_version in iati.version.STANDARD_VERSIONS_MAJOR:291            version = max(versions_for_integer(major_version))292        elif str(major_version) == str(version):  # specifying only a major component293            version = Version(str(major_version) + '.0.0')294    except (ValueError, TypeError, OverflowError):295        pass296    return version297def _extract_version_arg(arg_list):298    """Extract a version argument from an args list, raising an error if something is wrong.299    Args:300        arg_list (list): The input args to extract a version argument from. The `version` argument is expected to be the first argument.301    Returns:302        Any: The value in the specified argument index.303    Raises:304        TypeError: If the argument list is not long enough to access the specified index (since the function the argument list was taken from does not permit the required number of attributes).305    """306    try:307        version = arg_list[0]308    except IndexError:309        raise TypeError('The first argument of this function must be a specified version.')310    return version311def _is_fully_supported(version):312    """Detect whether a Version is fully supported by pyIATI.313    Args:314        version (Any): The Version to check support of.315    Returns:316        bool: True if version is a fully supported iati.Version. False in all other cases.317    """318    return version in iati.version.STANDARD_VERSIONS_SUPPORTED319def _is_known(version):320    """Detect whether a Version is a version of the Standard that pyIATI knows to exist.321    Args:322        version (iati.Version): The Version to check support of.323    Returns:324        bool: True if version is an iati.Version known by pyIATI to be a released version. False in all other cases.325    """326    return version in iati.version.STANDARD_VERSIONS327def _normalise_decimal_version(version):328    """Normalise the format of Decimal Versions.329    If the specified version is a value that can act as a Decimal Version of the IATI Standard, convert it to an iati.Version.330    Any other value will be returned as-is.331    Args:332        version (Any): A value that may be a known method to represent a Decimal Version of the IATI Standard.333    Returns:334        Any: An iati.Version if the input value represents a Decimal Version of the IATI Standard. The input version in all other cases.335    """336    try:337        version = Version(version)338    except (TypeError, ValueError):339        pass340    return version341def _prevent_non_version_representations(version):342    """Detect whether a value specified to be a Version could possibly represent a Version.343    In terms of value:344    * Permitted values representing an Integer or Decimal Version in a known format will remain unchanged.345    * STANDARD_VERSION_ANY will remain unchanged, as a way of representing all versions.346    * strings, integers and Decimals with values that cannot represent a Version will cause a ValueError.347    * Values of types other than string, Decimal, integer and iati.Version will cause a TypeError.348    Args:349        version (Any): The value to check to see whether it may represent a Version in a known manner.350    Raises:351        TypeError: If anything other than an iati.Version, string, Decimal or integer is provided.352        ValueError: If a string, Decimal or integer has a value that is not in a format that is known to represent an IATI Version Number.353    """354    if not isinstance(version, (str, Decimal, int, Version)) or isinstance(version, bool):355        raise TypeError('IATI Version Numbers may only be represented as a string, Decimal, int or iati.Version. A {0} was provided.'.format(type(version)))356    try:357        Version(version)358    except ValueError:359        try:360            if version == '0' or (not version.isdigit() and version != STANDARD_VERSION_ANY):  # accept string representations of positive numbers361                raise ValueError('{0} is not a known representation of a potential IATI Version Number'.format(version))362        except AttributeError:  # invalid decimal363            raise ValueError('Only permitted versions at major version 1 may be represented using `decimal.Decimals` - {0} is not a permitted v1.0x version.'.format(version))364    except TypeError:365        # will be an int or None or iati.Version if reaching this point366        if not isinstance(version, Version) and version < 1:367            raise ValueError('IATI Integer Versions are all positive. {0} is a non-positive number.'.format(version))...Solver.py
Source:Solver.py  
...160        :type parameter: int161        :return: all possible values for the given parameter162        :rtype: list163        """164        def is_permitted_value(one_value_constraints):165            if one_value_constraints is None:166                return True167            if len(one_value_constraints) == 0:168                return False169            for constraints in one_value_constraints:170                is_ok = False171                for constraint in constraints:172                    if row[constraint[self.CON_NAME]] != constraint[self.CON_VAL]:173                        is_ok = True174                        break175                if not is_ok:176                    return False177            return True178        return [179            i180            for i, c in enumerate(self.parameters[parameter].constraints)181            if is_permitted_value(c)...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!!
