Skip to content
Snippets Groups Projects
Commit 8425d915 authored by Claudiu Popa's avatar Claudiu Popa
Browse files

Remove Python 2 branches, assume we always run on Python 3

parent 29eb92e6
No related branches found
No related tags found
No related merge requests found
Loading
Loading
@@ -9,7 +9,7 @@
Various helper utilities.
"""
 
import six
import builtins
 
from astroid import bases
from astroid import context as contextmod
Loading
Loading
@@ -21,7 +21,7 @@ from astroid import scoped_nodes
from astroid import util
 
 
BUILTINS = six.moves.builtins.__name__
BUILTINS = builtins.__name__
 
 
def _build_proxy_class(cls_name, builtins):
Loading
Loading
@@ -37,15 +37,9 @@ def _function_type(function, builtins):
else:
cls_name = 'function'
elif isinstance(function, bases.BoundMethod):
if six.PY2:
cls_name = 'instancemethod'
else:
cls_name = 'method'
cls_name = 'method'
elif isinstance(function, bases.UnboundMethod):
if six.PY2:
cls_name = 'instancemethod'
else:
cls_name = 'function'
cls_name = 'function'
return _build_proxy_class(cls_name, builtins)
 
 
Loading
Loading
Loading
Loading
@@ -20,17 +20,12 @@ attribute. Thus the model can be viewed as a special part of the lookup
mechanism.
"""
 
try:
from functools import lru_cache
except ImportError:
from backports.functools_lru_cache import lru_cache
import builtins
import itertools
import pprint
import os
import types
import six
from functools import lru_cache
 
import astroid
from astroid import context as contextmod
Loading
Loading
@@ -114,18 +109,12 @@ class ObjectModel(object):
class ModuleModel(ObjectModel):
 
def _builtins(self):
builtins = astroid.MANAGER.astroid_cache[six.moves.builtins.__name__]
return builtins.special_attributes.lookup('__dict__')
if six.PY3:
@property
def pybuiltins(self):
return self._builtins()
builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__]
return builtins_ast_module.special_attributes.lookup('__dict__')
 
else:
@property
def py__builtin__(self):
return self._builtins()
@property
def pybuiltins(self):
return self._builtins()
 
# __path__ is a standard attribute on *packages* not
# non-package modules. The only mention of it in the
Loading
Loading
@@ -234,8 +223,8 @@ class FunctionModel(ObjectModel):
 
args = self._instance.args
pair_annotations = itertools.chain(
six.moves.zip(args.args or [], args.annotations),
six.moves.zip(args.kwonlyargs, args.kwonlyargs_annotations)
zip(args.args or [], args.annotations),
zip(args.kwonlyargs, args.kwonlyargs_annotations)
)
 
annotations = {
Loading
Loading
@@ -345,15 +334,6 @@ class FunctionModel(ObjectModel):
py__closure__ = py__ne__
py__code__ = py__ne__
 
if six.PY2:
pyfunc_name = py__name__
pyfunc_doc = py__doc__
pyfunc_globals = py__globals__
pyfunc_dict = py__dict__
pyfunc_defaults = py__defaults__
pyfunc_code = py__code__
pyfunc_closure = py__closure__
 
class ClassModel(ObjectModel):
 
Loading
Loading
@@ -508,7 +488,7 @@ class GeneratorModel(FunctionModel):
def __new__(cls, *args, **kwargs):
# Append the values from the GeneratorType unto this object.
ret = super(GeneratorModel, cls).__new__(cls, *args, **kwargs)
generator = astroid.MANAGER.astroid_cache[six.moves.builtins.__name__]['generator']
generator = astroid.MANAGER.astroid_cache[builtins.__name__]['generator']
for name, values in generator.locals.items():
method = values[0]
patched = lambda cls, meth=method: meth
Loading
Loading
@@ -556,21 +536,11 @@ class ExceptionInstanceModel(InstanceModel):
args.postinit((message, ))
return args
 
if six.PY3:
# It's available only on Python 3.
@property
def py__traceback__(self):
builtins = astroid.MANAGER.astroid_cache[six.moves.builtins.__name__]
traceback_type = builtins[types.TracebackType.__name__]
return traceback_type.instantiate_class()
if six.PY2:
# It's available only on Python 2.
@property
def pymessage(self):
return node_classes.Const('')
@property
def py__traceback__(self):
builtins_ast_module = astroid.MANAGER.astroid_cache[builtins.__name__]
traceback_type = builtins_ast_module[types.TracebackType.__name__]
return traceback_type.instantiate_class()
 
 
class DictModel(ObjectModel):
Loading
Loading
@@ -599,9 +569,8 @@ class DictModel(ObjectModel):
elems.append(elem)
obj.postinit(elts=elems)
 
if six.PY3:
from astroid import objects
obj = objects.DictItems(obj)
from astroid import objects
obj = objects.DictItems(obj)
 
return self._generic_dict_attribute(obj, 'items')
 
Loading
Loading
@@ -611,9 +580,8 @@ class DictModel(ObjectModel):
obj = node_classes.List(parent=self._instance)
obj.postinit(elts=keys)
 
if six.PY3:
from astroid import objects
obj = objects.DictKeys(obj)
from astroid import objects
obj = objects.DictKeys(obj)
 
return self._generic_dict_attribute(obj, 'keys')
 
Loading
Loading
@@ -624,8 +592,7 @@ class DictModel(ObjectModel):
obj = node_classes.List(parent=self._instance)
obj.postinit(values)
 
if six.PY3:
from astroid import objects
obj = objects.DictValues(obj)
from astroid import objects
obj = objects.DictValues(obj)
 
return self._generic_dict_attribute(obj, 'values')
Loading
Loading
@@ -12,14 +12,11 @@
"""
 
import abc
import builtins
import itertools
import pprint
import warnings
try:
from functools import singledispatch as _singledispatch
except ImportError:
from singledispatch import singledispatch as _singledispatch
import six
from functools import singledispatch as _singledispatch
 
from astroid import as_string
from astroid import bases
Loading
Loading
@@ -31,7 +28,7 @@ from astroid import mixins
from astroid import util
 
 
BUILTINS = six.moves.builtins.__name__
BUILTINS = builtins.__name__
MANAGER = manager.AstroidManager()
 
 
Loading
Loading
@@ -891,9 +888,10 @@ class Statement(NodeNG):
return stmts[index -1]
return None
 
@six.add_metaclass(abc.ABCMeta)
class _BaseContainer(mixins.ParentAssignTypeMixin,
NodeNG, bases.Instance):
NodeNG, bases.Instance,
metaclass=abc.ABCMeta):
"""Base class for Set, FrozenSet, Tuple and List."""
 
_astroid_fields = ('elts',)
Loading
Loading
@@ -1262,33 +1260,31 @@ class Arguments(mixins.AssignTypeMixin, NodeNG):
>>> node.args
<Arguments l.1 at 0x7effe1db82e8>
"""
if six.PY3:
# Python 3.4+ uses a different approach regarding annotations,
# each argument is a new class, _ast.arg, which exposes an
# 'annotation' attribute. In astroid though, arguments are exposed
# as is in the Arguments node and the only way to expose annotations
# is by using something similar with Python 3.3:
# - we expose 'varargannotation' and 'kwargannotation' of annotations
# of varargs and kwargs.
# - we expose 'annotation', a list with annotations for
# for each normal argument. If an argument doesn't have an
# annotation, its value will be None.
_astroid_fields = ('args', 'defaults', 'kwonlyargs',
'kw_defaults', 'annotations', 'varargannotation',
'kwargannotation', 'kwonlyargs_annotations')
varargannotation = None
"""The type annotation for the variable length arguments.
# Python 3.4+ uses a different approach regarding annotations,
# each argument is a new class, _ast.arg, which exposes an
# 'annotation' attribute. In astroid though, arguments are exposed
# as is in the Arguments node and the only way to expose annotations
# is by using something similar with Python 3.3:
# - we expose 'varargannotation' and 'kwargannotation' of annotations
# of varargs and kwargs.
# - we expose 'annotation', a list with annotations for
# for each normal argument. If an argument doesn't have an
# annotation, its value will be None.
_astroid_fields = ('args', 'defaults', 'kwonlyargs',
'kw_defaults', 'annotations', 'varargannotation',
'kwargannotation', 'kwonlyargs_annotations')
varargannotation = None
"""The type annotation for the variable length arguments.
 
:type: NodeNG
"""
kwargannotation = None
"""The type annotation for the variable length keyword arguments.
:type: NodeNG
"""
kwargannotation = None
"""The type annotation for the variable length keyword arguments.
:type: NodeNG
"""
 
:type: NodeNG
"""
else:
_astroid_fields = ('args', 'defaults', 'kwonlyargs', 'kw_defaults')
_other_fields = ('vararg', 'kwarg')
 
def __init__(self, vararg=None, kwarg=None, parent=None):
Loading
Loading
@@ -1525,7 +1521,7 @@ def _format_args(args, defaults=None, annotations=None):
annotations = []
if defaults is not None:
default_offset = len(args) - len(defaults)
packed = six.moves.zip_longest(args, annotations)
packed = itertools.zip_longest(args, annotations)
for i, (arg, annotation) in enumerate(packed):
if isinstance(arg, Tuple):
values.append('(%s)' % _format_args(arg.elts))
Loading
Loading
@@ -2246,12 +2242,7 @@ class Const(NodeNG, bases.Instance):
)
 
try:
if isinstance(self.value, six.string_types):
return Const(self.value[index_value])
if isinstance(self.value, bytes) and six.PY3:
# Bytes aren't instances of six.string_types
# on Python 3. Also, indexing them should return
# integers.
if isinstance(self.value, (str, bytes)):
return Const(self.value[index_value])
except IndexError as exc:
util.reraise(exceptions.AstroidIndexError(
Loading
Loading
@@ -2284,7 +2275,7 @@ class Const(NodeNG, bases.Instance):
 
:raises TypeError: If this node does not represent something that is iterable.
"""
if isinstance(self.value, six.string_types):
if isinstance(self.value, str):
return self.value
raise TypeError()
 
Loading
Loading
@@ -3404,53 +3395,24 @@ class Raise(Statement):
 
:type: NodeNG or None
"""
if six.PY2:
_astroid_fields = ('exc', 'inst', 'tback')
inst = None
"""The "value" of the exception being raised.
:type: NodeNG or None
"""
tback = None
"""The traceback object to raise with.
:type: NodeNG or None
"""
_astroid_fields = ('exc', 'cause')
cause = None
"""The exception being used to raise this one.
 
def postinit(self, exc=None, inst=None, tback=None):
"""Do some setup after initialisation.
:type: NodeNG or None
"""
 
:param exc: What is being raised.
:type exc: NodeNG or None
def postinit(self, exc=None, cause=None):
"""Do some setup after initialisation.
 
:param inst: The "value" of the exception being raised.
:type inst: NodeNG or None
:param exc: What is being raised.
:type exc: NodeNG or None
 
:param tback: The traceback object to raise with.
:type tback: NodeNG or None
"""
self.exc = exc
self.inst = inst
self.tback = tback
else:
_astroid_fields = ('exc', 'cause')
cause = None
"""The exception being used to raise this one.
:type: NodeNG or None
:param cause: The exception being used to raise this one.
:type cause: NodeNG or None
"""
def postinit(self, exc=None, cause=None):
"""Do some setup after initialisation.
:param exc: What is being raised.
:type exc: NodeNG or None
:param cause: The exception being used to raise this one.
:type cause: NodeNG or None
"""
self.exc = exc
self.cause = cause
self.exc = exc
self.cause = cause
 
def raises_not_implemented(self):
"""Check if this node raises a :class:`NotImplementedError`.
Loading
Loading
@@ -4197,11 +4159,7 @@ CONST_CLS = {
 
def _update_const_classes():
"""update constant classes, so the keys of CONST_CLS can be reused"""
klasses = (bool, int, float, complex, str)
if six.PY2:
# pylint: disable=undefined-variable
klasses += (unicode, long)
klasses += (bytes,)
klasses = (bool, int, float, complex, str, bytes)
for kls in klasses:
CONST_CLS[kls] = Const
_update_const_classes()
Loading
Loading
Loading
Loading
@@ -14,8 +14,6 @@ import collections
import operator as operator_mod
import sys
 
import six
from astroid import arguments
from astroid import bases
from astroid import context as contextmod
Loading
Loading
@@ -39,7 +37,7 @@ def _augmented_name(name):
_CONTEXTLIB_MGR = 'contextlib.contextmanager'
BIN_OP_METHOD = {'+': '__add__',
'-': '__sub__',
'/': '__div__' if six.PY2 else '__truediv__',
'/': '__truediv__',
'//': '__floordiv__',
'*': '__mul__',
'**': '__pow__',
Loading
Loading
@@ -123,7 +121,7 @@ def const_infer_binary_op(self, opnode, operator, other, context, _):
yield util.Uninferable
except TypeError:
yield not_implemented
elif isinstance(self.value, six.string_types) and operator == '%':
elif isinstance(self.value, str) and operator == '%':
# TODO(cpopa): implement string interpolation later on.
yield util.Uninferable
else:
Loading
Loading
Loading
Loading
@@ -14,13 +14,12 @@ new local scope in the language definition : Module, ClassDef, FunctionDef (and
Lambda, GeneratorExp, DictComp and SetComp to some extent).
"""
 
import builtins
import sys
import io
import itertools
import warnings
 
import six
from astroid import bases
from astroid import context as contextmod
from astroid import exceptions
Loading
Loading
@@ -33,7 +32,7 @@ from astroid import node_classes
from astroid import util
 
 
BUILTINS = six.moves.builtins.__name__
BUILTINS = builtins.__name__
ITER_METHODS = ('__iter__', '__getitem__')
 
 
Loading
Loading
@@ -96,7 +95,7 @@ def builtin_lookup(name):
return the list of matching statements and the astroid for the builtin
module
"""
builtin_astroid = MANAGER.ast_from_module(six.moves.builtins)
builtin_astroid = MANAGER.ast_from_module(builtins)
if name == '__dict__':
return builtin_astroid, ()
try:
Loading
Loading
@@ -552,15 +551,7 @@ class Module(LocalsDictNodeNG):
"""
return
 
if six.PY2:
@decorators_mod.cachedproperty
def _absolute_import_activated(self):
for stmt in self.locals.get('absolute_import', ()):
if isinstance(stmt, node_classes.ImportFrom) and stmt.modname == '__future__':
return True
return False
else:
_absolute_import_activated = True
_absolute_import_activated = True
 
def absolute_import_activated(self):
"""Whether :pep:`328` absolute import behaviour has been enabled.
Loading
Loading
@@ -675,7 +666,7 @@ class Module(LocalsDictNodeNG):
return default
 
str_const = lambda node: (isinstance(node, node_classes.Const) and
isinstance(node.value, six.string_types))
isinstance(node.value, str))
for node in explicit.elts:
if str_const(node):
inferred.append(node.value)
Loading
Loading
@@ -967,33 +958,24 @@ class _ListComp(node_classes.NodeNG):
return util.Uninferable
 
 
if six.PY3:
class ListComp(_ListComp, ComprehensionScope):
"""Class representing an :class:`ast.ListComp` node.
>>> node = astroid.extract_node('[thing for thing in things if thing]')
>>> node
<ListComp l.1 at 0x7f23b2e418d0>
"""
_other_other_fields = ('locals',)
def __init__(self, lineno=None, col_offset=None, parent=None):
self.locals = {}
"""A map of the name of a local variable to the node defining it.
class ListComp(_ListComp, ComprehensionScope):
"""Class representing an :class:`ast.ListComp` node.
 
:type: dict(str, NodeNG)
"""
>>> node = astroid.extract_node('[thing for thing in things if thing]')
>>> node
<ListComp l.1 at 0x7f23b2e418d0>
"""
_other_other_fields = ('locals',)
 
super(ListComp, self).__init__(lineno, col_offset, parent)
else:
class ListComp(_ListComp):
"""Class representing an :class:`ast.ListComp` node.
def __init__(self, lineno=None, col_offset=None, parent=None):
self.locals = {}
"""A map of the name of a local variable to the node defining it.
 
>>> node = astroid.extract_node('[thing for thing in things if thing]')
>>> node
<ListComp l.1 at 0x7f23b2e418d0>
:type: dict(str, NodeNG)
"""
 
super(ListComp, self).__init__(lineno, col_offset, parent)
 
def _infer_decorator_callchain(node):
"""Detect decorator call chaining and see if the end result is a
Loading
Loading
@@ -1203,11 +1185,8 @@ class FunctionDef(node_classes.Statement, Lambda):
>>> node
<FunctionDef.my_func l.2 at 0x7f23b2e71e10>
"""
if six.PY3:
_astroid_fields = ('decorators', 'args', 'returns', 'body')
returns = None
else:
_astroid_fields = ('decorators', 'args', 'body')
_astroid_fields = ('decorators', 'args', 'returns', 'body')
returns = None
decorators = None
"""The decorators that are applied to this method or function.
 
Loading
Loading
@@ -1286,7 +1265,7 @@ class FunctionDef(node_classes.Statement, Lambda):
self.decorators = decorators
self.returns = returns
 
if six.PY3 and isinstance(self.parent.frame(), ClassDef):
if isinstance(self.parent.frame(), ClassDef):
self.set_local('__class__', self.parent.frame())
 
@decorators_mod.cachedproperty
Loading
Loading
@@ -1936,7 +1915,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
def _infer_type_call(self, caller, context):
name_node = next(caller.args[0].infer(context))
if (isinstance(name_node, node_classes.Const) and
isinstance(name_node.value, six.string_types)):
isinstance(name_node.value, str)):
name = name_node.value
else:
return util.Uninferable
Loading
Loading
@@ -1962,7 +1941,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if members and isinstance(members, node_classes.Dict):
for attr, value in members.items:
if (isinstance(attr, node_classes.Const) and
isinstance(attr.value, six.string_types)):
isinstance(attr.value, str)):
result.locals[attr.value] = [value]
 
result.parent = caller.parent
Loading
Loading
@@ -2001,7 +1980,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
# inside this class.
lookup_upper_frame = (
isinstance(node.parent, node_classes.Decorators) and
name in MANAGER.astroid_cache[six.moves.builtins.__name__]
name in MANAGER.astroid_cache[builtins.__name__]
)
if any(node == base or base.parent_of(node)
for base in self.bases) or lookup_upper_frame:
Loading
Loading
@@ -2050,10 +2029,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
yielded = set([self])
if context is None:
context = contextmod.InferenceContext()
if six.PY3:
if not self.bases and self.qname() != 'builtins.object':
yield builtin_lookup("object")[1][0]
return
if not self.bases and self.qname() != 'builtins.object':
yield builtin_lookup("object")[1][0]
return
 
for stmt in self.bases:
with context.restore_path():
Loading
Loading
@@ -2456,29 +2434,8 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if node is not util.Uninferable)
except (exceptions.InferenceError, StopIteration):
return None
if six.PY3:
return None
if '__metaclass__' in self.locals:
assignment = self.locals['__metaclass__'][-1]
elif self.bases:
return None
elif '__metaclass__' in self.root().locals:
assignments = [ass for ass in self.root().locals['__metaclass__']
if ass.lineno < self.lineno]
if not assignments:
return None
assignment = assignments[-1]
else:
return None
 
try:
inferred = next(assignment.infer())
except exceptions.InferenceError:
return None
if inferred is util.Uninferable: # don't expose this
return None
return inferred
return None
 
def _find_metaclass(self, seen=None):
if seen is None:
Loading
Loading
@@ -2551,8 +2508,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
if inferred is util.Uninferable:
continue
if (not isinstance(inferred, node_classes.Const) or
not isinstance(inferred.value,
six.string_types)):
not isinstance(inferred.value, str)):
continue
if not inferred.value:
continue
Loading
Loading
@@ -2626,10 +2582,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
 
if context is None:
context = contextmod.InferenceContext()
if six.PY3:
if not self.bases and self.qname() != 'builtins.object':
yield builtin_lookup("object")[1][0]
return
if not self.bases and self.qname() != 'builtins.object':
yield builtin_lookup("object")[1][0]
return
 
for stmt in self.bases:
try:
Loading
Loading
Loading
Loading
@@ -9,6 +9,8 @@
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
 
"""Tests for basic functionality in astroid.brain."""
import queue
try:
import multiprocessing # pylint: disable=unused-import
HAS_MULTIPROCESSING = True
Loading
Loading
@@ -51,8 +53,6 @@ try:
except ImportError:
HAS_ATTR = False
 
import six
from astroid import MANAGER
from astroid import bases
from astroid import builder
Loading
Loading
@@ -325,65 +325,35 @@ class SixBrainTest(unittest.TestCase):
''')
http_client = next(ast_nodes[0].infer())
self.assertIsInstance(http_client, nodes.Module)
self.assertEqual(http_client.name,
'http.client' if six.PY3 else 'httplib')
self.assertEqual(http_client.name, 'http.client')
 
urllib_parse = next(ast_nodes[1].infer())
if six.PY3:
self.assertIsInstance(urllib_parse, nodes.Module)
self.assertEqual(urllib_parse.name, 'urllib.parse')
else:
# On Python 2, this is a fake module, the same behaviour
# being mimicked in brain's tip for six.moves.
self.assertIsInstance(urllib_parse, astroid.Instance)
self.assertIsInstance(urllib_parse, nodes.Module)
self.assertEqual(urllib_parse.name, 'urllib.parse')
urljoin = next(urllib_parse.igetattr('urljoin'))
urlencode = next(urllib_parse.igetattr('urlencode'))
if six.PY2:
# In reality it's a function, but our implementations
# transforms it into a method.
self.assertIsInstance(urljoin, astroid.BoundMethod)
self.assertEqual(urljoin.qname(), 'urlparse.urljoin')
self.assertIsInstance(urlencode, astroid.BoundMethod)
self.assertEqual(urlencode.qname(), 'urllib.urlencode')
else:
self.assertIsInstance(urljoin, nodes.FunctionDef)
self.assertEqual(urljoin.qname(), 'urllib.parse.urljoin')
self.assertIsInstance(urlencode, nodes.FunctionDef)
self.assertEqual(urlencode.qname(), 'urllib.parse.urlencode')
self.assertIsInstance(urljoin, nodes.FunctionDef)
self.assertEqual(urljoin.qname(), 'urllib.parse.urljoin')
self.assertIsInstance(urlencode, nodes.FunctionDef)
self.assertEqual(urlencode.qname(), 'urllib.parse.urlencode')
 
urllib_error = next(ast_nodes[2].infer())
if six.PY3:
self.assertIsInstance(urllib_error, nodes.Module)
self.assertEqual(urllib_error.name, 'urllib.error')
else:
# On Python 2, this is a fake module, the same behaviour
# being mimicked in brain's tip for six.moves.
self.assertIsInstance(urllib_error, astroid.Instance)
self.assertIsInstance(urllib_error, nodes.Module)
self.assertEqual(urllib_error.name, 'urllib.error')
urlerror = next(urllib_error.igetattr('URLError'))
self.assertIsInstance(urlerror, nodes.ClassDef)
content_too_short = next(urllib_error.igetattr('ContentTooShortError'))
self.assertIsInstance(content_too_short, nodes.ClassDef)
 
urllib_request = next(ast_nodes[3].infer())
if six.PY3:
self.assertIsInstance(urllib_request, nodes.Module)
self.assertEqual(urllib_request.name, 'urllib.request')
else:
self.assertIsInstance(urllib_request, astroid.Instance)
self.assertIsInstance(urllib_request, nodes.Module)
self.assertEqual(urllib_request.name, 'urllib.request')
urlopen = next(urllib_request.igetattr('urlopen'))
urlretrieve = next(urllib_request.igetattr('urlretrieve'))
if six.PY2:
# In reality it's a function, but our implementations
# transforms it into a method.
self.assertIsInstance(urlopen, astroid.BoundMethod)
self.assertEqual(urlopen.qname(), 'urllib2.urlopen')
self.assertIsInstance(urlretrieve, astroid.BoundMethod)
self.assertEqual(urlretrieve.qname(), 'urllib.urlretrieve')
else:
self.assertIsInstance(urlopen, nodes.FunctionDef)
self.assertEqual(urlopen.qname(), 'urllib.request.urlopen')
self.assertIsInstance(urlretrieve, nodes.FunctionDef)
self.assertEqual(urlretrieve.qname(), 'urllib.request.urlretrieve')
self.assertIsInstance(urlopen, nodes.FunctionDef)
self.assertEqual(urlopen.qname(), 'urllib.request.urlopen')
self.assertIsInstance(urlretrieve, nodes.FunctionDef)
self.assertEqual(urlretrieve.qname(), 'urllib.request.urlretrieve')
 
def test_from_imports(self):
ast_node = builder.extract_node('''
Loading
Loading
@@ -392,14 +362,9 @@ class SixBrainTest(unittest.TestCase):
''')
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
if six.PY3:
qname = 'http.client.HTTPSConnection'
else:
qname = 'httplib.HTTPSConnection'
qname = 'http.client.HTTPSConnection'
self.assertEqual(inferred.qname(), qname)
 
@unittest.skipIf(six.PY2,
"The python 2 six brain uses dummy classes")
def test_from_submodule_imports(self):
"""Make sure ulrlib submodules can be imported from
 
Loading
Loading
@@ -462,16 +427,15 @@ class MultiprocessingBrainTest(unittest.TestCase):
array = manager.Array()
namespace = manager.Namespace()
""")
queue = next(module['queue'].infer())
self.assertEqual(queue.qname(),
"{}.Queue".format(six.moves.queue.__name__))
ast_queue = next(module['queue'].infer())
self.assertEqual(ast_queue.qname(), "{}.Queue".format(queue.__name__))
 
joinable_queue = next(module['joinable_queue'].infer())
self.assertEqual(joinable_queue.qname(),
"{}.Queue".format(six.moves.queue.__name__))
"{}.Queue".format(queue.__name__))
 
event = next(module['event'].infer())
event_name = "threading.{}".format("Event" if six.PY3 else "_Event")
event_name = "threading.Event"
self.assertEqual(event.qname(), event_name)
 
rlock = next(module['rlock'].infer())
Loading
Loading
@@ -479,8 +443,7 @@ class MultiprocessingBrainTest(unittest.TestCase):
self.assertEqual(rlock.qname(), rlock_name)
 
bounded_semaphore = next(module['bounded_semaphore'].infer())
semaphore_name = "threading.{}".format(
"BoundedSemaphore" if six.PY3 else "_BoundedSemaphore")
semaphore_name = "threading.BoundedSemaphore"
self.assertEqual(bounded_semaphore.qname(), semaphore_name)
 
pool = next(module['pool'].infer())
Loading
Loading
@@ -701,7 +664,7 @@ def streams_are_fine():
 
class IOBrainTest(unittest.TestCase):
@unittest.skipUnless(
six.PY3 and streams_are_fine(),
streams_are_fine(),
"Needs Python 3 io model / doesn't work with plain pytest."
"use pytest -s for this test to work")
def test_sys_streams(self):
Loading
Loading
Loading
Loading
@@ -8,12 +8,11 @@
 
"""tests for the astroid builder and rebuilder module"""
 
import builtins
import os
import sys
import unittest
 
import six
from astroid import builder
from astroid import exceptions
from astroid import manager
Loading
Loading
@@ -23,7 +22,7 @@ from astroid import util
from astroid.tests import resources
 
MANAGER = manager.AstroidManager()
BUILTINS = six.moves.builtins.__name__
BUILTINS = builtins.__name__
 
 
class FromToLineNoTest(unittest.TestCase):
Loading
Loading
@@ -265,17 +264,6 @@ class BuilderTest(unittest.TestCase):
def test_inspect_build0(self):
"""test astroid tree build from a living object"""
builtin_ast = MANAGER.ast_from_module_name(BUILTINS)
if six.PY2:
fclass = builtin_ast['file']
self.assertIn('name', fclass)
self.assertIn('mode', fclass)
self.assertIn('read', fclass)
self.assertTrue(fclass.newstyle)
self.assertTrue(fclass.pytype(), '%s.type' % BUILTINS)
self.assertIsInstance(fclass['read'], nodes.FunctionDef)
# check builtin function has args.args == None
dclass = builtin_ast['dict']
self.assertIsNone(dclass['has_key'].args.args)
# just check type and object are there
builtin_ast.getattr('type')
objectastroid = builtin_ast.getattr('object')[0]
Loading
Loading
@@ -290,12 +278,8 @@ class BuilderTest(unittest.TestCase):
self.assertIsInstance(builtin_ast['None'], nodes.Const)
self.assertIsInstance(builtin_ast['True'], nodes.Const)
self.assertIsInstance(builtin_ast['False'], nodes.Const)
if six.PY3:
self.assertIsInstance(builtin_ast['Exception'], nodes.ClassDef)
self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.ClassDef)
else:
self.assertIsInstance(builtin_ast['Exception'], nodes.ImportFrom)
self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.ImportFrom)
self.assertIsInstance(builtin_ast['Exception'], nodes.ClassDef)
self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.ClassDef)
 
def test_inspect_build1(self):
time_ast = MANAGER.ast_from_module_name('time')
Loading
Loading
@@ -417,14 +401,9 @@ class BuilderTest(unittest.TestCase):
"new style"
'''
mod_ast = builder.parse(data, __name__)
if six.PY3:
self.assertTrue(mod_ast['A'].newstyle)
self.assertTrue(mod_ast['B'].newstyle)
self.assertTrue(mod_ast['E'].newstyle)
else:
self.assertFalse(mod_ast['A'].newstyle)
self.assertFalse(mod_ast['B'].newstyle)
self.assertFalse(mod_ast['E'].newstyle)
self.assertTrue(mod_ast['A'].newstyle)
self.assertTrue(mod_ast['B'].newstyle)
self.assertTrue(mod_ast['E'].newstyle)
self.assertTrue(mod_ast['C'].newstyle)
self.assertTrue(mod_ast['D'].newstyle)
self.assertTrue(mod_ast['F'].newstyle)
Loading
Loading
@@ -637,10 +616,7 @@ class FileBuildTest(unittest.TestCase):
self.assertEqual(klass.parent.frame(), module)
self.assertEqual(klass.root(), module)
self.assertEqual(klass.basenames, [])
if six.PY3:
self.assertTrue(klass.newstyle)
else:
self.assertFalse(klass.newstyle)
self.assertTrue(klass.newstyle)
 
def test_class_locals(self):
"""test the 'locals' dictionary of a astroid class"""
Loading
Loading
@@ -726,56 +702,6 @@ class ModuleBuildTest(resources.SysPathSetup, FileBuildTest):
else:
self.module = abuilder.module_build(data.module, 'data.module')
 
@unittest.skipIf(six.PY3, "guess_encoding not used on Python 3")
class TestGuessEncoding(unittest.TestCase):
def setUp(self):
self.guess_encoding = builder._guess_encoding
def testEmacs(self):
e = self.guess_encoding('# -*- coding: UTF-8 -*-')
self.assertEqual(e, 'UTF-8')
e = self.guess_encoding('# -*- coding:UTF-8 -*-')
self.assertEqual(e, 'UTF-8')
e = self.guess_encoding('''
### -*- coding: ISO-8859-1 -*-
''')
self.assertEqual(e, 'ISO-8859-1')
e = self.guess_encoding('''
### -*- coding: ISO-8859-1 -*-
''')
self.assertIsNone(e)
def testVim(self):
e = self.guess_encoding('# vim:fileencoding=UTF-8')
self.assertEqual(e, 'UTF-8')
e = self.guess_encoding('''
### vim:fileencoding=ISO-8859-1
''')
self.assertEqual(e, 'ISO-8859-1')
e = self.guess_encoding('''
### vim:fileencoding= ISO-8859-1
''')
self.assertIsNone(e)
def test_wrong_coding(self):
# setting "coding" variable
e = self.guess_encoding("coding = UTF-8")
self.assertIsNone(e)
# setting a dictionary entry
e = self.guess_encoding("coding:UTF-8")
self.assertIsNone(e)
# setting an argument
e = self.guess_encoding("def do_something(a_word_with_coding=None):")
self.assertIsNone(e)
def testUTF8(self):
e = self.guess_encoding('\xef\xbb\xbf any UTF-8 data')
self.assertEqual(e, 'UTF-8')
e = self.guess_encoding(' any UTF-8 data \xef\xbb\xbf')
self.assertIsNone(e)
 
if __name__ == '__main__':
unittest.main()
Loading
Loading
@@ -6,9 +6,7 @@
 
 
import unittest
import six
from six.moves import builtins
import builtins
 
from astroid import builder
from astroid import exceptions
Loading
Loading
@@ -93,10 +91,10 @@ class TestHelpers(unittest.TestCase):
self.assert_classes_equal(instance_type, cls)
 
expected_method_types = [
(ast_nodes[3], 'instancemethod' if six.PY2 else 'function'),
(ast_nodes[4], 'instancemethod' if six.PY2 else 'method'),
(ast_nodes[5], 'instancemethod' if six.PY2 else 'method'),
(ast_nodes[6], 'instancemethod' if six.PY2 else 'method'),
(ast_nodes[3], 'function'),
(ast_nodes[4], 'method'),
(ast_nodes[5], 'method'),
(ast_nodes[6], 'method'),
(ast_nodes[7], 'function'),
(ast_nodes[8], 'function'),
(ast_nodes[9], 'generator'),
Loading
Loading
Loading
Loading
@@ -17,8 +17,6 @@ from functools import partial
import unittest
import warnings
 
import six
from astroid import InferenceError, builder, nodes
from astroid.builder import parse, extract_node
from astroid.inference import infer_end as inference_infer_end
Loading
Loading
@@ -732,10 +730,7 @@ class InferenceTest(resources.SysPathSetup, unittest.TestCase):
node = extract_node('''b'a'[0]''')
inferred = next(node.infer())
self.assertIsInstance(inferred, nodes.Const)
if six.PY2:
self.assertEqual(inferred.value, 'a')
else:
self.assertEqual(inferred.value, 97)
self.assertEqual(inferred.value, 97)
 
def test_simple_tuple(self):
module = parse("""
Loading
Loading
Loading
Loading
@@ -2,11 +2,10 @@
# 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 builtins
import unittest
import xml
 
import six
import astroid
from astroid import builder
from astroid import exceptions
Loading
Loading
@@ -15,7 +14,7 @@ from astroid import test_utils
from astroid import objects
 
 
BUILTINS = MANAGER.astroid_cache[six.moves.builtins.__name__]
BUILTINS = MANAGER.astroid_cache[builtins.__name__]
 
 
class InstanceModelTest(unittest.TestCase):
Loading
Loading
@@ -103,10 +102,7 @@ class UnboundMethodModelTest(unittest.TestCase):
 
cls = next(ast_nodes[0].infer())
self.assertIsInstance(cls, astroid.ClassDef)
if six.PY2:
unbound_name = 'instancemethod'
else:
unbound_name = 'function'
unbound_name = 'function'
 
self.assertEqual(cls.name, unbound_name)
 
Loading
Loading
@@ -169,16 +165,6 @@ class ClassModelTest(unittest.TestCase):
self.assertIsInstance(inferred.bound, astroid.ClassDef)
self.assertEqual(inferred.bound.name, 'type')
 
@unittest.skipUnless(six.PY2, "Needs old style classes")
def test_old_style_classes_no_mro(self):
ast_node = builder.extract_node('''
class A:
pass
A.mro #@
''')
with self.assertRaises(exceptions.InferenceError):
next(ast_node.infer())
def test_class_model(self):
ast_nodes = builder.extract_node('''
class A(object):
Loading
Loading
@@ -499,7 +485,6 @@ class GeneratorModelTest(unittest.TestCase):
 
class ExceptionModelTest(unittest.TestCase):
 
@unittest.skipIf(six.PY2, "needs Python 3")
def test_model_py3(self):
ast_nodes = builder.extract_node('''
try:
Loading
Loading
@@ -519,25 +504,6 @@ class ExceptionModelTest(unittest.TestCase):
with self.assertRaises(exceptions.InferenceError):
next(ast_nodes[2].infer())
 
@unittest.skipUnless(six.PY2, "needs Python 2")
def test_model_py2(self):
ast_nodes = builder.extract_node('''
try:
x[42]
except ValueError as err:
err.args #@
err.message #@
err.__traceback__ #@
''')
args = next(ast_nodes[0].infer())
self.assertIsInstance(args, astroid.Tuple)
message = next(ast_nodes[1].infer())
self.assertIsInstance(message, astroid.Const)
with self.assertRaises(exceptions.InferenceError):
next(ast_nodes[2].infer())
 
class DictObjectModelTest(unittest.TestCase):
 
Loading
Loading
@@ -557,28 +523,6 @@ class DictObjectModelTest(unittest.TestCase):
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.BoundMethod)
 
@unittest.skipUnless(six.PY2, "needs Python 2")
def test_concrete_objects_for_dict_methods(self):
ast_nodes = builder.extract_node('''
{1:1, 2:3}.values() #@
{1:1, 2:3}.keys() #@
{1:1, 2:3}.items() #@
''')
values = next(ast_nodes[0].infer())
self.assertIsInstance(values, astroid.List)
self.assertEqual([value.value for value in values.elts], [1, 3])
keys = next(ast_nodes[1].infer())
self.assertIsInstance(keys, astroid.List)
self.assertEqual([key.value for key in keys.elts], [1, 2])
items = next(ast_nodes[2].infer())
self.assertIsInstance(items, astroid.List)
for expected, elem in zip([(1, 1), (2, 3)], items.elts):
self.assertIsInstance(elem, astroid.Tuple)
self.assertEqual(list(expected), [elt.value for elt in elem.elts])
@unittest.skipIf(six.PY2, "needs Python 3")
def test_wrapper_objects_for_dict_methods_python3(self):
ast_nodes = builder.extract_node('''
{1:1, 2:3}.values() #@
Loading
Loading
@@ -597,7 +541,6 @@ class DictObjectModelTest(unittest.TestCase):
 
class LruCacheModelTest(unittest.TestCase):
 
@unittest.skipIf(six.PY2, "needs Python 3")
def test_lru_cache(self):
ast_nodes = builder.extract_node('''
import functools
Loading
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment