Python sys.version_info() Examples

The following are 30 code examples of sys.version_info(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: conftest.py    From mutatest with MIT License 8 votes vote down vote up
def write_cov_file(line_data: Dict[str, List[int]], fname: str) -> None:
    """Write a coverage file supporting both Coverage v4 and v5.

    Args:
        line_data: Dictionary of line data for the coverage file.
        fname: string filename for output location (absolute path)

    Returns:
        None
    """
    if coverage.version_info[0] == 4:
        covdata = coverage.CoverageData()
        covdata.add_lines(line_data)
        covdata.write_file(fname)

    else:
        # assume coverage v 5
        covdata = coverage.CoverageData(basename=fname)
        covdata.add_lines(line_data)
        covdata.write()


####################################################################################################
# CLI: MOCK ARGS
#################################################################################################### 
Example #2
Source File: GXManufacturerCollection.py    From Gurux.DLMS.Python with GNU General Public License v2.0 7 votes vote down vote up
def isUpdatesAvailable(cls, path):
        if sys.version_info < (3, 0):
            return False
        # pylint: disable=broad-except
        if not os.path.isfile(os.path.join(path, "files.xml")):
            return True
        try:
            available = dict()
            for it in ET.parse(os.path.join(path, "files.xml")).iter():
                if it.tag == "File":
                    available[it.text] = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")

            path = NamedTemporaryFile()
            path.close()
            urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path.name)
            for it in ET.parse(path.name).iter():
                if it.tag == "File":
                    tmp = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")
                    if not it.text in available or available[it.text] != tmp:
                        return True
        except Exception as e:
            print(e)
            return True
        return False 
Example #3
Source File: api.py    From django-payfast with MIT License 6 votes vote down vote up
def _prepare_signable_fields(
        valid_field_order,  # type: Sequence[str]
        data_fields,  # type: Mapping[str, str]
):  # type: (...) -> SignableFields
    """
    Prepare PayFast submission variables for signing, using the given field order.

    :raise ValueError:
        If `data_fields` contains any unexpected field names not in `valid_field_order`.
    """
    present_fields = (set(data_fields.keys()) if sys.version_info < (3,) else
                      data_fields.keys())
    extra_fields = present_fields - set(valid_field_order)
    if extra_fields:
        raise ValueError('Data contains unexpected fields: {!r}'.format(extra_fields))

    return [
        (name, data_fields[name]) for name in valid_field_order
        if name in data_fields
    ] 
Example #4
Source File: bd_server.py    From sump2 with GNU General Public License v3.0 6 votes vote down vote up
def wr( self, str ):
    if ( self.debug ):
      print("FT600_WR:" +  str );
    str = "~".join( str );# only using 8bits of 16bit FT600, so pad with ~
    bytes_to_write = len( str );# str is now "~1~2~3 .. ~e~f" - Twice as long
    channel = 0;
    result = False;
    timeout = 5;
    tx_pipe = 0x02 + channel;
    if sys.platform == 'linux2':
      tx_pipe -= 0x02;
    if ( sys.version_info.major == 3 ):
      str = str.encode('latin1');
    xferd = 0
    while ( xferd != bytes_to_write ):
      # write data to specified pipe
      xferd += self.D3XX.writePipe(tx_pipe,str,bytes_to_write-xferd);
    return; 
Example #5
Source File: test_recordio.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_recordio():
    frec = tempfile.mktemp()
    N = 255

    writer = mx.recordio.MXRecordIO(frec, 'w')
    for i in range(N):
        if sys.version_info[0] < 3:
            writer.write(str(chr(i)))
        else:
            writer.write(bytes(str(chr(i)), 'utf-8'))
    del writer

    reader = mx.recordio.MXRecordIO(frec, 'r')
    for i in range(N):
        res = reader.read()
        if sys.version_info[0] < 3:
            assert res == str(chr(i))
        else:
            assert res == bytes(str(chr(i)), 'utf-8') 
Example #6
Source File: test_recordio.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_indexed_recordio():
    fidx = tempfile.mktemp()
    frec = tempfile.mktemp()
    N = 255

    writer = mx.recordio.MXIndexedRecordIO(fidx, frec, 'w')
    for i in range(N):
        if sys.version_info[0] < 3:
            writer.write_idx(i, str(chr(i)))
        else:
            writer.write_idx(i, bytes(str(chr(i)), 'utf-8'))
    del writer

    reader = mx.recordio.MXIndexedRecordIO(fidx, frec, 'r')
    keys = reader.keys
    assert sorted(keys) == [i for i in range(N)]
    random.shuffle(keys)
    for i in keys:
        res = reader.read_idx(i)
        if sys.version_info[0] < 3:
            assert res == str(chr(i))
        else:
            assert res == bytes(str(chr(i)), 'utf-8') 
Example #7
Source File: versioneer.py    From aospy with Apache License 2.0 6 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #8
Source File: test_operator_gpu.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_kernel_error_checking():
    # Running tests that may throw exceptions out of worker threads will stop CI testing
    # if not run in a separate process (with its own address space for CUDA compatibility).
    try:
        mpctx = mp.get_context('spawn')
    except:
        print('SKIP: python%s.%s lacks the required process fork-exec support ... ' %
              sys.version_info[0:2], file=sys.stderr, end='')
    else:
        with discard_stderr():
            for f in [kernel_error_check_imperative, kernel_error_check_symbolic]:
                p = mpctx.Process(target=f)
                p.start()
                p.join()
                assert p.exitcode != 0,\
                    "Expected a synchronous kernel error from %s(), none seen." % f.__name__ 
Example #9
Source File: test_params.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_syntax(self):
        if sys.version_info < (3,):
            return self.skip('skipped (Python 3 only)')
        code = textwrap.dedent("""
            class Root:
                @cherrypy.expose
                @cherrypy.tools.params()
                def resource(self, limit: int):
                    return type(limit).__name__
            conf = {'/': {'tools.params.on': True}}
            cherrypy.tree.mount(Root(), config=conf)
            """)
        exec(code)

        self.getPage('/resource?limit=0')
        self.assertStatus(200)
        self.assertBody('int') 
Example #10
Source File: profiler.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stats(self, filename, sortby='cumulative'):
        """:rtype stats(index): output of print_stats() for the given profile.
        """
        sio = io.StringIO()
        if sys.version_info >= (2, 5):
            s = pstats.Stats(os.path.join(self.path, filename), stream=sio)
            s.strip_dirs()
            s.sort_stats(sortby)
            s.print_stats()
        else:
            # pstats.Stats before Python 2.5 didn't take a 'stream' arg,
            # but just printed to stdout. So re-route stdout.
            s = pstats.Stats(os.path.join(self.path, filename))
            s.strip_dirs()
            s.sort_stats(sortby)
            oldout = sys.stdout
            try:
                sys.stdout = sio
                s.print_stats()
            finally:
                sys.stdout = oldout
        response = sio.getvalue()
        sio.close()
        return response 
Example #11
Source File: reprconf.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def build_Call(self, o):
        if sys.version_info >= (3, 5):
            return self._build_call35(o)

        callee = self.build(o.func)

        if o.args is None:
            args = ()
        else:
            args = tuple([self.build(a) for a in o.args])

        if o.starargs is None:
            starargs = ()
        else:
            starargs = tuple(self.build(o.starargs))

        if o.kwargs is None:
            kwargs = {}
        else:
            kwargs = self.build(o.kwargs)
        if o.keywords is not None:  # direct a=b keywords
            for kw in o.keywords:
                # preference because is a direct keyword against **kwargs
                kwargs[kw.arg] = self.build(kw.value)
        return callee(*(args + starargs), **kwargs) 
Example #12
Source File: realtime.py    From twstock with MIT License 6 votes vote down vote up
def get_raw(stocks) -> dict:
    req = requests.Session()
    req.get(SESSION_URL, proxies=get_proxies())

    r = req.get(
        STOCKINFO_URL.format(
            stock_id=_join_stock_id(stocks),
            time=int(time.time()) * 1000))

    if sys.version_info < (3, 5):
        try:
            return r.json()
        except ValueError:
            return {'rtmessage': 'json decode error', 'rtcode': '5000'}
    else:
        try:
            return r.json()
        except json.decoder.JSONDecodeError:
            return {'rtmessage': 'json decode error', 'rtcode': '5000'} 
Example #13
Source File: cifar10.py    From Recipes with MIT License 6 votes vote down vote up
def download_dataset(path, source='https://www.cs.toronto.edu/~kriz/'
                                  'cifar-10-python.tar.gz'):
    """
    Downloads and extracts the dataset, if needed.
    """
    files = ['data_batch_%d' % (i + 1) for i in range(5)] + ['test_batch']
    for fn in files:
        if not os.path.exists(os.path.join(path, 'cifar-10-batches-py', fn)):
            break  # at least one file is missing
    else:
        return  # dataset is already complete

    print("Downloading and extracting %s into %s..." % (source, path))
    if sys.version_info[0] == 2:
        from urllib import urlopen
    else:
        from urllib.request import urlopen
    import tarfile
    if not os.path.exists(path):
        os.makedirs(path)
    u = urlopen(source)
    with tarfile.open(fileobj=u, mode='r|gz') as f:
        f.extractall(path=path)
    u.close() 
Example #14
Source File: forms.py    From django-payfast with MIT License 6 votes vote down vote up
def is_payfast_ip_address(ip_address_str):
    """
    Return True if ip_address_str matches one of PayFast's server IP addresses.

    Setting: `PAYFAST_IP_ADDRESSES`

    :type ip_address_str: str
    :rtype: bool
    """
    # TODO: Django system check for validity?
    payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
                                   conf.DEFAULT_PAYFAST_IP_ADDRESSES)

    if sys.version_info < (3,):
        # Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
        # (On Python 3, this should generally not happen:
        #  let unexpected bytes values fail as expected.)
        ip_address_str = unicode(ip_address_str)  # noqa: F821
        payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses]  # noqa: F821

    return any(ip_address(ip_address_str) in ip_network(payfast_address)
               for payfast_address in payfast_ip_addresses) 
Example #15
Source File: GXByteBuffer.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def hex(cls, value, addSpace=True, index=0, count=None):
        """
        Convert byte array to hex string.
        """
        #Return empty string if array is empty.
        if not value:
            return ""
        hexChars = ""
        #Python 2.7 handles bytes as a string array. It's changed to bytearray.
        if sys.version_info < (3, 0) and not isinstance(value, bytearray):
            value = bytearray(value)
        if count is None:
            count = len(value)
        for it in value[index:count]:
            hexChars += GXByteBuffer.__HEX_ARRAY[it >> GXByteBuffer.__NIBBLE]
            hexChars += GXByteBuffer.__HEX_ARRAY[it & GXByteBuffer.__LOW_BYTE_PART]
            if addSpace:
                hexChars += ' '
        return hexChars.strip() 
Example #16
Source File: shutil.py    From smbprotocol with MIT License 5 votes vote down vote up
def copystat(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the read only attribute, last access time, and last modification time from src to dst. The file contents,
    owner, and group are unaffected.

    If follow_symlinks is 'False' and src and dst both refer to symbolic links, copystat() will operate on the
    symbolic links themselves rather than the files the symbolic links refer to.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_stat = _get_file_stat(src, follow_symlinks, **kwargs)
    src_mode = stat.S_IMODE(src_stat.st_mode)

    # *_ns was only added in Python 3, fallback to a manual calculation from seconds since EPOCH.
    atime_ns = getattr(src_stat, 'st_atime_ns', src_stat.st_atime * 1000000000)
    mtime_ns = getattr(src_stat, 'st_mtime_ns', src_stat.st_mtime * 1000000000)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, atime_ns=atime_ns, mtime_ns=mtime_ns, **kwargs)
    else:
        if not follow_symlinks and sys.version_info[0] < 3:
            # Python 2 always follows symlinks and does not have a kwarg to override, we can only just fail here.
            raise NotImplementedError("utime: follow_symlinks unavailable on this platform")

        _local_chmod(dst, src_mode, follow_symlinks)

        if sys.version_info[0] < 3:
            os.utime(dst, (atime_ns / 1000000000, mtime_ns / 1000000000))
        else:
            os.utime(dst, ns=(atime_ns, mtime_ns), follow_symlinks=follow_symlinks) 
Example #17
Source File: util.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def makedirs(d):
    """Create directories recursively if they don't exist. os.makedirs(exist_ok=True) is not
    available in Python2"""
    if sys.version_info[0] < 3:
        from distutils.dir_util import mkpath
        mkpath(d)
    else:
        os.makedirs(d, exist_ok=True)  # pylint: disable=unexpected-keyword-arg 
Example #18
Source File: shutil.py    From smbprotocol with MIT License 5 votes vote down vote up
def _local_chmod(path, mode, follow_symlinks):
    if sys.version_info[0] < 3:
        if not follow_symlinks:
            if not hasattr(os, 'lchmod'):
                raise NotImplementedError("chmod: follow_symlinks unavailable on this platform")
            os.lchmod(path, mode)
        else:
            os.chmod(path, mode)
    else:
        os.chmod(path, mode, follow_symlinks=follow_symlinks) 
Example #19
Source File: BitVector.py    From knob with MIT License 5 votes vote down vote up
def write_bits_to_stream_object( self, fp ):                       
        '''
        You can write a bitvector directly to a stream object, as
        illustrated by:

            fp_write = io.StringIO()
            bitvec.write_bits_to_stream_object(fp_write)
            print(fp_write.getvalue())   

        This method does not return anything. 

        This function is meant to write a bitvector directly to a file like
        object.  Note that whereas 'write_to_file' method creates a memory
        footprint that corresponds exactly to the bitvector, the
        'write_bits_to_stream_object' actually writes out the 1's and 0's
        as individual items to the file object.  That makes this method
        convenient for creating a string representation of a bitvector,
        especially if you use the StringIO class, as shown in the test
        code.

        '''
        for bit_index in range(self.size):                          
            if sys.version_info[0] == 3:                            
                if self[bit_index] == 0:                            
                    if sys.version_info[1] == 5 and sys.version_info[2] <= 2:
                        fp.write( str('0') )                            
                    else:
                        fp.write( b'0' )                            
                else:                                               
                    if sys.version_info[1] == 5 and sys.version_info[2] <= 2:
                        fp.write( str('1') )                            
                    else:
                        fp.write( b'1' )                            
            else:                                                   
                if self[bit_index] == 0:                            
                    fp.write( unicode('0') )                        
                else:                                               
                    fp.write( unicode('1') ) 
Example #20
Source File: test_api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_py37_above(self, mocker):
        target_typ = int

        mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 7))

        built_typ = mocker.patch(
            "{}._typing._GenericAlias".format(TARGET_MODULE),
            create=True, _name="List", __args__=[target_typ])

        if sys.version_info >= (3, 0):
            mocker.patch("builtins.type", create=True, return_value=built_typ)
        else:
            mocker.patch("__builtin__.type", create=True, return_value=built_typ)

        assert _arm.detect_list_type(built_typ) == target_typ 
Example #21
Source File: _version.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen(
                [c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)
            )
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #22
Source File: BitVector.py    From knob with MIT License 5 votes vote down vote up
def write_bits_to_stream_object_old( self, fp ):                       
        '''
        You can write a bitvector directly to a stream object, as
        illustrated by:

            fp_write = io.StringIO()
            bitvec.write_bits_to_stream_object(fp_write)
            print(fp_write.getvalue())   

        This method does not return anything. 

        This function is meant to write a bitvector directly to a file like
        object.  Note that whereas 'write_to_file' method creates a memory
        footprint that corresponds exactly to the bitvector, the
        'write_bits_to_stream_object' actually writes out the 1's and 0's as
        individual items to the file object.  That makes this method
        convenient for creating a string representation of a bitvector,
        especially if you use the StringIO class, as shown in the test
        code.
        '''
        for bit_index in range(self.size):                          
            if sys.version_info[0] == 3:                            
                if self[bit_index] == 0:                            
                    fp.write( str('0') )                            
                else:                                               
                    fp.write( str('1') )                            
            else:                                                   
                if self[bit_index] == 0:                            
                    fp.write( unicode('0') )                        
                else:                                               
                    fp.write( unicode('1') ) 
Example #23
Source File: _version.py    From NiBetaSeries with MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #24
Source File: versioneer.py    From NiBetaSeries with MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #25
Source File: test_api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_py2(self, mocker):
        mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(2, 7))
        assert not _arm.is_type_variable(None) 
Example #26
Source File: test_api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_py30_to_36_with_type_exception(self, mocker):
        target_typ = int

        mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 0))

        built_typ = mocker.MagicMock(__origin__=typing.List, __args__=[target_typ])

        #FIXME: Investigate this test in Python 3.6
        #assert _arm.is_type_variable(built_typ) 
Example #27
Source File: test_api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_py30_to_36(self, mocker):
        target_typ = int

        mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 0))

        built_typ = mocker.patch(
            "{}._typing.GenericMeta".format(TARGET_MODULE),
            create=True, __extra__=list, __args__=[target_typ])

        mocker.patch("{}.type".format(TARGET_MODULE), return_value=built_typ)

        #FIXME: Investigate this test in Python 3.6
        #assert _arm.is_type_variable(built_typ) 
Example #28
Source File: test_api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_py30_to_36_with_type_exception(self, mocker):
        target_typ = int

        mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 0))

        built_typ = mocker.patch(
            "{}._typing.GenericMeta".format(TARGET_MODULE),
            create=True, __origin__=typing.List, __args__=[target_typ])

        mocker.patch("{}.type".format(TARGET_MODULE), side_effect=AttributeError())

        assert _arm.detect_list_type(built_typ) == target_typ 
Example #29
Source File: test_api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_py30_to_36(self, mocker):
        target_typ = int

        mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 0))

        built_typ = mocker.patch(
            "{}._typing.GenericMeta".format(TARGET_MODULE),
            create=True, __extra__=list, __args__=[target_typ])

        mocker.patch("{}.type".format(TARGET_MODULE), return_value=built_typ)

        assert _arm.detect_list_type(built_typ) == target_typ 
Example #30
Source File: configparserwrapper.py    From CAMISIM with Apache License 2.0 5 votes vote down vote up
def read(self, config_file):
        """
            Read a configuration file in ini format

            @attention: config_file argument may be file path or stream.

            @param config_file: file handler or file path to a config file
            @type config_file: file | FileIO | StringIO

            @rtype: None
        """
        assert isinstance(config_file, str) or self.is_stream(config_file), "Invalid config file path: {}".format(config_file)
        if isinstance(config_file, str) and not os.path.isfile(config_file):
            self._logger.error("Config file does not exist: '{}'".format(config_file))
            raise Exception("File does not exist")

        if isinstance(config_file, str):
            self._config.read(config_file)
            self._config_file_path = config_file
        elif self.is_stream(config_file):
            if sys.version_info < (3,):
                self._config.readfp(config_file)
            else:
                self._config.read_file(config_file)
            self._config_file_path = config_file.name
        else:
            self._logger.error("Invalid config file argument '{}'".format(config_file))
            raise Exception("Unknown argument")