Exemple #1
0
 def test_custom_move_module(self):
     attr = six.MovedModule('spam', 'six', 'six')
     six.add_move(attr)
     six.remove_move('spam')
     assert not hasattr(six.moves, 'spam')
     attr = six.MovedModule('spam', 'six', 'six')
     six.add_move(attr)
     from six.moves import spam
     assert spam is six
     six.remove_move('spam')
     assert not hasattr(six.moves, 'spam')
Exemple #2
0
 def test_custom_move_attribute(self):
     attr = six.MovedAttribute('spam', 'six', 'six', 'u', 'u')
     six.add_move(attr)
     six.remove_move('spam')
     assert not hasattr(six.moves, 'spam')
     attr = six.MovedAttribute('spam', 'six', 'six', 'u', 'u')
     six.add_move(attr)
     from six.moves import spam
     assert spam is six.u
     six.remove_move('spam')
     assert not hasattr(six.moves, 'spam')
Exemple #3
0
 def test_custom_move_module(self):
     attr = six.MovedModule("spam", "six", "six")
     six.add_move(attr)
     six.remove_move("spam")
     assert not hasattr(six.moves, "spam")
     attr = six.MovedModule("spam", "six", "six")
     six.add_move(attr)
     from six.moves import spam
     assert spam is six
     six.remove_move("spam")
     assert not hasattr(six.moves, "spam")
Exemple #4
0
 def test_custom_move_attribute(self):
     attr = six.MovedAttribute("spam", "six", "six", "u", "u")
     six.add_move(attr)
     six.remove_move("spam")
     assert not hasattr(six.moves, "spam")
     attr = six.MovedAttribute("spam", "six", "six", "u", "u")
     six.add_move(attr)
     from six.moves import spam
     assert spam is six.u
     six.remove_move("spam")
     assert not hasattr(six.moves, "spam")
Exemple #5
0
import time
from xml.etree import cElementTree as et
import six
six.add_move(six.MovedAttribute('html_escape', 'cgi', 'html', 'escape'))
from six.moves import html_escape

from . import Device
from ..color import get_profiles, limit_to_gamut

CAPABILITY_ID2NAME = dict((
    ('10006', "onoff"),
    ('10008', "levelcontrol"),
    ('30008', "sleepfader"),
    ('30009', "levelcontrol_move"),
    ('3000A', "levelcontrol_stop"),
    ('10300', "colorcontrol"),
    ('30301', "colortemperature"),
))
CAPABILITY_NAME2ID = dict(
    (val, cap) for cap, val in CAPABILITY_ID2NAME.items())

# acceptable values for 'onoff'
OFF = 0
ON = 1
TOGGLE = 2


def limit(value, min_val, max_val):
    """Returns value clipped to the range [min_val, max_val]"""
    return max(min_val, min(value, max_val))
Exemple #6
0
import sys
import unittest

from collections import namedtuple

import pytest
import six

from convert2rhel import logger, systeminfo, unit_tests, utils  # Imports unit_tests/__init__.py
from convert2rhel.systeminfo import RELEASE_VER_MAPPING, system_info
from convert2rhel.toolopts import tool_opts
from convert2rhel.unit_tests import is_rpm_based_os
from convert2rhel.unit_tests.conftest import all_systems, centos8


six.add_move(six.MovedModule("mock", "mock", "unittest.mock"))
from six.moves import mock


class TestSysteminfo(unittest.TestCase):
    class RunSubprocessMocked(unit_tests.MockFunction):
        def __init__(self, output_tuple=("output", 0)):
            self.output_tuple = output_tuple
            self.called = 0
            self.used_args = []

        def __call__(self, *args, **kwargs):
            self.called += 1
            self.used_args.append(args)
            return self.output_tuple
import tempfile
import unittest

import pytest
from six import MovedModule, add_move
from traitlets.config.loader import Config

from . import TESTS_DATA_DIR
from xero_map_gen.config import load_cli_config, load_config, load_file_config
from xero_map_gen.contain import XeroContact
from xero_map_gen.core import dump_map_contacts, get_map_contacts
from xero_map_gen.log import PKG_LOGGER, setup_logging
from xero_map_gen.transport import XeroApiWrapper

if True:
    add_move(MovedModule("mock", "mock", "unittest.mock"))
    from six.moves import mock

    from mock import patch


@pytest.mark.usefixtures("debug")
class AbstractXMGTestCase(unittest.TestCase):
    config_dir = TESTS_DATA_DIR
    config_path = "config.json"
    override_args = ""
    debug = False

    example_api_contact = {
        "Addresses": [
            {
Exemple #8
0
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function

import contextlib
import logging
import os

import six
import sys
import tomlkit

six.add_move(six.MovedAttribute("Mapping", "collections", "collections.abc"))
six.add_move(six.MovedAttribute("Sequence", "collections", "collections.abc"))
six.add_move(six.MovedAttribute("Set", "collections", "collections.abc"))
six.add_move(six.MovedAttribute("ItemsView", "collections", "collections.abc"))
from six.moves import Mapping, Sequence, Set, ItemsView
from six.moves.urllib.parse import urlparse, urlsplit

import pip_shims.shims
from vistir.compat import Path
from vistir.path import is_valid_url, ensure_mkdir_p, create_tracked_tempdir

VCS_LIST = ("git", "svn", "hg", "bzr")


def setup_logger():
    logger = logging.getLogger("requirementslib")
    loglevel = logging.DEBUG
    handler = logging.StreamHandler(stream=sys.stderr)
    handler.setLevel(loglevel)
    logger.addHandler(handler)
Exemple #9
0
    class FileExistsError(OSError):
        def __init__(self, *args, **kwargs):
            self.errno = errno.EEXIST
            super(FileExistsError, self).__init__(*args, **kwargs)

else:  # pragma: no cover
    from builtins import (
        ResourceWarning,
        FileNotFoundError,
        PermissionError,
        IsADirectoryError,
        FileExistsError,
    )
    from io import StringIO

six.add_move(six.MovedAttribute("Iterable", "collections",
                                "collections.abc"))  # type: ignore
six.add_move(six.MovedAttribute("Mapping", "collections",
                                "collections.abc"))  # type: ignore
six.add_move(six.MovedAttribute("Sequence", "collections",
                                "collections.abc"))  # type: ignore
six.add_move(six.MovedAttribute("Set", "collections",
                                "collections.abc"))  # type: ignore
six.add_move(six.MovedAttribute("ItemsView", "collections",
                                "collections.abc"))  # type: ignore

# fmt: off
from six.moves import ItemsView, Iterable, Mapping, Sequence, Set  # type: ignore  # noqa  # isort:skip
# fmt: on

if not sys.warnoptions:
    warnings.simplefilter("default", ResourceWarning)
Exemple #10
0
Date:    2018/9/2 下午6:31
"""
from __future__ import unicode_literals

import os.path
import sys
import tempfile
import time
from io import open
from unittest import TestCase

import requests
from docopt import DocoptExit
import six

six.add_move(
    six.MovedAttribute('TemporaryDirectory', "backports.tempfile", "tempfile"))
# noinspection PyUnresolvedReferences
from six.moves import TemporaryDirectory

from qPyUtils.debug import start_in_thread
from qPyUtils.system import portforward
import qPyUtils.system.file_system


class TestSystemUtils(TestCase):
    def test_portforward(self):
        # ---------- empty args_in should raise 'Usage'
        with self.assertRaises(DocoptExit):
            del sys.argv[:]
            portforward.main()
Exemple #11
0
import os
import unittest

from six import add_move, MovedModule
add_move(MovedModule('test_support', 'test.test_support', 'test.support'))
from six.moves import test_support
import vcr

from ..orbital_gateway import Order, Profile, Reversal
from .live_orbital_gateway_certification import Certification


TEST_DATA_DIR = os.path.dirname(__file__)


def create_sequence(current_value):
    # if we are here
    while True:
        yield str(current_value)
        current_value += 1


class TestProfileFunctions(unittest.TestCase):
    def setUp(self):
        # setup test env vars
        self.env = test_support.EnvironmentVarGuard()
        self.env.set('ORBITAL_PASSWORD', 'potato')
        self.env.set('ORBITAL_MERCHANT_ID', '1234')
        self.env.set('ORBITAL_USERNAME', 'yeah')

        self.c = Certification(
Exemple #12
0
def add_moves():
    add_move(MovedAttribute('HTTPError', 'urllib2', 'urllib.error'))
    add_move(MovedAttribute('HTTPCookieProcessor', 'urllib2',
                            'urllib.request'))
    add_move(MovedAttribute('Request', 'urllib2', 'urllib.request'))
    add_move(MovedAttribute('URLError', 'urllib2', 'urllib.error'))
    add_move(MovedAttribute('build_opener', 'urllib2', 'urllib.request'))
    add_move(MovedAttribute('quote', 'urllib2', 'urllib.parse'))
    add_move(MovedAttribute('urlencode', 'urllib', 'urllib.parse'))
    add_move(MovedAttribute('urljoin', 'urlparse', 'urllib.parse'))
Exemple #13
0
from fnmatch import fnmatch
from itertools import chain

import attr
import six

import vistir

from .exceptions import InvalidPythonVersion

try:
    from functools import lru_cache
except ImportError:
    from backports.functools_lru_cache import lru_cache

six.add_move(six.MovedAttribute("Iterable", "collections", "collections.abc"))
from six.moves import Iterable


PYTHON_IMPLEMENTATIONS = (
    "python", "ironpython", "jython", "pypy", "anaconda", "miniconda",
    "stackless", "activepython", "micropython"
)
RULES_BASE = ["*{0}", "*{0}?", "*{0}?.?", "*{0}?.?m"]
RULES = [rule.format(impl) for impl in PYTHON_IMPLEMENTATIONS for rule in RULES_BASE]

KNOWN_EXTS = {"exe", "py", "fish", "sh", ""}
KNOWN_EXTS = KNOWN_EXTS | set(
    filter(None, os.environ.get("PATHEXT", "").split(os.pathsep))
)
Exemple #14
0
# from http://stackoverflow.com/questions/28215214/how-to-add-custom-renames-in-six

import six
mod = six.MovedModule('mock', 'mock', 'unittest.mock')
six.add_move(mod)
six._importer._add_module(mod, "moves." + mod.name)

# issue open at https://bitbucket.org/gutworth/six/issue/116/enable-importing-from-within-custom
import sys

from puck.backend import (PYPI_URL, echo_backend, high_version_backend,
                          pypi_backend)
from six import MovedModule, add_move

import pytest

add_move(MovedModule('mock', 'mock', 'unittest.mock'))  # isort:skip
from six.moves import mock  # noqa isort:skip


def test_high_version_backend():
    assert high_version_backend('foo') == '99.99.99'


def test_echo_backend():
    assert echo_backend('foo') == 'foo'


@pytest.mark.skipif(sys.version_info < (3, 3), reason="requires python3.3")
@mock.patch('xmlrpc.client.ServerProxy')
def test_pypi_backend_py3(server_mock):
    expected = None
    pypi_mock = server_mock.return_value
    pypi_mock.package_releases.return_value = [expected]

    return_val = pypi_backend('foo')

    server_mock.assert_called_with(PYPI_URL)
    pypi_mock.package_releases.assert_called_once()
Exemple #16
0
from __future__ import print_function
import time

from six.moves import xrange
from six import add_move, MovedModule
add_move(MovedModule('autopy', 'autopy', 'autopy3'))
from six.moves import autopy


def take_screenshot(filename, delay):
    for i in xrange(1, delay+1):
        time.sleep(1)
        print(i)
    autopy.bitmap.capture_screen().save(filename)
    autopy.alert.alert('A screenshot has been saved.')
Exemple #17
0
import sys

import pip_shims.shims
import six
import six.moves
import tomlkit
import vistir
from six.moves.urllib.parse import urlparse, urlsplit, urlunparse
from vistir.compat import Path, fs_decode
from vistir.path import ensure_mkdir_p, is_valid_url

from .environment import MYPY_RUNNING

# fmt: off
six.add_move(  # type: ignore
    six.MovedAttribute("Mapping", "collections",
                       "collections.abc")  # type: ignore
)  # noqa  # isort:skip
six.add_move(  # type: ignore
    six.MovedAttribute("Sequence", "collections",
                       "collections.abc")  # type: ignore
)  # noqa  # isort:skip
six.add_move(  # type: ignore
    six.MovedAttribute("Set", "collections", "collections.abc")  # type: ignore
)  # noqa  # isort:skip
six.add_move(  # type: ignore
    six.MovedAttribute("ItemsView", "collections",
                       "collections.abc")  # type: ignore
)  # noqa
from six.moves import ItemsView, Mapping, Sequence, Set  # type: ignore  # noqa  # isort:skip
# fmt: on
Exemple #18
0
#!/usr/bin/env python

import shutil
import tempfile
from unittest import TestCase

import six

six.add_move(six.MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock

from ansibullbot.utils.component_tools import AnsibleComponentMatcher as ComponentMatcher
from ansibullbot.utils.git_tools import GitRepoWrapper
from ansibullbot.utils.file_tools import FileIndexer
from ansibullbot.utils.systemtools import run_command


class GitShallowRepo(GitRepoWrapper):
    """Perform a shallow copy"""
    def create_checkout(self):
        """checkout ansible"""
        cmd = "git clone --depth=1 --single-branch %s %s" % (self.repo,
                                                             self.checkoutdir)
        (rc, so, se) = run_command(cmd)
        if rc:
            raise Exception("Fail to execute '{}: {} ({}, {})'".format(
                cmd, rc, so, se))

    def update_checkout(self):
        return False
Exemple #19
0
def add_move(mod):
    _six.add_move(mod)
    # https://bitbucket.org/gutworth/six/issues/116/enable-importing-from-within-custom
    _six._importer._add_module(mod, "moves." + mod.name)
Exemple #20
0
        * Symbol : contains a constant, a variable or a predicate. Instantiated before executing the datalog program
    * Function : represents f[X]
    * Operation : made of an operator and 2 operands. Instantiated when an operator is applied to a symbol while executing the datalog program
    * Lambda : represents a lambda function, used in expressions
* Aggregate : represents calls to aggregation method, e.g. min(X)

"""

import ast
from collections import defaultdict, OrderedDict
import inspect
import os
import re
import string
import six
six.add_move(six.MovedModule('UserList', 'UserList', 'collections'))
from six.moves import builtins, xrange, UserList
import sys
import weakref

PY3 = sys.version_info[0] == 3
func_code = '__code__' if PY3 else 'func_code'

try:
    from . import pyEngine
except ValueError:
    import pyEngine
pyDatalog = None  #circ: later set by pyDatalog to avoid circular import
""" global variable to differentiate between in-line queries and pyDatalog program / ask"""
ProgramMode = False
Exemple #21
0
from __future__ import absolute_import
import unittest

from six import add_move, MovedModule  # noqa: E402

add_move(MovedModule('mock', 'mock', 'unittest.mock'))  # noqa: E221

from six.moves import mock  # noqa: E221

from aurorapy.client import AuroraBaseClient, AuroraError


class TestClient(unittest.TestCase):
    def setUp(self):
        self.client = AuroraBaseClient(1)

    def test_crc(self):
        """ Test the crc calculation.
        """

        buf = bytearray([0x0f, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
        crc = self.client.crc(buf)
        self.assertEqual(crc, bytearray([0x30, 0xd3]))

        buf = bytearray([0x00, 0x08, 0x03, 0x02, 0x02, 0x10])
        crc = self.client.crc(buf)
        self.assertEqual(crc, bytearray([0xeb, 0x1e]))

    def test_check_transmission_state(self):
        """
        Test transmission state byte control, it should raise an AuroraError
Exemple #22
0
import re
import subprocess
from collections import OrderedDict
from fnmatch import fnmatch
from threading import Timer

import attr
import six
from packaging.version import LegacyVersion, Version

from .compat import Path, lru_cache, TimeoutError  # noqa
from .environment import MYPY_RUNNING, PYENV_ROOT, SUBPROCESS_TIMEOUT
from .exceptions import InvalidPythonVersion

six.add_move(
    six.MovedAttribute("Iterable", "collections", "collections.abc")
)  # type: ignore  # noqa
six.add_move(
    six.MovedAttribute("Sequence", "collections", "collections.abc")
)  # type: ignore  # noqa
# fmt: off
from six.moves import Iterable  # type: ignore  # noqa  # isort:skip
from six.moves import Sequence  # type: ignore  # noqa  # isort:skip
# fmt: on

if MYPY_RUNNING:
    from typing import Any, Union, List, Callable, Set, Tuple, Dict, Optional, Iterator
    from attr.validators import _OptionalValidator  # type: ignore
    from .models.path import PathEntry

import six


six.add_move(
    six.MovedAttribute(
        name='string_letters',
        old_mod='string',
        new_mod='string',
        old_attr='letters',
        new_attr='ascii_letters',
    )
)
Exemple #24
0
# This file is part of reddit_api.
#
# reddit_api is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# reddit_api is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with reddit_api.  If not, see <http://www.gnu.org/licenses/>.

from six import MovedAttribute, add_move

add_move(MovedAttribute("HTTPError", "urllib2", "urllib.error"))
add_move(MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"))
add_move(MovedAttribute("Request", "urllib2", "urllib.request"))
add_move(MovedAttribute("URLError", "urllib2", "urllib.error"))
add_move(MovedAttribute("build_opener", "urllib2", "urllib.request"))
add_move(MovedAttribute("quote", "urllib2", "urllib.parse"))
add_move(MovedAttribute("urlencode", "urllib", "urllib.parse"))
add_move(MovedAttribute("urljoin", "urlparse", "urllib.parse"))
Exemple #25
0
'''A collection of all of the tests for Ways.

In this module, we set up the mock imports needed to run all of our tests.

'''

# IMPORT THIRD-PARTY LIBRARIES
import six

six.add_move(six.MovedModule('io', 'StringIO', 'io'))
six.add_move(six.MovedModule('mock', 'mock', 'unittest.mock'))
Exemple #26
0
import sys
import six
""" Custom 'moves' extensions for 'six' module.
Just import this module ('_six') to install custom moves to global namespace 'six.moves.clckwrkbdgr.*':
Also handles all available backports (like shutil_get_terminal_size, functools_lru_cache),
again automatically just by importing this module.
"""

six.add_move(
    six.MovedModule('clckwrkbdgr', 'clckwrkbdgr._six', 'clckwrkbdgr._six'))


def _backport(
        module,
        backport_name):  # pragma: no cover -- TODO need some way to test this.
    """ Applies backport patch for the module.
	`backport_name` should be in form `<module_name>_<function_name>,
	e.g.: shutil_get_terminal_size.
	If `shutil.get_terminal_size` is not defined,
	it tries to import `get_terminal_size` from `backports.shutil_get_terminal_size` into `shutil` module.
	"""
    backport_module_name, function_name = backport_name.split('_', 1)
    if hasattr(module, function_name):
        return
    if module.__name__ in sys.modules and hasattr(sys.modules[module.__name__],
                                                  function_name):
        return
    backport_module = __import__('backports.' + backport_name,
                                 fromlist=(b'', ))
    function = getattr(backport_module, function_name)
    setattr(module, function_name, function)
"""formatters we use
"""
# stdlib
import cgi

# pypi
import formencode
import six
six.add_move(six.MovedAttribute("html_escape", "cgi", "html", "escape", "escape"))
from six.moves import html_escape


def formatter_help_inline(error):
    """
    Formatter that escapes the error, wraps the error in a span with
    class ``help-inline``, and doesn't add a ``<br>`` ; somewhat compatible with twitter's bootstrap
    """
    return '<span class="help-inline">%s</span>\n' % formencode.rewritingparser.html_quote(error)


def formatter_hidden(error):
    """
    returns a hidden field with the error in the name
    """
    return '<input type="hidden" name="%s" />\n' % html_escape(error)


def formatter_nobr(error):
    """
    This is a variant of the htmlfill `default_formatter`, in which a trailing <br/> is not included
Exemple #28
0
import time
from xml.etree import cElementTree as et
import six
six.add_move(six.MovedAttribute('html_escape', 'cgi', 'html', 'escape'))
from six.moves import html_escape

from . import Device
from ..color import get_profiles, limit_to_gamut

CAPABILITY_ID2NAME = dict((
    ('10006', "onoff"),
    ('10008', "levelcontrol"),
    ('30008', "sleepfader"),
    ('30009', "levelcontrol_move"),
    ('3000A', "levelcontrol_stop"),
    ('10300', "colorcontrol"),
    ('30301', "colortemperature"),
))
CAPABILITY_NAME2ID = dict(
    (val, cap) for cap, val in CAPABILITY_ID2NAME.items())

# acceptable values for 'onoff'
OFF = 0
ON = 1
TOGGLE = 2


def limit(value, min_val, max_val):
    """Returns value clipped to the range [min_val, max_val]"""
    return max(min_val, min(value, max_val))
Exemple #29
0
def pkg_root():
    """Return the pathlib.Path of the convert2rhel package root."""
    six.add_move(six.MovedModule("pathlib", "pathlib2", "pathlib"))
    from six.moves import pathlib

    return pathlib.Path(__file__).parents[2]
Exemple #30
0
# PRAW is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# PRAW is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# PRAW.  If not, see <http://www.gnu.org/licenses/>.
import sys
from six import MovedAttribute, add_move

# Define additional moves for the six import
add_move(MovedAttribute('HTTPError', 'urllib2', 'urllib.error'))
add_move(MovedAttribute('HTTPCookieProcessor', 'urllib2', 'urllib.request'))
add_move(MovedAttribute('Request', 'urllib2', 'urllib.request'))
add_move(MovedAttribute('URLError', 'urllib2', 'urllib.error'))
add_move(MovedAttribute('build_opener', 'urllib2', 'urllib.request'))
add_move(MovedAttribute('quote', 'urllib2', 'urllib.parse'))
add_move(MovedAttribute('urlencode', 'urllib', 'urllib.parse'))
add_move(MovedAttribute('urljoin', 'urlparse', 'urllib.parse'))


class CompatImporter(object):
    @classmethod
    def load_module(cls, fullname):
        if fullname in sys.modules:
            return sys.modules[fullname]
        module = fullname.rsplit('.', 1)[1]
Exemple #31
0
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import absolute_import

import six

moves = [
    six.MovedAttribute("getoutput", "commands", "subprocess"),
]

for m in moves:
    six.add_move(m)

# Here, we can't use six.Moved* methods because being able to import asyncio vs
# trollius is not strictly Py 2 vs Py 3, but rather asyncio for >=3.4, and
# possibly 3.3 with Tulip, and trollius for 2 and <=3.2, and 3.3 without Tulip.
# We can no longer direct assign to six.moves, so let's just leave it here so
# we don't need to keep try/except importing asyncio.
try:
    import asyncio  # noqa
except ImportError:
    import trollius as asyncio  # noqa
Exemple #32
0
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
#
# Copyright (c) 2017 Wind River Systems, Inc.
#

import six


six.add_move(six.MovedModule('mox', 'mox', 'mox3.mox'))
Exemple #33
0
"""A series of modules for making Python packages Python-2 and 3 compatible."""

import six

six.add_move(six.MovedModule("io", "StringIO", "io"))
# Make mock importable in Python 2 and 3. `from six.moves import mock`
six.add_move(six.MovedModule("mock", "mock", "unittest.mock"))
Exemple #34
0
# -*- coding=utf-8 -*-
import importlib
import os
import sys
from collections import namedtuple
from contextlib import contextmanager

import six

# format: off
six.add_move(six.MovedAttribute("Callable", "collections", "collections.abc"))  # noqa
from six.moves import Callable  # type: ignore  # noqa  # isort:skip

# format: on


class _shims(object):
    CURRENT_PIP_VERSION = "19.1.1"
    BASE_IMPORT_PATH = os.environ.get("PIP_SHIMS_BASE_MODULE", "pip")
    path_info = namedtuple("PathInfo", "path start_version end_version")

    def __dir__(self):
        result = list(self._locations.keys()) + list(self.__dict__.keys())
        result.extend(
            (
                "__file__",
                "__doc__",
                "__all__",
                "__docformat__",
                "__name__",
                "__path__",
Exemple #35
0
from __future__ import absolute_import, division, print_function, unicode_literals

# isort: STDLIB
import errno
import os
import re
import subprocess
import sys

# isort: THIRDPARTY
import six
from six.moves import collections_abc

six.add_move(
    six.MovedModule(
        "collections_abc",
        "collections",
        "collections.abc" if sys.version_info >= (3, 3) else "collections",
    ))


class UDevAdm(object):
    """
    Wrap ``udevadm`` utility.
    """

    CANDIDATES = ["/sbin/udevadm", "udevadm"]
    _adm = None

    @classmethod
    def find(cls):
        """
Exemple #36
0
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Unit tests for main scripts (ccget, ccwrite)."""

from __future__ import print_function

import os
import sys
import unittest

from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock

import cclib

__filedir__ = os.path.dirname(__file__)
__filepath__ = os.path.realpath(__filedir__)
__datadir__ = os.path.join(__filepath__, "..", "..", "data")

INPUT_FILE = os.path.join(__datadir__, 'ADF/basicADF2007.01/dvb_gopt.adfout')
CJSON_OUTPUT_FILENAME = 'dvb_gopt.cjson'


@mock.patch("cclib.scripts.ccget.ccread")
class ccgetTest(unittest.TestCase):
    def setUp(self):
Exemple #37
0
#
# Copyright (c) 2019, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.

"""Unit tests for the logfileparser module."""

import io
import os
import sys
import tempfile
import unittest

from six import add_move, MovedModule
add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock
from six.moves.urllib.request import urlopen

import numpy

import cclib


__filedir__ = os.path.dirname(__file__)
__filepath__ = os.path.realpath(__filedir__)
__datadir__ = os.path.join(__filepath__, "..", "..")

class FileWrapperTest(unittest.TestCase):

    def test_file_seek(self):
Exemple #38
0
        class finalize(object):
            def __init__(self, *args, **kwargs):
                logging.warn("weakref.finalize unavailable, not cleaning...")

            def detach(self):
                return False


logging.basicConfig(level=logging.ERROR)

from distutils.spawn import find_executable
from contextlib import contextmanager
from . import environments
from .pep508checker import lookup

six.add_move(six.MovedAttribute("Mapping", "collections", "collections.abc"))
from six.moves.urllib.parse import urlparse
from six.moves import Mapping

if six.PY2:

    class ResourceWarning(Warning):
        pass


specifiers = [k for k in lookup.keys()]
# List of version control systems we support.
VCS_LIST = ("git", "svn", "hg", "bzr")
SCHEME_LIST = ("http://", "https://", "ftp://", "ftps://", "file://")
requests_session = None
Exemple #39
0
"""Add Python 2 / 3 mapping for the io.StringIO class."""

import six

six.add_move(six.MovedModule("io", "StringIO", "io"))
#!/usr/bin/env python

import shutil
import tempfile
from unittest import TestCase

import six
six.add_move(six.MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock

from ansibullbot.utils.component_tools import AnsibleComponentMatcher as ComponentMatcher
from ansibullbot.utils.component_tools import make_prefixes
from ansibullbot.utils.git_tools import GitRepoWrapper
from ansibullbot.utils.file_tools import FileIndexer
from ansibullbot.utils.systemtools import run_command


class TestMakePrefixes(TestCase):

    def test_simple_path_is_split_correctly(self):
        fp = u'lib/ansible/foo/bar'
        prefixes = make_prefixes(fp)
        assert len(prefixes) == len(fp)
        assert fp in prefixes
        assert prefixes[0] == fp
        assert prefixes[-1] == u'l'


class GitShallowRepo(GitRepoWrapper):
    """Perform a shallow copy"""
import six
six.add_move(six.MovedModule('mox', 'mox', 'mox3.mox'))
Exemple #42
0
__all__ = ['utf8_cat']

from six import PY3
from six import MovedModule
from six import MovedAttribute
from six import add_move


attributes = [
    MovedModule('xmlrpc_client', 'xmlrpclib', 'xmlrpc.client'),
    MovedAttribute('HTTPError', 'urllib2', 'urllib.error'),
    MovedAttribute('URLError', 'urllib2', 'urllib.error'),
    MovedAttribute('Request', 'urllib2', 'urllib.request'),
    MovedAttribute('urlopen', 'urllib2', 'urllib.request'),
    MovedAttribute('urllib_version', 'urllib2', 'urllib.request', '__version__'),
    MovedAttribute('urlparse', 'urlparse', 'urllib.parse'),
]
for attr in attributes:
    add_move(attr)
del attr
del attributes

if PY3:
    def utf8_cat(f):
        """Read the given file in utf8 encoding"""
        return open(f, encoding='utf8').read()
else:
    def utf8_cat(f):
        """Read the given file in utf8 encoding"""
        return open(f).read().decode('utf8')
Exemple #43
0
        * Symbol : contains a constant, a variable or a predicate. Instantiated before executing the datalog program
    * Function : represents f[X]
    * Operation : made of an operator and 2 operands. Instantiated when an operator is applied to a symbol while executing the datalog program
    * Lambda : represents a lambda function, used in expressions
* Aggregate : represents calls to aggregation method, e.g. min(X)

"""

import ast
from collections import defaultdict, OrderedDict
import inspect
import os
import re
import string
import six
six.add_move(six.MovedModule('UserList', 'UserList', 'collections'))
from six.moves import builtins, xrange, UserList
import sys
import weakref
    
PY3 = sys.version_info[0] == 3
func_code = '__code__' if PY3 else 'func_code'

try:
    from . import pyEngine
except ValueError:
    import pyEngine
pyDatalog = None #circ: later set by pyDatalog to avoid circular import

""" global variable to differentiate between in-line queries and pyDatalog program / ask"""
ProgramMode = False