diff options
-rw-r--r-- | MANIFEST.in | 6 | ||||
-rw-r--r-- | astroid/test_utils.py | 12 | ||||
-rw-r--r-- | astroid/tests/resources.py | 48 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/MyPyPa-0.1.0-py2.5.egg (renamed from astroid/tests/data/MyPyPa-0.1.0-py2.5.egg) | bin | 1222 -> 1222 bytes | |||
-rw-r--r-- | astroid/tests/testdata/python2/data/MyPyPa-0.1.0-py2.5.zip (renamed from astroid/tests/data/MyPyPa-0.1.0-py2.5.zip) | bin | 1222 -> 1222 bytes | |||
-rw-r--r-- | astroid/tests/testdata/python2/data/SSL1/Connection1.py (renamed from astroid/tests/data/SSL1/Connection1.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/SSL1/__init__.py (renamed from astroid/tests/data/SSL1/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/__init__.py (renamed from astroid/tests/data/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/absimp/__init__.py (renamed from astroid/tests/regrtest_data/absimp/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/absimp/sidepackage/__init__.py (renamed from astroid/tests/regrtest_data/absimp/sidepackage/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/absimp/string.py (renamed from astroid/tests/regrtest_data/absimp/string.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/absimport.py (renamed from astroid/tests/data/absimport.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/all.py (renamed from astroid/tests/data/all.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/appl/__init__.py (renamed from astroid/tests/data/appl/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/appl/myConnection.py (renamed from astroid/tests/data/appl/myConnection.py) | 2 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/clientmodule_test.py (renamed from astroid/tests/data2/clientmodule_test.py) | 2 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/descriptor_crash.py (renamed from astroid/tests/regrtest_data/descriptor_crash.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/email.py (renamed from astroid/tests/data/email.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/find_test/__init__.py (renamed from astroid/tests/data/find_test/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/find_test/module.py (renamed from astroid/tests/data/find_test/module.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/find_test/module2.py (renamed from astroid/tests/data/find_test/module2.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/find_test/noendingnewline.py (renamed from astroid/tests/data/find_test/noendingnewline.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/find_test/nonregr.py (renamed from astroid/tests/data/find_test/nonregr.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/format.py (renamed from astroid/tests/data/format.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/lmfp/__init__.py (renamed from astroid/tests/data/lmfp/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/lmfp/foo.py (renamed from astroid/tests/data/lmfp/foo.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/module.py (renamed from astroid/tests/data/module.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/module1abs/__init__.py (renamed from astroid/tests/data/module1abs/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/module1abs/core.py (renamed from astroid/tests/data/module1abs/core.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/module2.py (renamed from astroid/tests/data/module2.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/noendingnewline.py (renamed from astroid/tests/data/noendingnewline.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/nonregr.py (renamed from astroid/tests/data/nonregr.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/notall.py (renamed from astroid/tests/data/notall.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/package/__init__.py (renamed from astroid/tests/regrtest_data/package/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/package/absimport.py (renamed from astroid/tests/regrtest_data/package/absimport.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/package/hello.py (renamed from astroid/tests/regrtest_data/package/hello.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/package/import_package_subpackage_module.py (renamed from astroid/tests/regrtest_data/package/import_package_subpackage_module.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/package/subpackage/__init__.py (renamed from astroid/tests/regrtest_data/package/subpackage/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/package/subpackage/module.py (renamed from astroid/tests/regrtest_data/package/subpackage/module.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/recursion.py (renamed from astroid/tests/regrtest_data/recursion.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/suppliermodule_test.py (renamed from astroid/tests/data2/suppliermodule_test.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/unicode_package/__init__.py (renamed from astroid/tests/regrtest_data/unicode_package/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python2/data/unicode_package/core/__init__.py (renamed from astroid/tests/data2/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/MyPyPa-0.1.0-py2.5.egg (renamed from astroid/tests/data_py3/MyPyPa-0.1.0-py2.5.egg) | bin | 1222 -> 1222 bytes | |||
-rw-r--r-- | astroid/tests/testdata/python3/data/MyPyPa-0.1.0-py2.5.zip (renamed from astroid/tests/data_py3/MyPyPa-0.1.0-py2.5.zip) | bin | 1222 -> 1222 bytes | |||
-rw-r--r-- | astroid/tests/testdata/python3/data/SSL1/Connection1.py (renamed from astroid/tests/data_py3/SSL1/Connection1.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/SSL1/__init__.py (renamed from astroid/tests/data_py3/SSL1/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/__init__.py (renamed from astroid/tests/data_py3/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/absimp/__init__.py | 5 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/absimp/sidepackage/__init__.py | 3 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/absimp/string.py | 3 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/absimport.py (renamed from astroid/tests/data_py3/absimport.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/all.py (renamed from astroid/tests/data_py3/all.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/appl/__init__.py (renamed from astroid/tests/data_py3/appl/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/appl/myConnection.py (renamed from astroid/tests/data_py3/appl/myConnection.py) | 2 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/clientmodule_test.py | 32 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/descriptor_crash.py | 11 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/email.py (renamed from astroid/tests/data_py3/email.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/find_test/__init__.py (renamed from astroid/tests/data_py3/find_test/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/find_test/module.py (renamed from astroid/tests/data_py3/find_test/module.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/find_test/module2.py (renamed from astroid/tests/data_py3/find_test/module2.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/find_test/noendingnewline.py (renamed from astroid/tests/data_py3/find_test/noendingnewline.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/find_test/nonregr.py (renamed from astroid/tests/data_py3/find_test/nonregr.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/format.py (renamed from astroid/tests/data_py3/format.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/lmfp/__init__.py (renamed from astroid/tests/data_py3/lmfp/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/lmfp/foo.py (renamed from astroid/tests/data_py3/lmfp/foo.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/module.py (renamed from astroid/tests/data_py3/module.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/module1abs/__init__.py (renamed from astroid/tests/data_py3/module1abs/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/module1abs/core.py (renamed from astroid/tests/data_py3/module1abs/core.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/module2.py (renamed from astroid/tests/data_py3/module2.py) | 6 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/noendingnewline.py (renamed from astroid/tests/data_py3/noendingnewline.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/nonregr.py (renamed from astroid/tests/data_py3/nonregr.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/notall.py (renamed from astroid/tests/data_py3/notall.py) | 0 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/package/__init__.py | 4 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/package/absimport.py | 6 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/package/hello.py | 2 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/package/import_package_subpackage_module.py | 49 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/package/subpackage/__init__.py | 1 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/package/subpackage/module.py | 1 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/recursion.py | 3 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/suppliermodule_test.py | 13 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/unicode_package/__init__.py | 1 | ||||
-rw-r--r-- | astroid/tests/testdata/python3/data/unicode_package/core/__init__.py (renamed from astroid/tests/regrtest_data/unicode_package/core/__init__.py) | 0 | ||||
-rw-r--r-- | astroid/tests/unittest_builder.py | 514 | ||||
-rw-r--r-- | astroid/tests/unittest_inference.py | 930 | ||||
-rw-r--r-- | astroid/tests/unittest_inspector.py | 26 | ||||
-rw-r--r-- | astroid/tests/unittest_lookup.py | 249 | ||||
-rw-r--r-- | astroid/tests/unittest_manager.py | 57 | ||||
-rw-r--r-- | astroid/tests/unittest_modutils.py | 100 | ||||
-rw-r--r-- | astroid/tests/unittest_nodes.py | 289 | ||||
-rw-r--r-- | astroid/tests/unittest_regrtest.py | 7 | ||||
-rw-r--r-- | astroid/tests/unittest_scoped_nodes.py | 804 | ||||
-rw-r--r-- | tox.ini | 3 |
93 files changed, 1642 insertions, 1549 deletions
diff --git a/MANIFEST.in b/MANIFEST.in index 6b779861..4837adf1 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,8 +2,6 @@ include ChangeLog include README include COPYING include COPYING.LESSER -recursive-include astroid/tests/data *.py *.zip *.egg -recursive-include astroid/tests/data_py3 *.py *.zip *.egg -recursive-include astroid/tests/data2 *.py -recursive-include astroid/tests/regrtest_data *.py +include tox.ini +recursive-include astroid/tests/testdata *.py *.zip *.egg recursive-include astroid/brain *.py diff --git a/astroid/test_utils.py b/astroid/test_utils.py index 5fc31d63..19bd7b96 100644 --- a/astroid/test_utils.py +++ b/astroid/test_utils.py @@ -157,9 +157,9 @@ def extract_node(code, module_name=''): if requested_lines: for line in requested_lines: extracted.append(_find_statement_by_line(tree, line)) - else: - # Modifies the tree. - extracted = list(_extract_expressions(tree)) + + # Modifies the tree. + extracted.extend(_extract_expressions(tree)) if not extracted: extracted.append(tree.body[-1]) @@ -171,17 +171,19 @@ def extract_node(code, module_name=''): return extracted -def build_module(code, module_name=''): +def build_module(code, module_name='', path=None): """Parses a string module with a builder. :param code: The code for the module. :type code: str :param module_name: The name for the module :type module_name: str + :param path: The path for the module + :type module_name: str :returns: The module AST. :rtype: astroid.bases.NodeNG """ code = textwrap.dedent(code) - return builder.AstroidBuilder(None).string_build(code, modname=module_name) + return builder.AstroidBuilder(None).string_build(code, modname=module_name, path=path) def require_version(minver=None, maxver=None): diff --git a/astroid/tests/resources.py b/astroid/tests/resources.py new file mode 100644 index 00000000..755b3e99 --- /dev/null +++ b/astroid/tests/resources.py @@ -0,0 +1,48 @@ +# Copyright 2014 Google, Inc. All rights reserved. +# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr +# +# This file is part of astroid. +# +# astroid is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by the +# Free Software Foundation, either version 2.1 of the License, or (at your +# option) any later version. +# +# astroid 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 Lesser General Public License +# for more details. +# +# You should have received a copy of the GNU Lesser General Public License along +# with astroid. If not, see <http://www.gnu.org/licenses/>. +import os +import sys + +import pkg_resources + +from astroid import builder + + +DATA_DIR = 'testdata/python{}/'.format(sys.version_info[0]) + +def find(name): + return pkg_resources.resource_filename( + 'astroid.tests', os.path.normpath(os.path.join(DATA_DIR, name))) + + +def build_file(path, modname=None): + return builder.AstroidBuilder().file_build(find(path), modname) + + +class SysPathSetup(object): + def setUp(self): + sys.path.insert(0, find('')) + + def tearDown(self): + del sys.path[0] + datadir = find('') + for key in list(sys.path_importer_cache): + if key.startswith(key): + del sys.path_importer_cache[key] + + diff --git a/astroid/tests/data/MyPyPa-0.1.0-py2.5.egg b/astroid/tests/testdata/python2/data/MyPyPa-0.1.0-py2.5.egg Binary files differindex f62599c7..f62599c7 100644 --- a/astroid/tests/data/MyPyPa-0.1.0-py2.5.egg +++ b/astroid/tests/testdata/python2/data/MyPyPa-0.1.0-py2.5.egg diff --git a/astroid/tests/data/MyPyPa-0.1.0-py2.5.zip b/astroid/tests/testdata/python2/data/MyPyPa-0.1.0-py2.5.zip Binary files differindex f62599c7..f62599c7 100644 --- a/astroid/tests/data/MyPyPa-0.1.0-py2.5.zip +++ b/astroid/tests/testdata/python2/data/MyPyPa-0.1.0-py2.5.zip diff --git a/astroid/tests/data/SSL1/Connection1.py b/astroid/tests/testdata/python2/data/SSL1/Connection1.py index c0f01522..c0f01522 100644 --- a/astroid/tests/data/SSL1/Connection1.py +++ b/astroid/tests/testdata/python2/data/SSL1/Connection1.py diff --git a/astroid/tests/data/SSL1/__init__.py b/astroid/tests/testdata/python2/data/SSL1/__init__.py index a007b049..a007b049 100644 --- a/astroid/tests/data/SSL1/__init__.py +++ b/astroid/tests/testdata/python2/data/SSL1/__init__.py diff --git a/astroid/tests/data/__init__.py b/astroid/tests/testdata/python2/data/__init__.py index 332e2e72..332e2e72 100644 --- a/astroid/tests/data/__init__.py +++ b/astroid/tests/testdata/python2/data/__init__.py diff --git a/astroid/tests/regrtest_data/absimp/__init__.py b/astroid/tests/testdata/python2/data/absimp/__init__.py index b98444df..b98444df 100644 --- a/astroid/tests/regrtest_data/absimp/__init__.py +++ b/astroid/tests/testdata/python2/data/absimp/__init__.py diff --git a/astroid/tests/regrtest_data/absimp/sidepackage/__init__.py b/astroid/tests/testdata/python2/data/absimp/sidepackage/__init__.py index 239499a6..239499a6 100644 --- a/astroid/tests/regrtest_data/absimp/sidepackage/__init__.py +++ b/astroid/tests/testdata/python2/data/absimp/sidepackage/__init__.py diff --git a/astroid/tests/regrtest_data/absimp/string.py b/astroid/tests/testdata/python2/data/absimp/string.py index e68e7496..e68e7496 100644 --- a/astroid/tests/regrtest_data/absimp/string.py +++ b/astroid/tests/testdata/python2/data/absimp/string.py diff --git a/astroid/tests/data/absimport.py b/astroid/tests/testdata/python2/data/absimport.py index f98effa6..f98effa6 100644 --- a/astroid/tests/data/absimport.py +++ b/astroid/tests/testdata/python2/data/absimport.py diff --git a/astroid/tests/data/all.py b/astroid/tests/testdata/python2/data/all.py index 23f7d2b6..23f7d2b6 100644 --- a/astroid/tests/data/all.py +++ b/astroid/tests/testdata/python2/data/all.py diff --git a/astroid/tests/data/appl/__init__.py b/astroid/tests/testdata/python2/data/appl/__init__.py index d652ffd9..d652ffd9 100644 --- a/astroid/tests/data/appl/__init__.py +++ b/astroid/tests/testdata/python2/data/appl/__init__.py diff --git a/astroid/tests/data/appl/myConnection.py b/astroid/tests/testdata/python2/data/appl/myConnection.py index 93026a60..4afc9e48 100644 --- a/astroid/tests/data/appl/myConnection.py +++ b/astroid/tests/testdata/python2/data/appl/myConnection.py @@ -1,4 +1,4 @@ -import SSL1 +from data import SSL1 class MyConnection(SSL1.Connection): """An SSL connection.""" diff --git a/astroid/tests/data2/clientmodule_test.py b/astroid/tests/testdata/python2/data/clientmodule_test.py index 196fff83..a178ca6d 100644 --- a/astroid/tests/data2/clientmodule_test.py +++ b/astroid/tests/testdata/python2/data/clientmodule_test.py @@ -1,5 +1,5 @@ """ docstring for file clientmodule.py """ -from data2.suppliermodule_test import Interface as IFace, DoNothing +from data.suppliermodule_test import Interface as IFace, DoNothing class Toto: pass diff --git a/astroid/tests/regrtest_data/descriptor_crash.py b/astroid/tests/testdata/python2/data/descriptor_crash.py index 11fbb4a2..11fbb4a2 100644 --- a/astroid/tests/regrtest_data/descriptor_crash.py +++ b/astroid/tests/testdata/python2/data/descriptor_crash.py diff --git a/astroid/tests/data/email.py b/astroid/tests/testdata/python2/data/email.py index dc593564..dc593564 100644 --- a/astroid/tests/data/email.py +++ b/astroid/tests/testdata/python2/data/email.py diff --git a/astroid/tests/data/find_test/__init__.py b/astroid/tests/testdata/python2/data/find_test/__init__.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data/find_test/__init__.py +++ b/astroid/tests/testdata/python2/data/find_test/__init__.py diff --git a/astroid/tests/data/find_test/module.py b/astroid/tests/testdata/python2/data/find_test/module.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data/find_test/module.py +++ b/astroid/tests/testdata/python2/data/find_test/module.py diff --git a/astroid/tests/data/find_test/module2.py b/astroid/tests/testdata/python2/data/find_test/module2.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data/find_test/module2.py +++ b/astroid/tests/testdata/python2/data/find_test/module2.py diff --git a/astroid/tests/data/find_test/noendingnewline.py b/astroid/tests/testdata/python2/data/find_test/noendingnewline.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data/find_test/noendingnewline.py +++ b/astroid/tests/testdata/python2/data/find_test/noendingnewline.py diff --git a/astroid/tests/data/find_test/nonregr.py b/astroid/tests/testdata/python2/data/find_test/nonregr.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data/find_test/nonregr.py +++ b/astroid/tests/testdata/python2/data/find_test/nonregr.py diff --git a/astroid/tests/data/format.py b/astroid/tests/testdata/python2/data/format.py index 73797061..73797061 100644 --- a/astroid/tests/data/format.py +++ b/astroid/tests/testdata/python2/data/format.py diff --git a/astroid/tests/data/lmfp/__init__.py b/astroid/tests/testdata/python2/data/lmfp/__init__.py index 74b26b82..74b26b82 100644 --- a/astroid/tests/data/lmfp/__init__.py +++ b/astroid/tests/testdata/python2/data/lmfp/__init__.py diff --git a/astroid/tests/data/lmfp/foo.py b/astroid/tests/testdata/python2/data/lmfp/foo.py index 8f7de1e8..8f7de1e8 100644 --- a/astroid/tests/data/lmfp/foo.py +++ b/astroid/tests/testdata/python2/data/lmfp/foo.py diff --git a/astroid/tests/data/module.py b/astroid/tests/testdata/python2/data/module.py index fb48dc1d..fb48dc1d 100644 --- a/astroid/tests/data/module.py +++ b/astroid/tests/testdata/python2/data/module.py diff --git a/astroid/tests/data/module1abs/__init__.py b/astroid/tests/testdata/python2/data/module1abs/__init__.py index 9eb5902a..9eb5902a 100644 --- a/astroid/tests/data/module1abs/__init__.py +++ b/astroid/tests/testdata/python2/data/module1abs/__init__.py diff --git a/astroid/tests/data/module1abs/core.py b/astroid/tests/testdata/python2/data/module1abs/core.py index de101117..de101117 100644 --- a/astroid/tests/data/module1abs/core.py +++ b/astroid/tests/testdata/python2/data/module1abs/core.py diff --git a/astroid/tests/data/module2.py b/astroid/tests/testdata/python2/data/module2.py index d6bf49eb..d6bf49eb 100644 --- a/astroid/tests/data/module2.py +++ b/astroid/tests/testdata/python2/data/module2.py diff --git a/astroid/tests/data/noendingnewline.py b/astroid/tests/testdata/python2/data/noendingnewline.py index e1d6e4a1..e1d6e4a1 100644 --- a/astroid/tests/data/noendingnewline.py +++ b/astroid/tests/testdata/python2/data/noendingnewline.py diff --git a/astroid/tests/data/nonregr.py b/astroid/tests/testdata/python2/data/nonregr.py index a670e39f..a670e39f 100644 --- a/astroid/tests/data/nonregr.py +++ b/astroid/tests/testdata/python2/data/nonregr.py diff --git a/astroid/tests/data/notall.py b/astroid/tests/testdata/python2/data/notall.py index b998d882..b998d882 100644 --- a/astroid/tests/data/notall.py +++ b/astroid/tests/testdata/python2/data/notall.py diff --git a/astroid/tests/regrtest_data/package/__init__.py b/astroid/tests/testdata/python2/data/package/__init__.py index 575d18b1..575d18b1 100644 --- a/astroid/tests/regrtest_data/package/__init__.py +++ b/astroid/tests/testdata/python2/data/package/__init__.py diff --git a/astroid/tests/regrtest_data/package/absimport.py b/astroid/tests/testdata/python2/data/package/absimport.py index 33ed117c..33ed117c 100644 --- a/astroid/tests/regrtest_data/package/absimport.py +++ b/astroid/tests/testdata/python2/data/package/absimport.py diff --git a/astroid/tests/regrtest_data/package/hello.py b/astroid/tests/testdata/python2/data/package/hello.py index b154c844..b154c844 100644 --- a/astroid/tests/regrtest_data/package/hello.py +++ b/astroid/tests/testdata/python2/data/package/hello.py diff --git a/astroid/tests/regrtest_data/package/import_package_subpackage_module.py b/astroid/tests/testdata/python2/data/package/import_package_subpackage_module.py index ad442c16..ad442c16 100644 --- a/astroid/tests/regrtest_data/package/import_package_subpackage_module.py +++ b/astroid/tests/testdata/python2/data/package/import_package_subpackage_module.py diff --git a/astroid/tests/regrtest_data/package/subpackage/__init__.py b/astroid/tests/testdata/python2/data/package/subpackage/__init__.py index dc4782e6..dc4782e6 100644 --- a/astroid/tests/regrtest_data/package/subpackage/__init__.py +++ b/astroid/tests/testdata/python2/data/package/subpackage/__init__.py diff --git a/astroid/tests/regrtest_data/package/subpackage/module.py b/astroid/tests/testdata/python2/data/package/subpackage/module.py index 4b7244ba..4b7244ba 100644 --- a/astroid/tests/regrtest_data/package/subpackage/module.py +++ b/astroid/tests/testdata/python2/data/package/subpackage/module.py diff --git a/astroid/tests/regrtest_data/recursion.py b/astroid/tests/testdata/python2/data/recursion.py index a34dad32..a34dad32 100644 --- a/astroid/tests/regrtest_data/recursion.py +++ b/astroid/tests/testdata/python2/data/recursion.py diff --git a/astroid/tests/data2/suppliermodule_test.py b/astroid/tests/testdata/python2/data/suppliermodule_test.py index ddacb477..ddacb477 100644 --- a/astroid/tests/data2/suppliermodule_test.py +++ b/astroid/tests/testdata/python2/data/suppliermodule_test.py diff --git a/astroid/tests/regrtest_data/unicode_package/__init__.py b/astroid/tests/testdata/python2/data/unicode_package/__init__.py index 713e5591..713e5591 100644 --- a/astroid/tests/regrtest_data/unicode_package/__init__.py +++ b/astroid/tests/testdata/python2/data/unicode_package/__init__.py diff --git a/astroid/tests/data2/__init__.py b/astroid/tests/testdata/python2/data/unicode_package/core/__init__.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data2/__init__.py +++ b/astroid/tests/testdata/python2/data/unicode_package/core/__init__.py diff --git a/astroid/tests/data_py3/MyPyPa-0.1.0-py2.5.egg b/astroid/tests/testdata/python3/data/MyPyPa-0.1.0-py2.5.egg Binary files differindex f62599c7..f62599c7 100644 --- a/astroid/tests/data_py3/MyPyPa-0.1.0-py2.5.egg +++ b/astroid/tests/testdata/python3/data/MyPyPa-0.1.0-py2.5.egg diff --git a/astroid/tests/data_py3/MyPyPa-0.1.0-py2.5.zip b/astroid/tests/testdata/python3/data/MyPyPa-0.1.0-py2.5.zip Binary files differindex f62599c7..f62599c7 100644 --- a/astroid/tests/data_py3/MyPyPa-0.1.0-py2.5.zip +++ b/astroid/tests/testdata/python3/data/MyPyPa-0.1.0-py2.5.zip diff --git a/astroid/tests/data_py3/SSL1/Connection1.py b/astroid/tests/testdata/python3/data/SSL1/Connection1.py index 7373271d..7373271d 100644 --- a/astroid/tests/data_py3/SSL1/Connection1.py +++ b/astroid/tests/testdata/python3/data/SSL1/Connection1.py diff --git a/astroid/tests/data_py3/SSL1/__init__.py b/astroid/tests/testdata/python3/data/SSL1/__init__.py index c83ededc..c83ededc 100644 --- a/astroid/tests/data_py3/SSL1/__init__.py +++ b/astroid/tests/testdata/python3/data/SSL1/__init__.py diff --git a/astroid/tests/data_py3/__init__.py b/astroid/tests/testdata/python3/data/__init__.py index 332e2e72..332e2e72 100644 --- a/astroid/tests/data_py3/__init__.py +++ b/astroid/tests/testdata/python3/data/__init__.py diff --git a/astroid/tests/testdata/python3/data/absimp/__init__.py b/astroid/tests/testdata/python3/data/absimp/__init__.py new file mode 100644 index 00000000..b98444df --- /dev/null +++ b/astroid/tests/testdata/python3/data/absimp/__init__.py @@ -0,0 +1,5 @@ +"""a package with absolute import activated +""" + +from __future__ import absolute_import + diff --git a/astroid/tests/testdata/python3/data/absimp/sidepackage/__init__.py b/astroid/tests/testdata/python3/data/absimp/sidepackage/__init__.py new file mode 100644 index 00000000..239499a6 --- /dev/null +++ b/astroid/tests/testdata/python3/data/absimp/sidepackage/__init__.py @@ -0,0 +1,3 @@ +"""a side package with nothing in it +""" + diff --git a/astroid/tests/testdata/python3/data/absimp/string.py b/astroid/tests/testdata/python3/data/absimp/string.py new file mode 100644 index 00000000..e68e7496 --- /dev/null +++ b/astroid/tests/testdata/python3/data/absimp/string.py @@ -0,0 +1,3 @@ +from __future__ import absolute_import, print_function +import string +print(string) diff --git a/astroid/tests/data_py3/absimport.py b/astroid/tests/testdata/python3/data/absimport.py index 88f9d955..88f9d955 100644 --- a/astroid/tests/data_py3/absimport.py +++ b/astroid/tests/testdata/python3/data/absimport.py diff --git a/astroid/tests/data_py3/all.py b/astroid/tests/testdata/python3/data/all.py index 587765b5..587765b5 100644 --- a/astroid/tests/data_py3/all.py +++ b/astroid/tests/testdata/python3/data/all.py diff --git a/astroid/tests/data_py3/appl/__init__.py b/astroid/tests/testdata/python3/data/appl/__init__.py index d652ffd9..d652ffd9 100644 --- a/astroid/tests/data_py3/appl/__init__.py +++ b/astroid/tests/testdata/python3/data/appl/__init__.py diff --git a/astroid/tests/data_py3/appl/myConnection.py b/astroid/tests/testdata/python3/data/appl/myConnection.py index b5b206a0..49269534 100644 --- a/astroid/tests/data_py3/appl/myConnection.py +++ b/astroid/tests/testdata/python3/data/appl/myConnection.py @@ -1,4 +1,4 @@ -import SSL1 +from data import SSL1 class MyConnection(SSL1.Connection): """An SSL connection.""" diff --git a/astroid/tests/testdata/python3/data/clientmodule_test.py b/astroid/tests/testdata/python3/data/clientmodule_test.py new file mode 100644 index 00000000..a178ca6d --- /dev/null +++ b/astroid/tests/testdata/python3/data/clientmodule_test.py @@ -0,0 +1,32 @@ +""" docstring for file clientmodule.py """ +from data.suppliermodule_test import Interface as IFace, DoNothing + +class Toto: pass + +class Ancestor: + """ Ancestor method """ + __implements__ = (IFace,) + + def __init__(self, value): + local_variable = 0 + self.attr = 'this method shouldn\'t have a docstring' + self.__value = value + + def get_value(self): + """ nice docstring ;-) """ + return self.__value + + def set_value(self, value): + self.__value = value + return 'this method shouldn\'t have a docstring' + +class Specialization(Ancestor): + TYPE = 'final class' + top = 'class' + + def __init__(self, value, _id): + Ancestor.__init__(self, value) + self._id = _id + self.relation = DoNothing() + self.toto = Toto() + diff --git a/astroid/tests/testdata/python3/data/descriptor_crash.py b/astroid/tests/testdata/python3/data/descriptor_crash.py new file mode 100644 index 00000000..11fbb4a2 --- /dev/null +++ b/astroid/tests/testdata/python3/data/descriptor_crash.py @@ -0,0 +1,11 @@ + +import urllib + +class Page(object): + _urlOpen = staticmethod(urllib.urlopen) + + def getPage(self, url): + handle = self._urlOpen(url) + data = handle.read() + handle.close() + return data diff --git a/astroid/tests/data_py3/email.py b/astroid/tests/testdata/python3/data/email.py index dc593564..dc593564 100644 --- a/astroid/tests/data_py3/email.py +++ b/astroid/tests/testdata/python3/data/email.py diff --git a/astroid/tests/data_py3/find_test/__init__.py b/astroid/tests/testdata/python3/data/find_test/__init__.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data_py3/find_test/__init__.py +++ b/astroid/tests/testdata/python3/data/find_test/__init__.py diff --git a/astroid/tests/data_py3/find_test/module.py b/astroid/tests/testdata/python3/data/find_test/module.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data_py3/find_test/module.py +++ b/astroid/tests/testdata/python3/data/find_test/module.py diff --git a/astroid/tests/data_py3/find_test/module2.py b/astroid/tests/testdata/python3/data/find_test/module2.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data_py3/find_test/module2.py +++ b/astroid/tests/testdata/python3/data/find_test/module2.py diff --git a/astroid/tests/data_py3/find_test/noendingnewline.py b/astroid/tests/testdata/python3/data/find_test/noendingnewline.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data_py3/find_test/noendingnewline.py +++ b/astroid/tests/testdata/python3/data/find_test/noendingnewline.py diff --git a/astroid/tests/data_py3/find_test/nonregr.py b/astroid/tests/testdata/python3/data/find_test/nonregr.py index e69de29b..e69de29b 100644 --- a/astroid/tests/data_py3/find_test/nonregr.py +++ b/astroid/tests/testdata/python3/data/find_test/nonregr.py diff --git a/astroid/tests/data_py3/format.py b/astroid/tests/testdata/python3/data/format.py index 73797061..73797061 100644 --- a/astroid/tests/data_py3/format.py +++ b/astroid/tests/testdata/python3/data/format.py diff --git a/astroid/tests/data_py3/lmfp/__init__.py b/astroid/tests/testdata/python3/data/lmfp/__init__.py index 74b26b82..74b26b82 100644 --- a/astroid/tests/data_py3/lmfp/__init__.py +++ b/astroid/tests/testdata/python3/data/lmfp/__init__.py diff --git a/astroid/tests/data_py3/lmfp/foo.py b/astroid/tests/testdata/python3/data/lmfp/foo.py index 8f7de1e8..8f7de1e8 100644 --- a/astroid/tests/data_py3/lmfp/foo.py +++ b/astroid/tests/testdata/python3/data/lmfp/foo.py diff --git a/astroid/tests/data_py3/module.py b/astroid/tests/testdata/python3/data/module.py index ec5b64aa..ec5b64aa 100644 --- a/astroid/tests/data_py3/module.py +++ b/astroid/tests/testdata/python3/data/module.py diff --git a/astroid/tests/data_py3/module1abs/__init__.py b/astroid/tests/testdata/python3/data/module1abs/__init__.py index f9d5b686..f9d5b686 100644 --- a/astroid/tests/data_py3/module1abs/__init__.py +++ b/astroid/tests/testdata/python3/data/module1abs/__init__.py diff --git a/astroid/tests/data_py3/module1abs/core.py b/astroid/tests/testdata/python3/data/module1abs/core.py index de101117..de101117 100644 --- a/astroid/tests/data_py3/module1abs/core.py +++ b/astroid/tests/testdata/python3/data/module1abs/core.py diff --git a/astroid/tests/data_py3/module2.py b/astroid/tests/testdata/python3/data/module2.py index 94a8bc79..1171bdfe 100644 --- a/astroid/tests/data_py3/module2.py +++ b/astroid/tests/testdata/python3/data/module2.py @@ -1,5 +1,5 @@ -from data_py3.module import YO, YOUPI -import data_py3 +from data.module import YO, YOUPI +import data class Specialization(YOUPI, YO): @@ -100,7 +100,7 @@ raise_string(*args, **kwargs) print('bonjour', file=stream) print('salut', end=' ', file=stream) -def make_class(any, base=data_py3.module.YO, *args, **kwargs): +def make_class(any, base=data.module.YO, *args, **kwargs): """check base is correctly resolved to Concrete0""" diff --git a/astroid/tests/data_py3/noendingnewline.py b/astroid/tests/testdata/python3/data/noendingnewline.py index e17b92cc..e17b92cc 100644 --- a/astroid/tests/data_py3/noendingnewline.py +++ b/astroid/tests/testdata/python3/data/noendingnewline.py diff --git a/astroid/tests/data_py3/nonregr.py b/astroid/tests/testdata/python3/data/nonregr.py index 78765c85..78765c85 100644 --- a/astroid/tests/data_py3/nonregr.py +++ b/astroid/tests/testdata/python3/data/nonregr.py diff --git a/astroid/tests/data_py3/notall.py b/astroid/tests/testdata/python3/data/notall.py index 9d35aa3a..9d35aa3a 100644 --- a/astroid/tests/data_py3/notall.py +++ b/astroid/tests/testdata/python3/data/notall.py diff --git a/astroid/tests/testdata/python3/data/package/__init__.py b/astroid/tests/testdata/python3/data/package/__init__.py new file mode 100644 index 00000000..575d18b1 --- /dev/null +++ b/astroid/tests/testdata/python3/data/package/__init__.py @@ -0,0 +1,4 @@ +"""package's __init__ file""" + + +from . import subpackage diff --git a/astroid/tests/testdata/python3/data/package/absimport.py b/astroid/tests/testdata/python3/data/package/absimport.py new file mode 100644 index 00000000..33ed117c --- /dev/null +++ b/astroid/tests/testdata/python3/data/package/absimport.py @@ -0,0 +1,6 @@ +from __future__ import absolute_import, print_function +import import_package_subpackage_module # fail +print(import_package_subpackage_module) + +from . import hello as hola + diff --git a/astroid/tests/testdata/python3/data/package/hello.py b/astroid/tests/testdata/python3/data/package/hello.py new file mode 100644 index 00000000..b154c844 --- /dev/null +++ b/astroid/tests/testdata/python3/data/package/hello.py @@ -0,0 +1,2 @@ +"""hello module""" + diff --git a/astroid/tests/testdata/python3/data/package/import_package_subpackage_module.py b/astroid/tests/testdata/python3/data/package/import_package_subpackage_module.py new file mode 100644 index 00000000..ad442c16 --- /dev/null +++ b/astroid/tests/testdata/python3/data/package/import_package_subpackage_module.py @@ -0,0 +1,49 @@ +# pylint: disable-msg=I0011,C0301,W0611 +"""I found some of my scripts trigger off an AttributeError in pylint +0.8.1 (with common 0.12.0 and astroid 0.13.1). + +Traceback (most recent call last): + File "/usr/bin/pylint", line 4, in ? + lint.Run(sys.argv[1:]) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 729, in __init__ + linter.check(args) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 412, in check + self.check_file(filepath, modname, checkers) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 426, in check_file + astroid = self._check_file(filepath, modname, checkers) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 450, in _check_file + self.check_astroid_module(astroid, checkers) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 494, in check_astroid_module + self.astroid_events(astroid, [checker for checker in checkers + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 511, in astroid_events + self.astroid_events(child, checkers, _reversed_checkers) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 511, in astroid_events + self.astroid_events(child, checkers, _reversed_checkers) + File "/usr/lib/python2.4/site-packages/pylint/lint.py", line 508, in astroid_events + checker.visit(astroid) + File "/usr/lib/python2.4/site-packages/logilab/astroid/utils.py", line 84, in visit + method(node) + File "/usr/lib/python2.4/site-packages/pylint/checkers/variables.py", line 295, in visit_import + self._check_module_attrs(node, module, name_parts[1:]) + File "/usr/lib/python2.4/site-packages/pylint/checkers/variables.py", line 357, in _check_module_attrs + self.add_message('E0611', args=(name, module.name), +AttributeError: Import instance has no attribute 'name' + + +You can reproduce it by: +(1) create package structure like the following: + +package/ + __init__.py + subpackage/ + __init__.py + module.py + +(2) in package/__init__.py write: + +import subpackage + +(3) run pylint with a script importing package.subpackage.module. +""" +__revision__ = '$Id: import_package_subpackage_module.py,v 1.1 2005-11-10 15:59:32 syt Exp $' +import package.subpackage.module diff --git a/astroid/tests/testdata/python3/data/package/subpackage/__init__.py b/astroid/tests/testdata/python3/data/package/subpackage/__init__.py new file mode 100644 index 00000000..dc4782e6 --- /dev/null +++ b/astroid/tests/testdata/python3/data/package/subpackage/__init__.py @@ -0,0 +1 @@ +"""package.subpackage""" diff --git a/astroid/tests/testdata/python3/data/package/subpackage/module.py b/astroid/tests/testdata/python3/data/package/subpackage/module.py new file mode 100644 index 00000000..4b7244ba --- /dev/null +++ b/astroid/tests/testdata/python3/data/package/subpackage/module.py @@ -0,0 +1 @@ +"""package.subpackage.module""" diff --git a/astroid/tests/testdata/python3/data/recursion.py b/astroid/tests/testdata/python3/data/recursion.py new file mode 100644 index 00000000..a34dad32 --- /dev/null +++ b/astroid/tests/testdata/python3/data/recursion.py @@ -0,0 +1,3 @@ +""" For issue #25 """
+class Base(object):
+ pass
\ No newline at end of file diff --git a/astroid/tests/testdata/python3/data/suppliermodule_test.py b/astroid/tests/testdata/python3/data/suppliermodule_test.py new file mode 100644 index 00000000..ddacb477 --- /dev/null +++ b/astroid/tests/testdata/python3/data/suppliermodule_test.py @@ -0,0 +1,13 @@ +""" file suppliermodule.py """ + +class NotImplemented(Exception): + pass + +class Interface: + def get_value(self): + raise NotImplemented() + + def set_value(self, value): + raise NotImplemented() + +class DoNothing : pass diff --git a/astroid/tests/testdata/python3/data/unicode_package/__init__.py b/astroid/tests/testdata/python3/data/unicode_package/__init__.py new file mode 100644 index 00000000..713e5591 --- /dev/null +++ b/astroid/tests/testdata/python3/data/unicode_package/__init__.py @@ -0,0 +1 @@ +x = "șțîâ"
\ No newline at end of file diff --git a/astroid/tests/regrtest_data/unicode_package/core/__init__.py b/astroid/tests/testdata/python3/data/unicode_package/core/__init__.py index e69de29b..e69de29b 100644 --- a/astroid/tests/regrtest_data/unicode_package/core/__init__.py +++ b/astroid/tests/testdata/python3/data/unicode_package/core/__init__.py diff --git a/astroid/tests/unittest_builder.py b/astroid/tests/unittest_builder.py index 4baa271c..82f29f03 100644 --- a/astroid/tests/unittest_builder.py +++ b/astroid/tests/unittest_builder.py @@ -17,39 +17,25 @@ # with astroid. If not, see <http://www.gnu.org/licenses/>. """tests for the astroid builder and rebuilder module""" -import unittest +import os import sys -from os.path import join, abspath, dirname -from functools import partial - -from pprint import pprint +import unittest from astroid import builder, nodes, InferenceError, NotFoundError from astroid.nodes import Module from astroid.bases import YES, BUILTINS from astroid.manager import AstroidManager from astroid import test_utils +from astroid.tests import resources MANAGER = AstroidManager() +IS_PY3 = sys.version_info[0] == 3 -PY3K = sys.version_info >= (3, 0) - -if PY3K: - DATA = join(dirname(abspath(__file__)), 'data_py3') -else: - DATA = join(dirname(abspath(__file__)), 'data') -if PY3K: - import data_py3 as data - from data_py3 import module as test_module -else: - import data - from data import module as test_module +class FromToLineNoTest(unittest.TestCase): - -class FromToLineNoTC(unittest.TestCase): - - astroid = builder.AstroidBuilder().file_build(join(DATA, 'format.py')) + def setUp(self): + self.astroid = resources.build_file('data/format.py') def test_callfunc_lineno(self): stmts = self.astroid.body @@ -124,12 +110,12 @@ class FromToLineNoTC(unittest.TestCase): '(no line number on function args)') def test_decorated_function_lineno(self): - astroid = builder.AstroidBuilder().string_build(''' -@decorator -def function( - arg): - print (arg) -''', __name__, __file__) + astroid = test_utils.build_module(''' + @decorator + def function( + arg): + print (arg) + ''', __name__) function = astroid['function'] self.assertEqual(function.fromlineno, 3) # XXX discussable, but that's what is expected by pylint right now self.assertEqual(function.tolineno, 5) @@ -175,20 +161,19 @@ def function( def test_for_while_lineno(self): for code in (''' -for a in range(4): - print (a) - break -else: - print ("bouh") -''', ''' -while a: - print (a) - break -else: - print ("bouh") -''', - ): - astroid = builder.AstroidBuilder().string_build(code, __name__, __file__) + for a in range(4): + print (a) + break + else: + print ("bouh") + ''', ''' + while a: + print (a) + break + else: + print ("bouh") + '''): + astroid = test_utils.build_module(code, __name__) stmt = astroid.body[0] self.assertEqual(stmt.fromlineno, 2) self.assertEqual(stmt.tolineno, 6) @@ -196,16 +181,15 @@ else: self.assertEqual(stmt.orelse[0].fromlineno, 6) # XXX self.assertEqual(stmt.orelse[0].tolineno, 6) - def test_try_except_lineno(self): - astroid = builder.AstroidBuilder().string_build(''' -try: - print (a) -except: - pass -else: - print ("bouh") -''', __name__, __file__) + astroid = test_utils.build_module(''' + try: + print (a) + except: + pass + else: + print ("bouh") + ''', __name__) try_ = astroid.body[0] self.assertEqual(try_.fromlineno, 2) self.assertEqual(try_.tolineno, 7) @@ -219,12 +203,12 @@ else: def test_try_finally_lineno(self): - astroid = builder.AstroidBuilder().string_build(''' -try: - print (a) -finally: - print ("bouh") -''', __name__, __file__) + astroid = test_utils.build_module(''' + try: + print (a) + finally: + print ("bouh") + ''', __name__) try_ = astroid.body[0] self.assertEqual(try_.fromlineno, 2) self.assertEqual(try_.tolineno, 5) @@ -234,14 +218,14 @@ finally: def test_try_finally_25_lineno(self): - astroid = builder.AstroidBuilder().string_build(''' -try: - print (a) -except: - pass -finally: - print ("bouh") -''', __name__, __file__) + astroid = test_utils.build_module(''' + try: + print (a) + except: + pass + finally: + print ("bouh") + ''', __name__) try_ = astroid.body[0] self.assertEqual(try_.fromlineno, 2) self.assertEqual(try_.tolineno, 7) @@ -251,33 +235,34 @@ finally: def test_with_lineno(self): - astroid = builder.AstroidBuilder().string_build(''' -from __future__ import with_statement -with file("/tmp/pouet") as f: - print (f) -''', __name__, __file__) + astroid = test_utils.build_module(''' + from __future__ import with_statement + with file("/tmp/pouet") as f: + print (f) + ''', __name__) with_ = astroid.body[1] self.assertEqual(with_.fromlineno, 3) self.assertEqual(with_.tolineno, 4) self.assertEqual(with_.blockstart_tolineno, 3) - -class BuilderTC(unittest.TestCase): +class BuilderTest(unittest.TestCase): def setUp(self): self.builder = builder.AstroidBuilder() - def test_border_cases(self): + def test_missing_newline(self): """check that a file with no trailing new line is parseable""" - self.builder.file_build(join(DATA, 'noendingnewline.py'), 'data.noendingnewline') - self.assertRaises(builder.AstroidBuildingException, - self.builder.file_build, join(DATA, 'inexistant.py'), 'whatever') + resources.build_file('data/noendingnewline.py') + + def test_missing_file(self): + with self.assertRaises(builder.AstroidBuildingException): + resources.build_file('data/inexistant.py') def test_inspect_build0(self): """test astroid tree build from a living object""" builtin_ast = MANAGER.ast_from_module_name(BUILTINS) - if sys.version_info < (3, 0): + if not IS_PY3: fclass = builtin_ast['file'] self.assertIn('name', fclass) self.assertIn('mode', fclass) @@ -302,12 +287,12 @@ class BuilderTC(unittest.TestCase): self.assertIsInstance(builtin_ast['None'], nodes.Const) self.assertIsInstance(builtin_ast['True'], nodes.Const) self.assertIsInstance(builtin_ast['False'], nodes.Const) - if sys.version_info < (3, 0): - self.assertIsInstance(builtin_ast['Exception'], nodes.From) - self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.From) - else: + if IS_PY3: self.assertIsInstance(builtin_ast['Exception'], nodes.Class) self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.Class) + else: + self.assertIsInstance(builtin_ast['Exception'], nodes.From) + self.assertIsInstance(builtin_ast['NotImplementedError'], nodes.From) def test_inspect_build1(self): time_ast = MANAGER.ast_from_module_name('time') @@ -329,10 +314,9 @@ class BuilderTC(unittest.TestCase): def test_inspect_build3(self): self.builder.inspect_build(unittest) + @test_utils.require_version(maxver='3.0') def test_inspect_build_instance(self): """test astroid tree build from a living object""" - if sys.version_info >= (3, 0): - self.skipTest('The module "exceptions" is gone in py3.x') import exceptions builtin_ast = self.builder.inspect_build(exceptions) fclass = builtin_ast['OSError'] @@ -374,22 +358,22 @@ class BuilderTC(unittest.TestCase): def test_package_name(self): """test base properties and method of a astroid module""" - datap = self.builder.file_build(join(DATA, '__init__.py'), 'data') + datap = resources.build_file('data/__init__.py', 'data') self.assertEqual(datap.name, 'data') self.assertEqual(datap.package, 1) - datap = self.builder.file_build(join(DATA, '__init__.py'), 'data.__init__') + datap = resources.build_file('data/__init__.py', 'data.__init__') self.assertEqual(datap.name, 'data') self.assertEqual(datap.package, 1) def test_yield_parent(self): """check if we added discard nodes as yield parent (w/ compiler)""" - data = """ -def yiell(): - yield 0 - if noe: - yield more -""" - func = self.builder.string_build(data).body[0] + code = """ + def yiell(): #@ + yield 0 + if noe: + yield more + """ + func = test_utils.extract_node(code) self.assertIsInstance(func, nodes.Function) stmt = func.body[0] self.assertIsInstance(stmt, nodes.Discard) @@ -403,28 +387,28 @@ def yiell(): def test_newstyle_detection(self): data = ''' -class A: - "old style" + class A: + "old style" -class B(A): - "old style" + class B(A): + "old style" -class C(object): - "new style" + class C(object): + "new style" -class D(C): - "new style" + class D(C): + "new style" -__metaclass__ = type + __metaclass__ = type -class E(A): - "old style" + class E(A): + "old style" -class F: - "new style" -''' - mod_ast = self.builder.string_build(data, __name__, __file__) - if PY3K: + class F: + "new style" + ''' + mod_ast = test_utils.build_module(data, __name__) + if IS_PY3: self.assertTrue(mod_ast['A'].newstyle) self.assertTrue(mod_ast['B'].newstyle) self.assertTrue(mod_ast['E'].newstyle) @@ -438,25 +422,25 @@ class F: def test_globals(self): data = ''' -CSTE = 1 + CSTE = 1 -def update_global(): - global CSTE - CSTE += 1 + def update_global(): + global CSTE + CSTE += 1 -def global_no_effect(): - global CSTE2 - print (CSTE) -''' - astroid = self.builder.string_build(data, __name__, __file__) + def global_no_effect(): + global CSTE2 + print (CSTE) + ''' + astroid = test_utils.build_module(data, __name__) self.assertEqual(len(astroid.getattr('CSTE')), 2) self.assertIsInstance(astroid.getattr('CSTE')[0], nodes.AssName) self.assertEqual(astroid.getattr('CSTE')[0].fromlineno, 2) self.assertEqual(astroid.getattr('CSTE')[1].fromlineno, 6) - self.assertRaises(NotFoundError, - astroid.getattr, 'CSTE2') - self.assertRaises(InferenceError, - partial(next, astroid['global_no_effect'].ilookup('CSTE2'))) + with self.assertRaises(NotFoundError): + astroid.getattr('CSTE2') + with self.assertRaises(InferenceError): + next(astroid['global_no_effect'].ilookup('CSTE2')) def test_socket_build(self): import socket @@ -473,7 +457,7 @@ def global_no_effect(): def test_gen_expr_var_scope(self): data = 'l = list(n for n in range(10))\n' - astroid = self.builder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data, __name__) # n unavailable outside gen expr scope self.assertNotIn('n', astroid) # test n is inferable anyway @@ -497,21 +481,101 @@ def global_no_effect(): """) self.assertEqual(set(['print_function', 'absolute_import']), mod.future_imports) -class FileBuildTC(unittest.TestCase): - module = builder.AstroidBuilder().file_build( - join(DATA, 'module.py'), - '%s.module' % (data.__name__,)) - + def test_infered_build(self): + code = ''' + class A: pass + A.type = "class" + + def A_ass_type(self): + print (self) + A.ass_type = A_ass_type + ''' + astroid = test_utils.build_module(code) + lclass = list(astroid.igetattr('A')) + self.assertEqual(len(lclass), 1) + lclass = lclass[0] + self.assertIn('ass_type', lclass.locals) + self.assertIn('type', lclass.locals) + + def test_augassign_attr(self): + astroid = test_utils.build_module(""" + class Counter: + v = 0 + def inc(self): + self.v += 1 + """, __name__) + # Check self.v += 1 generate AugAssign(AssAttr(...)), not AugAssign(GetAttr(AssName...)) + + def test_infered_dont_pollute(self): + code = ''' + def func(a=None): + a.custom_attr = 0 + def func2(a={}): + a.custom_attr = 0 + ''' + astroid = test_utils.build_module(code) + nonetype = nodes.const_factory(None) + self.assertNotIn('custom_attr', nonetype.locals) + self.assertNotIn('custom_attr', nonetype.instance_attrs) + nonetype = nodes.const_factory({}) + self.assertNotIn('custom_attr', nonetype.locals) + self.assertNotIn('custom_attr', nonetype.instance_attrs) + + def test_asstuple(self): + code = 'a, b = range(2)' + astroid = test_utils.build_module(code) + self.assertIn('b', astroid.locals) + code = ''' + def visit_if(self, node): + node.test, body = node.tests[0] + ''' + astroid = test_utils.build_module(code) + self.assertIn('body', astroid['visit_if'].locals) + + def test_build_constants(self): + '''test expected values of constants after rebuilding''' + code = ''' + def func(): + return None + return + return 'None' + ''' + astroid = test_utils.build_module(code) + none, nothing, chain = [ret.value for ret in astroid.body[0].body] + self.assertIsInstance(none, nodes.Const) + self.assertIsNone(none.value) + self.assertIsNone(nothing) + self.assertIsInstance(chain, nodes.Const) + self.assertEqual(chain.value, 'None') + + def test_lgc_classproperty(self): + '''test expected values of constants after rebuilding''' + code = ''' + from logilab.common.decorators import classproperty + + class A(object): + @classproperty + def hop(cls): #@ + return None + ''' + method = test_utils.extract_node(code) + self.assertEqual('classmethod', method.type) + + +class FileBuildTest(unittest.TestCase): + def setUp(self): + self.module = resources.build_file('data/module.py', 'data.module') + def test_module_base_props(self): """test base properties and method of a astroid module""" module = self.module - self.assertEqual(module.name, '%s.module' % (data.__name__)) + self.assertEqual(module.name, 'data.module') self.assertEqual(module.doc, "test module for astroid\n") self.assertEqual(module.fromlineno, 0) self.assertIsNone(module.parent) self.assertEqual(module.frame(), module) self.assertEqual(module.root(), module) - self.assertEqual(module.file, join(abspath(data.__path__[0]), 'module.py')) + self.assertEqual(module.file, os.path.abspath(resources.find('data/module.py'))) self.assertEqual(module.pure_python, 1) self.assertEqual(module.package, 0) self.assertFalse(module.is_statement) @@ -563,7 +627,7 @@ class FileBuildTC(unittest.TestCase): self.assertEqual(klass.parent.frame(), module) self.assertEqual(klass.root(), module) self.assertEqual(klass.basenames, []) - if PY3K: + if IS_PY3: self.assertTrue(klass.newstyle) else: self.assertFalse(klass.newstyle) @@ -628,152 +692,64 @@ class FileBuildTC(unittest.TestCase): self.assertEqual(keys, ['autre', 'local', 'self']) -class ModuleBuildTC(FileBuildTC): +class ModuleBuildTest(resources.SysPathSetup, FileBuildTest): def setUp(self): + super(ModuleBuildTest, self).setUp() abuilder = builder.AstroidBuilder() - self.module = abuilder.module_build(test_module, test_module.__name__) - - -class MoreTC(unittest.TestCase): + import data.module + self.module = abuilder.module_build(data.module, 'data.module') +@unittest.skipIf(IS_PY3, "guess_encoding not used on Python 3") +class TestGuessEncoding(unittest.TestCase): def setUp(self): - self.builder = builder.AstroidBuilder() + 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" varaible + e = self.guess_encoding("coding = UTF-8") + self.assertIsNone(e) + # setting a dictionnary entry + e = self.guess_encoding("coding:UTF-8") + self.assertIsNone(e) + # setting an arguement + 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) - def test_infered_build(self): - code = '''class A: pass -A.type = "class" - -def A_ass_type(self): - print (self) -A.ass_type = A_ass_type - ''' - astroid = self.builder.string_build(code) - lclass = list(astroid.igetattr('A')) - self.assertEqual(len(lclass), 1) - lclass = lclass[0] - self.assertIn('ass_type', lclass.locals) - self.assertIn('type', lclass.locals) - - def test_augassign_attr(self): - astroid = self.builder.string_build("""class Counter: - v = 0 - def inc(self): - self.v += 1 - """, __name__, __file__) - # Check self.v += 1 generate AugAssign(AssAttr(...)), not AugAssign(GetAttr(AssName...)) - - def test_dumb_module(self): - astroid = self.builder.string_build("pouet") - - def test_infered_dont_pollute(self): - code = ''' -def func(a=None): - a.custom_attr = 0 -def func2(a={}): - a.custom_attr = 0 - ''' - astroid = self.builder.string_build(code) - nonetype = nodes.const_factory(None) - self.assertNotIn('custom_attr', nonetype.locals) - self.assertNotIn('custom_attr', nonetype.instance_attrs) - nonetype = nodes.const_factory({}) - self.assertNotIn('custom_attr', nonetype.locals) - self.assertNotIn('custom_attr', nonetype.instance_attrs) - - - def test_asstuple(self): - code = 'a, b = range(2)' - astroid = self.builder.string_build(code) - self.assertIn('b', astroid.locals) - code = ''' -def visit_if(self, node): - node.test, body = node.tests[0] -''' - astroid = self.builder.string_build(code) - self.assertIn('body', astroid['visit_if'].locals) - - def test_build_constants(self): - '''test expected values of constants after rebuilding''' - code = ''' -def func(): - return None - return - return 'None' -''' - astroid = self.builder.string_build(code) - none, nothing, chain = [ret.value for ret in astroid.body[0].body] - self.assertIsInstance(none, nodes.Const) - self.assertIsNone(none.value) - self.assertIsNone(nothing) - self.assertIsInstance(chain, nodes.Const) - self.assertEqual(chain.value, 'None') - - - def test_lgc_classproperty(self): - '''test expected values of constants after rebuilding''' - code = ''' -from logilab.common.decorators import classproperty - -class A(object): - @classproperty - def hop(cls): - return None -''' - astroid = self.builder.string_build(code) - self.assertEqual(astroid['A']['hop'].type, 'classmethod') - - -if sys.version_info < (3, 0): - guess_encoding = builder._guess_encoding - - class TestGuessEncoding(unittest.TestCase): - - def testEmacs(self): - e = guess_encoding('# -*- coding: UTF-8 -*-') - self.assertEqual(e, 'UTF-8') - e = guess_encoding('# -*- coding:UTF-8 -*-') - self.assertEqual(e, 'UTF-8') - e = guess_encoding(''' - ### -*- coding: ISO-8859-1 -*- - ''') - self.assertEqual(e, 'ISO-8859-1') - e = guess_encoding(''' - - ### -*- coding: ISO-8859-1 -*- - ''') - self.assertIsNone(e) - - def testVim(self): - e = guess_encoding('# vim:fileencoding=UTF-8') - self.assertEqual(e, 'UTF-8') - e = guess_encoding(''' - ### vim:fileencoding=ISO-8859-1 - ''') - self.assertEqual(e, 'ISO-8859-1') - e = guess_encoding(''' - - ### vim:fileencoding= ISO-8859-1 - ''') - self.assertIsNone(e) - - def test_wrong_coding(self): - # setting "coding" varaible - e = guess_encoding("coding = UTF-8") - self.assertIsNone(e) - # setting a dictionnary entry - e = guess_encoding("coding:UTF-8") - self.assertIsNone(e) - # setting an arguement - e = guess_encoding("def do_something(a_word_with_coding=None):") - self.assertIsNone(e) - - - def testUTF8(self): - e = guess_encoding('\xef\xbb\xbf any UTF-8 data') - self.assertEqual(e, 'UTF-8') - e = guess_encoding(' any UTF-8 data \xef\xbb\xbf') - self.assertIsNone(e) if __name__ == '__main__': unittest.main() diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py index f34279a5..2fdb6899 100644 --- a/astroid/tests/unittest_inference.py +++ b/astroid/tests/unittest_inference.py @@ -17,10 +17,8 @@ # with astroid. If not, see <http://www.gnu.org/licenses/>. """tests for the astroid inference capabilities """ -from os.path import join, dirname, abspath import sys from functools import partial -from textwrap import dedent import unittest import six @@ -29,7 +27,8 @@ from astroid import InferenceError, builder, nodes from astroid.inference import infer_end as inference_infer_end from astroid.bases import YES, Instance, BoundMethod, UnboundMethod,\ path_wrapper, BUILTINS -from astroid.test_utils import require_version, get_name_node +from astroid import test_utils +from astroid.tests import resources def get_node_of_class(start_from, klass): @@ -37,58 +36,57 @@ def get_node_of_class(start_from, klass): builder = builder.AstroidBuilder() -class InferenceUtilsTC(unittest.TestCase): +if sys.version_info < (3, 0): + EXC_MODULE = 'exceptions' +else: + EXC_MODULE = BUILTINS + + +class InferenceUtilsTest(unittest.TestCase): def test_path_wrapper(self): def infer_default(self, *args): raise InferenceError infer_default = path_wrapper(infer_default) infer_end = path_wrapper(inference_infer_end) - self.assertRaises(InferenceError, - partial(next, infer_default(1))) + with self.assertRaises(InferenceError): + next(infer_default(1)) self.assertEqual(next(infer_end(1)), 1) -if sys.version_info < (3, 0): - EXC_MODULE = 'exceptions' -else: - EXC_MODULE = BUILTINS - - -class InferenceTC(unittest.TestCase): +class InferenceTest(resources.SysPathSetup, unittest.TestCase): CODE = ''' + class C(object): + "new style" + attr = 4 + + def meth1(self, arg1, optarg=0): + var = object() + print ("yo", arg1, optarg) + self.iattr = "hop" + return var + + def meth2(self): + self.meth1(*self.meth3) + + def meth3(self, d=attr): + b = self.attr + c = self.iattr + return b, c + + ex = Exception("msg") + v = C().meth1(1) + m_unbound = C.meth1 + m_bound = C().meth1 + a, b, c = ex, 1, "bonjour" + [d, e, f] = [ex, 1.0, ("bonjour", v)] + g, h = f + i, (j, k) = "glup", f + + a, b= b, a # Gasp ! + ''' -class C(object): - "new style" - attr = 4 - - def meth1(self, arg1, optarg=0): - var = object() - print ("yo", arg1, optarg) - self.iattr = "hop" - return var - - def meth2(self): - self.meth1(*self.meth3) - - def meth3(self, d=attr): - b = self.attr - c = self.iattr - return b, c - -ex = Exception("msg") -v = C().meth1(1) -m_unbound = C.meth1 -m_bound = C().meth1 -a, b, c = ex, 1, "bonjour" -[d, e, f] = [ex, 1.0, ("bonjour", v)] -g, h = f -i, (j, k) = "glup", f - -a, b= b, a # Gasp ! -''' - - astroid = builder.string_build(CODE, __name__, __file__) + astroid = test_utils.build_module(CODE, __name__) def test_module_inference(self): infered = self.astroid.infer() @@ -249,7 +247,7 @@ a, b= b, a # Gasp ! self.assertRaises(StopIteration, partial(next, infered)) def test_args_default_inference1(self): - optarg = get_name_node(self.astroid['C']['meth1'], 'optarg') + optarg = test_utils.get_name_node(self.astroid['C']['meth1'], 'optarg') infered = optarg.infer() obj1 = next(infered) self.assertIsInstance(obj1, nodes.Const) @@ -268,53 +266,50 @@ a, b= b, a # Gasp ! self.assertRaises(StopIteration, partial(next, infered)) def test_inference_restrictions(self): - infered = get_name_node(self.astroid['C']['meth1'], 'arg1').infer() + infered = test_utils.get_name_node(self.astroid['C']['meth1'], 'arg1').infer() obj1 = next(infered) self.assertIs(obj1, YES, obj1) self.assertRaises(StopIteration, partial(next, infered)) def test_ancestors_inference(self): code = ''' -class A: - pass + class A: #@ + pass -class A(A): - pass + class A(A): #@ + pass ''' - astroid = builder.string_build(code, __name__, __file__) - a1 = astroid.locals['A'][0] - a2 = astroid.locals['A'][1] + a1, a2 = test_utils.extract_node(code, __name__) a2_ancestors = list(a2.ancestors()) self.assertEqual(len(a2_ancestors), 1) self.assertIs(a2_ancestors[0], a1) def test_ancestors_inference2(self): code = ''' -class A: - pass + class A: #@ + pass -class B(A): pass + class B(A): #@ + pass -class A(B): - pass + class A(B): #@ + pass ''' - astroid = builder.string_build(code, __name__, __file__) - a1 = astroid.locals['A'][0] - a2 = astroid.locals['A'][1] + a1, b, a2 = test_utils.extract_node(code, __name__) a2_ancestors = list(a2.ancestors()) self.assertEqual(len(a2_ancestors), 2) - self.assertIs(a2_ancestors[0], astroid.locals['B'][0]) + self.assertIs(a2_ancestors[0], b) self.assertIs(a2_ancestors[1], a1) def test_f_arg_f(self): code = ''' -def f(f=1): - return f + def f(f=1): + return f -a = f() + a = f() ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) a = astroid['a'] a_infered = a.infered() self.assertEqual(a_infered[0].value, 1) @@ -322,11 +317,10 @@ a = f() def test_exc_ancestors(self): code = ''' -def f(): - raise NotImplementedError + def f(): + raise __(NotImplementedError) ''' - astroid = builder.string_build(code, __name__, __file__) - error = next(astroid.nodes_of_class(nodes.Name)) + error = test_utils.extract_node(code, __name__) nie = error.infered()[0] self.assertIsInstance(nie, nodes.Class) nie_ancestors = [c.name for c in nie.ancestors()] @@ -337,17 +331,15 @@ def f(): def test_except_inference(self): code = ''' -try: - print (hop) -except NameError, ex: - ex1 = ex -except Exception, ex: - ex2 = ex - raise + try: + print (hop) + except NameError as ex: + ex1 = ex + except Exception as ex: + ex2 = ex + raise ''' - if sys.version_info >= (3, 0): - code = code.replace(', ex:', ' as ex:') - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) ex1 = astroid['ex1'] ex1_infer = ex1.infer() ex1 = next(ex1_infer) @@ -363,21 +355,21 @@ except Exception, ex: def test_del1(self): code = ''' -del undefined_attr + del undefined_attr ''' - delete = builder.string_build(code, __name__, __file__).body[0] + delete = test_utils.extract_node(code, __name__) self.assertRaises(InferenceError, delete.infer) def test_del2(self): code = ''' -a = 1 -b = a -del a -c = a -a = 2 -d = a + a = 1 + b = a + del a + c = a + a = 2 + d = a ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) n = astroid['b'] n_infer = n.infer() infered = next(n_infer) @@ -396,13 +388,13 @@ d = a def test_builtin_types(self): code = ''' -l = [1] -t = (2,) -d = {} -s = '' -s2 = '_' + l = [1] + t = (2,) + d = {} + s = '' + s2 = '_' ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) n = astroid['l'] infered = next(n.infer()) self.assertIsInstance(infered, nodes.List) @@ -435,10 +427,9 @@ s2 = '_' infered = next(n.infer()) self.assertEqual(infered.getitem(0).value, '_') - @require_version('2.7') - def test_builtin_types_py27(self): + def test_builtin_types(self): code = 's = {1}' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) n = astroid['s'] infered = next(n.infer()) self.assertIsInstance(infered, nodes.Set) @@ -446,11 +437,10 @@ s2 = '_' self.assertEqual(infered.name, 'set') self.assertIn('remove', infered._proxied.locals) + @test_utils.require_version(maxver='3.0') def test_unicode_type(self): - if sys.version_info >= (3, 0): - self.skipTest('unicode removed on py >= 3.0') code = '''u = u""''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) n = astroid['u'] infered = next(n.infer()) self.assertIsInstance(infered, nodes.Const) @@ -460,11 +450,11 @@ s2 = '_' def test_descriptor_are_callable(self): code = ''' -class A: - statm = staticmethod(open) - clsm = classmethod('whatever') + class A: + statm = staticmethod(open) + clsm = classmethod('whatever') ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) statm = next(astroid['A'].igetattr('statm')) self.assertTrue(statm.callable()) clsm = next(astroid['A'].igetattr('clsm')) @@ -472,10 +462,10 @@ class A: def test_bt_ancestor_crash(self): code = ''' -class Warning(Warning): - pass + class Warning(Warning): + pass ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) w = astroid['Warning'] ancestors = w.ancestors() ancestor = next(ancestors) @@ -494,95 +484,91 @@ class Warning(Warning): def test_qqch(self): code = ''' -from astroid.modutils import load_module_from_name -xxx = load_module_from_name('__pkginfo__') + from astroid.modutils import load_module_from_name + xxx = load_module_from_name('__pkginfo__') ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) xxx = astroid['xxx'] - self.assertSetEqual(set(n.__class__ for n in xxx.infered()), - set([nodes.Const, YES.__class__])) + self.assertSetEqual({n.__class__ for n in xxx.infered()}, + {nodes.Const, YES.__class__}) def test_method_argument(self): code = ''' -class ErudiEntitySchema: - """a entity has a type, a set of subject and or object relations""" - def __init__(self, e_type, **kwargs): - kwargs['e_type'] = e_type.capitalize().encode() - - def meth(self, e_type, *args, **kwargs): - kwargs['e_type'] = e_type.capitalize().encode() - print(args) - ''' - astroid = builder.string_build(code, __name__, __file__) - arg = get_name_node(astroid['ErudiEntitySchema']['__init__'], 'e_type') + class ErudiEntitySchema: + """a entity has a type, a set of subject and or object relations""" + def __init__(self, e_type, **kwargs): + kwargs['e_type'] = e_type.capitalize().encode() + + def meth(self, e_type, *args, **kwargs): + kwargs['e_type'] = e_type.capitalize().encode() + print(args) + ''' + astroid = test_utils.build_module(code, __name__) + arg = test_utils.get_name_node(astroid['ErudiEntitySchema']['__init__'], 'e_type') self.assertEqual([n.__class__ for n in arg.infer()], [YES.__class__]) - arg = get_name_node(astroid['ErudiEntitySchema']['__init__'], 'kwargs') + arg = test_utils.get_name_node(astroid['ErudiEntitySchema']['__init__'], 'kwargs') self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict]) - arg = get_name_node(astroid['ErudiEntitySchema']['meth'], 'e_type') + arg = test_utils.get_name_node(astroid['ErudiEntitySchema']['meth'], 'e_type') self.assertEqual([n.__class__ for n in arg.infer()], [YES.__class__]) - arg = get_name_node(astroid['ErudiEntitySchema']['meth'], 'args') + arg = test_utils.get_name_node(astroid['ErudiEntitySchema']['meth'], 'args') self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Tuple]) - arg = get_name_node(astroid['ErudiEntitySchema']['meth'], 'kwargs') + arg = test_utils.get_name_node(astroid['ErudiEntitySchema']['meth'], 'kwargs') self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict]) - def test_tuple_then_list(self): code = ''' -def test_view(rql, vid, tags=()): - tags = list(tags) - tags.append(vid) + def test_view(rql, vid, tags=()): + tags = list(tags) + __(tags).append(vid) ''' - astroid = builder.string_build(code, __name__, __file__) - name = get_name_node(astroid['test_view'], 'tags', -1) + name = test_utils.extract_node(code, __name__) it = name.infer() tags = next(it) self.assertEqual(tags.__class__, Instance) self.assertEqual(tags._proxied.name, 'list') - self.assertRaises(StopIteration, partial(next, it)) - - + with self.assertRaises(StopIteration): + next(it) def test_mulassign_inference(self): code = ''' + def first_word(line): + """Return the first word of a line""" -def first_word(line): - """Return the first word of a line""" - - return line.split()[0] + return line.split()[0] -def last_word(line): - """Return last word of a line""" + def last_word(line): + """Return last word of a line""" - return line.split()[-1] + return line.split()[-1] -def process_line(word_pos): - """Silly function: returns (ok, callable) based on argument. + def process_line(word_pos): + """Silly function: returns (ok, callable) based on argument. - For test purpose only. - """ + For test purpose only. + """ - if word_pos > 0: - return (True, first_word) - elif word_pos < 0: - return (True, last_word) - else: - return (False, None) + if word_pos > 0: + return (True, first_word) + elif word_pos < 0: + return (True, last_word) + else: + return (False, None) -if __name__ == '__main__': + if __name__ == '__main__': - line_number = 0 - for a_line in file('test_callable.py'): - tupletest = process_line(line_number) - (ok, fct) = process_line(line_number) - if ok: - fct(a_line) -''' - astroid = builder.string_build(code, __name__, __file__) + line_number = 0 + for a_line in file('test_callable.py'): + tupletest = process_line(line_number) + (ok, fct) = process_line(line_number) + if ok: + fct(a_line) + ''' + astroid = test_utils.build_module(code, __name__) self.assertEqual(len(list(astroid['process_line'].infer_call_result( None))), 3) self.assertEqual(len(list(astroid['tupletest'].infer())), 3) @@ -592,58 +578,60 @@ if __name__ == '__main__': def test_float_complex_ambiguity(self): code = ''' -def no_conjugate_member(magic_flag): - """should not raise E1101 on something.conjugate""" - if magic_flag: - something = 1.0 - else: - something = 1.0j - if isinstance(something, float): - return something - return something.conjugate() + def no_conjugate_member(magic_flag): #@ + """should not raise E1101 on something.conjugate""" + if magic_flag: + something = 1.0 + else: + something = 1.0j + if isinstance(something, float): + return something + return __(something).conjugate() ''' - astroid = builder.string_build(code, __name__, __file__) - self.assertEqual([i.value for i in - astroid['no_conjugate_member'].ilookup('something')], [1.0, 1.0j]) - self.assertEqual([i.value for i in - get_name_node(astroid, 'something', -1).infer()], [1.0, 1.0j]) + func, retval = test_utils.extract_node(code, __name__) + self.assertEqual( + [i.value for i in func.ilookup('something')], + [1.0, 1.0j]) + self.assertEqual( + [i.value for i in retval.infer()], + [1.0, 1.0j]) def test_lookup_cond_branches(self): code = ''' -def no_conjugate_member(magic_flag): - """should not raise E1101 on something.conjugate""" - something = 1.0 - if magic_flag: - something = 1.0j - return something.conjugate() + def no_conjugate_member(magic_flag): + """should not raise E1101 on something.conjugate""" + something = 1.0 + if magic_flag: + something = 1.0j + return something.conjugate() ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertEqual([i.value for i in - get_name_node(astroid, 'something', -1).infer()], [1.0, 1.0j]) + test_utils.get_name_node(astroid, 'something', -1).infer()], [1.0, 1.0j]) def test_simple_subscript(self): code = ''' -a = [1, 2, 3][0] -b = (1, 2, 3)[1] -c = (1, 2, 3)[-1] -d = a + b + c -print (d) -e = {'key': 'value'} -f = e['key'] -print (f) + a = [1, 2, 3][0] + b = (1, 2, 3)[1] + c = (1, 2, 3)[-1] + d = a + b + c + print (d) + e = {'key': 'value'} + f = e['key'] + print (f) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertEqual([i.value for i in - get_name_node(astroid, 'a', -1).infer()], [1]) + test_utils.get_name_node(astroid, 'a', -1).infer()], [1]) self.assertEqual([i.value for i in - get_name_node(astroid, 'b', -1).infer()], [2]) + test_utils.get_name_node(astroid, 'b', -1).infer()], [2]) self.assertEqual([i.value for i in - get_name_node(astroid, 'c', -1).infer()], [3]) + test_utils.get_name_node(astroid, 'c', -1).infer()], [3]) self.assertEqual([i.value for i in - get_name_node(astroid, 'd', -1).infer()], [6]) + test_utils.get_name_node(astroid, 'd', -1).infer()], [6]) self.assertEqual([i.value for i in - get_name_node(astroid, 'f', -1).infer()], ['value']) + test_utils.get_name_node(astroid, 'f', -1).infer()], ['value']) #def test_simple_tuple(self): #"""test case for a simple tuple value""" @@ -658,57 +646,55 @@ print (f) def test_simple_for(self): code = ''' -for a in [1, 2, 3]: - print (a) -for b,c in [(1,2), (3,4)]: - print (b) - print (c) + for a in [1, 2, 3]: + print (a) + for b,c in [(1,2), (3,4)]: + print (b) + print (c) -print ([(d,e) for e,d in ([1,2], [3,4])]) + print ([(d,e) for e,d in ([1,2], [3,4])]) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertEqual([i.value for i in - get_name_node(astroid, 'a', -1).infer()], [1, 2, 3]) + test_utils.get_name_node(astroid, 'a', -1).infer()], [1, 2, 3]) self.assertEqual([i.value for i in - get_name_node(astroid, 'b', -1).infer()], [1, 3]) + test_utils.get_name_node(astroid, 'b', -1).infer()], [1, 3]) self.assertEqual([i.value for i in - get_name_node(astroid, 'c', -1).infer()], [2, 4]) + test_utils.get_name_node(astroid, 'c', -1).infer()], [2, 4]) self.assertEqual([i.value for i in - get_name_node(astroid, 'd', -1).infer()], [2, 4]) + test_utils.get_name_node(astroid, 'd', -1).infer()], [2, 4]) self.assertEqual([i.value for i in - get_name_node(astroid, 'e', -1).infer()], [1, 3]) + test_utils.get_name_node(astroid, 'e', -1).infer()], [1, 3]) def test_simple_for_genexpr(self): code = ''' -print ((d,e) for e,d in ([1,2], [3,4])) + print ((d,e) for e,d in ([1,2], [3,4])) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertEqual([i.value for i in - get_name_node(astroid, 'd', -1).infer()], [2, 4]) + test_utils.get_name_node(astroid, 'd', -1).infer()], [2, 4]) self.assertEqual([i.value for i in - get_name_node(astroid, 'e', -1).infer()], [1, 3]) + test_utils.get_name_node(astroid, 'e', -1).infer()], [1, 3]) def test_builtin_help(self): code = ''' -help() + help() ''' # XXX failing since __builtin__.help assignment has # been moved into a function... - astroid = builder.string_build(code, __name__, __file__) - node = get_name_node(astroid, 'help', -1) - infered = list(node.infer()) + node = test_utils.extract_node(code, __name__) + infered = list(node.func.infer()) self.assertEqual(len(infered), 1, infered) self.assertIsInstance(infered[0], Instance) self.assertEqual(infered[0].name, "_Helper") def test_builtin_open(self): code = ''' -open("toto.txt") + open("toto.txt") ''' - astroid = builder.string_build(code, __name__, __file__) - node = get_name_node(astroid, 'open', -1) + node = test_utils.extract_node(code, __name__).func infered = list(node.infer()) self.assertEqual(len(infered), 1) if hasattr(sys, 'pypy_version_info'): @@ -720,12 +706,12 @@ open("toto.txt") def test_callfunc_context_func(self): code = ''' -def mirror(arg=None): - return arg + def mirror(arg=None): + return arg -un = mirror(1) + un = mirror(1) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid.igetattr('un')) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], nodes.Const) @@ -733,11 +719,11 @@ un = mirror(1) def test_callfunc_context_lambda(self): code = ''' -mirror = lambda x=None: x + mirror = lambda x=None: x -un = mirror(1) + un = mirror(1) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid.igetattr('mirror')) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], nodes.Lambda) @@ -748,18 +734,18 @@ un = mirror(1) def test_factory_method(self): code = ''' -class Super(object): - @classmethod - def instance(cls): - return cls() + class Super(object): + @classmethod + def instance(cls): + return cls() -class Sub(Super): - def method(self): - print ('method called') + class Sub(Super): + def method(self): + print ('method called') -sub = Sub.instance() + sub = Sub.instance() ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid.igetattr('sub')) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], Instance) @@ -768,16 +754,16 @@ sub = Sub.instance() def test_import_as(self): code = ''' -import os.path as osp -print (osp.dirname(__file__)) + import os.path as osp + print (osp.dirname(__file__)) -from os.path import exists as e -assert e(__file__) + from os.path import exists as e + assert e(__file__) -from new import code as make_code -print (make_code) + from new import code as make_code + print (make_code) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid.igetattr('osp')) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], nodes.Module) @@ -876,23 +862,23 @@ print (make_code) def test_binary_op_custom_class(self): code = ''' -class myarray: - def __init__(self, array): - self.array = array - def __mul__(self, x): - return myarray([2,4,6]) - def astype(self): - return "ASTYPE" - -def randint(maximum): - if maximum is not None: - return myarray([1,2,3]) * 2 - else: - return int(5) - -x = randint(1) + class myarray: + def __init__(self, array): + self.array = array + def __mul__(self, x): + return myarray([2,4,6]) + def astype(self): + return "ASTYPE" + + def randint(maximum): + if maximum is not None: + return myarray([1,2,3]) * 2 + else: + return int(5) + + x = randint(1) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid.igetattr('x')) self.assertEqual(len(infered), 2) value = [str(v) for v in infered] @@ -904,11 +890,10 @@ x = randint(1) def test_nonregr_lambda_arg(self): code = ''' -def f(g = lambda: None): - g().x + def f(g = lambda: None): + __(g()).x ''' - astroid = builder.string_build(code, __name__, __file__) - callfuncnode = astroid['f'].body[0].value.expr # 'g()' + callfuncnode = test_utils.extract_node(code) infered = list(callfuncnode.infer()) self.assertEqual(len(infered), 2, infered) infered.remove(YES) @@ -917,10 +902,10 @@ def f(g = lambda: None): def test_nonregr_getitem_empty_tuple(self): code = ''' -def f(x): - a = ()[x] + def f(x): + a = ()[x] ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid['f'].ilookup('a')) self.assertEqual(len(infered), 1) self.assertEqual(infered[0], YES) @@ -929,17 +914,17 @@ def f(x): """non regression for instance_attrs infinite loop : pylint / #4""" code = """ -class Foo(object): + class Foo(object): - def set_42(self): - self.attr = 42 + def set_42(self): + self.attr = 42 -class Bar(Foo): + class Bar(Foo): - def __init__(self): - self.attr = 41 + def __init__(self): + self.attr = 41 """ - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) foo_class = astroid['Foo'] bar_class = astroid['Bar'] bar_self = astroid['Bar']['__init__']['self'] @@ -969,23 +954,21 @@ class Bar(Foo): # !! FIXME also this relative import would not work 'in real' (no __init__.py in test/) # the test works since we pretend we have a package by passing the full modname astroid = builder.string_build(data, 'astroid.test.unittest_inference', __file__) - infered = next(get_name_node(astroid, 'date').infer()) + infered = next(test_utils.get_name_node(astroid, 'date').infer()) self.assertIsInstance(infered, nodes.Module) self.assertEqual(infered.name, 'logilab.common.date') def test_python25_no_relative_import(self): - fname = join(abspath(dirname(__file__)), 'regrtest_data', 'package', 'absimport.py') - astroid = builder.file_build(fname, 'absimport') + astroid = resources.build_file('data/package/absimport.py') self.assertTrue(astroid.absolute_import_activated(), True) - infered = next(get_name_node(astroid, 'import_package_subpackage_module').infer()) + infered = next(test_utils.get_name_node(astroid, 'import_package_subpackage_module').infer()) # failed to import since absolute_import is activated self.assertIs(infered, YES) def test_nonregr_absolute_import(self): - fname = join(abspath(dirname(__file__)), 'regrtest_data', 'absimp', 'string.py') - astroid = builder.file_build(fname, 'absimp.string') + astroid = resources.build_file('data/absimp/string.py', 'data.absimp.string') self.assertTrue(astroid.absolute_import_activated(), True) - infered = next(get_name_node(astroid, 'string').infer()) + infered = next(test_utils.get_name_node(astroid, 'string').infer()) self.assertIsInstance(infered, nodes.Module) self.assertEqual(infered.name, 'string') self.assertIn('ascii_letters', infered.locals) @@ -995,19 +978,20 @@ class Bar(Foo): import mechanize except ImportError: self.skipTest('require mechanize installed') - data = '''from mechanize import Browser -print (Browser) -b = Browser() -''' - astroid = builder.string_build(data, __name__, __file__) - browser = next(get_name_node(astroid, 'Browser').infer()) + data = ''' + from mechanize import Browser + print(Browser) + b = Browser() + ''' + astroid = test_utils.build_string(data, __name__) + browser = next(test_utils.get_name_node(astroid, 'Browser').infer()) self.assertIsInstance(browser, nodes.Class) bopen = list(browser.igetattr('open')) self.skipTest('the commit said: "huum, see that later"') self.assertEqual(len(bopen), 1) self.assertIsInstance(bopen[0], nodes.Function) self.assertTrue(bopen[0].callable()) - b = next(get_name_node(astroid, 'b').infer()) + b = next(test_utils.get_name_node(astroid, 'b').infer()) self.assertIsInstance(b, Instance) bopen = list(b.igetattr('open')) self.assertEqual(len(bopen), 1) @@ -1016,22 +1000,22 @@ b = Browser() def test_property(self): code = ''' -from smtplib import SMTP -class SendMailController(object): + from smtplib import SMTP + class SendMailController(object): - @property - def smtp(self): - return SMTP(mailhost, port) + @property + def smtp(self): + return SMTP(mailhost, port) - @property - def me(self): - return self + @property + def me(self): + return self -my_smtp = SendMailController().smtp -my_me = SendMailController().me -''' + my_smtp = SendMailController().smtp + my_me = SendMailController().me + ''' decorators = set(['%s.property' % BUILTINS]) - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertEqual(astroid['SendMailController']['smtp'].decoratornames(), decorators) propinfered = list(astroid.body[2].value.infer()) @@ -1052,35 +1036,34 @@ my_me = SendMailController().me def test_im_func_unwrap(self): code = ''' -class EnvBasedTC: - def pactions(self): - pass -pactions = EnvBasedTC.pactions.im_func -print (pactions) - -class EnvBasedTC2: - pactions = EnvBasedTC.pactions.im_func - print (pactions) - -''' - astroid = builder.string_build(code, __name__, __file__) - pactions = get_name_node(astroid, 'pactions') + class EnvBasedTC: + def pactions(self): + pass + pactions = EnvBasedTC.pactions.im_func + print (pactions) + + class EnvBasedTC2: + pactions = EnvBasedTC.pactions.im_func + print (pactions) + ''' + astroid = test_utils.build_module(code, __name__) + pactions = test_utils.get_name_node(astroid, 'pactions') infered = list(pactions.infer()) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], nodes.Function) - pactions = get_name_node(astroid['EnvBasedTC2'], 'pactions') + pactions = test_utils.get_name_node(astroid['EnvBasedTC2'], 'pactions') infered = list(pactions.infer()) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], nodes.Function) def test_augassign(self): code = ''' -a = 1 -a += 2 -print (a) -''' - astroid = builder.string_build(code, __name__, __file__) - infered = list(get_name_node(astroid, 'a').infer()) + a = 1 + a += 2 + print (a) + ''' + astroid = test_utils.build_module(code, __name__) + infered = list(test_utils.get_name_node(astroid, 'a').infer()) self.assertEqual(len(infered), 1) self.assertIsInstance(infered[0], nodes.Const) @@ -1088,43 +1071,43 @@ print (a) def test_nonregr_func_arg(self): code = ''' -def foo(self, bar): - def baz(): - pass - def qux(): - return baz - spam = bar(None, qux) - print (spam) -''' - astroid = builder.string_build(code, __name__, __file__) - infered = list(get_name_node(astroid['foo'], 'spam').infer()) + def foo(self, bar): + def baz(): + pass + def qux(): + return baz + spam = bar(None, qux) + print (spam) + ''' + astroid = test_utils.build_module(code, __name__) + infered = list(test_utils.get_name_node(astroid['foo'], 'spam').infer()) self.assertEqual(len(infered), 1) self.assertIs(infered[0], YES) def test_nonregr_func_global(self): code = ''' -active_application = None - -def get_active_application(): - global active_application - return active_application - -class Application(object): - def __init__(self): - global active_application - active_application = self - -class DataManager(object): - def __init__(self, app=None): - self.app = get_active_application() - def test(self): - p = self.app - print (p) + active_application = None + + def get_active_application(): + global active_application + return active_application + + class Application(object): + def __init__(self): + global active_application + active_application = self + + class DataManager(object): + def __init__(self, app=None): + self.app = get_active_application() + def test(self): + p = self.app + print (p) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(Instance(astroid['DataManager']).igetattr('app')) self.assertEqual(len(infered), 2, infered) # None / Instance(Application) - infered = list(get_name_node(astroid['DataManager']['test'], 'p').infer()) + infered = list(test_utils.get_name_node(astroid['DataManager']['test'], 'p').infer()) self.assertEqual(len(infered), 2, infered) for node in infered: if isinstance(node, Instance) and node.name == 'Application': @@ -1135,29 +1118,29 @@ class DataManager(object): def test_list_inference(self): """#20464""" code = ''' -import optparse + import optparse -A = [] -B = [] + A = [] + B = [] -def test(): - xyz = [ - "foobar=%s" % options.ca, - ] + A + B + def test(): + xyz = [ + "foobar=%s" % options.ca, + ] + A + B - if options.bind is not None: - xyz.append("bind=%s" % options.bind) - return xyz + if options.bind is not None: + xyz.append("bind=%s" % options.bind) + return xyz -def main(): - global options + def main(): + global options - parser = optparse.OptionParser() - (options, args) = parser.parse_args() + parser = optparse.OptionParser() + (options, args) = parser.parse_args() -Z = test() + Z = test() ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) infered = list(astroid['Z'].infer()) self.assertEqual(len(infered), 1, infered) self.assertIsInstance(infered[0], Instance) @@ -1166,16 +1149,16 @@ Z = test() def test__new__(self): code = ''' -class NewTest(object): - "doc" - def __new__(cls, arg): - self = object.__new__(cls) - self.arg = arg - return self - -n = NewTest() + class NewTest(object): + "doc" + def __new__(cls, arg): + self = object.__new__(cls) + self.arg = arg + return self + + n = NewTest() ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertRaises(InferenceError, list, astroid['NewTest'].igetattr('arg')) n = next(astroid['n'].infer()) infered = list(n.igetattr('arg')) @@ -1183,23 +1166,22 @@ n = NewTest() def test_two_parents_from_same_module(self): - module = 'data_py3' if sys.version_info[0] == 3 else 'data' code = ''' -from %s import nonregr -class Xxx(nonregr.Aaa, nonregr.Ccc): - "doc" - ''' % (module,) - astroid = builder.string_build(code, __name__, __file__) + from data import nonregr + class Xxx(nonregr.Aaa, nonregr.Ccc): + "doc" + ''' + astroid = test_utils.build_module(code, __name__) parents = list(astroid['Xxx'].ancestors()) self.assertEqual(len(parents), 3, parents) # Aaa, Ccc, object def test_pluggable_inference(self): code = ''' -from collections import namedtuple -A = namedtuple('A', ['a', 'b']) -B = namedtuple('B', 'a b') + from collections import namedtuple + A = namedtuple('A', ['a', 'b']) + B = namedtuple('B', 'a b') ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) aclass = astroid['A'].infered()[0] self.assertIsInstance(aclass, nodes.Class) self.assertIn('a', aclass.instance_attrs) @@ -1211,27 +1193,27 @@ B = namedtuple('B', 'a b') def test_infer_arguments(self): code = ''' -class A(object): - def first(self, arg1, arg2): - return arg1 - @classmethod - def method(cls, arg1, arg2): - return arg2 - @classmethod - def empty(cls): - return 2 - @staticmethod - def static(arg1, arg2): - return arg1 - def empty_method(self): - return [] -x = A().first(1, []) -y = A.method(1, []) -z = A.static(1, []) -empty = A.empty() -empty_list = A().empty_method() + class A(object): + def first(self, arg1, arg2): + return arg1 + @classmethod + def method(cls, arg1, arg2): + return arg2 + @classmethod + def empty(cls): + return 2 + @staticmethod + def static(arg1, arg2): + return arg1 + def empty_method(self): + return [] + x = A().first(1, []) + y = A.method(1, []) + z = A.static(1, []) + empty = A.empty() + empty_list = A().empty_method() ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) int_node = astroid['x'].infered()[0] self.assertIsInstance(int_node, nodes.Const) self.assertEqual(int_node.value, 1) @@ -1248,11 +1230,11 @@ empty_list = A().empty_method() def test_infer_variable_arguments(self): code = ''' -def test(*args, **kwargs): - vararg = args - kwarg = kwargs + def test(*args, **kwargs): + vararg = args + kwarg = kwargs ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) func = astroid['test'] vararg = func.body[0].value kwarg = func.body[1].value @@ -1266,33 +1248,33 @@ def test(*args, **kwargs): self.assertIs(vararg_infered.parent, func.args) def test_infer_nested(self): - code = dedent(""" - def nested(): - from threading import Thread - - class NestedThread(Thread): - def __init__(self): - Thread.__init__(self) - """) + code = """ + def nested(): + from threading import Thread + + class NestedThread(Thread): + def __init__(self): + Thread.__init__(self) + """ # Test that inferring Thread.__init__ looks up in # the nested scope. - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) callfunc = next(astroid.nodes_of_class(nodes.CallFunc)) func = callfunc.func infered = func.infered()[0] self.assertIsInstance(infered, UnboundMethod) def test_instance_binary_operations(self): - code = dedent(""" - class A(object): - def __mul__(self, other): - return 42 - a = A() - b = A() - sub = a - b - mul = a * b - """) - astroid = builder.string_build(code, __name__, __file__) + code = """ + class A(object): + def __mul__(self, other): + return 42 + a = A() + b = A() + sub = a - b + mul = a * b + """ + astroid = test_utils.build_module(code, __name__) sub = astroid['sub'].infered()[0] mul = astroid['mul'].infered()[0] self.assertIs(sub, YES) @@ -1300,18 +1282,18 @@ def test(*args, **kwargs): self.assertEqual(mul.value, 42) def test_instance_binary_operations_parent(self): - code = dedent(""" - class A(object): - def __mul__(self, other): - return 42 - class B(A): - pass - a = B() - b = B() - sub = a - b - mul = a * b - """) - astroid = builder.string_build(code, __name__, __file__) + code = """ + class A(object): + def __mul__(self, other): + return 42 + class B(A): + pass + a = B() + b = B() + sub = a - b + mul = a * b + """ + astroid = test_utils.build_module(code, __name__) sub = astroid['sub'].infered()[0] mul = astroid['mul'].infered()[0] self.assertIs(sub, YES) @@ -1319,19 +1301,19 @@ def test(*args, **kwargs): self.assertEqual(mul.value, 42) def test_instance_binary_operations_multiple_methods(self): - code = dedent(""" - class A(object): - def __mul__(self, other): - return 42 - class B(A): - def __mul__(self, other): - return [42] - a = B() - b = B() - sub = a - b - mul = a * b - """) - astroid = builder.string_build(code, __name__, __file__) + code = """ + class A(object): + def __mul__(self, other): + return 42 + class B(A): + def __mul__(self, other): + return [42] + a = B() + b = B() + sub = a - b + mul = a * b + """ + astroid = test_utils.build_module(code, __name__) sub = astroid['sub'].infered()[0] mul = astroid['mul'].infered()[0] self.assertIs(sub, YES) @@ -1340,17 +1322,16 @@ def test(*args, **kwargs): self.assertEqual(mul.elts[0].value, 42) def test_infer_call_result_crash(self): - # Test for issue 11. - code = dedent(""" - class A(object): - def __mul__(self, other): - return type.__new__() - - a = A() - b = A() - c = a * b - """) - astroid = builder.string_build(code, __name__, __file__) + code = """ + class A(object): + def __mul__(self, other): + return type.__new__() + + a = A() + b = A() + c = a * b + """ + astroid = test_utils.build_module(code, __name__) node = astroid['c'] self.assertEqual(node.infered(), [YES]) @@ -1362,16 +1343,17 @@ def test(*args, **kwargs): def test_infinite_loop_for_decorators(self): # Issue https://bitbucket.org/logilab/astroid/issue/50 # A decorator that returns itself leads to an infinite loop. - code = dedent(""" - def decorator(): - def wrapper(): - return decorator() - return wrapper - - @decorator() - def do_a_thing(): - pass""") - astroid = builder.string_build(code, __name__, __file__) + code = """ + def decorator(): + def wrapper(): + return decorator() + return wrapper + + @decorator() + def do_a_thing(): + pass + """ + astroid = test_utils.build_module(code, __name__) node = astroid['do_a_thing'] self.assertEqual(node.type, 'function') diff --git a/astroid/tests/unittest_inspector.py b/astroid/tests/unittest_inspector.py index 5d5eaa2d..fa48a5e5 100644 --- a/astroid/tests/unittest_inspector.py +++ b/astroid/tests/unittest_inspector.py @@ -24,8 +24,8 @@ import unittest from astroid import nodes, inspector from astroid.bases import Instance, YES - from astroid.manager import AstroidManager, _silent_no_wrap +from astroid.tests import resources MANAGER = AstroidManager() @@ -33,28 +33,26 @@ def astroid_wrapper(func, modname): return func(modname) -DATA2 = join(dirname(abspath(__file__)), 'data2') - - -class LinkerTC(unittest.TestCase): +class LinkerTest(resources.SysPathSetup, unittest.TestCase): def setUp(self): - self.project = MANAGER.project_from_files([DATA2], astroid_wrapper) + super(LinkerTest, self).setUp() + self.project = MANAGER.project_from_files([resources.find('data')], astroid_wrapper) self.linker = inspector.Linker(self.project) self.linker.visit(self.project) def test_class_implements(self): - klass = self.project.get_module('data2.clientmodule_test')['Ancestor'] + klass = self.project.get_module('data.clientmodule_test')['Ancestor'] self.assertTrue(hasattr(klass, 'implements')) self.assertEqual(len(klass.implements), 1) self.assertTrue(isinstance(klass.implements[0], nodes.Class)) self.assertEqual(klass.implements[0].name, "Interface") - klass = self.project.get_module('data2.clientmodule_test')['Specialization'] + klass = self.project.get_module('data.clientmodule_test')['Specialization'] self.assertTrue(hasattr(klass, 'implements')) self.assertEqual(len(klass.implements), 0) def test_locals_assignment_resolution(self): - klass = self.project.get_module('data2.clientmodule_test')['Specialization'] + klass = self.project.get_module('data.clientmodule_test')['Specialization'] self.assertTrue(hasattr(klass, 'locals_type')) type_dict = klass.locals_type self.assertEqual(len(type_dict), 2) @@ -66,7 +64,7 @@ class LinkerTC(unittest.TestCase): self.assertEqual(type_dict['top'][0].value, 'class') def test_instance_attrs_resolution(self): - klass = self.project.get_module('data2.clientmodule_test')['Specialization'] + klass = self.project.get_module('data.clientmodule_test')['Specialization'] self.assertTrue(hasattr(klass, 'instance_attrs_type')) type_dict = klass.instance_attrs_type self.assertEqual(len(type_dict), 3) @@ -79,15 +77,15 @@ class LinkerTC(unittest.TestCase): self.assertIs(type_dict['_id'][0], YES) -class LinkerTC2(LinkerTC): +class LinkerTest2(LinkerTest): def setUp(self): - self.project = MANAGER.project_from_files([DATA2], func_wrapper=_silent_no_wrap) + resources.SysPathSetup.setUp(self) + self.project = MANAGER.project_from_files( + [resources.find('data')], func_wrapper=_silent_no_wrap) self.linker = inspector.Linker(self.project) self.linker.visit(self.project) -__all__ = ('LinkerTC', 'LinkerTC2') - if __name__ == '__main__': unittest.main() diff --git a/astroid/tests/unittest_lookup.py b/astroid/tests/unittest_lookup.py index 0c5d5eb7..1074e21b 100644 --- a/astroid/tests/unittest_lookup.py +++ b/astroid/tests/unittest_lookup.py @@ -22,41 +22,34 @@ from os.path import join, abspath, dirname from functools import partial import unittest -from astroid import builder, nodes, scoped_nodes, \ - InferenceError, NotFoundError, UnresolvableName -from astroid.scoped_nodes import builtin_lookup, Function +from astroid import nodes, InferenceError, NotFoundError, UnresolvableName +from astroid.scoped_nodes import builtin_lookup from astroid.bases import YES -from astroid.test_utils import require_version, get_name_node +from astroid import test_utils +from astroid.tests import resources -builder = builder.AstroidBuilder() -PY3K = sys.version_info >= (3, 0) -if PY3K: - DATA = join(dirname(abspath(__file__)), 'data_py3') - import data_py3 as data -else: - DATA = join(dirname(abspath(__file__)), 'data') - import data +class LookupTest(resources.SysPathSetup, unittest.TestCase): -MODULE = builder.file_build(join(DATA, 'module.py'), 'data.module') -MODULE2 = builder.file_build(join(DATA, 'module2.py'), 'data.module2') -NONREGR = builder.file_build(join(DATA, 'nonregr.py'), 'data.nonregr') - -class LookupTC(unittest.TestCase): + def setUp(self): + super(LookupTest, self).setUp() + self.module = resources.build_file('data/module.py', 'data.module') + self.module2 = resources.build_file('data/module2.py', 'data.module2') + self.nonregr = resources.build_file('data/nonregr.py', 'data.nonregr') def test_limit(self): code = ''' -l = [a - for a,b in list] + l = [a + for a,b in list] -a = 1 -b = a -a = None + a = 1 + b = a + a = None -def func(): - c = 1 + def func(): + c = 1 ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) # a & b a = next(astroid.nodes_of_class(nodes.Name)) self.assertEqual(a.lineno, 2) @@ -80,7 +73,7 @@ def func(): self.assertEqual(len(func.lookup('c')[1]), 1) def test_module(self): - astroid = builder.string_build('pass', __name__, __file__) + astroid = test_utils.build_module('pass', __name__) # built-in objects none = next(astroid.ilookup('None')) self.assertIsNone(none.value) @@ -90,17 +83,17 @@ def func(): self.assertRaises(InferenceError, partial(next, astroid.ilookup('YOAA'))) # XXX - self.assertEqual(len(list(NONREGR.ilookup('enumerate'))), 2) + self.assertEqual(len(list(self.nonregr.ilookup('enumerate'))), 2) def test_class_ancestor_name(self): code = ''' -class A: - pass + class A: + pass -class A(A): - pass + class A(A): + pass ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) cls1 = astroid.locals['A'][0] cls2 = astroid.locals['A'][1] name = next(cls2.nodes_of_class(nodes.Name)) @@ -108,7 +101,7 @@ class A(A): ### backport those test to inline code def test_method(self): - method = MODULE['YOUPI']['method'] + method = self.module['YOUPI']['method'] my_dict = next(method.ilookup('MY_DICT')) self.assertTrue(isinstance(my_dict, nodes.Dict), my_dict) none = next(method.ilookup('None')) @@ -117,14 +110,14 @@ class A(A): def test_function_argument_with_default(self): - make_class = MODULE2['make_class'] + make_class = self.module2['make_class'] base = next(make_class.ilookup('base')) self.assertTrue(isinstance(base, nodes.Class), base.__class__) self.assertEqual(base.name, 'YO') - self.assertEqual(base.root().name, '%s.module' % (data.__name__,)) + self.assertEqual(base.root().name, 'data.module') def test_class(self): - klass = MODULE['YOUPI'] + klass = self.module['YOUPI'] my_dict = next(klass.ilookup('MY_DICT')) self.assertIsInstance(my_dict, nodes.Dict) none = next(klass.ilookup('None')) @@ -135,19 +128,19 @@ class A(A): self.assertRaises(InferenceError, partial(next, klass.ilookup('YOAA'))) def test_inner_classes(self): - ddd = list(NONREGR['Ccc'].ilookup('Ddd')) + ddd = list(self.nonregr['Ccc'].ilookup('Ddd')) self.assertEqual(ddd[0].name, 'Ddd') def test_loopvar_hiding(self): - astroid = builder.string_build(""" -x = 10 -for x in range(5): - print (x) - -if x > 0: - print ('#' * x) - """, __name__, __file__) + astroid = test_utils.build_module(""" + x = 10 + for x in range(5): + print (x) + + if x > 0: + print ('#' * x) + """, __name__) xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'x'] # inside the loop, only one possible assignment self.assertEqual(len(xnames[0].lookup('x')[1]), 1) @@ -156,11 +149,11 @@ if x > 0: self.assertEqual(len(xnames[2].lookup('x')[1]), 2) def test_list_comps(self): - astroid = builder.string_build(""" -print ([ i for i in range(10) ]) -print ([ i for i in range(10) ]) -print ( list( i for i in range(10) ) ) - """, __name__, __file__) + astroid = test_utils.build_module(""" + print ([ i for i in range(10) ]) + print ([ i for i in range(10) ]) + print ( list( i for i in range(10) ) ) + """, __name__) xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i'] self.assertEqual(len(xnames[0].lookup('i')[1]), 1) self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2) @@ -171,9 +164,9 @@ print ( list( i for i in range(10) ) ) def test_list_comp_target(self): """test the list comprehension target""" - astroid = builder.string_build(""" -ten = [ var for var in range(10) ] -var + astroid = test_utils.build_module(""" + ten = [ var for var in range(10) ] + var """) var = astroid.body[1].value if sys.version_info < (3, 0): @@ -181,12 +174,11 @@ var else: self.assertRaises(UnresolvableName, var.infered) - @require_version('2.7') def test_dict_comps(self): - astroid = builder.string_build(""" -print ({ i: j for i in range(10) for j in range(10) }) -print ({ i: j for i in range(10) for j in range(10) }) - """, __name__, __file__) + astroid = test_utils.build_module(""" + print ({ i: j for i in range(10) for j in range(10) }) + print ({ i: j for i in range(10) for j in range(10) }) + """, __name__) xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i'] self.assertEqual(len(xnames[0].lookup('i')[1]), 1) self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2) @@ -199,59 +191,57 @@ print ({ i: j for i in range(10) for j in range(10) }) self.assertEqual(len(xnames[1].lookup('i')[1]), 1) self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3) - @require_version('2.7') def test_set_comps(self): - astroid = builder.string_build(""" -print ({ i for i in range(10) }) -print ({ i for i in range(10) }) - """, __name__, __file__) + astroid = test_utils.build_module(""" + print ({ i for i in range(10) }) + print ({ i for i in range(10) }) + """, __name__) xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'i'] self.assertEqual(len(xnames[0].lookup('i')[1]), 1) self.assertEqual(xnames[0].lookup('i')[1][0].lineno, 2) self.assertEqual(len(xnames[1].lookup('i')[1]), 1) self.assertEqual(xnames[1].lookup('i')[1][0].lineno, 3) - @require_version('2.7') def test_set_comp_closure(self): - astroid = builder.string_build(""" -ten = { var for var in range(10) } -var + astroid = test_utils.build_module(""" + ten = { var for var in range(10) } + var """) var = astroid.body[1].value self.assertRaises(UnresolvableName, var.infered) def test_generator_attributes(self): - tree = builder.string_build(""" -def count(): - "test" - yield 0 + tree = test_utils.build_module(""" + def count(): + "test" + yield 0 -iterer = count() -num = iterer.next() + iterer = count() + num = iterer.next() """) next = tree.body[2].value.func # Getattr gener = next.expr.infered()[0] # Generator if sys.version_info < (3, 0): - self.assertIsInstance(gener.getattr('next')[0], Function) + self.assertIsInstance(gener.getattr('next')[0], nodes.Function) else: - self.assertIsInstance(gener.getattr('__next__')[0], Function) - self.assertIsInstance(gener.getattr('send')[0], Function) - self.assertIsInstance(gener.getattr('throw')[0], Function) - self.assertIsInstance(gener.getattr('close')[0], Function) + self.assertIsInstance(gener.getattr('__next__')[0], nodes.Function) + self.assertIsInstance(gener.getattr('send')[0], nodes.Function) + self.assertIsInstance(gener.getattr('throw')[0], nodes.Function) + self.assertIsInstance(gener.getattr('close')[0], nodes.Function) def test_explicit___name__(self): code = ''' -class Pouet: - __name__ = "pouet" -p1 = Pouet() + class Pouet: + __name__ = "pouet" + p1 = Pouet() -class PouetPouet(Pouet): pass -p2 = Pouet() + class PouetPouet(Pouet): pass + p2 = Pouet() -class NoName: pass -p3 = NoName() -''' - astroid = builder.string_build(code, __name__, __file__) + class NoName: pass + p3 = NoName() + ''' + astroid = test_utils.build_module(code, __name__) p1 = next(astroid['p1'].infer()) self.assertTrue(p1.getattr('__name__')) p2 = next(astroid['p2'].infer()) @@ -262,11 +252,11 @@ p3 = NoName() def test_function_module_special(self): - astroid = builder.string_build(''' -def initialize(linter): - """initialize linter with checkers in this package """ - package_load(linter, __path__[0]) - ''', 'data.__init__', 'data/__init__.py') + astroid = test_utils.build_module(''' + def initialize(linter): + """initialize linter with checkers in this package """ + package_load(linter, __path__[0]) + ''', 'data.__init__') path = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == '__path__'][0] self.assertEqual(len(path.lookup('__path__')[1]), 1) @@ -282,20 +272,19 @@ def initialize(linter): def test_decorator_arguments_lookup(self): code = ''' -def decorator(value): - def wrapper(function): - return function - return wrapper + def decorator(value): + def wrapper(function): + return function + return wrapper -class foo: - member = 10 + class foo: + member = 10 #@ - @decorator(member) #This will cause pylint to complain - def test(self): - pass + @decorator(member) #This will cause pylint to complain + def test(self): + pass ''' - astroid = builder.string_build(code, __name__, __file__) - member = get_name_node(astroid['foo'], 'member') + member = test_utils.extract_node(code, __name__).targets[0] it = member.infer() obj = next(it) self.assertIsInstance(obj, nodes.Const) @@ -305,16 +294,15 @@ class foo: def test_inner_decorator_member_lookup(self): code = ''' -class FileA: - def decorator(bla): - return bla + class FileA: + def decorator(bla): + return bla - @decorator - def funcA(): - return 4 + @__(decorator) + def funcA(): + return 4 ''' - astroid = builder.string_build(code, __name__, __file__) - decname = get_name_node(astroid['FileA'], 'decorator') + decname = test_utils.extract_node(code, __name__) it = decname.infer() obj = next(it) self.assertIsInstance(obj, nodes.Function) @@ -323,19 +311,19 @@ class FileA: def test_static_method_lookup(self): code = ''' -class FileA: - @staticmethod - def funcA(): - return 4 + class FileA: + @staticmethod + def funcA(): + return 4 -class Test: - FileA = [1,2,3] + class Test: + FileA = [1,2,3] - def __init__(self): - print (FileA.funcA()) + def __init__(self): + print (FileA.funcA()) ''' - astroid = builder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) it = astroid['Test']['__init__'].ilookup('FileA') obj = next(it) self.assertIsInstance(obj, nodes.Class) @@ -344,23 +332,24 @@ class Test: def test_global_delete(self): code = ''' -def run2(): - f = Frobble() + def run2(): + f = Frobble() -class Frobble: - pass -Frobble.mumble = True + class Frobble: + pass + Frobble.mumble = True -del Frobble + del Frobble -def run1(): - f = Frobble() -''' - astroid = builder.string_build(code, __name__, __file__) + def run1(): + f = Frobble() + ''' + astroid = test_utils.build_module(code, __name__) stmts = astroid['run2'].lookup('Frobbel')[1] self.assertEqual(len(stmts), 0) stmts = astroid['run1'].lookup('Frobbel')[1] self.assertEqual(len(stmts), 0) + if __name__ == '__main__': unittest.main() diff --git a/astroid/tests/unittest_manager.py b/astroid/tests/unittest_manager.py index f9c08905..8edc5d7b 100644 --- a/astroid/tests/unittest_manager.py +++ b/astroid/tests/unittest_manager.py @@ -15,24 +15,19 @@ # # You should have received a copy of the GNU Lesser General Public License along # with astroid. If not, see <http://www.gnu.org/licenses/>. +import os +import sys import unittest -import sys -from os.path import join, abspath, dirname from astroid.manager import AstroidManager, _silent_no_wrap from astroid.bases import BUILTINS from astroid.exceptions import AstroidBuildingException +from astroid.tests import resources -PY3K = sys.version_info >= (3, 0) - -if PY3K: - DATA = join(dirname(abspath(__file__)), 'data_py3') -else: - DATA = join(dirname(abspath(__file__)), 'data') - -class AstroidManagerTC(unittest.TestCase): +class AstroidManagerTest(resources.SysPathSetup, unittest.TestCase): def setUp(self): + super(AstroidManagerTest, self).setUp() self.manager = AstroidManager() self.manager.clear_cache() # take care of borg @@ -90,12 +85,12 @@ class AstroidManagerTC(unittest.TestCase): def _test_ast_from_zip(self, archive): origpath = sys.path[:] sys.modules.pop('mypypa', None) - archive_path = join(DATA, archive) + archive_path = resources.find(archive) sys.path.insert(0, archive_path) try: module = self.manager.ast_from_module_name('mypypa') self.assertEqual(module.name, 'mypypa') - end = join(archive, 'mypypa') + end = os.path.join(archive, 'mypypa') self.assertTrue(module.file.endswith(end), "%s doesn't endswith %s" % (module.file, end)) finally: @@ -108,14 +103,14 @@ class AstroidManagerTC(unittest.TestCase): sys.path = origpath def test_ast_from_module_name_egg(self): - self._test_ast_from_zip('MyPyPa-0.1.0-py2.5.egg') + self._test_ast_from_zip('data/MyPyPa-0.1.0-py2.5.egg') def test_ast_from_module_name_zip(self): - self._test_ast_from_zip('MyPyPa-0.1.0-py2.5.zip') + self._test_ast_from_zip('data/MyPyPa-0.1.0-py2.5.zip') def test_zip_import_data(self): """check if zip_import_data works""" - filepath = join(DATA, 'MyPyPa-0.1.0-py2.5.zip/mypypa') + filepath = resources.find('data/MyPyPa-0.1.0-py2.5.zip/mypypa') astroid = self.manager.zip_import_data(filepath) self.assertEqual(astroid.name, 'mypypa') @@ -126,7 +121,7 @@ class AstroidManagerTC(unittest.TestCase): def test_file_from_module(self): """check if the unittest filepath is equals to the result of the method""" import unittest - if PY3K: + if sys.version_info > (3, 0): unittest_file = unittest.__file__ else: unittest_file = unittest.__file__[:-1] @@ -178,20 +173,25 @@ class AstroidManagerTC(unittest.TestCase): self.assertRaises(AstroidBuildingException, self.manager.ast_from_class, None) def test_from_directory(self): - obj = self.manager.project_from_files([DATA], _silent_no_wrap, 'data') + obj = self.manager.project_from_files([resources.find('data')], _silent_no_wrap, 'data') self.assertEqual(obj.name, 'data') - self.assertEqual(obj.path, join(DATA, '__init__.py')) + self.assertEqual(obj.path, os.path.abspath(resources.find('data/__init__.py'))) def test_project_node(self): - obj = self.manager.project_from_files([DATA], _silent_no_wrap, 'data') + obj = self.manager.project_from_files([resources.find('data')], _silent_no_wrap, 'data') expected = [ 'data', 'data.SSL1', 'data.SSL1.Connection1', + 'data.absimp', + 'data.absimp.sidepackage', + 'data.absimp.string', 'data.absimport', 'data.all', 'data.appl', - 'data.appl.myConnection', + 'data.appl.myConnection', + 'data.clientmodule_test', + 'data.descriptor_crash', 'data.email', 'data.find_test', 'data.find_test.module', @@ -207,10 +207,19 @@ class AstroidManagerTC(unittest.TestCase): 'data.module2', 'data.noendingnewline', 'data.nonregr', - 'data.notall'] - if PY3K: - expected = [e.replace('data', 'data_py3') for e in expected] - self.assertListEqual(sorted(k for k in obj.keys()), expected) + 'data.notall', + 'data.package', + 'data.package.absimport', + 'data.package.hello', + 'data.package.import_package_subpackage_module', + 'data.package.subpackage', + 'data.package.subpackage.module', + 'data.recursion', + 'data.suppliermodule_test', + 'data.unicode_package', + 'data.unicode_package.core'] + self.assertListEqual(sorted(obj.keys()), expected) + class BorgAstroidManagerTC(unittest.TestCase): diff --git a/astroid/tests/unittest_modutils.py b/astroid/tests/unittest_modutils.py index 50e0ab8a..c8d7411f 100644 --- a/astroid/tests/unittest_modutils.py +++ b/astroid/tests/unittest_modutils.py @@ -18,57 +18,51 @@ """ unit tests for module modutils (module manipulation utilities) """ - +import os import sys import unittest -try: - __file__ -except NameError: - __file__ = sys.argv[0] - -from os import path, getcwd, sep +from logilab.common import configuration from astroid import modutils - -sys.path.insert(0, path.dirname(__file__)) -DATADIR = path.abspath(path.normpath(path.join(path.dirname(__file__), 'data'))) +from astroid.tests import resources -class ModuleFileTC(unittest.TestCase): +class ModuleFileTest(unittest.TestCase): package = "mypypa" def tearDown(self): - super(ModuleFileTC, self).tearDown() for k in list(sys.path_importer_cache.keys()): if 'MyPyPa' in k: del sys.path_importer_cache[k] def test_find_zipped_module(self): - mtype, mfile = modutils._module_file([self.package], [path.join(DATADIR, 'MyPyPa-0.1.0-py2.5.zip')]) + mtype, mfile = modutils._module_file( + [self.package], [resources.find('data/MyPyPa-0.1.0-py2.5.zip')]) self.assertEqual(mtype, modutils.PY_ZIPMODULE) - self.assertEqual(mfile.split(sep)[-4:], ["tests", "data", "MyPyPa-0.1.0-py2.5.zip", self.package]) + self.assertEqual(mfile.split(os.sep)[-3:], ["data", "MyPyPa-0.1.0-py2.5.zip", self.package]) def test_find_egg_module(self): - mtype, mfile = modutils._module_file([self.package], [path.join(DATADIR, 'MyPyPa-0.1.0-py2.5.egg')]) + mtype, mfile = modutils._module_file( + [self.package], [resources.find('data/MyPyPa-0.1.0-py2.5.egg')]) self.assertEqual(mtype, modutils.PY_ZIPMODULE) - self.assertEqual(mfile.split(sep)[-4:], ["tests", "data", "MyPyPa-0.1.0-py2.5.egg", self.package]) + self.assertEqual(mfile.split(os.sep)[-3:], ["data", "MyPyPa-0.1.0-py2.5.egg", self.package]) -class load_module_from_name_tc(unittest.TestCase): +class LoadModuleFromNameTest(unittest.TestCase): """ load a python module from it's name """ def test_knownValues_load_module_from_name_1(self): self.assertEqual(modutils.load_module_from_name('sys'), sys) def test_knownValues_load_module_from_name_2(self): - self.assertEqual(modutils.load_module_from_name('os.path'), path) + self.assertEqual(modutils.load_module_from_name('os.path'), os.path) def test_raise_load_module_from_name_1(self): self.assertRaises(ImportError, modutils.load_module_from_name, 'os.path', use_sys=0) -class get_module_part_tc(unittest.TestCase): +class GetModulePartTest(unittest.TestCase): """given a dotted name return the module part of the name""" def test_knownValues_get_module_part_1(self): @@ -97,46 +91,44 @@ class get_module_part_tc(unittest.TestCase): modutils.__file__) -class modpath_from_file_tc(unittest.TestCase): +class ModPathFromFileTest(unittest.TestCase): """ given an absolute file path return the python module's path as a list """ def test_knownValues_modpath_from_file_1(self): - self.assertEqual(modutils.modpath_from_file(modutils.__file__), - ['astroid', 'modutils']) + self.assertEqual(modutils.modpath_from_file(configuration.__file__), + ['logilab', 'common', 'configuration']) def test_knownValues_modpath_from_file_2(self): self.assertEqual(modutils.modpath_from_file('unittest_modutils.py', - {getcwd(): 'arbitrary.pkg'}), + {os.getcwd(): 'arbitrary.pkg'}), ['arbitrary', 'pkg', 'unittest_modutils']) def test_raise_modpath_from_file_Exception(self): self.assertRaises(Exception, modutils.modpath_from_file, '/turlututu') -class load_module_from_path_tc(unittest.TestCase): +class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase): def test_do_not_load_twice(self): - sys.path.insert(0, DATADIR) - foo = modutils.load_module_from_modpath(['lmfp', 'foo']) - lmfp = modutils.load_module_from_modpath(['lmfp']) + foo = modutils.load_module_from_modpath(['data', 'lmfp', 'foo']) + lmfp = modutils.load_module_from_modpath(['data', 'lmfp']) self.assertEqual(len(sys.just_once), 1) - sys.path.pop(0) del sys.just_once -class file_from_modpath_tc(unittest.TestCase): +class FileFromModPathTest(resources.SysPathSetup, unittest.TestCase): """given a mod path (i.e. splited module / package name), return the corresponding file, giving priority to source file over precompiled file if it exists""" def test_site_packages(self): - self.assertEqual(path.realpath(modutils.file_from_modpath(['astroid', 'modutils'])), - path.realpath(modutils.__file__.replace('.pyc', '.py'))) + self.assertEqual(os.path.realpath(modutils.file_from_modpath(['astroid', 'modutils'])), + os.path.realpath(modutils.__file__.replace('.pyc', '.py'))) def test_std_lib(self): from os import path - self.assertEqual(path.realpath(modutils.file_from_modpath(['os', 'path']).replace('.pyc', '.py')), - path.realpath(path.__file__.replace('.pyc', '.py'))) + self.assertEqual(os.path.realpath(modutils.file_from_modpath(['os', 'path']).replace('.pyc', '.py')), + os.path.realpath(path.__file__.replace('.pyc', '.py'))) def test_xmlplus(self): try: @@ -145,8 +137,8 @@ class file_from_modpath_tc(unittest.TestCase): except ImportError: pass else: - self.assertEqual(path.realpath(modutils.file_from_modpath(['xml', 'dom', 'ext']).replace('.pyc', '.py')), - path.realpath(ext.__file__.replace('.pyc', '.py'))) + self.assertEqual(os.path.realpath(modutils.file_from_modpath(['xml', 'dom', 'ext']).replace('.pyc', '.py')), + os.path.realpath(ext.__file__.replace('.pyc', '.py'))) def test_builtin(self): self.assertEqual(modutils.file_from_modpath(['sys']), @@ -159,25 +151,20 @@ class file_from_modpath_tc(unittest.TestCase): def test_unicode_in_package_init(self): # file_from_modpath should not crash when reading an __init__ # file with unicode characters. - sys.path.insert(0, path.join(path.dirname(path.abspath(__file__)), - 'regrtest_data')) - self.addCleanup(sys.path.pop, 0) + modutils.file_from_modpath(["data", "unicode_package", "core"]) - modutils.file_from_modpath(["unicode_package", "core"]) - -class get_source_file_tc(unittest.TestCase): +class GetSourceFileTest(unittest.TestCase): def test(self): - from os import path - self.assertEqual(modutils.get_source_file(path.__file__), - path.normpath(path.__file__.replace('.pyc', '.py'))) + self.assertEqual(modutils.get_source_file(os.path.__file__), + os.path.normpath(os.path.__file__.replace('.pyc', '.py'))) def test_raise(self): self.assertRaises(modutils.NoSourceFile, modutils.get_source_file, 'whatever') -class is_standard_module_tc(unittest.TestCase): +class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase): """ return true if the module may be considered as a module from the standard library @@ -214,10 +201,11 @@ class is_standard_module_tc(unittest.TestCase): self.assertEqual(modutils.is_standard_module('StringIO'), sys.version_info < (3, 0)) def test_custom_path(self): - if DATADIR.startswith(modutils.EXT_LIB_DIR): + datadir = resources.find('') + if datadir.startswith(modutils.EXT_LIB_DIR): self.skipTest('known breakage of is_standard_module on installed package') - self.assertEqual(modutils.is_standard_module('data.module', (DATADIR,)), True) - self.assertEqual(modutils.is_standard_module('data.module', (path.abspath(DATADIR),)), True) + self.assertEqual(modutils.is_standard_module('data.module', (datadir,)), True) + self.assertEqual(modutils.is_standard_module('data.module', (os.path.abspath(datadir),)), True) def test_failing_edge_cases(self): from logilab import common @@ -230,7 +218,7 @@ class is_standard_module_tc(unittest.TestCase): self.assertEqual(modutils.is_standard_module('logilab.whatever', common.__path__), False) -class is_relative_tc(unittest.TestCase): +class IsRelativeTest(unittest.TestCase): def test_knownValues_is_relative_1(self): @@ -249,17 +237,17 @@ class is_relative_tc(unittest.TestCase): False) -class get_module_files_tc(unittest.TestCase): +class GetModuleFilesTest(unittest.TestCase): - def test_knownValues_get_module_files_1(self): # XXXFIXME: TOWRITE + def test_get_module_files_1(self): """given a directory return a list of all available python module's files, even in subdirectories """ - import data - modules = sorted(modutils.get_module_files(path.join(DATADIR, 'find_test'), - data.__path__[0])) - self.assertEqual(modules, - [path.join(DATADIR, 'find_test', x) for x in ['__init__.py', 'module.py', 'module2.py', 'noendingnewline.py', 'nonregr.py']]) + package = resources.find('data/find_test') + modules = set(modutils.get_module_files(package, [])) + self.assertEqual( + modules, + {os.path.join(package, x) for x in ['__init__.py', 'module.py', 'module2.py', 'noendingnewline.py', 'nonregr.py']}) def test_load_module_set_attribute(self): import logilab.common.fileutils diff --git a/astroid/tests/unittest_nodes.py b/astroid/tests/unittest_nodes.py index e9c688cc..7cedd7e1 100644 --- a/astroid/tests/unittest_nodes.py +++ b/astroid/tests/unittest_nodes.py @@ -17,7 +17,7 @@ # with astroid. If not, see <http://www.gnu.org/licenses/>. """tests for specific behaviour of astroid nodes """ -from os.path import join, abspath, dirname +import os import sys import unittest @@ -25,20 +25,13 @@ from astroid.node_classes import unpack_infer from astroid.bases import BUILTINS, YES, InferenceContext from astroid.exceptions import AstroidBuildingException, NotFoundError from astroid import builder, nodes -from astroid.test_utils import require_version - -PY3K = sys.version_info >= (3, 0) - -if PY3K: - from data_py3 import module as test_module - DATA = join(dirname(abspath(__file__)), 'data_py3') -else: - from data import module as test_module - DATA = join(dirname(abspath(__file__)), 'data') +from astroid import test_utils +from astroid.tests import resources abuilder = builder.AstroidBuilder() -class AsString(unittest.TestCase): + +class AsStringTest(unittest.TestCase): def test_tuple_as_string(self): def build(string): @@ -56,17 +49,18 @@ class AsString(unittest.TestCase): def test_module_as_string(self): """check as_string on a whole module prepared to be returned identically """ - data = open(join(DATA, 'module.py')).read() - self.assertMultiLineEqual(MODULE.as_string(), data) + module = resources.build_file('data/module.py', 'data.module') + with open(resources.find('data/module.py'), 'r') as fobj: + self.assertMultiLineEqual(module.as_string(), fobj.read()) def test_module2_as_string(self): """check as_string on a whole module prepared to be returned identically """ - data = open(join(DATA, 'module2.py')).read() - self.assertMultiLineEqual(MODULE2.as_string(), data) + module2 = resources.build_file('data/module2.py', 'data.module2') + with open(resources.find('data/module2.py'), 'r') as fobj: + self.assertMultiLineEqual(module2.as_string(), fobj.read()) - @require_version('2.7') - def test_2_7_as_string(self): + def test_as_string(self): """check as_string for python syntax >= 2.7""" code = '''one_two = {1, 2} b = {v: k for (k, v) in enumerate('string')} @@ -74,7 +68,7 @@ cdd = {k for k in b}\n\n''' ast = abuilder.string_build(code) self.assertMultiLineEqual(ast.as_string(), code) - @require_version('3.0') + @test_utils.require_version('3.0') def test_3k_as_string(self): """check as_string for python 3k syntax""" code = '''print() @@ -98,44 +92,74 @@ class Language(metaclass=Natural): ast = abuilder.string_build(code) self.assertEqual(ast.as_string(), code) + def test_ellipsis(self): + ast = abuilder.string_build('a[...]').body[0] + self.assertEqual(ast.as_string(), 'a[...]') + + def test_slices(self): + for code in ('a[0]', 'a[1:3]', 'a[:-1:step]', 'a[:,newaxis]', + 'a[newaxis,:]', 'del L[::2]', 'del A[1]', 'del Br[:]'): + ast = abuilder.string_build(code).body[0] + self.assertEqual(ast.as_string(), code) -class _NodeTC(unittest.TestCase): + def test_slice_and_subscripts(self): + code = """a[:1] = bord[2:] +a[:1] = bord[2:] +del bree[3:d] +bord[2:] +del av[d::f], a[df:] +a[:1] = bord[2:] +del SRC[::1,newaxis,1:] +tous[vals] = 1010 +del thousand[key] +del a[::2], a[:-1:step] +del Fee.form[left:] +aout.vals = miles.of_stuff +del (ccok, (name.thing, foo.attrib.value)), Fee.form[left:] +if all[1] == bord[0:]: + pass\n\n""" + ast = abuilder.string_build(code) + self.assertEqual(ast.as_string(), code) + + +class _NodeTest(unittest.TestCase): """test transformation of If Node""" CODE = None + @property def astroid(self): try: return self.__class__.__dict__['CODE_Astroid'] except KeyError: - astroid = abuilder.string_build(self.CODE) + astroid = test_utils.build_module(self.CODE) self.__class__.CODE_Astroid = astroid return astroid -class IfNodeTC(_NodeTC): +class IfNodeTest(_NodeTest): """test transformation of If Node""" CODE = """ -if 0: - print() - -if True: - print() -else: - pass - -if "": - print() -elif []: - raise - -if 1: - print() -elif True: - print() -elif func(): - pass -else: - raise + if 0: + print() + + if True: + print() + else: + pass + + if "": + print() + elif []: + raise + + if 1: + print() + elif True: + print() + elif func(): + pass + else: + raise """ def test_if_elif_else_node(self): @@ -158,17 +182,18 @@ else: self.assertEqual(self.astroid.body[1].orelse[0].block_range(8), (8, 8)) -class TryExceptNodeTC(_NodeTC): +class TryExceptNodeTest(_NodeTest): CODE = """ -try: - print ('pouet') -except IOError: - pass -except UnicodeError: - print() -else: - print() + try: + print ('pouet') + except IOError: + pass + except UnicodeError: + print() + else: + print() """ + def test_block_range(self): # XXX ensure expected values self.assertEqual(self.astroid.body[0].block_range(1), (1, 8)) @@ -181,13 +206,14 @@ else: self.assertEqual(self.astroid.body[0].block_range(8), (8, 8)) -class TryFinallyNodeTC(_NodeTC): +class TryFinallyNodeTest(_NodeTest): CODE = """ -try: - print ('pouet') -finally: - print ('pouet') + try: + print ('pouet') + finally: + print ('pouet') """ + def test_block_range(self): # XXX ensure expected values self.assertEqual(self.astroid.body[0].block_range(1), (1, 4)) @@ -196,15 +222,16 @@ finally: self.assertEqual(self.astroid.body[0].block_range(4), (4, 4)) -class TryFinally25NodeTC(_NodeTC): +class TryExceptFinallyNodeTest(_NodeTest): CODE = """ -try: - print('pouet') -except Exception: - print ('oops') -finally: - print ('pouet') + try: + print('pouet') + except Exception: + print ('oops') + finally: + print ('pouet') """ + def test_block_range(self): # XXX ensure expected values self.assertEqual(self.astroid.body[0].block_range(1), (1, 6)) @@ -215,12 +242,12 @@ finally: self.assertEqual(self.astroid.body[0].block_range(6), (6, 6)) -class TryExcept2xNodeTC(_NodeTC): +class TryExcept2xNodeTest(_NodeTest): CODE = """ -try: - hello -except AttributeError, (retval, desc): - pass + try: + hello + except AttributeError, (retval, desc): + pass """ def test_tuple_attribute(self): if sys.version_info >= (3, 0): @@ -229,21 +256,21 @@ except AttributeError, (retval, desc): self.assertIsInstance(handler.name, nodes.Tuple) -MODULE = abuilder.module_build(test_module) -MODULE2 = abuilder.file_build(join(DATA, 'module2.py'), 'data.module2') - - -class ImportNodeTC(unittest.TestCase): +class ImportNodeTest(resources.SysPathSetup, unittest.TestCase): + def setUp(self): + super(ImportNodeTest, self).setUp() + self.module = resources.build_file('data/module.py', 'data.module') + self.module2 = resources.build_file('data/module2.py', 'data.module2') def test_import_self_resolve(self): - myos = next(MODULE2.igetattr('myos')) + myos = next(self.module2.igetattr('myos')) self.assertTrue(isinstance(myos, nodes.Module), myos) self.assertEqual(myos.name, 'os') self.assertEqual(myos.qname(), 'os') self.assertEqual(myos.pytype(), '%s.module' % BUILTINS) def test_from_self_resolve(self): - pb = next(MODULE.igetattr('pb')) + pb = next(self.module.igetattr('pb')) self.assertTrue(isinstance(pb, nodes.Class), pb) self.assertEqual(pb.root().name, 'logilab.common.shellutils') self.assertEqual(pb.qname(), 'logilab.common.shellutils.ProgressBar') @@ -251,31 +278,31 @@ class ImportNodeTC(unittest.TestCase): self.assertEqual(pb.pytype(), '%s.type' % BUILTINS) else: self.assertEqual(pb.pytype(), '%s.classobj' % BUILTINS) - abspath = next(MODULE2.igetattr('abspath')) + abspath = next(self.module2.igetattr('abspath')) self.assertTrue(isinstance(abspath, nodes.Function), abspath) self.assertEqual(abspath.root().name, 'os.path') self.assertEqual(abspath.qname(), 'os.path.abspath') self.assertEqual(abspath.pytype(), '%s.function' % BUILTINS) def test_real_name(self): - from_ = MODULE['pb'] + from_ = self.module['pb'] self.assertEqual(from_.real_name('pb'), 'ProgressBar') - imp_ = MODULE['os'] + imp_ = self.module['os'] self.assertEqual(imp_.real_name('os'), 'os') self.assertRaises(NotFoundError, imp_.real_name, 'os.path') - imp_ = MODULE['pb'] + imp_ = self.module['pb'] self.assertEqual(imp_.real_name('pb'), 'ProgressBar') self.assertRaises(NotFoundError, imp_.real_name, 'ProgressBar') - imp_ = MODULE2['YO'] + imp_ = self.module2['YO'] self.assertEqual(imp_.real_name('YO'), 'YO') self.assertRaises(NotFoundError, imp_.real_name, 'data') def test_as_string(self): - ast = MODULE['modutils'] + ast = self.module['modutils'] self.assertEqual(ast.as_string(), "from astroid import modutils") - ast = MODULE['pb'] + ast = self.module['pb'] self.assertEqual(ast.as_string(), "from logilab.common.shellutils import ProgressBar as pb") - ast = MODULE['os'] + ast = self.module['os'] self.assertEqual(ast.as_string(), "import os.path") code = """from . import here from .. import door @@ -293,47 +320,42 @@ from ..cave import wine\n\n""" will catch this exception and yield and YES instead. ''' - code = '''try: - from pickle import PickleError -except ImportError: - from nonexistent import PickleError + code = ''' + try: + from pickle import PickleError + except ImportError: + from nonexistent import PickleError -try: - pass -except PickleError: - pass + try: + pass + except PickleError: + pass ''' - - astroid = abuilder.string_build(code) - from_node = astroid.body[1].handlers[0].body[0] + astroid = test_utils.build_module(code) handler_type = astroid.body[1].handlers[0].type excs = list(unpack_infer(handler_type)) def test_absolute_import(self): - astroid = abuilder.file_build(join(DATA, 'absimport.py')) + astroid = resources.build_file('data/absimport.py') ctx = InferenceContext() # will fail if absolute import failed next(astroid['message'].infer(ctx, lookupname='message')) m = next(astroid['email'].infer(ctx, lookupname='email')) - self.assertFalse(m.file.startswith(join(DATA, 'email.py'))) + self.assertFalse(m.file.startswith(os.path.join('data', 'email.py'))) def test_more_absolute_import(self): - sys.path.insert(0, join(DATA, 'moreabsimport')) - try: - astroid = abuilder.file_build(join(DATA, 'module1abs/__init__.py')) - self.assertIn('sys', astroid.locals) - finally: - sys.path.pop(0) + astroid = resources.build_file('data/module1abs/__init__.py', 'data.module1abs') + self.assertIn('sys', astroid.locals) -class CmpNodeTC(unittest.TestCase): +class CmpNodeTest(unittest.TestCase): def test_as_string(self): ast = abuilder.string_build("a == 2").body[0] self.assertEqual(ast.as_string(), "a == 2") -class ConstNodeTC(unittest.TestCase): +class ConstNodeTest(unittest.TestCase): def _test(self, value): node = nodes.const_factory(value) @@ -365,19 +387,20 @@ class ConstNodeTC(unittest.TestCase): self._test(u'a') -class NameNodeTC(unittest.TestCase): +class NameNodeTest(unittest.TestCase): def test_assign_to_True(self): """test that True and False assignements don't crash""" - code = """True = False -def hello(False): - pass -del True - """ + code = """ + True = False + def hello(False): + pass + del True + """ if sys.version_info >= (3, 0): - self.assertRaises(SyntaxError,#might become AstroidBuildingException - abuilder.string_build, code) + with self.assertRaises(SyntaxError): + test_utils.build_module(code) else: - ast = abuilder.string_build(code) + ast = test_utils.build_module(code) ass_true = ast['True'] self.assertIsInstance(ass_true, nodes.AssName) self.assertEqual(ass_true.name, "True") @@ -388,10 +411,10 @@ del True class ArgumentsNodeTC(unittest.TestCase): def test_linenumbering(self): - ast = abuilder.string_build(''' -def func(a, - b): pass -x = lambda x: None + ast = test_utils.build_module(''' + def func(a, + b): pass + x = lambda x: None ''') self.assertEqual(ast['func'].args.fromlineno, 2) self.assertFalse(ast['func'].args.is_statement) @@ -406,36 +429,6 @@ x = lambda x: None '(no line number on function args)') -class SliceNodeTC(unittest.TestCase): - def test(self): - for code in ('a[0]', 'a[1:3]', 'a[:-1:step]', 'a[:,newaxis]', - 'a[newaxis,:]', 'del L[::2]', 'del A[1]', 'del Br[:]'): - ast = abuilder.string_build(code).body[0] - self.assertEqual(ast.as_string(), code) - - def test_slice_and_subscripts(self): - code = """a[:1] = bord[2:] -a[:1] = bord[2:] -del bree[3:d] -bord[2:] -del av[d::f], a[df:] -a[:1] = bord[2:] -del SRC[::1,newaxis,1:] -tous[vals] = 1010 -del thousand[key] -del a[::2], a[:-1:step] -del Fee.form[left:] -aout.vals = miles.of_stuff -del (ccok, (name.thing, foo.attrib.value)), Fee.form[left:] -if all[1] == bord[0:]: - pass\n\n""" - ast = abuilder.string_build(code) - self.assertEqual(ast.as_string(), code) - -class EllipsisNodeTC(unittest.TestCase): - def test(self): - ast = abuilder.string_build('a[...]').body[0] - self.assertEqual(ast.as_string(), 'a[...]') if __name__ == '__main__': unittest.main() diff --git a/astroid/tests/unittest_regrtest.py b/astroid/tests/unittest_regrtest.py index b38c3cbe..dcc4d2cf 100644 --- a/astroid/tests/unittest_regrtest.py +++ b/astroid/tests/unittest_regrtest.py @@ -24,12 +24,12 @@ from astroid.builder import AstroidBuilder from astroid.raw_building import build_module from astroid.manager import AstroidManager from astroid.test_utils import require_version +from astroid.tests import resources - -class NonRegressionTC(unittest.TestCase): +class NonRegressionTests(unittest.TestCase): def setUp(self): - sys.path.insert(0, join(dirname(abspath(__file__)), 'regrtest_data')) + sys.path.insert(0, resources.find('data')) def tearDown(self): # Since we may have created a brainless manager, leading @@ -37,6 +37,7 @@ class NonRegressionTC(unittest.TestCase): # clear out the global manager cache. MANAGER.clear_cache() sys.path.pop(0) + sys.path_importer_cache.pop(resources.find('data'), None) def brainless_manager(self): manager = AstroidManager() diff --git a/astroid/tests/unittest_scoped_nodes.py b/astroid/tests/unittest_scoped_nodes.py index 1b34c36a..0fd9e91e 100644 --- a/astroid/tests/unittest_scoped_nodes.py +++ b/astroid/tests/unittest_scoped_nodes.py @@ -18,33 +18,17 @@ """tests for specific behaviour of astroid scoped nodes (i.e. module, class and function) """ +import os import sys -from os.path import join, abspath, dirname from functools import partial -from textwrap import dedent import unittest from astroid import YES, builder, nodes, scoped_nodes, \ InferenceError, NotFoundError, NoDefault from astroid.bases import BUILTINS, Instance, BoundMethod, UnboundMethod -from astroid.test_utils import extract_node, require_version +from astroid import test_utils +from astroid.tests import resources -abuilder = builder.AstroidBuilder() -PY3K = sys.version_info >= (3, 0) - -if PY3K: - DATA = join(dirname(abspath(__file__)), 'data_py3') - import data_py3 as data -else: - DATA = join(dirname(abspath(__file__)), 'data') - import data - -REGRTEST_DATA = join(dirname(abspath(__file__)), 'regrtest_data') -MODULE = abuilder.file_build(join(DATA, 'module.py'), 'data.module') -MODULE2 = abuilder.file_build(join(DATA, 'module2.py'), 'data.module2') -NONREGR = abuilder.file_build(join(DATA, 'nonregr.py'), 'data.nonregr') - -PACK = abuilder.file_build(join(DATA, '__init__.py'), 'data') def _test_dict_interface(self, node, test_attr): self.assertIs(node[test_attr], node[test_attr]) @@ -55,82 +39,88 @@ def _test_dict_interface(self, node, test_attr): iter(node) -class ModuleNodeTC(unittest.TestCase): +class ModuleLoader(resources.SysPathSetup): + def setUp(self): + super(ModuleLoader, self).setUp() + self.module = resources.build_file('data/module.py', 'data.module') + self.module2 = resources.build_file('data/module2.py', 'data.module2') + self.nonregr = resources.build_file('data/nonregr.py', 'data.nonregr') + self.pack = resources.build_file('data/__init__.py', 'data') + + +class ModuleNodeTest(ModuleLoader, unittest.TestCase): def test_special_attributes(self): - self.assertEqual(len(MODULE.getattr('__name__')), 1) - self.assertIsInstance(MODULE.getattr('__name__')[0], nodes.Const) - self.assertEqual(MODULE.getattr('__name__')[0].value, 'data.module') - self.assertEqual(len(MODULE.getattr('__doc__')), 1) - self.assertIsInstance(MODULE.getattr('__doc__')[0], nodes.Const) - self.assertEqual(MODULE.getattr('__doc__')[0].value, 'test module for astroid\n') - self.assertEqual(len(MODULE.getattr('__file__')), 1) - self.assertIsInstance(MODULE.getattr('__file__')[0], nodes.Const) - self.assertEqual(MODULE.getattr('__file__')[0].value, join(DATA, 'module.py')) - self.assertEqual(len(MODULE.getattr('__dict__')), 1) - self.assertIsInstance(MODULE.getattr('__dict__')[0], nodes.Dict) - self.assertRaises(NotFoundError, MODULE.getattr, '__path__') - self.assertEqual(len(PACK.getattr('__path__')), 1) - self.assertIsInstance(PACK.getattr('__path__')[0], nodes.List) + self.assertEqual(len(self.module.getattr('__name__')), 1) + self.assertIsInstance(self.module.getattr('__name__')[0], nodes.Const) + self.assertEqual(self.module.getattr('__name__')[0].value, 'data.module') + self.assertEqual(len(self.module.getattr('__doc__')), 1) + self.assertIsInstance(self.module.getattr('__doc__')[0], nodes.Const) + self.assertEqual(self.module.getattr('__doc__')[0].value, 'test module for astroid\n') + self.assertEqual(len(self.module.getattr('__file__')), 1) + self.assertIsInstance(self.module.getattr('__file__')[0], nodes.Const) + self.assertEqual(self.module.getattr('__file__')[0].value, + os.path.abspath(resources.find('data/module.py'))) + self.assertEqual(len(self.module.getattr('__dict__')), 1) + self.assertIsInstance(self.module.getattr('__dict__')[0], nodes.Dict) + self.assertRaises(NotFoundError, self.module.getattr, '__path__') + self.assertEqual(len(self.pack.getattr('__path__')), 1) + self.assertIsInstance(self.pack.getattr('__path__')[0], nodes.List) def test_dict_interface(self): - _test_dict_interface(self, MODULE, 'YO') + _test_dict_interface(self, self.module, 'YO') def test_getattr(self): - yo = MODULE.getattr('YO')[0] + yo = self.module.getattr('YO')[0] self.assertIsInstance(yo, nodes.Class) self.assertEqual(yo.name, 'YO') - red = next(MODULE.igetattr('redirect')) + red = next(self.module.igetattr('redirect')) self.assertIsInstance(red, nodes.Function) self.assertEqual(red.name, 'four_args') - pb = next(MODULE.igetattr('pb')) + pb = next(self.module.igetattr('pb')) self.assertIsInstance(pb, nodes.Class) self.assertEqual(pb.name, 'ProgressBar') # resolve packageredirection - sys.path.insert(1, DATA) - mod = abuilder.file_build(join(DATA, 'appl/myConnection.py'), - 'appl.myConnection') - try: - ssl = next(mod.igetattr('SSL1')) - cnx = next(ssl.igetattr('Connection')) - self.assertEqual(cnx.__class__, nodes.Class) - self.assertEqual(cnx.name, 'Connection') - self.assertEqual(cnx.root().name, 'SSL1.Connection1') - finally: - del sys.path[1] - self.assertEqual(len(NONREGR.getattr('enumerate')), 2) + mod = resources.build_file('data/appl/myConnection.py', + 'data.appl.myConnection') + ssl = next(mod.igetattr('SSL1')) + cnx = next(ssl.igetattr('Connection')) + self.assertEqual(cnx.__class__, nodes.Class) + self.assertEqual(cnx.name, 'Connection') + self.assertEqual(cnx.root().name, 'data.SSL1.Connection1') + self.assertEqual(len(self.nonregr.getattr('enumerate')), 2) # raise ResolveError - self.assertRaises(InferenceError, MODULE.igetattr, 'YOAA') + self.assertRaises(InferenceError, self.nonregr.igetattr, 'YOAA') def test_wildard_import_names(self): - m = abuilder.file_build(join(DATA, 'all.py'), 'all') + m = resources.build_file('data/all.py', 'all') self.assertEqual(m.wildcard_import_names(), ['Aaa', '_bla', 'name']) - m = abuilder.file_build(join(DATA, 'notall.py'), 'notall') + m = resources.build_file('data/notall.py', 'notall') res = sorted(m.wildcard_import_names()) self.assertEqual(res, ['Aaa', 'func', 'name', 'other']) - m = abuilder.string_build(dedent(''' - from missing import tzop - trop = "test" - __all__ = (trop, "test1", tzop, 42) - ''')) + m = test_utils.build_module(''' + from missing import tzop + trop = "test" + __all__ = (trop, "test1", tzop, 42) + ''') res = sorted(m.wildcard_import_names()) self.assertEqual(res, ["test", "test1"]) - m = abuilder.string_build(dedent(''' - test = tzop = 42 - __all__ = ('test', ) + ('tzop', ) - ''')) + m = test_utils.build_module(''' + test = tzop = 42 + __all__ = ('test', ) + ('tzop', ) + ''') res = sorted(m.wildcard_import_names()) self.assertEqual(res, ['test', 'tzop']) def test_module_getattr(self): data = ''' -appli = application -appli += 2 -del appli + appli = application + appli += 2 + del appli ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data, __name__) # test del statement not returned by getattr self.assertEqual(len(astroid.getattr('appli')), 2, astroid.getattr('appli')) @@ -161,8 +151,8 @@ del appli def test_import_1(self): data = '''from . import subpackage''' - astroid = abuilder.string_build(data, 'package', join(REGRTEST_DATA, 'package', '__init__.py')) - sys.path.insert(1, REGRTEST_DATA) + sys.path.insert(0, resources.find('data')) + astroid = test_utils.build_module(data, 'package', 'data/package/__init__.py') try: m = astroid.import_module('', level=1) self.assertEqual(m.name, 'package') @@ -170,13 +160,13 @@ del appli self.assertEqual(len(infered), 1) self.assertEqual(infered[0].name, 'package.subpackage') finally: - del sys.path[1] + del sys.path[0] def test_import_2(self): data = '''from . import subpackage as pouet''' - astroid = abuilder.string_build(data, 'package', join(dirname(abspath(__file__)), 'regrtest_data', 'package', '__init__.py')) - sys.path.insert(1, REGRTEST_DATA) + astroid = test_utils.build_module(data, 'package', 'data/package/__init__.py') + sys.path.insert(0, resources.find('data')) try: m = astroid.import_module('', level=1) self.assertEqual(m.name, 'package') @@ -184,39 +174,39 @@ del appli self.assertEqual(len(infered), 1) self.assertEqual(infered[0].name, 'package.subpackage') finally: - del sys.path[1] + del sys.path[0] def test_file_stream_in_memory(self): data = '''irrelevant_variable is irrelevant''' - astroid = abuilder.string_build(data, 'in_memory') + astroid = test_utils.build_module(data, 'in_memory') self.assertEqual(astroid.file_stream.read().decode(), data) def test_file_stream_physical(self): - path = join(DATA, 'all.py') - astroid = abuilder.file_build(path, 'all') + path = resources.find('data/all.py') + astroid = builder.AstroidBuilder().file_build(path, 'all') with open(path, 'rb') as file_io: self.assertEqual(astroid.file_stream.read(), file_io.read()) -class FunctionNodeTC(unittest.TestCase): +class FunctionNodeTest(ModuleLoader, unittest.TestCase): def test_special_attributes(self): - func = MODULE2['make_class'] + func = self.module2['make_class'] self.assertEqual(len(func.getattr('__name__')), 1) self.assertIsInstance(func.getattr('__name__')[0], nodes.Const) self.assertEqual(func.getattr('__name__')[0].value, 'make_class') self.assertEqual(len(func.getattr('__doc__')), 1) self.assertIsInstance(func.getattr('__doc__')[0], nodes.Const) self.assertEqual(func.getattr('__doc__')[0].value, 'check base is correctly resolved to Concrete0') - self.assertEqual(len(MODULE.getattr('__dict__')), 1) - self.assertIsInstance(MODULE.getattr('__dict__')[0], nodes.Dict) + self.assertEqual(len(self.module.getattr('__dict__')), 1) + self.assertIsInstance(self.module.getattr('__dict__')[0], nodes.Dict) def test_dict_interface(self): - _test_dict_interface(self, MODULE['global_access'], 'local') + _test_dict_interface(self, self.module['global_access'], 'local') def test_default_value(self): - func = MODULE2['make_class'] + func = self.module2['make_class'] self.assertIsInstance(func.args.default_value('base'), nodes.Getattr) self.assertRaises(NoDefault, func.args.default_value, 'args') self.assertRaises(NoDefault, func.args.default_value, 'kwargs') @@ -226,7 +216,7 @@ class FunctionNodeTC(unittest.TestCase): #self.assertIsNone(func.mularg_class('base')) def test_navigation(self): - function = MODULE['global_access'] + function = self.module['global_access'] self.assertEqual(function.statement(), function) l_sibling = function.previous_sibling() # check taking parent if child is not a stmt @@ -247,113 +237,110 @@ class FunctionNodeTC(unittest.TestCase): if sys.version_info >= (3, 0): self.skipTest("nested args has been removed in py3.x") code = ''' -def nested_args(a, (b, c, d)): - "nested arguments test" + def nested_args(a, (b, c, d)): + "nested arguments test" ''' - tree = abuilder.string_build(code) + tree = test_utils.build_module(code) func = tree['nested_args'] self.assertEqual(sorted(func.locals), ['a', 'b', 'c', 'd']) self.assertEqual(func.args.format_args(), 'a, (b, c, d)') def test_four_args(self): - func = MODULE['four_args'] + func = self.module['four_args'] #self.assertEqual(func.args.args, ['a', ('b', 'c', 'd')]) local = sorted(func.keys()) self.assertEqual(local, ['a', 'b', 'c', 'd']) self.assertEqual(func.type, 'function') def test_format_args(self): - func = MODULE2['make_class'] + func = self.module2['make_class'] self.assertEqual(func.args.format_args(), - 'any, base=%s.module.YO, *args, **kwargs' % (data.__name__,)) - func = MODULE['four_args'] + 'any, base=data.module.YO, *args, **kwargs') + func = self.module['four_args'] self.assertEqual(func.args.format_args(), 'a, b, c, d') def test_is_generator(self): - self.assertTrue(MODULE2['generator'].is_generator()) - self.assertFalse(MODULE2['not_a_generator'].is_generator()) - self.assertFalse(MODULE2['make_class'].is_generator()) + self.assertTrue(self.module2['generator'].is_generator()) + self.assertFalse(self.module2['not_a_generator'].is_generator()) + self.assertFalse(self.module2['make_class'].is_generator()) def test_is_abstract(self): - method = MODULE2['AbstractClass']['to_override'] + method = self.module2['AbstractClass']['to_override'] self.assertTrue(method.is_abstract(pass_is_abstract=False)) self.assertEqual(method.qname(), 'data.module2.AbstractClass.to_override') self.assertEqual(method.pytype(), '%s.instancemethod' % BUILTINS) - method = MODULE2['AbstractClass']['return_something'] + method = self.module2['AbstractClass']['return_something'] self.assertFalse(method.is_abstract(pass_is_abstract=False)) # non regression : test raise "string" doesn't cause an exception in is_abstract - func = MODULE2['raise_string'] + func = self.module2['raise_string'] self.assertFalse(func.is_abstract(pass_is_abstract=False)) def test_is_abstract_decorated(self): - methods = extract_node(""" - import abc - - class Klass(object): - @abc.abstractproperty - def prop(self): #@ - pass - - @abc.abstractmethod - def method1(self): #@ - pass - - some_other_decorator = lambda x: x - @some_other_decorator - def method2(self): #@ - pass - + methods = test_utils.extract_node(""" + import abc + + class Klass(object): + @abc.abstractproperty + def prop(self): #@ + pass + + @abc.abstractmethod + def method1(self): #@ + pass + + some_other_decorator = lambda x: x + @some_other_decorator + def method2(self): #@ + pass """) self.assertTrue(methods[0].is_abstract(pass_is_abstract=False)) self.assertTrue(methods[1].is_abstract(pass_is_abstract=False)) self.assertFalse(methods[2].is_abstract(pass_is_abstract=False)) ## def test_raises(self): -## method = MODULE2['AbstractClass']['to_override'] +## method = self.module2['AbstractClass']['to_override'] ## self.assertEqual([str(term) for term in method.raises()], ## ["CallFunc(Name('NotImplementedError'), [], None, None)"] ) ## def test_returns(self): -## method = MODULE2['AbstractClass']['return_something'] +## method = self.module2['AbstractClass']['return_something'] ## # use string comp since Node doesn't handle __cmp__ ## self.assertEqual([str(term) for term in method.returns()], ## ["Const('toto')", "Const(None)"]) def test_lambda_pytype(self): data = ''' -def f(): - g = lambda: None + def f(): + g = lambda: None ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data) g = list(astroid['f'].ilookup('g'))[0] self.assertEqual(g.pytype(), '%s.function' % BUILTINS) def test_lambda_qname(self): - astroid = abuilder.string_build(''' -lmbd = lambda: None -''', __name__, __file__) + astroid = test_utils.build_module('lmbd = lambda: None', __name__) self.assertEqual('%s.<lambda>' % __name__, astroid['lmbd'].parent.value.qname()) def test_is_method(self): data = ''' -class A: - def meth1(self): - return 1 - @classmethod - def meth2(cls): - return 2 - @staticmethod - def meth3(): - return 3 - -def function(): - return 0 - -@staticmethod -def sfunction(): - return -1 + class A: + def meth1(self): + return 1 + @classmethod + def meth2(cls): + return 2 + @staticmethod + def meth3(): + return 3 + + def function(): + return 0 + + @staticmethod + def sfunction(): + return -1 ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data) self.assertTrue(astroid['A']['meth1'].is_method()) self.assertTrue(astroid['A']['meth2'].is_method()) self.assertTrue(astroid['A']['meth3'].is_method()) @@ -365,18 +352,18 @@ def sfunction(): code = 'def f(a, (b, c), *args, **kwargs): pass' else: code = 'def f(a, b, c, *args, **kwargs): pass' - astroid = abuilder.string_build(code, __name__, __file__) + astroid = test_utils.build_module(code, __name__) self.assertEqual(astroid['f'].argnames(), ['a', 'b', 'c', 'args', 'kwargs']) def test_return_nothing(self): """test infered value on a function with empty return""" data = ''' -def func(): - return + def func(): + return -a = func() -''' - astroid = abuilder.string_build(data, __name__, __file__) + a = func() + ''' + astroid = test_utils.build_module(data) call = astroid.body[1].value func_vals = call.infered() self.assertEqual(len(func_vals), 1) @@ -386,13 +373,13 @@ a = func() def test_func_instance_attr(self): """test instance attributes for functions""" data= """ -def test(): - print(test.bar) + def test(): + print(test.bar) -test.bar = 1 -test() + test.bar = 1 + test() """ - astroid = abuilder.string_build(data, 'mod', __file__) + astroid = test_utils.build_module(data, 'mod') func = astroid.body[2].value.func.infered()[0] self.assertIsInstance(func, nodes.Function) self.assertEqual(func.name, 'test') @@ -401,26 +388,26 @@ test() self.assertEqual(one.value, 1) def test_type_builtin_descriptor_subclasses(self): - astroid = abuilder.string_build(dedent(""" - class classonlymethod(classmethod): - pass - class staticonlymethod(staticmethod): - pass - - class Node: - @classonlymethod - def clsmethod_subclass(cls): + astroid = test_utils.build_module(""" + class classonlymethod(classmethod): pass - @classmethod - def clsmethod(cls): + class staticonlymethod(staticmethod): pass - @staticonlymethod - def staticmethod_subclass(cls): - pass - @staticmethod - def stcmethod(cls): - pass - """)) + + class Node: + @classonlymethod + def clsmethod_subclass(cls): + pass + @classmethod + def clsmethod(cls): + pass + @staticonlymethod + def staticmethod_subclass(cls): + pass + @staticmethod + def stcmethod(cls): + pass + """) node = astroid.locals['Node'][0] self.assertEqual(node.locals['clsmethod_subclass'][0].type, 'classmethod') @@ -432,36 +419,35 @@ test() 'staticmethod') def test_decorator_builtin_descriptors(self): - astroid = abuilder.string_build(dedent(""" - def static_decorator(platform=None, order=50): - def wrapper(f): - f.cgm_module = True - f.cgm_module_order = order - f.cgm_module_platform = platform - return staticmethod(f) - return wrapper - - def classmethod_decorator(platform=None): - def wrapper(f): - f.platform = platform - return classmethod(f) - return wrapper - - class SomeClass(object): - @static_decorator() - def static(node, cfg): - pass - @classmethod_decorator() - def classmethod(cls): - pass - @static_decorator - def not_so_static(node): - pass - @classmethod_decorator - def not_so_classmethod(node): - pass - - """)) + astroid = test_utils.build_module(""" + def static_decorator(platform=None, order=50): + def wrapper(f): + f.cgm_module = True + f.cgm_module_order = order + f.cgm_module_platform = platform + return staticmethod(f) + return wrapper + + def classmethod_decorator(platform=None): + def wrapper(f): + f.platform = platform + return classmethod(f) + return wrapper + + class SomeClass(object): + @static_decorator() + def static(node, cfg): + pass + @classmethod_decorator() + def classmethod(cls): + pass + @static_decorator + def not_so_static(node): + pass + @classmethod_decorator + def not_so_classmethod(node): + pass + """) node = astroid.locals['SomeClass'][0] self.assertEqual(node.locals['static'][0].type, 'staticmethod') @@ -473,13 +459,13 @@ test() 'method') -class ClassNodeTC(unittest.TestCase): +class ClassNodeTest(ModuleLoader, unittest.TestCase): def test_dict_interface(self): - _test_dict_interface(self, MODULE['YOUPI'], 'method') + _test_dict_interface(self, self.module['YOUPI'], 'method') def test_cls_special_attributes_1(self): - cls = MODULE['YO'] + cls = self.module['YO'] self.assertEqual(len(cls.getattr('__bases__')), 1) self.assertEqual(len(cls.getattr('__name__')), 1) self.assertIsInstance(cls.getattr('__name__')[0], nodes.Const) @@ -503,18 +489,18 @@ class ClassNodeTC(unittest.TestCase): self.assertEqual(len(cls.getattr('__mro__')), 1) def test_cls_special_attributes_2(self): - astroid = abuilder.string_build(''' -class A: pass -class B: pass + astroid = test_utils.build_module(''' + class A: pass + class B: pass -A.__bases__ += (B,) -''', __name__, __file__) + A.__bases__ += (B,) + ''', __name__) self.assertEqual(len(astroid['A'].getattr('__bases__')), 2) self.assertIsInstance(astroid['A'].getattr('__bases__')[0], nodes.Tuple) self.assertIsInstance(astroid['A'].getattr('__bases__')[1], nodes.AssAttr) def test_instance_special_attributes(self): - for inst in (Instance(MODULE['YO']), nodes.List(), nodes.Const(1)): + for inst in (Instance(self.module['YO']), nodes.List(), nodes.Const(1)): self.assertRaises(NotFoundError, inst.getattr, '__mro__') self.assertRaises(NotFoundError, inst.getattr, '__bases__') self.assertRaises(NotFoundError, inst.getattr, '__name__') @@ -522,7 +508,7 @@ A.__bases__ += (B,) self.assertEqual(len(inst.getattr('__doc__')), 1) def test_navigation(self): - klass = MODULE['YO'] + klass = self.module['YO'] self.assertEqual(klass.statement(), klass) l_sibling = klass.previous_sibling() self.assertTrue(isinstance(l_sibling, nodes.Function), l_sibling) @@ -532,7 +518,7 @@ A.__bases__ += (B,) self.assertEqual(r_sibling.name, 'YOUPI') def test_local_attr_ancestors(self): - klass2 = MODULE['YOUPI'] + klass2 = self.module['YOUPI'] it = klass2.local_attr_ancestors('__init__') anc_klass = next(it) self.assertIsInstance(anc_klass, nodes.Class) @@ -542,18 +528,18 @@ A.__bases__ += (B,) self.assertRaises(StopIteration, partial(next, it)) def test_instance_attr_ancestors(self): - klass2 = MODULE['YOUPI'] + klass2 = self.module['YOUPI'] it = klass2.instance_attr_ancestors('yo') anc_klass = next(it) self.assertIsInstance(anc_klass, nodes.Class) self.assertEqual(anc_klass.name, 'YO') self.assertRaises(StopIteration, partial(next, it)) - klass2 = MODULE['YOUPI'] + klass2 = self.module['YOUPI'] it = klass2.instance_attr_ancestors('member') self.assertRaises(StopIteration, partial(next, it)) def test_methods(self): - klass2 = MODULE['YOUPI'] + klass2 = self.module['YOUPI'] methods = sorted([m.name for m in klass2.methods()]) self.assertEqual(methods, ['__init__', 'class_method', 'method', 'static_method']) @@ -561,7 +547,7 @@ A.__bases__ += (B,) methods.sort() self.assertEqual(methods, ['__init__', 'class_method', 'method', 'static_method']) - klass2 = MODULE2['Specialization'] + klass2 = self.module2['Specialization'] methods = [m.name for m in klass2.mymethods()] methods.sort() self.assertEqual(methods, []) @@ -575,36 +561,36 @@ A.__bases__ += (B,) 'method', 'static_method']) #def test_rhs(self): - # my_dict = MODULE['MY_DICT'] + # my_dict = self.module['MY_DICT'] # self.assertIsInstance(my_dict.rhs(), nodes.Dict) - # a = MODULE['YO']['a'] + # a = self.module['YO']['a'] # value = a.rhs() # self.assertIsInstance(value, nodes.Const) # self.assertEqual(value.value, 1) def test_ancestors(self): - klass = MODULE['YOUPI'] + klass = self.module['YOUPI'] ancs = [a.name for a in klass.ancestors()] self.assertEqual(ancs, ['YO']) - klass = MODULE2['Specialization'] + klass = self.module2['Specialization'] ancs = [a.name for a in klass.ancestors()] self.assertEqual(ancs, ['YOUPI', 'YO']) def test_type(self): - klass = MODULE['YOUPI'] + klass = self.module['YOUPI'] self.assertEqual(klass.type, 'class') - klass = MODULE2['Metaclass'] + klass = self.module2['Metaclass'] self.assertEqual(klass.type, 'metaclass') - klass = MODULE2['MyException'] + klass = self.module2['MyException'] self.assertEqual(klass.type, 'exception') - klass = MODULE2['MyIFace'] + klass = self.module2['MyIFace'] self.assertEqual(klass.type, 'interface') - klass = MODULE2['MyError'] + klass = self.module2['MyError'] self.assertEqual(klass.type, 'exception') # the following class used to be detected as a metaclass # after the fix which used instance._proxied in .ancestors(), # when in fact it is a normal class - klass = MODULE2['NotMetaclass'] + klass = self.module2['NotMetaclass'] self.assertEqual(klass.type, 'class') def test_interfaces(self): @@ -612,46 +598,45 @@ A.__bases__ += (B,) ('Concrete1', ['MyIFace', 'AnotherIFace']), ('Concrete2', ['MyIFace', 'AnotherIFace']), ('Concrete23', ['MyIFace', 'AnotherIFace'])): - klass = MODULE2[klass] + klass = self.module2[klass] self.assertEqual([i.name for i in klass.interfaces()], interfaces) def test_concat_interfaces(self): - astroid = abuilder.string_build(''' -class IMachin: pass - -class Correct2: - """docstring""" - __implements__ = (IMachin,) + astroid = test_utils.build_module(''' + class IMachin: pass -class BadArgument: - """docstring""" - __implements__ = (IMachin,) + class Correct2: + """docstring""" + __implements__ = (IMachin,) -class InterfaceCanNowBeFound: - """docstring""" - __implements__ = BadArgument.__implements__ + Correct2.__implements__ + class BadArgument: + """docstring""" + __implements__ = (IMachin,) + class InterfaceCanNowBeFound: + """docstring""" + __implements__ = BadArgument.__implements__ + Correct2.__implements__ ''') self.assertEqual([i.name for i in astroid['InterfaceCanNowBeFound'].interfaces()], ['IMachin']) def test_inner_classes(self): - eee = NONREGR['Ccc']['Eee'] + eee = self.nonregr['Ccc']['Eee'] self.assertEqual([n.name for n in eee.ancestors()], ['Ddd', 'Aaa', 'object']) def test_classmethod_attributes(self): data = ''' -class WebAppObject(object): - def registered(cls, application): - cls.appli = application - cls.schema = application.schema - cls.config = application.config - return cls - registered = classmethod(registered) + class WebAppObject(object): + def registered(cls, application): + cls.appli = application + cls.schema = application.schema + cls.config = application.config + return cls + registered = classmethod(registered) ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data, __name__) cls = astroid['WebAppObject'] self.assertEqual(sorted(cls.locals.keys()), ['appli', 'config', 'registered', 'schema']) @@ -659,26 +644,26 @@ class WebAppObject(object): def test_class_getattr(self): data = ''' -class WebAppObject(object): - appli = application - appli += 2 - del self.appli + class WebAppObject(object): + appli = application + appli += 2 + del self.appli ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data, __name__) cls = astroid['WebAppObject'] # test del statement not returned by getattr self.assertEqual(len(cls.getattr('appli')), 2) def test_instance_getattr(self): - data = ''' -class WebAppObject(object): - def __init__(self, application): - self.appli = application - self.appli += 2 - del self.appli + data = ''' + class WebAppObject(object): + def __init__(self, application): + self.appli = application + self.appli += 2 + del self.appli ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data) inst = Instance(astroid['WebAppObject']) # test del statement not returned by getattr self.assertEqual(len(inst.getattr('appli')), 2) @@ -686,23 +671,23 @@ class WebAppObject(object): def test_instance_getattr_with_class_attr(self): data = ''' -class Parent: - aa = 1 - cc = 1 - -class Klass(Parent): - aa = 0 - bb = 0 - - def incr(self, val): - self.cc = self.aa - if val > self.aa: - val = self.aa - if val < self.bb: - val = self.bb - self.aa += val + class Parent: + aa = 1 + cc = 1 + + class Klass(Parent): + aa = 0 + bb = 0 + + def incr(self, val): + self.cc = self.aa + if val > self.aa: + val = self.aa + if val < self.bb: + val = self.bb + self.aa += val ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data) inst = Instance(astroid['Klass']) self.assertEqual(len(inst.getattr('aa')), 3, inst.getattr('aa')) self.assertEqual(len(inst.getattr('bb')), 1, inst.getattr('bb')) @@ -711,21 +696,21 @@ class Klass(Parent): def test_getattr_method_transform(self): data = ''' -class Clazz(object): + class Clazz(object): - def m1(self, value): - self.value = value - m2 = m1 + def m1(self, value): + self.value = value + m2 = m1 -def func(arg1, arg2): - "function that will be used as a method" - return arg1.value + arg2 + def func(arg1, arg2): + "function that will be used as a method" + return arg1.value + arg2 -Clazz.m3 = func -inst = Clazz() -inst.m4 = func + Clazz.m3 = func + inst = Clazz() + inst.m4 = func ''' - astroid = abuilder.string_build(data, __name__, __file__) + astroid = test_utils.build_module(data) cls = astroid['Clazz'] # test del statement not returned by getattr for method in ('m1', 'm2', 'm3'): @@ -741,16 +726,16 @@ inst.m4 = func def test_getattr_from_grandpa(self): data = ''' -class Future: - attr = 1 + class Future: + attr = 1 -class Present(Future): - pass + class Present(Future): + pass -class Past(Present): - pass -''' - astroid = abuilder.string_build(data) + class Past(Present): + pass + ''' + astroid = test_utils.build_module(data) past = astroid['Past'] attr = past.getattr('attr') self.assertEqual(len(attr), 1) @@ -760,51 +745,48 @@ class Past(Present): def test_function_with_decorator_lineno(self): data = ''' -@f(a=2, - b=3) -def g1(x): - print(x) - -@f(a=2, - b=3) -def g2(): - pass -''' - astroid = abuilder.string_build(data) + @f(a=2, + b=3) + def g1(x): + print(x) + + @f(a=2, + b=3) + def g2(): + pass + ''' + astroid = test_utils.build_module(data) self.assertEqual(astroid['g1'].fromlineno, 4) self.assertEqual(astroid['g1'].tolineno, 5) self.assertEqual(astroid['g2'].fromlineno, 9) self.assertEqual(astroid['g2'].tolineno, 10) + @test_utils.require_version(maxver='3.0') def test_simple_metaclass(self): - if PY3K: - self.skipTest('__metaclass__ syntax is python2-specific') - astroid = abuilder.string_build(dedent(""" - class Test(object): - __metaclass__ = type - """)) + astroid = test_utils.build_module(""" + class Test(object): + __metaclass__ = type + """) klass = astroid['Test'] - metaclass = klass.metaclass() self.assertIsInstance(metaclass, scoped_nodes.Class) self.assertEqual(metaclass.name, 'type') def test_metaclass_error(self): - astroid = abuilder.string_build(dedent(""" - class Test(object): - __metaclass__ = typ - """)) + astroid = test_utils.build_module(""" + class Test(object): + __metaclass__ = typ + """) klass = astroid['Test'] self.assertFalse(klass.metaclass()) + @test_utils.require_version(maxver='3.0') def test_metaclass_imported(self): - if PY3K: - self.skipTest('__metaclass__ syntax is python2-specific') - astroid = abuilder.string_build(dedent(""" - from abc import ABCMeta - class Test(object): - __metaclass__ = ABCMeta - """)) + astroid = test_utils.build_module(""" + from abc import ABCMeta + class Test(object): + __metaclass__ = ABCMeta + """) klass = astroid['Test'] metaclass = klass.metaclass() @@ -812,51 +794,49 @@ def g2(): self.assertEqual(metaclass.name, 'ABCMeta') def test_metaclass_yes_leak(self): - astroid = abuilder.string_build(dedent(""" - # notice `ab` instead of `abc` - from ab import ABCMeta + astroid = test_utils.build_module(""" + # notice `ab` instead of `abc` + from ab import ABCMeta - class Meta(object): - __metaclass__ = ABCMeta - """)) + class Meta(object): + __metaclass__ = ABCMeta + """) klass = astroid['Meta'] self.assertIsNone(klass.metaclass()) + @test_utils.require_version(maxver='3.0') def test_newstyle_and_metaclass_good(self): - if PY3K: - self.skipTest('__metaclass__ syntax is python2-specific') - astroid = abuilder.string_build(dedent(""" - from abc import ABCMeta - class Test: - __metaclass__ = ABCMeta - """)) + astroid = test_utils.build_module(""" + from abc import ABCMeta + class Test: + __metaclass__ = ABCMeta + """) klass = astroid['Test'] self.assertTrue(klass.newstyle) self.assertEqual(klass.metaclass().name, 'ABCMeta') - astroid = abuilder.string_build(dedent(""" - from abc import ABCMeta - __metaclass__ = ABCMeta - class Test: - pass - """)) + astroid = test_utils.build_module(""" + from abc import ABCMeta + __metaclass__ = ABCMeta + class Test: + pass + """) klass = astroid['Test'] self.assertTrue(klass.newstyle) self.assertEqual(klass.metaclass().name, 'ABCMeta') + @test_utils.require_version(maxver='3.0') def test_nested_metaclass(self): - if PY3K: - self.skipTest('__metaclass__ syntax is python2-specific') - astroid = abuilder.string_build(dedent(""" - from abc import ABCMeta - class A(object): - __metaclass__ = ABCMeta - class B: pass + astroid = test_utils.build_module(""" + from abc import ABCMeta + class A(object): + __metaclass__ = ABCMeta + class B: pass - __metaclass__ = ABCMeta - class C: - __metaclass__ = type - class D: pass - """)) + __metaclass__ = ABCMeta + class C: + __metaclass__ = type + class D: pass + """) a = astroid['A'] b = a.locals['B'][0] c = astroid['C'] @@ -867,41 +847,39 @@ def g2(): self.assertEqual(c.metaclass().name, 'type') self.assertEqual(d.metaclass().name, 'ABCMeta') + @test_utils.require_version(maxver='3.0') def test_parent_metaclass(self): - if PY3K: - self.skipTest('__metaclass__ syntax is python2-specific') - astroid = abuilder.string_build(dedent(""" - from abc import ABCMeta - class Test: - __metaclass__ = ABCMeta - class SubTest(Test): pass - """)) + astroid = test_utils.build_module(""" + from abc import ABCMeta + class Test: + __metaclass__ = ABCMeta + class SubTest(Test): pass + """) klass = astroid['SubTest'] self.assertTrue(klass.newstyle) metaclass = klass.metaclass() self.assertIsInstance(metaclass, scoped_nodes.Class) self.assertEqual(metaclass.name, 'ABCMeta') + @test_utils.require_version(maxver='3.0') def test_metaclass_ancestors(self): - if PY3K: - self.skipTest('__metaclass__ syntax is python2-specific') - astroid = abuilder.string_build(dedent(""" - from abc import ABCMeta + astroid = test_utils.build_module(""" + from abc import ABCMeta - class FirstMeta(object): - __metaclass__ = ABCMeta + class FirstMeta(object): + __metaclass__ = ABCMeta - class SecondMeta(object): - __metaclass__ = type + class SecondMeta(object): + __metaclass__ = type - class Simple(object): - pass + class Simple(object): + pass - class FirstImpl(FirstMeta): pass - class SecondImpl(FirstImpl): pass - class ThirdImpl(Simple, SecondMeta): - pass - """)) + class FirstImpl(FirstMeta): pass + class SecondImpl(FirstImpl): pass + class ThirdImpl(Simple, SecondMeta): + pass + """) classes = { 'ABCMeta': ('FirstImpl', 'SecondImpl'), 'type': ('ThirdImpl', ) @@ -914,23 +892,23 @@ def g2(): self.assertEqual(meta.name, metaclass) def test_metaclass_type(self): - klass = extract_node(""" - def with_metaclass(meta, base=object): - return meta("NewBase", (base, ), {}) + klass = test_utils.extract_node(""" + def with_metaclass(meta, base=object): + return meta("NewBase", (base, ), {}) - class ClassWithMeta(with_metaclass(type)): #@ - pass + class ClassWithMeta(with_metaclass(type)): #@ + pass """) self.assertEqual( ['NewBase', 'object'], [base.name for base in klass.ancestors()]) def test_metaclass_generator_hack(self): - klass = extract_node(""" - import six + klass = test_utils.extract_node(""" + import six - class WithMeta(six.with_metaclass(type, object)): #@ - pass + class WithMeta(six.with_metaclass(type, object)): #@ + pass """) self.assertEqual( ['object'], @@ -939,44 +917,44 @@ def g2(): 'type', klass.metaclass().name) def test_nonregr_infer_callresult(self): - astroid = abuilder.string_build(dedent(""" - class Delegate(object): - def __get__(self, obj, cls): - return getattr(obj._subject, self.attribute) + astroid = test_utils.build_module(""" + class Delegate(object): + def __get__(self, obj, cls): + return getattr(obj._subject, self.attribute) - class CompositeBuilder(object): - __call__ = Delegate() + class CompositeBuilder(object): + __call__ = Delegate() - builder = CompositeBuilder(result, composite) - tgts = builder() - """)) + builder = CompositeBuilder(result, composite) + tgts = builder() + """) instance = astroid['tgts'] # used to raise "'_Yes' object is not iterable", see # https://bitbucket.org/logilab/astroid/issue/17 self.assertEqual(list(instance.infer()), [YES]) def test_slots(self): - astroid = abuilder.string_build(dedent(""" - from collections import deque - from textwrap import dedent - - class First(object): - __slots__ = ("a", "b", 1) - class Second(object): - __slots__ = "a" - class Third(object): - __slots__ = deque(["a", "b", "c"]) - class Fourth(object): - __slots__ = {"a": "a", "b": "b"} - class Fifth(object): - __slots__ = list - class Sixth(object): - __slots__ = "" - class Seventh(object): - __slots__ = dedent.__name__ - class Eight(object): - __slots__ = ("parens") - """)) + astroid = test_utils.build_module(""" + from collections import deque + from textwrap import dedent + + class First(object): + __slots__ = ("a", "b", 1) + class Second(object): + __slots__ = "a" + class Third(object): + __slots__ = deque(["a", "b", "c"]) + class Fourth(object): + __slots__ = {"a": "a", "b": "b"} + class Fifth(object): + __slots__ = list + class Sixth(object): + __slots__ = "" + class Seventh(object): + __slots__ = dedent.__name__ + class Eight(object): + __slots__ = ("parens") + """) first = astroid['First'] first_slots = first.slots() self.assertEqual(len(first_slots), 2) @@ -1015,7 +993,5 @@ def g2(): self.assertEqual(eight_slots[0].value, "parens") -__all__ = ('ModuleNodeTC', 'ImportNodeTC', 'FunctionNodeTC', 'ClassNodeTC') - if __name__ == '__main__': unittest.main() @@ -6,5 +6,4 @@ envlist = py27, py33 deps =
logilab-common
six
-changedir = {envsitepackagesdir}/astroid/tests
-commands = python -Wi -m unittest discover -p "unittest*.py"
+commands = python -Wi -m unittest discover -s {envsitepackagesdir}/astroid/tests -p "unittest*.py"
|