Ejemplo n.º 1
0
from blib2to3.pgen2.tokenize import TokenError


# This test uses the Hypothesis and Hypothesmith libraries to generate random
# syntatically-valid Python source code and run Black in odd modes.
@settings(
    max_examples=1000,  # roughly 1k tests/minute, or half that under coverage
    derandomize=True,  # deterministic mode to avoid CI flakiness
    deadline=None,  # ignore Hypothesis' health checks; we already know that
    suppress_health_check=HealthCheck.all(),  # this is slow and filter-heavy.
)
@given(
    # Note that while Hypothesmith might generate code unlike that written by
    # humans, it's a general test that should pass for any *valid* source code.
    # (so e.g. running it against code scraped of the internet might also help)
    src_contents=hypothesmith.from_grammar() | hypothesmith.from_node(),
    # Using randomly-varied modes helps us to exercise less common code paths.
    mode=st.builds(
        black.FileMode,
        line_length=st.just(88) | st.integers(0, 200),
        string_normalization=st.booleans(),
        is_pyi=st.booleans(),
    ),
)
def test_idempotent_any_syntatically_valid_python(
        src_contents: str, mode: black.FileMode) -> None:
    # Before starting, let's confirm that the input string is valid Python:
    compile(src_contents, "<string>",
            "exec")  # else the bug is in hypothesmith

    # Then format the code...
Ejemplo n.º 2
0
        if str(e).startswith("Can't instantiate"):
            pytest.skip("abstract classes somehow leaking into builds()")
        raise
    note(val)
    if not isinstance(val, libcst.Module):
        val = libcst.Module([val])
    try:
        code = val.code
    except libcst._nodes.base.CSTCodegenError:
        pytest.skip("codegen not supported yet, e.g. Annotation")
    note(code)


@pytest.mark.skipif(not hasattr(ast, "unparse"),
                    reason="Can't test before available")
@given(source_code=hypothesmith.from_node())
def test_ast_unparse_from_nodes(source_code):
    first = ast.parse(source_code)
    unparsed = ast.unparse(first)
    second = ast.parse(unparsed)
    assert ast.dump(first) == ast.dump(second)


@pytest.mark.xfail
@example("A\u2592", black.FileMode())
@given(
    source_code=hypothesmith.from_node(),
    mode=st.builds(
        black.FileMode,
        line_length=st.just(88) | st.integers(0, 200),
        string_normalization=st.booleans(),
Ejemplo n.º 3
0

# This test uses the Hypothesis and Hypothesmith libraries to generate random
# syntatically-valid Python source code and run Pycln in odd modes.
@settings(
    max_examples=1750,  # roughly 1750 tests/minute,
    derandomize=True,  # deterministic mode to avoid CI flakiness
    deadline=None,  # ignore Hypothesis' health checks; we already know that
    suppress_health_check=HealthCheck.all(),  # this is slow and filter-heavy.
)
@given(
    # Note that while Hypothesmith might generate code unlike that written by
    # humans, it's a general test that should pass for any *valid* source code.
    # (so e.g. running it against code scraped of the internet might also help)
    src_contents=hypothesmith.from_grammar()
    | hypothesmith.from_node()
)
def test_idempotent_any_syntatically_valid_python(src_contents: str) -> None:

    # Form feed char is detected by `pycln.utils.iou.safe_read`.
    if FORM_FEED_CHAR not in src_contents:

        # Before starting, let's confirm that the input string is valid Python:
        compile(src_contents, "<string>", "exec")  # else the bug is in hypothesmith

        # Then format the code...
        configs = config.Config(paths=[Path("pycln/")], all_=True)
        reporter = report.Report(configs)
        session_maker = refactor.Refactor(configs, reporter)
        dst_contents = session_maker._code_session(src_contents)
Ejemplo n.º 4
0
        return result
    errors = [
        err
        for err in ComprehensionChecker(tree).run()
        if not err[2].startswith(NOT_YET_FIXED)
    ]
    assert not errors
    return result


example_kwargs = {"refactor": True, "provides": frozenset(), "min_version": (3, 8)}


@given(
    source_code=hypothesmith.from_grammar(auto_target=False)
    | hypothesmith.from_node(auto_target=False),
    refactor=st.booleans(),
    provides=st.frozensets(st.from_regex(r"\A[\w\d_]+\Z").filter(str.isidentifier)),
    min_version=st.sampled_from(sorted(_version_map.values())),
)
@example(source_code=TEYIT_TWO_PASS, **example_kwargs)
@example(source_code="class A:\n\x0c pass\n", **example_kwargs)
@example(
    source_code="from.import(A)#",
    refactor=False,
    provides=frozenset(),
    min_version=(3, 7),
)
# Minimum-version examples via https://github.com/jwilk/python-syntax-errors/
@example(source_code="lambda: (x := 0)\n", **example_kwargs)
@example(source_code="@0\ndef f(): pass\n", **example_kwargs)
Ejemplo n.º 5
0
        st.sampled_from(sorted(isort.settings.profiles)),
        "py_version":
        st.sampled_from(("auto", ) + isort.settings.VALID_PY_TARGETS),
    }
    kwargs = {**inferred_kwargs, **specific, **force_strategies}
    return st.fixed_dictionaries({}, optional=kwargs).map(_as_config)


st.register_type_strategy(isort.Config, configs())


@hypothesis.example("import A\nimportA\r\n\n", isort.Config(), False)
@hypothesis.given(
    source_code=st.lists(
        from_grammar(auto_target=False)
        | from_node(auto_target=False)
        | from_node(libcst.Import, auto_target=False)
        | from_node(libcst.ImportFrom, auto_target=False),
        min_size=1,
        max_size=10,
    ).map("\n".join),
    config=st.builds(isort.Config),
    disregard_skip=st.booleans(),
)
@hypothesis.seed(235738473415671197623909623354096762459)
@hypothesis.settings(suppress_health_check=[
    hypothesis.HealthCheck.too_slow, hypothesis.HealthCheck.filter_too_much
])
def test_isort_is_idempotent(source_code: str, config: isort.Config,
                             disregard_skip: bool) -> None:
    # NOTE: if this test finds a bug, please notify @Zac-HD so that it can be added to the