python_code stringlengths 0 456k |
|---|
import pytest
from isort import api
imperfect_content = "import b\nimport a\n"
fixed_content = "import a\nimport b\n"
@pytest.fixture
def imperfect(tmpdir) -> None:
imperfect_file = tmpdir.join("test_needs_changes.py")
imperfect_file.write_text(imperfect_content, "utf8")
return imperfect_file
def test... |
from isort.utils import Trie
def test_trie():
trie_root = Trie("default", {"line_length": 70})
trie_root.insert("/temp/config1/.isort.cfg", {"line_length": 71})
trie_root.insert("/temp/config2/setup.cfg", {"line_length": 72})
trie_root.insert("/temp/config3/pyproject.toml", {"line_length": 73})
... |
import pytest
import isort.literal
from isort import exceptions
from isort.settings import Config
def test_value_mismatch():
with pytest.raises(exceptions.LiteralSortTypeMismatch):
isort.literal.assignment("x = [1, 2, 3]", "set", "py")
def test_invalid_syntax():
with pytest.raises(exceptions.Litera... |
"""isort test wide fixtures and configuration"""
import os
from pathlib import Path
import pytest
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = os.path.abspath(os.path.join(TEST_DIR, "../../isort/"))
@pytest.fixture
def test_dir():
return TEST_DIR
@pytest.fixture
def src_dir():
return SR... |
"""Tests for isort action comments, such as isort: skip"""
import isort
def test_isort_off_and_on():
"""Test so ensure isort: off action comment and associated on action comment work together"""
# as top of file comment
assert (
isort.code(
"""# isort: off
import a
import a
# isort: ... |
from hypothesis import given
from hypothesis import strategies as st
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
import (\\ # one
one as \\ # two
three)
import \\
zebra as \\ # one
not_bacon
from x import (\\ # one
one as \\ # two
three)
... |
from isort.pylama_isort import Linter
class TestLinter:
instance = Linter()
def test_allow(self):
assert not self.instance.allow("test_case.pyc")
assert not self.instance.allow("test_case.c")
assert self.instance.allow("test_case.py")
def test_run(self, tmpdir):
correct =... |
import importlib.machinery
import os
import posixpath
from pathlib import Path
from unittest.mock import patch
from isort import sections, settings
from isort.deprecated import finders
from isort.deprecated.finders import FindersManager
from isort.settings import Config
PIPFILE = """
[[source]]
url = "https://pypi.or... |
from isort import setuptools_commands
def test_isort_command_smoke(src_dir):
"""A basic smoke test for the setuptools_commands command"""
from distutils.dist import Distribution
command = setuptools_commands.ISortCommand(Distribution())
command.distribution.packages = ["isort"]
command.distributi... |
"""Tests all major functionality of the isort library
Should be ran using py.test by simply running py.test in the isort project directory
"""
import os
import os.path
import subprocess
import sys
from io import StringIO
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING,... |
import pickle
from isort import exceptions
class TestISortError:
def setup_class(self):
self.instance = exceptions.ISortError()
def test_init(self):
assert isinstance(self.instance, exceptions.ISortError)
def test_pickleable(self):
assert isinstance(pickle.loads(pickle.dumps(sel... |
import pytest
from hypothesis import given, reject
from hypothesis import strategies as st
import isort
from isort import wrap_modes
def test_wrap_mode_interface():
assert (
wrap_modes._wrap_mode_interface("statement", [], "", "", 80, [], "", "", True, True) == ""
)
def test_auto_saved():
"""hy... |
import sys
from unittest.mock import patch
import pytest
from isort import io
class TestFile:
@pytest.mark.skipif(sys.platform == "win32", reason="Can't run file encoding test in AppVeyor")
def test_read(self, tmpdir):
test_file_content = """# -*- encoding: ascii -*-
import Ὡ
"""
test_file ... |
from hypothesis import given, reject
from hypothesis import strategies as st
import isort.comments
@given(
comments=st.one_of(st.none(), st.lists(st.text())),
original_string=st.text(),
removed=st.booleans(),
comment_prefix=st.text(),
)
def test_fuzz_add_to_line(comments, original_string, removed, co... |
"""Basic set of tests to ensure entire code base is importable"""
import pytest
def test_importable():
"""Simple smoketest to ensure all isort modules are importable"""
import isort
import isort._future
import isort._future._dataclasses
import isort._version
import isort.api
import isort.... |
"""A growing set of tests designed to ensure when isort implements a feature described in a ticket
it fully works as defined in the associated ticket.
"""
from functools import partial
from io import StringIO
import pytest
import isort
from isort import Config, api, exceptions
def test_semicolon_ignored_for_dynamic... |
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
from isort import exceptions, hooks
def test_git_hook(src_dir):
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.g... |
from isort import files
from isort.settings import DEFAULT_CONFIG
def test_find(tmpdir):
tmp_file = tmpdir.join("file.py")
tmp_file.write("import os, sys\n")
assert tuple(files.find((tmp_file,), DEFAULT_CONFIG, [], [])) == (tmp_file,)
|
from io import BytesIO, StringIO, TextIOWrapper
import isort
class UnseekableTextIOWrapper(TextIOWrapper):
def seek(self, *args, **kwargs):
raise ValueError("underlying stream is not seekable")
class UnreadableStream(StringIO):
def readable(self, *args, **kwargs) -> bool:
return False
def... |
from io import StringIO
from typing import List
from isort import Config, identify
from isort.identify import Import
def imports_in_code(code: str, **kwargs) -> List[identify.Import]:
return list(identify.imports(StringIO(code), **kwargs))
def test_top_only():
imports_in_function = """
import abc
def xyz(... |
"""Tests for the isort import placement module"""
from functools import partial
from isort import place, sections
from isort.settings import Config
def test_module(src_path):
place_tester = partial(place.module, config=Config(src_paths=[src_path]))
assert place_tester("isort") == sections.FIRSTPARTY
asse... |
from hypothesis import given
from hypothesis import strategies as st
import isort.comments
def test_add_to_line():
assert (
isort.comments.add_to_line([], "import os # comment", removed=True).strip() == "import os"
)
# These tests were written by the `hypothesis.extra.ghostwriter` module
# and is ... |
"""Tests the isort API module"""
import os
from io import StringIO
from unittest.mock import MagicMock, patch
import pytest
from isort import ImportKey, api
from isort.settings import Config
imperfect_content = "import b\nimport a\n"
fixed_content = "import a\nimport b\n"
fixed_diff = "+import a\n import b\n-import ... |
import b
import a
def func():
x = 1
y = 2
z = 3
c = 4
return x + y + z + c
|
"""A growing set of tests designed to ensure isort doesn't have regressions in new versions"""
from io import StringIO
import pytest
import isort
def test_isort_duplicating_comments_issue_1264():
"""Ensure isort doesn't duplicate comments when force_sort_within_sections is set to `True`
as was the case in i... |
import json
import os
import subprocess
from datetime import datetime
import py
import pytest
from hypothesis import given
from hypothesis import strategies as st
from isort import main
from isort._version import __version__
from isort.exceptions import InvalidSettingsPath
from isort.settings import DEFAULT_CONFIG, C... |
from isort import wrap
from isort.settings import Config
def test_import_statement():
assert wrap.import_statement("", [], []) == ""
assert (
wrap.import_statement("from x import ", ["y"], [], config=Config(balanced_wrapping=True))
== "from x import (y)"
)
assert (
wrap.import_... |
from io import StringIO
from pathlib import Path
from unittest.mock import MagicMock, patch
import colorama
import pytest
from hypothesis import given, reject
from hypothesis import strategies as st
import isort.format
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(r... |
import os
import sys
from pathlib import Path
import pytest
from isort import exceptions, settings
from isort.settings import Config
from isort.wrap_modes import WrapModes
class TestConfig:
instance = Config()
def test_init(self):
assert Config()
def test_init_unsupported_settings_fails_gracef... |
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
|
description = "基于FastAPI + Mysql的 TodoList" # Exception: UnicodeDecodeError
|
__import__("pkg_resources").declare_namespace(__name__)
|
from functools import partial
from ..utils import isort_test
hug_isort_test = partial(isort_test, profile="hug", known_first_party=["hug"])
def test_hug_code_snippet_one():
hug_isort_test(
'''
from __future__ import absolute_import
import asyncio
import sys
from collections import OrderedDict, namedtup... |
"""A set of test cases for the wemake isort profile.
Snippets are taken directly from the wemake-python-styleguide project here:
https://github.com/wemake-services/wemake-python-styleguide
"""
from functools import partial
from ..utils import isort_test
wemake_isort_test = partial(
isort_test, profile="wemake", ... |
from functools import partial
from ..utils import isort_test
pycharm_isort_test = partial(isort_test, profile="pycharm")
def test_pycharm_snippet_one():
pycharm_isort_test(
"""import shutil
import sys
from io import StringIO
from pathlib import Path
from typing import (
Optional,
TextIO,
Uni... |
from functools import partial
from ..utils import isort_test
attrs_isort_test = partial(isort_test, profile="attrs")
def test_attrs_code_snippet_one():
attrs_isort_test(
"""from __future__ import absolute_import, division, print_function
import sys
from functools import partial
from . import converte... |
from functools import partial
from ..utils import isort_test
django_isort_test = partial(isort_test, profile="django", known_first_party=["django"])
def test_django_snippet_one():
django_isort_test(
"""import copy
import inspect
import warnings
from functools import partialmethod
from itertools import c... |
import black
from black.report import NothingChanged
import isort
def black_format(code: str, is_pyi: bool = False, line_length: int = 88) -> str:
"""Formats the provided code snippet using black"""
try:
return black.format_file_contents(
code,
fast=True,
mode=blac... |
from functools import partial
from ..utils import isort_test
open_stack_isort_test = partial(isort_test, profile="open_stack")
def test_open_stack_code_snippet_one():
open_stack_isort_test(
"""import httplib
import logging
import random
import StringIO
import time
import unittest
import eventlet
import... |
from functools import partial
from ..utils import isort_test
plone_isort_test = partial(isort_test, profile="plone")
def test_plone_code_snippet_one():
plone_isort_test(
"""# -*- coding: utf-8 -*-
from plone.app.multilingual.testing import PLONE_APP_MULTILINGUAL_PRESET_FIXTURE # noqa
from plone.app.rob... |
from functools import partial
from ..utils import isort_test
google_isort_test = partial(isort_test, profile="google")
def test_google_code_snippet_shared_example():
"""Tests snippet examples directly shared with the isort project.
See: https://github.com/PyCQA/isort/issues/1486.
"""
google_isort_te... |
import ast
from typing import get_type_hints
import hypothesis
import libcst
from hypothesis import strategies as st
from hypothesmith import from_grammar, from_node
import isort
def _as_config(kw) -> isort.Config:
if "wrap_length" in kw and "line_length" in kw:
kw["wrap_length"], kw["line_length"] = so... |
"""Tests projects that use isort to see if any differences are found between
their current imports and what isort suggest on the develop branch.
This is an important early warning signal of regressions.
NOTE: If you use isort within a public repository, please feel empowered to add your project here!
It is important t... |
from typing import get_type_hints
import hypothesis
from hypothesis import strategies as st
import isort
def _as_config(kw) -> isort.Config:
kw["atomic"] = False
if "wrap_length" in kw and "line_length" in kw:
kw["wrap_length"], kw["line_length"] = sorted([kw["wrap_length"], kw["line_length"]])
... |
import black
import isort
def black_format_import_section(
contents: str, extension: str, config: isort.settings.Config
) -> str:
"""Formats the given import section using black."""
if extension.lower() not in ("pyi", "py"):
return contents
try:
return black.format_file_contents(
... |
import os
from pathlib import Path
from typing import Iterable, Iterator, List, Set
from isort.settings import Config
def find(
paths: Iterable[str], config: Config, skipped: List[str], broken: List[str]
) -> Iterator[str]:
"""Fines and provides an iterator for all Python source files defined in paths."""
... |
"""Contains all logic related to placing an import within a certain section."""
import importlib
from fnmatch import fnmatch
from functools import lru_cache
from pathlib import Path
from typing import FrozenSet, Iterable, Optional, Tuple
from isort import sections
from isort.settings import DEFAULT_CONFIG, Config
from... |
"""Defines a git hook to allow pre-commit warnings and errors about import order.
usage:
exit_code = git_hook(strict=True|False, modify=True|False)
"""
import os
import subprocess # nosec - Needed for hook
from pathlib import Path
from typing import List
from isort import Config, api, exceptions
def get_output... |
"""Defines all sections isort uses by default"""
from typing import Tuple
FUTURE: str = "FUTURE"
STDLIB: str = "STDLIB"
THIRDPARTY: str = "THIRDPARTY"
FIRSTPARTY: str = "FIRSTPARTY"
LOCALFOLDER: str = "LOCALFOLDER"
DEFAULT: Tuple[str, ...] = (FUTURE, STDLIB, THIRDPARTY, FIRSTPARTY, LOCALFOLDER)
|
import ast
from pprint import PrettyPrinter
from typing import Any, Callable, Dict, List, Set, Tuple
from isort.exceptions import (
AssignmentsFormatMismatch,
LiteralParsingFailure,
LiteralSortTypeMismatch,
)
from isort.settings import DEFAULT_CONFIG, Config
class ISortPrettyPrinter(PrettyPrinter):
"... |
__version__ = "5.10.1"
|
"""Defines any IO utilities used by isort"""
import re
import tokenize
from contextlib import contextmanager
from io import BytesIO, StringIO, TextIOWrapper
from pathlib import Path
from typing import Any, Callable, Iterator, TextIO, Union
from isort._future import dataclass
from isort.exceptions import UnsupportedEnc... |
import re
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional
if TYPE_CHECKING:
from .settings import Config
else:
Config = Any
_import_line_intro_re = re.compile("^(?:from|import) ")
_import_line_midline_import_re = re.compile(" import ")
def module_key(
module_name: str,
conf... |
"""Defines the public isort interface"""
__all__ = (
"Config",
"ImportKey",
"__version__",
"check_code",
"check_file",
"check_stream",
"code",
"file",
"find_imports_in_code",
"find_imports_in_file",
"find_imports_in_paths",
"find_imports_in_stream",
"place_module",
... |
import re
import sys
from datetime import datetime
from difflib import unified_diff
from pathlib import Path
from typing import Optional, TextIO
try:
import colorama
except ImportError:
colorama_unavailable = True
else:
colorama_unavailable = False
colorama.init(strip=False)
ADDED_LINE_PATTERN = re.c... |
import textwrap
from io import StringIO
from itertools import chain
from typing import List, TextIO, Union
import isort.literal
from isort.settings import DEFAULT_CONFIG, Config
from . import output, parse
from .exceptions import ExistingSyntaxErrors, FileSkipComment
from .format import format_natural, remove_whitesp... |
from ._version import __version__
ASCII_ART = rf"""
_ _
(_) ___ ___ _ __| |_
| |/ _/ / _ \/ '__ _/
| |\__ \/\_\/| | | |_
|_|\___/\___/\_/ \_/
isort your imports, so you don't have to.
VERS... |
__all__ = (
"ImportKey",
"check_code_string",
"check_file",
"check_stream",
"find_imports_in_code",
"find_imports_in_file",
"find_imports_in_paths",
"find_imports_in_stream",
"place_module",
"place_module_with_reason",
"sort_code_string",
"sort_file",
"sort_stream",
)... |
import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, Iterator, List, Optional
from pylama.lint import Linter as BaseLinter # type: ignore
from isort.exceptions import FileSkipped
from . import api
@contextmanager
def suppress_stdout() -> Iterator[None]:
stdout = sys.stdout
... |
import os
import sys
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
class TrieNode:
def __init__(self, config_file: str = "", config_data: Optional[Dict[str, Any]] = None) -> None:
if not config_data:
config_data = {}
self.nodes: Dict[str, TrieNode] = {}
... |
"""Defines all wrap modes that can be used when outputting formatted imports"""
import enum
from inspect import signature
from typing import Any, Callable, Dict, List
import isort.comments
_wrap_modes: Dict[str, Callable[..., str]] = {}
def from_string(value: str) -> "WrapModes":
return getattr(WrapModes, str(v... |
"""isort/settings.py.
Defines how the default settings for isort should be loaded
"""
import configparser
import fnmatch
import os
import posixpath
import re
import stat
import subprocess # nosec: Needed for gitignore support.
import sys
from functools import lru_cache
from pathlib import Path
from typing import (
... |
"""All isort specific exception classes should be defined here"""
from functools import partial
from pathlib import Path
from typing import Any, Dict, List, Type, Union
from .profiles import profiles
class ISortError(Exception):
"""Base isort exception object from which all isort sourced exceptions should inheri... |
"""Defines parsing functions used by isort for parsing import definitions"""
from collections import OrderedDict, defaultdict
from functools import partial
from itertools import chain
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Set, Tuple
from warnings import warn
from . import place
from ... |
"""Fast stream based import identification.
Eventually this will likely replace parse.py
"""
from functools import partial
from pathlib import Path
from typing import Iterator, NamedTuple, Optional, TextIO, Tuple
from isort.parse import _normalize_line, _strip_syntax, skip_line
from .comments import parse as parse_co... |
"""Tool for sorting imports alphabetically, and automatically separated into sections."""
import argparse
import functools
import json
import os
import sys
from gettext import gettext as _
from io import TextIOWrapper
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
from warnings i... |
import copy
import re
from typing import List, Optional, Sequence
from .settings import DEFAULT_CONFIG, Config
from .wrap_modes import WrapModes as Modes
from .wrap_modes import formatter_from_string, vertical_hanging_indent
def import_statement(
import_start: str,
from_imports: List[str],
comments: Sequ... |
"""Common profiles are defined here to be easily used within a project using --profile {name}"""
from typing import Any, Dict
black = {
"multi_line_output": 3,
"include_trailing_comma": True,
"force_grid_wrap": 0,
"use_parentheses": True,
"ensure_newline_before_comments": True,
"line_length": 8... |
from isort.main import main
main()
|
import copy
import itertools
from functools import partial
from typing import Any, Iterable, List, Optional, Set, Tuple, Type
from isort.format import format_simplified
from . import parse, sorting, wrap
from .comments import add_to_line as with_comments
from .identify import STATEMENT_DECLARATIONS
from .settings imp... |
from typing import List, Optional, Tuple
def parse(line: str) -> Tuple[str, str]:
"""Parses import lines for comments and returns back the
import statement and the associated comment.
"""
comment_start = line.find("#")
if comment_start != -1:
return (line[:comment_start], line[comment_star... |
import glob
import os
import sys
from typing import Any, Dict, Iterator, List
from warnings import warn
import setuptools # type: ignore
from . import api
from .settings import DEFAULT_CONFIG
class ISortCommand(setuptools.Command): # type: ignore
"""The :class:`ISortCommand` class is used by setuptools to per... |
import sys
if sys.version_info.major <= 3 and sys.version_info.minor <= 6:
from . import _dataclasses as dataclasses
else:
import dataclasses # type: ignore
dataclass = dataclasses.dataclass # type: ignore
field = dataclasses.field # type: ignore
__all__ = ["dataclasses", "dataclass", "field"]
|
# type: ignore
# flake8: noqa
# flake8: noqa
"""Backport of Python3.7 dataclasses Library
Taken directly from here: https://github.com/ericvsmith/dataclasses
Licensed under the Apache License: https://github.com/ericvsmith/dataclasses/blob/master/LICENSE.txt
Needed due to isorts strict no non-optional requirements st... |
"""A lil' TOML parser."""
__all__ = ("loads", "load", "TOMLDecodeError")
__version__ = "1.2.0" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
from ._parser import TOMLDecodeError, load, loads
|
import string
import warnings
from types import MappingProxyType
from typing import IO, Any, Callable, Dict, FrozenSet, Iterable, NamedTuple, Optional, Tuple
from ._re import (
RE_DATETIME,
RE_LOCALTIME,
RE_NUMBER,
match_to_datetime,
match_to_localtime,
match_to_number,
)
ASCII_CTRL = frozense... |
import re
from datetime import date, datetime, time, timedelta, timezone, tzinfo
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Optional, Union
if TYPE_CHECKING:
from tomli._parser import ParseFloat
# E.g.
# - 00:32:00.999999
# - 00:32:00
_TIME_RE_STR = r"([01][0-9]|2[0-3]):([0-5][0-9]):([... |
"""
File contains the standard library of Python 3.8.
DO NOT EDIT. If the standard library changes, a new list should be created
using the mkstdlibs.py script.
"""
stdlib = {
"_ast",
"_dummy_thread",
"_thread",
"abc",
"aifc",
"argparse",
"array",
"ast",
"asynchat",
"asyncio",
... |
"""
File contains the standard library of Python 3.9.
DO NOT EDIT. If the standard library changes, a new list should be created
using the mkstdlibs.py script.
"""
stdlib = {
"_ast",
"_thread",
"abc",
"aifc",
"argparse",
"array",
"ast",
"asynchat",
"asyncio",
"asyncore",
"a... |
"""
File contains the standard library of Python 3.6.
DO NOT EDIT. If the standard library changes, a new list should be created
using the mkstdlibs.py script.
"""
stdlib = {
"_ast",
"_dummy_thread",
"_thread",
"abc",
"aifc",
"argparse",
"array",
"ast",
"asynchat",
"asyncio",
... |
from . import py27
stdlib = py27.stdlib
|
from . import py35, py36, py37, py38, py39, py310
stdlib = py35.stdlib | py36.stdlib | py37.stdlib | py38.stdlib | py39.stdlib | py310.stdlib
|
from . import all as _all
from . import py2, py3, py27, py35, py36, py37, py38, py39, py310
|
"""
File contains the standard library of Python 2.7.
DO NOT EDIT. If the standard library changes, a new list should be created
using the mkstdlibs.py script.
"""
stdlib = {
"AL",
"BaseHTTPServer",
"Bastion",
"CGIHTTPServer",
"Carbon",
"ColorPicker",
"ConfigParser",
"Cookie",
"DEV... |
from . import py2, py3
stdlib = py2.stdlib | py3.stdlib
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.