Example #1
0
    ACS_S1 = 1
    ACS_S3 = 1
    ACS_S7 = 1
    ACS_S9 = 1
    ACS_SBBS = 1
    ACS_SBSB = 1
    ACS_SBSS = 1
    ACS_SSBB = 1
    ACS_SSBS = 1
    ACS_SSSB = 1
    ACS_SSSS = 1
    ACS_STERLING = 1
    ACS_TTEE = 1
    ACS_UARROW = 1
    ACS_ULCORNER = 1
    ACS_URCORNER = 1
    ACS_VLINE = 1
    COLOR_BLACK = 1
    COLOR_BLUE = 1
    COLOR_CYAN = 1
    COLOR_GREEN = 1
    COLOR_MAGENTA = 1
    COLOR_RED = 1
    COLOR_WHITE = 1
    COLOR_YELLOW = 1
        """
    )


astroid.register_module_extender(astroid.MANAGER, "curses", _curses_transform)
Example #2
0
# Copyright (c) 2015-2016 Claudiu Popa <*****@*****.**>
# Copyright (c) 2015 raylu <*****@*****.**>
# Copyright (c) 2016 Ceridwen <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER

"""Astroid hooks for dateutil"""

import textwrap

from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder

def dateutil_transform():
    return AstroidBuilder(MANAGER).string_build(textwrap.dedent('''
    import datetime
    def parse(timestr, parserinfo=None, **kwargs):
        return datetime.datetime()
    '''))

register_module_extender(MANAGER, 'dateutil.parser', dateutil_transform)
        %(communicate_signature)s:
            return %(communicate)r
        %(wait_signature)s:
            return self.returncode
        def poll(self):
            return self.returncode
        def send_signal(self, signal):
            pass
        def terminate(self):
            pass
        def kill(self):
            pass
        %(ctx_manager)s
       """
        % {
            "communicate": communicate,
            "communicate_signature": communicate_signature,
            "wait_signature": wait_signature,
            "ctx_manager": ctx_manager,
            "py3_args": py3_args,
        }
    )

    init_lines = textwrap.dedent(init).splitlines()
    indented_init = "\n".join(" " * 4 + line for line in init_lines)
    code += indented_init
    return astroid.parse(code)


astroid.register_module_extender(astroid.MANAGER, "subprocess", _subprocess_transform)
Example #4
0
PY36 = sys.version_info >= (3, 6)

if PY36:
    # Since Python 3.6 there is the RegexFlag enum
    # where every entry will be exposed via updating globals()

    def _re_transform():
        return astroid.parse('''
        import sre_compile
        ASCII = sre_compile.SRE_FLAG_ASCII
        IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE
        LOCALE = sre_compile.SRE_FLAG_LOCALE
        UNICODE = sre_compile.SRE_FLAG_UNICODE
        MULTILINE = sre_compile.SRE_FLAG_MULTILINE
        DOTALL = sre_compile.SRE_FLAG_DOTALL
        VERBOSE = sre_compile.SRE_FLAG_VERBOSE
        A = ASCII
        I = IGNORECASE
        L = LOCALE
        U = UNICODE
        M = MULTILINE
        S = DOTALL
        X = VERBOSE
        TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE
        T = TEMPLATE
        DEBUG = sre_compile.SRE_FLAG_DEBUG
        ''')

    astroid.register_module_extender(astroid.MANAGER, 're', _re_transform)
Example #5
0
    module = parse('''
    class NotPySideSignal(object):
        def connect(self, receiver, type=None):
            pass
        def disconnect(self, receiver):
            pass
        def emit(self, *args):
            pass
    ''')
    signal_cls = module['NotPySideSignal']
    node.instance_attrs['connect'] = signal_cls['connect']
    node.instance_attrs['disconnect'] = signal_cls['disconnect']
    node.instance_attrs['emit'] = signal_cls['emit']


def pyqt4_qtcore_transform():
    return AstroidBuilder(MANAGER).string_build('''

def SIGNAL(signal_name): pass

class QObject(object):
    def emit(self, signal): pass
''')


register_module_extender(MANAGER, 'PyQt4.QtCore', pyqt4_qtcore_transform)
MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal,
                           _looks_like_signal)
MANAGER.register_transform(nodes.ClassDef, transform_pyside_signal,
                           lambda node: node.qname() == 'PySide.QtCore.Signal')
def _hashlib_transform():
    template = '''
    class %(name)s(object):
      def __init__(self, value=''): pass
      def digest(self):
        return %(digest)s
      def copy(self):
        return self
      def update(self, value): pass
      def hexdigest(self):
        return ''
      @property
      def name(self):
        return %(name)r
      @property
      def block_size(self):
        return 1
      @property
      def digest_size(self):
        return 1
    '''
    algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
    classes = "".join(
        template % {'name': hashfunc, 'digest': 'b""' if six.PY3 else '""'}
        for hashfunc in algorithms)
    return astroid.parse(classes)


astroid.register_module_extender(astroid.MANAGER, 'hashlib', _hashlib_transform)

    return get_provider(package_or_requirement).get_resource_string(
        self, resource_name)

def resource_listdir(package_or_requirement, resource_name):
    return get_provider(package_or_requirement).resource_listdir(
        resource_name)

def extraction_error():
    pass

def get_cache_path(archive_name, names=()):
    extract_path = self.extraction_path or get_default_cache()
    target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
    return target_path

def postprocess(tempname, filename):
    pass

def set_extraction_path(path):
    pass

def cleanup_resources(force=False):
    pass

def get_distribution(dist):
    return Distribution(dist)

''')

register_module_extender(MANAGER, 'pkg_resources', pkg_resources_transform)
Example #8
0
                      ALERT_DESCRIPTION_CLOSE_NOTIFY, ALERT_DESCRIPTION_DECODE_ERROR,
                      ALERT_DESCRIPTION_DECOMPRESSION_FAILURE,
                      ALERT_DESCRIPTION_DECRYPT_ERROR,
                      ALERT_DESCRIPTION_HANDSHAKE_FAILURE,
                      ALERT_DESCRIPTION_ILLEGAL_PARAMETER,
                      ALERT_DESCRIPTION_INSUFFICIENT_SECURITY,
                      ALERT_DESCRIPTION_INTERNAL_ERROR,
                      ALERT_DESCRIPTION_NO_RENEGOTIATION,
                      ALERT_DESCRIPTION_PROTOCOL_VERSION,
                      ALERT_DESCRIPTION_RECORD_OVERFLOW,
                      ALERT_DESCRIPTION_UNEXPECTED_MESSAGE,
                      ALERT_DESCRIPTION_UNKNOWN_CA,
                      ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY,
                      ALERT_DESCRIPTION_UNRECOGNIZED_NAME,
                      ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE,
                      ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION,
                      ALERT_DESCRIPTION_USER_CANCELLED)
    from _ssl import (SSL_ERROR_EOF, SSL_ERROR_INVALID_ERROR_CODE, SSL_ERROR_SSL,
                      SSL_ERROR_SYSCALL, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_READ,
                      SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_ZERO_RETURN)
    from _ssl import VERIFY_CRL_CHECK_CHAIN, VERIFY_CRL_CHECK_LEAF, VERIFY_DEFAULT, VERIFY_X509_STRICT
    from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
    from _ssl import _OPENSSL_API_VERSION
    from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
    from _ssl import PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, PROTOCOL_TLS_SERVER
    """
    )


register_module_extender(MANAGER, "ssl", ssl_transform)
    int_ = int32
    intc = int32
    intp = int32
    long = int32
    longcomplex = complex192
    longdouble = float96
    longfloat = float96
    longlong = int64
    object0 = object_
    object_ = object_
    short = int16
    single = float32
    singlecomplex = complex64
    str0 = str_
    string_ = bytes_
    ubyte = uint8
    uint = uint32
    uint0 = uint32
    uintc = uint32
    uintp = uint32
    ulonglong = uint64
    unicode = str_
    unicode_ = str_
    ushort = uint16
    void0 = void
    """)


astroid.register_module_extender(astroid.MANAGER, "numpy.core.numerictypes",
                                 numpy_core_numerictypes_transform)
Example #10
0
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/LICENSE
import sys

import astroid

PY37 = sys.version_info >= (3, 7)

if PY37:
    # Since Python 3.7 Hashing Methods are added
    # dynamically to globals()

    def _re_transform():
        return astroid.parse("""
        from collections import namedtuple
        _Method = namedtuple('_Method', 'name ident salt_chars total_size')

        METHOD_SHA512 = _Method('SHA512', '6', 16, 106)
        METHOD_SHA256 = _Method('SHA256', '5', 16, 63)
        METHOD_BLOWFISH = _Method('BLOWFISH', 2, 'b', 22)
        METHOD_MD5 = _Method('MD5', '1', 8, 34)
        METHOD_CRYPT = _Method('CRYPT', None, 2, 13)
        """)

    astroid.register_module_extender(astroid.MANAGER, "crypt", _re_transform)
Example #11
0
        def replace(method_or_response=None, url=None, body="", *args, **kwargs):
            return

        def add_callback(
            method, url, callback, match_querystring=False, content_type="text/plain"
        ):
            return

        calls = []

        def __enter__():
            return

        def __exit__(type, value, traceback):
            success = type is None
            return success

        def activate(func):
            return func

        def start():
            return

        def stop(allow_assert=True):
            return
        """)


astroid.register_module_extender(astroid.MANAGER, "responses", responses_funcs)
Example #12
0
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Claudiu Popa <*****@*****.**>
# Copyright (c) 2017 Łukasz Rogalski <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
import astroid


def _thread_transform():
    return astroid.parse("""
    class lock(object):
        def acquire(self, blocking=True, timeout=-1):
            return False
        def release(self):
            pass
        def __enter__(self):
            return True
        def __exit__(self, *args):
            pass
        def locked(self):
            return False

    def Lock():
        return lock()
    """)


astroid.register_module_extender(astroid.MANAGER, "threading",
                                 _thread_transform)
Example #13
0
def register(linter):
    register_module_extender(MANAGER, 'gi.repository', gi_repository_transform)
Example #14
0
def register(linter):
    register_module_extender(MANAGER, 'gi.repository', gi_repository_transform)
Example #15
0
        import email.mime.base as email_mime_base
        import urllib.parse as urllib_parse
        import urllib.error as urllib_error
        import tkinter
        import tkinter.dialog as tkinter_dialog
        import tkinter.filedialog as tkinter_filedialog
        import tkinter.scrolledtext as tkinter_scrolledtext
        import tkinter.simpledialog as tkinder_simpledialog
        import tkinter.tix as tkinter_tix
        import tkinter.ttk as tkinter_ttk
        import tkinter.constants as tkinter_constants
        import tkinter.dnd as tkinter_dnd
        import tkinter.colorchooser as tkinter_colorchooser
        import tkinter.commondialog as tkinter_commondialog
        import tkinter.filedialog as tkinter_tkfiledialog
        import tkinter.font as tkinter_font
        import tkinter.messagebox as tkinter_messagebox
        import urllib.request
        import urllib.robotparser as urllib_robotparser
        import urllib.parse as urllib_parse
        import urllib.error as urllib_error
    moves = Moves()
    '''))

if sys.version_info[0] == 2:
    TRANSFORM = six_moves_transform_py2
else:
    TRANSFORM = six_moves_transform_py3

register_module_extender(MANAGER, 'six', TRANSFORM)
Example #16
0
    except ImportError:
        pass

try:
    import _pytest.debugging
    set_trace = _pytest.debugging.pytestPDB().set_trace
except ImportError:
    try:
        import _pytest.pdb
        set_trace = _pytest.pdb.pytestPDB().set_trace
    except ImportError:
        pass

try:
    import _pytest.fixtures
    fixture = _pytest.fixtures.fixture
    yield_fixture = _pytest.fixtures.yield_fixture
except ImportError:
    try:
        import _pytest.python
        fixture = _pytest.python.fixture
        yield_fixture = _pytest.python.yield_fixture
    except ImportError:
        pass
"""
    )


register_module_extender(MANAGER, "pytest", pytest_transform)
register_module_extender(MANAGER, "py.test", pytest_transform)
Example #17
0
                # Replace all the assignments with our mocked class.
                classdef = dedent('''
                class %(name)s(object):
                    @property
                    def value(self):
                        # Not the best return.
                        return None 
                    @property
                    def name(self):
                        return %(name)r
                ''' % {'name': target.name})
                fake = AstroidBuilder(MANAGER).string_build(classdef)[target.name]
                fake.parent = target.parent
                for method in node.mymethods():
                    fake.locals[method.name] = [method]
                new_targets.append(fake.instanciate_class())
            node.locals[local] = new_targets
        break
    return node


MANAGER.register_transform(nodes.CallFunc, inference_tip(infer_named_tuple),
                           looks_like_namedtuple)
MANAGER.register_transform(nodes.CallFunc, inference_tip(infer_enum),
                           AsStringRegexpPredicate('Enum', 'func'))
MANAGER.register_transform(nodes.Class, infer_enum_class)
register_module_extender(MANAGER, 'hashlib', hashlib_transform)
register_module_extender(MANAGER, 'collections', collections_transform)
register_module_extender(MANAGER, 'pkg_resources', pkg_resources_transform)
register_module_extender(MANAGER, 'subprocess', subprocess_transform)
Example #18
0
def _pep8(name, caps=re.compile('([A-Z])')):
    return caps.sub(lambda m: '_' + m.groups()[0].lower(), name)


def nose_transform():
    """Custom transform for the nose.tools module."""

    builder = AstroidBuilder(MANAGER)
    stub = AstroidBuilder(MANAGER).string_build('''__all__ = []''')
    unittest_module = builder.module_build(unittest.case)
    case = unittest_module['TestCase']
    all_entries = ['ok_', 'eq_']

    for method_name, method in case.locals.items():
        if method_name.startswith('assert') and '_' not in method_name:
            pep8_name = _pep8(method_name)
            all_entries.append(pep8_name)
            stub[pep8_name] = method[0]

    # Update the __all__ variable, since nose.tools
    # does this manually with .append.
    all_assign = stub['__all__'].parent
    all_object = List(all_entries)
    all_object.parent = all_assign
    all_assign.value = all_object
    return stub


register_module_extender(MANAGER, 'nose.tools.trivial', nose_transform)
Example #19
0
    from numpy.core import machar
    from numpy.core import getlimits
    from numpy.core import shape_base
    __all__ = (['char', 'rec', 'memmap', 'chararray'] + numeric.__all__ +
               fromnumeric.__all__ +
               records.__all__ +
               function_base.__all__ +
               machar.__all__ +
               getlimits.__all__ +
               shape_base.__all__)
    ''')


def numpy_transform():
    return astroid.parse('''
    from numpy import core
    from numpy import matrixlib as _mat
    from numpy import lib
    __all__ = ['add_newdocs',
               'ModuleDeprecationWarning',
               'VisibleDeprecationWarning', 'linalg', 'fft', 'random',
               'ctypeslib', 'ma',
               '__version__', 'pkgload', 'PackageLoader',
               'show_config'] + core.__all__ + _mat.__all__ + lib.__all__

    ''')
    

astroid.register_module_extender(astroid.MANAGER, 'numpy.core', numpy_core_transform)
astroid.register_module_extender(astroid.MANAGER, 'numpy', numpy_transform)
Example #20
0
# Copyright (c) 2015-2016 Claudiu Popa <*****@*****.**>
# Copyright (c) 2015 raylu <*****@*****.**>
# Copyright (c) 2016 Ceridwen <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
"""Astroid hooks for dateutil"""

import textwrap

from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder


def dateutil_transform():
    return AstroidBuilder(MANAGER).string_build(
        textwrap.dedent('''
    import datetime
    def parse(timestr, parserinfo=None, **kwargs):
        return datetime.datetime()
    '''))


register_module_extender(MANAGER, 'dateutil.parser', dateutil_transform)
Example #21
0
        # This is a lie (lxml.builder *is* a Cython compiled module since
        # lxml 4.0, it's not pure Python) but we need it to convince pylint 
        # that the ElementMaker.__getattr__ method is actually real. Astroid's 
        # has_dynamic_getattr() method intentionally ignores a __getattr__ 
        # method which is present in compiled modules under the assumption that 
        # it's just a slot that is not necessarily implemented.
        # https://github.com/PyCQA/astroid/commit/a709fa17650d83d0caea78981e65454cea69f27a
        node.pure_python = True

def beaker_decl_enum_transform(cls):
    """
    DeclEnum uses some metaclass magic to fill in values as attributes on the type,
    based on the 'symbols' class attribute.
    """
    if cls.is_subtype_of('bkr.server.enum.DeclEnum') and cls.name != 'DeclEnum':
        symbols = eval(cls.locals['symbols'][0].statement().value.as_string(), {'_': lambda x: x})
        for pyname, dbname, attrs in symbols:
            cls.locals[pyname] = dbname

astroid.register_module_extender(astroid.MANAGER, 'socket', socket_extend)
astroid.register_module_extender(astroid.MANAGER, 'krbV', krbV_extend)
astroid.register_module_extender(astroid.MANAGER, 'sqlalchemy.orm.scoping', sqlalchemy_orm_scoping_extend)
astroid.register_module_extender(astroid.MANAGER, 'alembic.context', alembic_context_extend)
astroid.register_module_extender(astroid.MANAGER, 'alembic.op', alembic_op_extend)
astroid.register_module_extender(astroid.MANAGER, 'formencode.api', formencode_api_extend)
# XXX should be registered for 'gevent.socket' but pylint gets confused
astroid.register_module_extender(astroid.MANAGER, 'socket', gevent_socket_extend)
astroid.register_module_extender(astroid.MANAGER, 'lxml.builder', lxml_builder_extend)
astroid.MANAGER.register_transform(astroid.ClassDef, beaker_decl_enum_transform)
astroid.MANAGER.register_transform(astroid.Module, lxml_builder_transform)
Example #22
0
def resource_listdir(package_or_requirement, resource_name):
    return get_provider(package_or_requirement).resource_listdir(
        resource_name)

def extraction_error():
    pass

def get_cache_path(archive_name, names=()):
    extract_path = self.extraction_path or get_default_cache()
    target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
    return target_path

def postprocess(tempname, filename):
    pass

def set_extraction_path(path):
    pass

def cleanup_resources(force=False):
    pass

def get_distribution(dist):
    return Distribution(dist)

_namespace_packages = {}
""")


register_module_extender(MANAGER, "pkg_resources", pkg_resources_transform)
Example #23
0
            pass
        def shutdown(self):
            pass
    '''))

def thread_transform():
    return AstroidBuilder(MANAGER).string_build('''
class lock(object):
    def acquire(self, blocking=True):
        pass
    def release(self):
        pass

def Lock():
    return lock()
''')

MANAGER.register_transform(nodes.Call, inference_tip(infer_named_tuple),
                           _looks_like_namedtuple)
MANAGER.register_transform(nodes.Call, inference_tip(infer_enum),
                           _looks_like_enum)
MANAGER.register_transform(nodes.ClassDef, infer_enum_class)
register_module_extender(MANAGER, 'hashlib', hashlib_transform)
register_module_extender(MANAGER, 'collections', collections_transform)
register_module_extender(MANAGER, 'pkg_resources', pkg_resources_transform)
register_module_extender(MANAGER, 'subprocess', subprocess_transform)
register_module_extender(MANAGER, 'multiprocessing.managers',
                         multiprocessing_managers_transform)
register_module_extender(MANAGER, 'multiprocessing', multiprocessing_transform)
register_module_extender(MANAGER, 'threading', thread_transform)
Example #24
0
    from ipaplatform.base.services import wellknownservices
    from ipaplatform.base.services import wellknownports
    __all__ = ('knownservices', 'timedate_services', 'service',
               'wellknownservices', 'wellknownports')
    '''))


def ipaplatform_tasks_transform():
    return AstroidBuilder(MANAGER).string_build(
        textwrap.dedent('''
    from ipaplatform.base.tasks import tasks
    __all__ = ('tasks',)
    '''))


register_module_extender(MANAGER, 'ipaplatform.constants',
                         ipaplatform_constants_transform)
register_module_extender(MANAGER, 'ipaplatform.paths',
                         ipaplatform_paths_transform)
register_module_extender(MANAGER, 'ipaplatform.services',
                         ipaplatform_services_transform)
register_module_extender(MANAGER, 'ipaplatform.tasks',
                         ipaplatform_tasks_transform)


def ipalib_request_transform():
    """ipalib.request.context attribute
    """
    return AstroidBuilder(MANAGER).string_build(
        textwrap.dedent('''
    from ipalib.request import context
    context._pylint_attr = Connection("_pylint", lambda: None)
Example #25
0
# Copyright (c) 2012-2013 LOGILAB S.A. (Paris, FRANCE) <*****@*****.**>
# Copyright (c) 2014 Google, Inc.
# Copyright (c) 2015-2016 Claudiu Popa <*****@*****.**>
# Copyright (c) 2016 Ceridwen <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER

from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder

def mechanize_transform():
    return AstroidBuilder(MANAGER).string_build('''

class Browser(object):
    def open(self, url, data=None, timeout=None):
        return None
    def open_novisit(self, url, data=None, timeout=None):
        return None
    def open_local_file(self, filename):
        return None

''')


register_module_extender(MANAGER, 'mechanize', mechanize_transform)
Example #26
0
        import urllib.parse as urllib_parse
        import urllib.error as urllib_error
        import tkinter
        import tkinter.dialog as tkinter_dialog
        import tkinter.filedialog as tkinter_filedialog
        import tkinter.scrolledtext as tkinter_scrolledtext
        import tkinter.simpledialog as tkinder_simpledialog
        import tkinter.tix as tkinter_tix
        import tkinter.ttk as tkinter_ttk
        import tkinter.constants as tkinter_constants
        import tkinter.dnd as tkinter_dnd
        import tkinter.colorchooser as tkinter_colorchooser
        import tkinter.commondialog as tkinter_commondialog
        import tkinter.filedialog as tkinter_tkfiledialog
        import tkinter.font as tkinter_font
        import tkinter.messagebox as tkinter_messagebox
        import urllib.request
        import urllib.robotparser as urllib_robotparser
        import urllib.parse as urllib_parse
        import urllib.error as urllib_error
    moves = Moves()
    '''))


if sys.version_info[0] == 2:
    TRANSFORM = six_moves_transform_py2
else:
    TRANSFORM = six_moves_transform_py3

register_module_extender(MANAGER, 'six', TRANSFORM)
Example #27
0
# Copyright (c) 2016 Claudiu Popa <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER

import astroid


def _thread_transform():
    return astroid.parse('''
    class lock(object):
        def acquire(self, blocking=True):
            pass
        def release(self):
            pass

    def Lock():
        return lock()
    ''')


astroid.register_module_extender(astroid.MANAGER, 'threading', _thread_transform)
Example #28
0
    # This will cause an Uninferable result, which is okay
    return module

def transform_six_add_metaclass(node):
    """Check if the given class node is decorated with *six.add_metaclass*

    If so, inject its argument as the metaclass of the underlying class.
    """
    if not node.decorators:
        return

    for decorator in node.decorators.nodes:
        if not isinstance(decorator, nodes.Call):
            continue

        try:
            func = next(decorator.func.infer())
        except InferenceError:
            continue
        if func.qname() == SIX_ADD_METACLASS and decorator.args:
            metaclass = decorator.args[0]
            node._metaclass = metaclass
            return node


register_module_extender(MANAGER, 'six', six_moves_transform)
register_module_extender(MANAGER, 'requests.packages.urllib3.packages.six',
                         six_moves_transform)
MANAGER.register_failed_import_hook(_six_fail_hook)
MANAGER.register_transform(nodes.ClassDef, transform_six_add_metaclass)
Example #29
0
def register(linter):
    register_module_extender(MANAGER, 'subprocess', subprocess_transform)
Example #30
0
    node.instance_attrs["connect"] = signal_cls["connect"]
    node.instance_attrs["disconnect"] = signal_cls["disconnect"]
    node.instance_attrs["emit"] = signal_cls["emit"]


def pyqt4_qtcore_transform():
    return AstroidBuilder(MANAGER).string_build("""

def SIGNAL(signal_name): pass

class QObject(object):
    def emit(self, signal): pass
""")


register_module_extender(MANAGER, "PyQt4.QtCore", pyqt4_qtcore_transform)
MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal,
                           _looks_like_signal)
MANAGER.register_transform(
    nodes.ClassDef,
    transform_pyside_signal,
    lambda node: node.qname() in
    ("PySide.QtCore.Signal", "PySide2.QtCore.Signal"),
)
MANAGER.register_transform(
    nodes.FunctionDef,
    transform_pyside_signal,
    lambda node: (node.qname().partition(".")[0] == "PySide2" and any(
        cls.qname() == "Signal"
        for cls in node.instance_attrs.get("__class__", []))),
)
Example #31
0
        def startswith(self, prefix, start=None, end=None): pass
        def strip(self, chars=None): pass
        def swapcase(self): pass
        def title(self): pass
        def translate(self, table, deletechars=None): pass
        def upper(self): pass
        def zfill(self, width): pass

    class unicode_(string_):
        def isdecimal(self): pass
        def isnumeric(self): pass

    object_ = type('object_')
    ''')


def numpy_funcs():
    return astroid.parse('''
    import builtins
    def sum(a, axis=None, dtype=None, out=None, keepdims=None):
        return builtins.sum(a)
    ''')


astroid.register_module_extender(astroid.MANAGER, 'numpy.core.umath', numpy_core_umath_transform)
astroid.register_module_extender(astroid.MANAGER, 'numpy.random.mtrand',
                                 numpy_random_mtrand_transform)
astroid.register_module_extender(astroid.MANAGER, 'numpy.core.numerictypes',
                                 numpy_core_numerictypes_transform)
astroid.register_module_extender(astroid.MANAGER, 'numpy', numpy_funcs)
Example #32
0
def register(linter):
    register_module_extender(MANAGER, 'subprocess', subprocess_transform)
Example #33
0
    uint64 = type('uint64')
    int128 = type('int128')
    uint128 = type('uint128')
    float16 = type('float16')
    float32 = type('float32')
    float64 = type('float64')
    float80 = type('float80')
    float96 = type('float96')
    float128 = type('float128')
    float256 = type('float256')
    complex32 = type('complex32')
    complex64 = type('complex64')
    complex128 = type('complex128')
    complex160 = type('complex160')
    complex192 = type('complex192')
    complex256 = type('complex256')
    complex512 = type('complex512')
    timedelta64 = type('timedelta64')
    datetime64 = type('datetime64')
    unicode_ = type('unicode_')
    string_ = type('string_')
    object_ = type('object_')
    ''')


astroid.register_module_extender(astroid.MANAGER, 'numpy.core.umath', numpy_core_umath_transform)
astroid.register_module_extender(astroid.MANAGER, 'numpy.random.mtrand',
                                 numpy_random_mtrand_transform)
astroid.register_module_extender(astroid.MANAGER, 'numpy.core.numerictypes',
                                 numpy_core_numerictypes_transform)
Example #34
0
                classdef = dedent('''
                class %(name)s(object):
                    @property
                    def value(self):
                        # Not the best return.
                        return None 
                    @property
                    def name(self):
                        return %(name)r
                ''' % {'name': target.name})
                fake = AstroidBuilder(MANAGER).string_build(classdef)[
                    target.name]
                fake.parent = target.parent
                for method in node.mymethods():
                    fake.locals[method.name] = [method]
                new_targets.append(fake.instanciate_class())
            node.locals[local] = new_targets
        break
    return node


MANAGER.register_transform(nodes.CallFunc, inference_tip(infer_named_tuple),
                           looks_like_namedtuple)
MANAGER.register_transform(nodes.CallFunc, inference_tip(infer_enum),
                           AsStringRegexpPredicate('Enum', 'func'))
MANAGER.register_transform(nodes.Class, infer_enum_class)
register_module_extender(MANAGER, 'hashlib', hashlib_transform)
register_module_extender(MANAGER, 'collections', collections_transform)
register_module_extender(MANAGER, 'pkg_resources', pkg_resources_transform)
register_module_extender(MANAGER, 'subprocess', subprocess_transform)
    uintp = uint32
    ulonglong = uint64
    unicode = str_
    unicode_ = str_
    ushort = uint16
    void0 = void
    """
    )


def numpy_funcs():
    return astroid.parse(
        """
    import builtins
    def sum(a, axis=None, dtype=None, out=None, keepdims=None):
        return builtins.sum(a)
    """
    )


astroid.register_module_extender(
    astroid.MANAGER, "numpy.core.umath", numpy_core_umath_transform
)
astroid.register_module_extender(
    astroid.MANAGER, "numpy.random.mtrand", numpy_random_mtrand_transform
)
astroid.register_module_extender(
    astroid.MANAGER, "numpy.core.numerictypes", numpy_core_numerictypes_transform
)
astroid.register_module_extender(astroid.MANAGER, "numpy", numpy_funcs)
        def pop(self): pass
        def popleft(self): pass
        def remove(self, value): pass
        def reverse(self): pass
        def rotate(self, n=1): pass
        def __iter__(self): return self
        def __reversed__(self): return self.iterable[::-1]
        def __getitem__(self, index): pass
        def __setitem__(self, index, value): pass
        def __delitem__(self, index): pass
        def __bool__(self): return bool(self.iterable)
        def __nonzero__(self): return bool(self.iterable)
        def __contains__(self, o): return o in self.iterable
        def __len__(self): return len(self.iterable)
        def __copy__(self): return deque(self.iterable)'''
    if PY35:
        base_deque_class += '''
        def copy(self): return deque(self.iterable)
        def index(self, x, start=0, end=0): return 0
        def insert(self, x, i): pass
        def __add__(self, other): pass
        def __iadd__(self, other): pass
        def __mul__(self, other): pass
        def __imul__(self, other): pass
        def __rmul__(self, other): pass'''
    return base_deque_class


astroid.register_module_extender(astroid.MANAGER, 'collections',
                                 _collections_transform)
Example #37
0
def register(linter):
    register_module_extender(MANAGER, 'hashlib', hashlib_transform)
    hypot = FakeUfuncTwoArgs()
    heaviside = FakeUfuncTwoArgs()
    lcm = FakeUfuncTwoArgs()
    ldexp = FakeUfuncTwoArgs()
    left_shift = FakeUfuncTwoArgs()
    less = FakeUfuncTwoArgs()
    logaddexp = FakeUfuncTwoArgs()
    logaddexp2 = FakeUfuncTwoArgs()
    logical_and = FakeUfuncTwoArgs()
    logical_or = FakeUfuncTwoArgs()
    logical_xor = FakeUfuncTwoArgs()
    maximum = FakeUfuncTwoArgs()
    minimum = FakeUfuncTwoArgs()
    multiply = FakeUfuncTwoArgs()
    nextafter = FakeUfuncTwoArgs()
    not_equal = FakeUfuncTwoArgs()
    power = FakeUfuncTwoArgs()
    remainder = FakeUfuncTwoArgs()
    right_shift = FakeUfuncTwoArgs()
    subtract = FakeUfuncTwoArgs()
    true_divide = FakeUfuncTwoArgs()
    """.format(
            opt_args=ufunc_optional_keyword_arguments
        )
    )


astroid.register_module_extender(
    astroid.MANAGER, "numpy.core.umath", numpy_core_umath_transform
)
        def extendleft(self, iterable): pass
        def pop(self): pass
        def popleft(self): pass
        def remove(self, value): pass
        def reverse(self): pass
        def rotate(self, n=1): pass
        def __iter__(self): return self
        def __reversed__(self): return self.iterable[::-1]
        def __getitem__(self, index): pass
        def __setitem__(self, index, value): pass
        def __delitem__(self, index): pass
        def __bool__(self): return bool(self.iterable)
        def __nonzero__(self): return bool(self.iterable)
        def __contains__(self, o): return o in self.iterable
        def __len__(self): return len(self.iterable)
        def __copy__(self): return deque(self.iterable)'''
    if PY35:
        base_deque_class += '''
        def copy(self): return deque(self.iterable)
        def index(self, x, start=0, end=0): return 0
        def insert(self, x, i): pass
        def __add__(self, other): pass
        def __iadd__(self, other): pass
        def __mul__(self, other): pass
        def __imul__(self, other): pass
        def __rmul__(self, other): pass'''
    return base_deque_class

astroid.register_module_extender(astroid.MANAGER, 'collections', _collections_transform)

Example #40
0
        def send_signal(self, signal):
            pass
        def terminate(self):
            pass
        def kill(self):
            pass
        %(ctx_manager)s
       """ % {
            "check_output_signature": check_output_signature,
            "communicate": communicate,
            "communicate_signature": communicate_signature,
            "wait_signature": wait_signature,
            "ctx_manager": ctx_manager,
            "py3_args": py3_args,
        })
    if PY39:
        code += """
    @classmethod
    def __class_getitem__(cls, item):
        pass
        """

    init_lines = textwrap.dedent(init).splitlines()
    indented_init = "\n".join(" " * 4 + line for line in init_lines)
    code += indented_init
    return astroid.parse(code)


astroid.register_module_extender(astroid.MANAGER, "subprocess",
                                 _subprocess_transform)
    ACS_S1 = 1
    ACS_S3 = 1
    ACS_S7 = 1
    ACS_S9 = 1
    ACS_SBBS = 1
    ACS_SBSB = 1
    ACS_SBSS = 1
    ACS_SSBB = 1
    ACS_SSBS = 1
    ACS_SSSB = 1
    ACS_SSSS = 1
    ACS_STERLING = 1
    ACS_TTEE = 1
    ACS_UARROW = 1
    ACS_ULCORNER = 1
    ACS_URCORNER = 1
    ACS_VLINE = 1
    COLOR_BLACK = 1
    COLOR_BLUE = 1
    COLOR_CYAN = 1
    COLOR_GREEN = 1
    COLOR_MAGENTA = 1
    COLOR_RED = 1
    COLOR_WHITE = 1
    COLOR_YELLOW = 1
        """
    )


astroid.register_module_extender(astroid.MANAGER, "curses", _curses_transform)
Example #42
0
from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder

def mechanize_transform():
    return AstroidBuilder(MANAGER).string_build('''

class Browser(object):
    def open(self, url, data=None, timeout=None):
        return None
    def open_novisit(self, url, data=None, timeout=None):
        return None
    def open_local_file(self, filename):
        return None

''')


register_module_extender(MANAGER, 'mechanize', mechanize_transform)
Example #43
0
def _pep8(name, caps=re.compile('([A-Z])')):
    return caps.sub(lambda m: '_' + m.groups()[0].lower(), name)


def nose_transform():
    """Custom transform for the nose.tools module."""

    builder = AstroidBuilder(MANAGER)
    stub = AstroidBuilder(MANAGER).string_build('''__all__ = []''')
    unittest_module = builder.module_build(unittest.case)
    case = unittest_module['TestCase']
    all_entries = ['ok_', 'eq_']

    for method_name, method in case.locals.items():
        if method_name.startswith('assert') and '_' not in method_name:
            pep8_name = _pep8(method_name)
            all_entries.append(pep8_name)
            stub[pep8_name] = method[0]

    # Update the __all__ variable, since nose.tools
    # does this manually with .append.
    all_assign = stub['__all__'].parent
    all_object = List(all_entries)
    all_object.parent = all_assign
    all_assign.value = all_object
    return stub


register_module_extender(MANAGER, 'nose.tools.trivial', nose_transform)
Example #44
0
      @property
      def digest_size(self):
        return 1
    """
    algorithms_with_signature = dict.fromkeys(
        ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"], signature
    )
    if PY36:
        blake2b_signature = "data=b'', *, digest_size=64, key=b'', salt=b'', \
                person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
                node_depth=0, inner_size=0, last_node=False"
        blake2s_signature = "data=b'', *, digest_size=32, key=b'', salt=b'', \
                person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
                node_depth=0, inner_size=0, last_node=False"
        new_algorithms = dict.fromkeys(
            ["sha3_224", "sha3_256", "sha3_384", "sha3_512", "shake_128", "shake_256"],
            signature,
        )
        algorithms_with_signature.update(new_algorithms)
        algorithms_with_signature.update(
            {"blake2b": blake2b_signature, "blake2s": blake2s_signature}
        )
    classes = "".join(
        template % {"name": hashfunc, "digest": 'b""', "signature": signature}
        for hashfunc, signature in algorithms_with_signature.items()
    )
    return astroid.parse(classes)


astroid.register_module_extender(astroid.MANAGER, "hashlib", _hashlib_transform)
Example #45
0
            yield 'assert_equals', astroid.BoundMethod(method, case)


def _nose_tools_transform(node):
    for method_name, method in _nose_tools_functions():
        node.locals[method_name] = [method]


def _nose_tools_trivial_transform():
    """Custom transform for the nose.tools module."""
    stub = _BUILDER.string_build('''__all__ = []''')
    all_entries = ['ok_', 'eq_']

    for pep8_name, method in _nose_tools_functions():
        all_entries.append(pep8_name)
        stub[pep8_name] = method

    # Update the __all__ variable, since nose.tools
    # does this manually with .append.
    all_assign = stub['__all__'].parent
    all_object = astroid.List(all_entries)
    all_object.parent = all_assign
    all_assign.value = all_object
    return stub


astroid.register_module_extender(astroid.MANAGER, 'nose.tools.trivial',
                                 _nose_tools_trivial_transform)
astroid.MANAGER.register_transform(astroid.Module, _nose_tools_transform,
                                   lambda n: n.name == 'nose.tools')
def numpy_core_multiarray_transform():
    return astroid.parse(
        """
    # different functions defined in multiarray.py
    def inner(a, b):
        return numpy.ndarray([0, 0])

    def vdot(a, b):
        return numpy.ndarray([0, 0])
        """
    )


astroid.register_module_extender(
    astroid.MANAGER, "numpy.core.multiarray", numpy_core_multiarray_transform
)


METHODS_TO_BE_INFERRED = {
    "array": """def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
            return numpy.ndarray([0, 0])""",
    "dot": """def dot(a, b, out=None):
            return numpy.ndarray([0, 0])""",
    "empty_like": """def empty_like(a, dtype=None, order='K', subok=True):
            return numpy.ndarray((0, 0))""",
    "concatenate": """def concatenate(arrays, axis=None, out=None):
            return numpy.ndarray((0, 0))""",
    "where": """def where(condition, x=None, y=None):
            return numpy.ndarray([0, 0])""",
    "empty": """def empty(shape, dtype=float, order='C'):
Example #47
0
                      ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN,
                      ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE,
                      ALERT_DESCRIPTION_CLOSE_NOTIFY, ALERT_DESCRIPTION_DECODE_ERROR,
                      ALERT_DESCRIPTION_DECOMPRESSION_FAILURE,
                      ALERT_DESCRIPTION_DECRYPT_ERROR,
                      ALERT_DESCRIPTION_HANDSHAKE_FAILURE,
                      ALERT_DESCRIPTION_ILLEGAL_PARAMETER,
                      ALERT_DESCRIPTION_INSUFFICIENT_SECURITY,
                      ALERT_DESCRIPTION_INTERNAL_ERROR,
                      ALERT_DESCRIPTION_NO_RENEGOTIATION,
                      ALERT_DESCRIPTION_PROTOCOL_VERSION,
                      ALERT_DESCRIPTION_RECORD_OVERFLOW,
                      ALERT_DESCRIPTION_UNEXPECTED_MESSAGE,
                      ALERT_DESCRIPTION_UNKNOWN_CA,
                      ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY,
                      ALERT_DESCRIPTION_UNRECOGNIZED_NAME,
                      ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE,
                      ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION,
                      ALERT_DESCRIPTION_USER_CANCELLED)
    from _ssl import (SSL_ERROR_EOF, SSL_ERROR_INVALID_ERROR_CODE, SSL_ERROR_SSL,
                      SSL_ERROR_SYSCALL, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_READ,
                      SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_ZERO_RETURN)
    from _ssl import VERIFY_CRL_CHECK_CHAIN, VERIFY_CRL_CHECK_LEAF, VERIFY_DEFAULT, VERIFY_X509_STRICT
    from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
    from _ssl import _OPENSSL_API_VERSION
    from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
    ''')


register_module_extender(MANAGER, 'ssl', ssl_transform)
Example #48
0
        if isinstance(value, ModuleType):
            continue

        if hasattr(value, '__call__'):
            # name is a function
            names_str += name + "=None\n"
        else:
            # name is a value
            names_str += name + "=" + str(value) + "\n"

    return names_str


def transform():
    builder = AstroidBuilder(astroid.MANAGER)
    return builder.string_build(get_members())
    #return builder.string_build("""
    ## Fill in the rest of the fields that are missing
    #ITEM_TYPE_ROBOT = None
    #""")


def register(linter):
    print("RoboDK linter")


astroid.register_module_extender(astroid.MANAGER, "pylintrobodk", transform)

if __name__ == "__main__":
    print(get_members())
Example #49
0
    if class_name_with_module in ipa_class_members:
        fake_class(cls, ipa_class_members[class_name_with_module])

MANAGER.register_transform(scoped_nodes.Class, fix_ipa_classes)


def pytest_config_transform():
    """pylint.config attribute
    """
    return AstroidBuilder(MANAGER).string_build(textwrap.dedent('''
    from _pytest.config import get_config
    config = get_config()
    '''))


register_module_extender(MANAGER, 'pytest', pytest_config_transform)


def ipaplatform_constants_transform():
    return AstroidBuilder(MANAGER).string_build(textwrap.dedent('''
    from ipaplatform.base.constants import constants
    __all__ = ('constants',)
    '''))


def ipaplatform_paths_transform():
    return AstroidBuilder(MANAGER).string_build(textwrap.dedent('''
    from ipaplatform.base.paths import paths
    __all__ = ('paths',)
    '''))
Example #50
0
def register(linter):
    register_module_extender(MANAGER, "scapy.all", scapy_transform)
Example #51
0
    def Array(typecode, sequence, lock=True):
        return array.array(typecode, sequence)

    class SyncManager(object):
        Queue = JoinableQueue = six.moves.queue.Queue
        Event = threading.Event
        RLock = threading.RLock
        BoundedSemaphore = threading.BoundedSemaphore
        Condition = threading.Condition
        Barrier = threading.Barrier
        Pool = pool.Pool
        list = list
        dict = dict
        Value = Value
        Array = Array
        Namespace = Namespace
        __enter__ = lambda self: self
        __exit__ = lambda *args: args
        
        def start(self, initializer=None, initargs=None):
            pass
        def shutdown(self):
            pass
    ''')


astroid.register_module_extender(astroid.MANAGER, 'multiprocessing.managers',
                                 _multiprocessing_managers_transform)
astroid.register_module_extender(astroid.MANAGER, 'multiprocessing',
                                 _multiprocessing_transform)
Example #52
0
    def hanning(M, sym=True):
        return numpy.ndarray([0])

    def impulse2(system, X0=None, T=None, N=None, **kwargs):
        return numpy.ndarray([0]), numpy.ndarray([0])

    def kaiser(M, beta, sym=True):
        return numpy.ndarray([0])

    def nuttall(M, sym=True):
        return numpy.ndarray([0])

    def parzen(M, sym=True):
        return numpy.ndarray([0])

    def slepian(M, width, sym=True):
        return numpy.ndarray([0])

    def step2(system, X0=None, T=None, N=None, **kwargs):
        return numpy.ndarray([0]), numpy.ndarray([0])

    def triang(M, sym=True):
        return numpy.ndarray([0])

    def tukey(M, alpha=0.5, sym=True):
        return numpy.ndarray([0])
        """)


astroid.register_module_extender(astroid.MANAGER, "scipy.signal", scipy_signal)
Example #53
0
def register(linter):
    register_module_extender(MANAGER, 'httpretty', httpretty_transform)
# Copyright (c) 2019 hippo91 <*****@*****.**>
# Copyright (c) 2020 Claudiu Popa <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
"""Astroid hooks for numpy.core.fromnumeric module."""

import astroid


def numpy_core_fromnumeric_transform():
    return astroid.parse("""
    def sum(a, axis=None, dtype=None, out=None, keepdims=None, initial=None):
        return numpy.ndarray([0, 0])
    """)


astroid.register_module_extender(astroid.MANAGER, "numpy.core.fromnumeric",
                                 numpy_core_fromnumeric_transform)
Example #55
0
                      ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE,
                      ALERT_DESCRIPTION_CLOSE_NOTIFY, ALERT_DESCRIPTION_DECODE_ERROR,
                      ALERT_DESCRIPTION_DECOMPRESSION_FAILURE,
                      ALERT_DESCRIPTION_DECRYPT_ERROR,
                      ALERT_DESCRIPTION_HANDSHAKE_FAILURE,
                      ALERT_DESCRIPTION_ILLEGAL_PARAMETER,
                      ALERT_DESCRIPTION_INSUFFICIENT_SECURITY,
                      ALERT_DESCRIPTION_INTERNAL_ERROR,
                      ALERT_DESCRIPTION_NO_RENEGOTIATION,
                      ALERT_DESCRIPTION_PROTOCOL_VERSION,
                      ALERT_DESCRIPTION_RECORD_OVERFLOW,
                      ALERT_DESCRIPTION_UNEXPECTED_MESSAGE,
                      ALERT_DESCRIPTION_UNKNOWN_CA,
                      ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY,
                      ALERT_DESCRIPTION_UNRECOGNIZED_NAME,
                      ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE,
                      ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION,
                      ALERT_DESCRIPTION_USER_CANCELLED)
    from _ssl import (SSL_ERROR_EOF, SSL_ERROR_INVALID_ERROR_CODE, SSL_ERROR_SSL,
                      SSL_ERROR_SYSCALL, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_READ,
                      SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_ZERO_RETURN)
    from _ssl import VERIFY_CRL_CHECK_CHAIN, VERIFY_CRL_CHECK_LEAF, VERIFY_DEFAULT, VERIFY_X509_STRICT
    from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
    from _ssl import _OPENSSL_API_VERSION
    from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
    """
    )


register_module_extender(MANAGER, "ssl", ssl_transform)
Example #56
0
    LENGTH_REQUIRED = HTTPStatus.LENGTH_REQUIRED
    PRECONDITION_FAILED = HTTPStatus.PRECONDITION_FAILED
    REQUEST_ENTITY_TOO_LARGE = HTTPStatus.REQUEST_ENTITY_TOO_LARGE
    REQUEST_URI_TOO_LONG = HTTPStatus.REQUEST_URI_TOO_LONG
    UNSUPPORTED_MEDIA_TYPE = HTTPStatus.UNSUPPORTED_MEDIA_TYPE
    REQUESTED_RANGE_NOT_SATISFIABLE = HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE
    EXPECTATION_FAILED = HTTPStatus.EXPECTATION_FAILED
    UNPROCESSABLE_ENTITY = HTTPStatus.UNPROCESSABLE_ENTITY
    LOCKED = HTTPStatus.LOCKED
    FAILED_DEPENDENCY = HTTPStatus.FAILED_DEPENDENCY
    UPGRADE_REQUIRED = HTTPStatus.UPGRADE_REQUIRED
    PRECONDITION_REQUIRED = HTTPStatus.PRECONDITION_REQUIRED
    TOO_MANY_REQUESTS = HTTPStatus.TOO_MANY_REQUESTS
    REQUEST_HEADER_FIELDS_TOO_LARGE = HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE
    INTERNAL_SERVER_ERROR = HTTPStatus.INTERNAL_SERVER_ERROR
    NOT_IMPLEMENTED = HTTPStatus.NOT_IMPLEMENTED
    BAD_GATEWAY = HTTPStatus.BAD_GATEWAY
    SERVICE_UNAVAILABLE = HTTPStatus.SERVICE_UNAVAILABLE
    GATEWAY_TIMEOUT = HTTPStatus.GATEWAY_TIMEOUT
    HTTP_VERSION_NOT_SUPPORTED = HTTPStatus.HTTP_VERSION_NOT_SUPPORTED
    VARIANT_ALSO_NEGOTIATES = HTTPStatus.VARIANT_ALSO_NEGOTIATES
    INSUFFICIENT_STORAGE = HTTPStatus.INSUFFICIENT_STORAGE
    LOOP_DETECTED = HTTPStatus.LOOP_DETECTED
    NOT_EXTENDED = HTTPStatus.NOT_EXTENDED
    NETWORK_AUTHENTICATION_REQUIRED = HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED
    """))


astroid.register_module_extender(astroid.MANAGER, "http.client",
                                 _http_transform)
Example #57
0
from __future__ import absolute_import
from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder


def pytest_transform():
    return AstroidBuilder(MANAGER).string_build('''

try:
    import _pytest.mark
    import _pytest.recwarn
    import _pytest.runner
    import _pytest.python
except ImportError:
    pass
else:
    deprecated_call = _pytest.recwarn.deprecated_call
    exit = _pytest.runner.exit
    fail = _pytest.runner.fail
    fixture = _pytest.python.fixture
    importorskip = _pytest.runner.importorskip
    mark = _pytest.mark.MarkGenerator()
    raises = _pytest.python.raises
    skip = _pytest.runner.skip
    yield_fixture = _pytest.python.yield_fixture

''')

register_module_extender(MANAGER, 'pytest', pytest_transform)
register_module_extender(MANAGER, 'py.test', pytest_transform)
    def Array(typecode, sequence, lock=True):
        return array.array(typecode, sequence)

    class SyncManager(object):
        Queue = JoinableQueue = six.moves.queue.Queue
        Event = threading.Event
        RLock = threading.RLock
        BoundedSemaphore = threading.BoundedSemaphore
        Condition = threading.Condition
        Barrier = threading.Barrier
        Pool = pool.Pool
        list = list
        dict = dict
        Value = Value
        Array = Array
        Namespace = Namespace
        __enter__ = lambda self: self
        __exit__ = lambda *args: args

        def start(self, initializer=None, initargs=None):
            pass
        def shutdown(self):
            pass
    """)


astroid.register_module_extender(astroid.MANAGER, "multiprocessing.managers",
                                 _multiprocessing_managers_transform)
astroid.register_module_extender(astroid.MANAGER, "multiprocessing",
                                 _multiprocessing_transform)
Example #59
0
    module.name = 'six.moves'
    return module

def transform_six_add_metaclass(node):
    """Check if the given class node is decorated with *six.add_metaclass*

    If so, inject its argument as the metaclass of the underlying class.
    """
    if not node.decorators:
        return

    for decorator in node.decorators.nodes:
        if not isinstance(decorator, nodes.Call):
            continue

        try:
            func = next(decorator.func.infer())
        except InferenceError:
            continue
        if func.qname() == SIX_ADD_METACLASS and decorator.args:
            metaclass = decorator.args[0]
            node._metaclass = metaclass
            return node


register_module_extender(MANAGER, 'six', six_moves_transform)
register_module_extender(MANAGER, 'requests.packages.urllib3.packages.six',
                         six_moves_transform)
MANAGER.register_failed_import_hook(_six_fail_hook)
MANAGER.register_transform(nodes.ClassDef, transform_six_add_metaclass)
Example #60
0
            yield "assert_equals", astroid.BoundMethod(method, case)


def _nose_tools_transform(node):
    for method_name, method in _nose_tools_functions():
        node.locals[method_name] = [method]


def _nose_tools_trivial_transform():
    """Custom transform for the nose.tools module."""
    stub = _BUILDER.string_build("""__all__ = []""")
    all_entries = ["ok_", "eq_"]

    for pep8_name, method in _nose_tools_functions():
        all_entries.append(pep8_name)
        stub[pep8_name] = method

    # Update the __all__ variable, since nose.tools
    # does this manually with .append.
    all_assign = stub["__all__"].parent
    all_object = astroid.List(all_entries)
    all_object.parent = all_assign
    all_assign.value = all_object
    return stub


astroid.register_module_extender(astroid.MANAGER, "nose.tools.trivial",
                                 _nose_tools_trivial_transform)
astroid.MANAGER.register_transform(astroid.Module, _nose_tools_transform,
                                   lambda n: n.name == "nose.tools")