Remove a lot of sys.version_info references

This commit is contained in:
Dave Halter
2020-07-02 02:45:35 +02:00
parent cfd8eb23b8
commit f4e537fd72
18 changed files with 22 additions and 98 deletions

View File

@@ -152,12 +152,11 @@ def _load_module(inference_state, path):
def _get_object_to_check(python_object): def _get_object_to_check(python_object):
"""Check if inspect.getfile has a chance to find the source.""" """Check if inspect.getfile has a chance to find the source."""
if sys.version_info[0] > 2: try:
try: python_object = inspect.unwrap(python_object)
python_object = inspect.unwrap(python_object) except ValueError:
except ValueError: # Can return a ValueError when it wraps around
# Can return a ValueError when it wraps around pass
pass
if (inspect.ismodule(python_object) if (inspect.ismodule(python_object)
or inspect.isclass(python_object) or inspect.isclass(python_object)

View File

@@ -334,15 +334,8 @@ class Listener(object):
# because stdout is used for IPC. # because stdout is used for IPC.
sys.stdout = open(os.devnull, 'w') sys.stdout = open(os.devnull, 'w')
stdin = sys.stdin stdin = sys.stdin
if sys.version_info[0] > 2: stdout = stdout.buffer
stdout = stdout.buffer stdin = stdin.buffer
stdin = stdin.buffer
# Python 2 opens streams in text mode on Windows. Set stdout and stdin
# to binary mode.
elif sys.platform == 'win32':
import msvcrt
msvcrt.setmode(stdout.fileno(), os.O_BINARY)
msvcrt.setmode(stdin.fileno(), os.O_BINARY)
while True: while True:
try: try:

View File

@@ -2,8 +2,6 @@
Contains all classes and functions to deal with lists, dicts, generators and Contains all classes and functions to deal with lists, dicts, generators and
iterators in general. iterators in general.
""" """
import sys
from jedi.inference import compiled from jedi.inference import compiled
from jedi.inference import analysis from jedi.inference import analysis
from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \ from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \
@@ -31,14 +29,7 @@ class IterableMixin(object):
# doing this in the end as well. # doing this in the end as well.
# This mostly speeds up patterns like `sys.version_info >= (3, 0)` in # This mostly speeds up patterns like `sys.version_info >= (3, 0)` in
# typeshed. # typeshed.
if sys.version_info[0] == 2: get_safe_value = Value.get_safe_value
# Python 2...........
def get_safe_value(self, default=sentinel):
if default is sentinel:
raise ValueError("There exists no safe value for value %s" % self)
return default
else:
get_safe_value = Value.get_safe_value
class GeneratorBase(LazyAttributeOverwrite, IterableMixin): class GeneratorBase(LazyAttributeOverwrite, IterableMixin):

View File

@@ -8,7 +8,6 @@ from __future__ import with_statement
import os import os
import platform import platform
import re import re
import sys
from parso import split_lines from parso import split_lines
@@ -90,8 +89,6 @@ def _collect_file_tests(code, path, lines_to_execute):
def collect_dir_tests(base_dir, test_files): def collect_dir_tests(base_dir, test_files):
if sys.version_info[0] == 2:
return
for f_name in os.listdir(base_dir): for f_name in os.listdir(base_dir):
files_to_execute = [a for a in test_files.items() if a[0] in f_name] files_to_execute = [a for a in test_files.items() if a[0] in f_name]
lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, []) lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, [])

View File

@@ -1,10 +1,4 @@
import sys def test_issue436(Script):
import pytest
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_issue436(Script, skip_python2):
code = "bar = 0\nbar += 'foo' + 4" code = "bar = 0\nbar += 'foo' + 4"
errors = set(repr(e) for e in Script(code)._analysis()) errors = set(repr(e) for e in Script(code)._analysis())
assert len(errors) == 2 assert len(errors) == 2

View File

@@ -3,7 +3,6 @@ Test all things related to the ``jedi.api`` module.
""" """
import os import os
import sys
from textwrap import dedent from textwrap import dedent
import pytest import pytest
@@ -16,7 +15,6 @@ from jedi.inference.gradual import typeshed
from test.helpers import test_dir, get_example_dir from test.helpers import test_dir, get_example_dir
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, EoL")
def test_preload_modules(): def test_preload_modules():
def check_loaded(*modules): def check_loaded(*modules):
for grammar_cache in cache.parser_cache.values(): for grammar_cache in cache.parser_cache.values():
@@ -119,8 +117,8 @@ def test_completion_on_complex_literals(Script):
# However this has been disabled again, because it apparently annoyed # However this has been disabled again, because it apparently annoyed
# users. So no completion after j without a space :) # users. So no completion after j without a space :)
assert not Script('4j').complete() assert not Script('4j').complete()
assert ({c.name for c in Script('4j ').complete()} == assert ({c.name for c in Script('4j ').complete()}
{'if', 'and', 'in', 'is', 'not', 'or'}) == {'if', 'and', 'in', 'is', 'not', 'or'})
def test_goto_non_name(Script, environment): def test_goto_non_name(Script, environment):

View File

@@ -1,4 +1,3 @@
import sys
from textwrap import dedent from textwrap import dedent
import inspect import inspect
from unittest import TestCase from unittest import TestCase
@@ -515,7 +514,6 @@ def test_signature_index(skip_python2, Script, environment, code, call, expected
assert expected_index == index assert expected_index == index
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Python 2 doesn't support __signature__")
@pytest.mark.parametrize('code', ['foo', 'instance.foo']) @pytest.mark.parametrize('code', ['foo', 'instance.foo'])
def test_arg_defaults(Script, environment, code): def test_arg_defaults(Script, environment, code):
def foo(arg="bla", arg1=1): def foo(arg="bla", arg1=1):

View File

@@ -1,6 +1,5 @@
from os.path import join, sep as s, dirname, expanduser from os.path import join, sep as s, dirname, expanduser
import os import os
import sys
from textwrap import dedent from textwrap import dedent
import pytest import pytest
@@ -75,10 +74,7 @@ def test_loading_unicode_files_with_bad_global_charset(Script, monkeypatch, tmpd
dirname = str(tmpdir.mkdir('jedi-test')) dirname = str(tmpdir.mkdir('jedi-test'))
filename1 = join(dirname, 'test1.py') filename1 = join(dirname, 'test1.py')
filename2 = join(dirname, 'test2.py') filename2 = join(dirname, 'test2.py')
if sys.version_info < (3, 0): data = "# coding: latin-1\nfoo = 'm\xf6p'\n".encode("latin-1")
data = "# coding: latin-1\nfoo = 'm\xf6p'\n"
else:
data = "# coding: latin-1\nfoo = 'm\xf6p'\n".encode("latin-1")
with open(filename1, "wb") as f: with open(filename1, "wb") as f:
f.write(data) f.write(data)
@@ -372,7 +368,6 @@ _dict_keys_completion_tests = [
] ]
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize( @pytest.mark.parametrize(
'added_code, column, expected', _dict_keys_completion_tests 'added_code, column, expected', _dict_keys_completion_tests
) )
@@ -398,7 +393,6 @@ def test_dict_keys_completions(Script, added_code, column, expected):
assert [c.complete for c in comps] == expected assert [c.complete for c in comps] == expected
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_dict_keys_in_weird_case(Script): def test_dict_keys_in_weird_case(Script):
assert Script('a[\n# foo\nx]').complete(line=2, column=0) assert Script('a[\n# foo\nx]').complete(line=2, column=0)

View File

@@ -117,7 +117,6 @@ def test_create_environment_executable():
assert environment.executable == sys.executable assert environment.executable == sys.executable
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_get_default_environment_from_env_does_not_use_safe(tmpdir, monkeypatch): def test_get_default_environment_from_env_does_not_use_safe(tmpdir, monkeypatch):
fake_python = os.path.join(str(tmpdir), 'fake_python') fake_python = os.path.join(str(tmpdir), 'fake_python')
with open(fake_python, 'w', newline='') as f: with open(fake_python, 'w', newline='') as f:

View File

@@ -184,7 +184,6 @@ def test_property_warnings(stacklevel, allow_unsafe_getattr):
_assert_interpreter_complete('foo.prop.uppe', locals(), expected) _assert_interpreter_complete('foo.prop.uppe', locals(), expected)
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize('class_is_findable', [False, True]) @pytest.mark.parametrize('class_is_findable', [False, True])
def test__getattr__completions(allow_unsafe_getattr, class_is_findable): def test__getattr__completions(allow_unsafe_getattr, class_is_findable):
class CompleteGetattr(object): class CompleteGetattr(object):
@@ -275,7 +274,6 @@ def test_property_content():
assert def_.name == 'int' assert def_.name == 'int'
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_param_completion(): def test_param_completion():
def foo(bar): def foo(bar):
pass pass
@@ -326,7 +324,6 @@ def test_completion_param_annotations():
assert d.name == 'bytes' assert d.name == 'bytes'
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_keyword_argument(): def test_keyword_argument():
def f(some_keyword_argument): def f(some_keyword_argument):
pass pass
@@ -433,7 +430,6 @@ def test_sys_path_docstring(): # Was an issue in #1298
s.complete(line=2, column=4)[0].docstring() s.complete(line=2, column=4)[0].docstring()
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize( @pytest.mark.parametrize(
'code, completions', [ 'code, completions', [
('x[0].uppe', ['upper']), ('x[0].uppe', ['upper']),
@@ -479,7 +475,6 @@ def test_simple_completions(code, completions):
assert [d.name for d in defs] == completions assert [d.name for d in defs] == completions
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Python 2 doesn't have lru_cache")
def test__wrapped__(): def test__wrapped__():
from functools import lru_cache from functools import lru_cache
@@ -492,7 +487,6 @@ def test__wrapped__():
assert c.line == syslogs_to_df.__wrapped__.__code__.co_firstlineno + 1 assert c.line == syslogs_to_df.__wrapped__.__code__.co_firstlineno + 1
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_illegal_class_instance(): def test_illegal_class_instance():
class X: class X:
__class__ = 1 __class__ = 1
@@ -502,14 +496,12 @@ def test_illegal_class_instance():
assert not v.is_instance() assert not v.is_instance()
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize('module_name', ['sys', 'time', 'unittest.mock']) @pytest.mark.parametrize('module_name', ['sys', 'time', 'unittest.mock'])
def test_core_module_completes(module_name): def test_core_module_completes(module_name):
module = import_module(module_name) module = import_module(module_name)
assert jedi.Interpreter('module.', [locals()]).complete() assert jedi.Interpreter('module.', [locals()]).complete()
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize( @pytest.mark.parametrize(
'code, expected, index', [ 'code, expected, index', [
('a(', ['a', 'b', 'c'], 0), ('a(', ['a', 'b', 'c'], 0),
@@ -535,7 +527,6 @@ def test_partial_signatures(code, expected, index):
assert index == sig.index assert index == sig.index
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_type_var(): def test_type_var():
"""This was an issue before, see Github #1369""" """This was an issue before, see Github #1369"""
import typing import typing
@@ -544,7 +535,6 @@ def test_type_var():
assert def_.name == 'TypeVar' assert def_.name == 'TypeVar'
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize('class_is_findable', [False, True]) @pytest.mark.parametrize('class_is_findable', [False, True])
def test_param_annotation_completion(class_is_findable): def test_param_annotation_completion(class_is_findable):
class Foo: class Foo:
@@ -558,7 +548,6 @@ def test_param_annotation_completion(class_is_findable):
assert def_.name == 'bar' assert def_.name == 'bar'
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize( @pytest.mark.parametrize(
'code, column, expected', [ 'code, column, expected', [
('strs[', 5, ["'asdf'", "'fbar'", "'foo'", Ellipsis]), ('strs[', 5, ["'asdf'", "'fbar'", "'foo'", Ellipsis]),
@@ -589,7 +578,6 @@ def test_dict_completion(code, column, expected):
assert [c.complete for c in comps] == expected assert [c.complete for c in comps] == expected
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize( @pytest.mark.parametrize(
'code, types', [ 'code, types', [
('dct[1]', ['int']), ('dct[1]', ['int']),

View File

@@ -1,5 +1,4 @@
import os import os
import sys
import pytest import pytest
@@ -133,7 +132,6 @@ def test_load_save_project(tmpdir):
('multiprocessin', ['multiprocessing'], dict(complete=True)), ('multiprocessin', ['multiprocessing'], dict(complete=True)),
] ]
) )
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Ignore Python 2, because EOL")
def test_search(string, full_names, kwargs): def test_search(string, full_names, kwargs):
some_search_test_var = 1.0 some_search_test_var = 1.0
project = Project(test_dir) project = Project(test_dir)
@@ -152,7 +150,6 @@ def test_search(string, full_names, kwargs):
('test_load_save_p', ['roject'], False), ('test_load_save_p', ['roject'], False),
] ]
) )
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Ignore Python 2, because EOL")
def test_complete_search(Script, string, completions, all_scopes): def test_complete_search(Script, string, completions, all_scopes):
project = Project(test_dir) project = Project(test_dir)
defs = project.complete_search(string, all_scopes=all_scopes) defs = project.complete_search(string, all_scopes=all_scopes)

View File

@@ -66,9 +66,6 @@ class SomeClass:
] ]
) )
def test_simple_search(Script, string, descriptions, kwargs): def test_simple_search(Script, string, descriptions, kwargs):
if sys.version_info < (3, 6):
pytest.skip()
if kwargs.pop('complete', False) is True: if kwargs.pop('complete', False) is True:
defs = Script(path=__file__).complete_search(string, **kwargs) defs = Script(path=__file__).complete_search(string, **kwargs)
else: else:

View File

@@ -1,6 +1,5 @@
from textwrap import dedent from textwrap import dedent
import math import math
import sys
from collections import Counter from collections import Counter
from datetime import datetime from datetime import datetime
@@ -146,7 +145,6 @@ def test_parent_context(same_process_inference_state, attribute, expected_name,
assert x.parent_context.parent_context is None assert x.parent_context.parent_context is None
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
@pytest.mark.parametrize( @pytest.mark.parametrize(
'obj, expected_names', [ 'obj, expected_names', [
('', ['str']), ('', ['str']),

View File

@@ -3,7 +3,6 @@ Testing of docstring related issues and especially ``jedi.docstrings``.
""" """
import os import os
import sys
from textwrap import dedent from textwrap import dedent
import pytest import pytest
@@ -25,11 +24,6 @@ except ImportError:
else: else:
numpy_unavailable = False numpy_unavailable = False
if sys.version_info.major == 2:
# In Python 2 there's an issue with tox/docutils that makes the tests fail,
# Python 2 is soon end-of-life, so just don't support numpydoc for it anymore.
numpydoc_unavailable = True
def test_function_doc(Script): def test_function_doc(Script):
defs = Script(""" defs = Script("""

View File

@@ -19,8 +19,7 @@ from ..helpers import get_example_dir, test_dir, test_dir_project, root_dir
THIS_DIR = os.path.dirname(__file__) THIS_DIR = os.path.dirname(__file__)
@pytest.mark.skipif('sys.version_info < (3,3)') def test_find_module_basic():
def test_find_module_py33():
"""Needs to work like the old find_module.""" """Needs to work like the old find_module."""
assert find_module_py33('_io') == (None, False) assert find_module_py33('_io') == (None, False)
with pytest.raises(ImportError): with pytest.raises(ImportError):

View File

@@ -1,5 +1,4 @@
from typing import Generic, TypeVar, List from typing import Generic, TypeVar, List
import sys
import pytest import pytest
@@ -86,7 +85,6 @@ def test_mixed_module_cache():
assert isinstance(jedi_module, ModuleValue) assert isinstance(jedi_module, ModuleValue)
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, EoL")
def test_signature(): def test_signature():
""" """
For performance reasons we use the signature of the compiled object and not For performance reasons we use the signature of the compiled object and not

View File

@@ -39,16 +39,14 @@ def pyc_project_path(tmpdir):
compileall.compile_file(dummy_path) compileall.compile_file(dummy_path)
os.remove(dummy_path) os.remove(dummy_path)
if sys.version_info.major == 3: # To import pyc modules, we must move them out of the __pycache__
# Python3 specific: # directory and rename them to remove ".cpython-%s%d"
# To import pyc modules, we must move them out of the __pycache__ # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files
# directory and rename them to remove ".cpython-%s%d" pycache = os.path.join(dummy_package_path, "__pycache__")
# see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files for f in os.listdir(pycache):
pycache = os.path.join(dummy_package_path, "__pycache__") dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "")
for f in os.listdir(pycache): dst = os.path.join(dummy_package_path, dst)
dst = f.replace('.cpython-%s%s' % sys.version_info[:2], "") shutil.copy(os.path.join(pycache, f), dst)
dst = os.path.join(dummy_package_path, dst)
shutil.copy(os.path.join(pycache, f), dst)
try: try:
yield path yield path
finally: finally:
@@ -56,7 +54,6 @@ def pyc_project_path(tmpdir):
@pytest.mark.parametrize('load_unsafe_extensions', [False, True]) @pytest.mark.parametrize('load_unsafe_extensions', [False, True])
@pytest.mark.skipif(sys.version_info[0] == 2, reason="Ignore Python 2, because EOL")
def test_pyc(pyc_project_path, environment, load_unsafe_extensions): def test_pyc(pyc_project_path, environment, load_unsafe_extensions):
""" """
The list of completion must be greater than 2. The list of completion must be greater than 2.

View File

@@ -1,5 +1,4 @@
import os import os
import sys
import pytest import pytest
@@ -41,10 +40,7 @@ def test_completion(case, monkeypatch, environment, has_django):
if skip_reason is not None: if skip_reason is not None:
pytest.skip(skip_reason) pytest.skip(skip_reason)
if 'pep0484_typing' in case.path and sys.version_info[0] == 2: if (not has_django) and case.path.endswith('django.py'):
pytest.skip('ditch python 2 finally')
if (not has_django or environment.version_info.major == 2) and case.path.endswith('django.py'):
pytest.skip('Needs django to be installed to run this test.') pytest.skip('Needs django to be installed to run this test.')
repo_root = helpers.root_dir repo_root = helpers.root_dir
monkeypatch.chdir(os.path.join(repo_root, 'jedi')) monkeypatch.chdir(os.path.join(repo_root, 'jedi'))
@@ -65,9 +61,6 @@ def test_refactor(refactor_case, environment):
:type refactor_case: :class:`.refactor.RefactoringCase` :type refactor_case: :class:`.refactor.RefactoringCase`
""" """
if sys.version_info < (3, 6):
pytest.skip()
desired_result = refactor_case.get_desired_result() desired_result = refactor_case.get_desired_result()
if refactor_case.type == 'error': if refactor_case.type == 'error':
with pytest.raises(RefactoringError) as e: with pytest.raises(RefactoringError) as e: