Esempio n. 1
0
import json
import subprocess
from datetime import datetime
from io import BytesIO, TextIOWrapper

import pytest
from hypothesis_auto import auto_pytest_magic

from isort import main
from isort._version import __version__
from isort.exceptions import InvalidSettingsPath
from isort.settings import DEFAULT_CONFIG, Config
from isort.wrap_modes import WrapModes

auto_pytest_magic(main.sort_imports)


def test_iter_source_code(tmpdir):
    tmp_file = tmpdir.join("file.py")
    tmp_file.write("import os, sys\n")
    assert tuple(main.iter_source_code((tmp_file,), DEFAULT_CONFIG, [])) == (tmp_file,)


def test_sort_imports(tmpdir):
    tmp_file = tmpdir.join("file.py")
    tmp_file.write("import os, sys\n")
    assert main.sort_imports(str(tmp_file), DEFAULT_CONFIG, check=True).incorrectly_sorted
    main.sort_imports(str(tmp_file), DEFAULT_CONFIG)
    assert not main.sort_imports(str(tmp_file), DEFAULT_CONFIG, check=True).incorrectly_sorted

    skip_config = Config(skip=["file.py"])
Esempio n. 2
0
    return number_1 + number_2


def test_auto_test():
    auto_test(my_function)
    auto_test(my_function, auto_verify_=lambda test_call: int(test_call.result))

    with pytest.raises(TypeError):
        auto_test(my_function, number_1=strategies.text())

    with pytest.raises(ValueError):
        auto_test(my_raise_function)
    auto_test(my_raise_function, auto_allow_exceptions_=(ValueError,))


auto_pytest_magic(my_function)


def my_custom_verifier(scenario: Scenario):
    if scenario.kwargs["number_1"] > 0 and scenario.kwargs["number_2"] > 0:
        assert scenario.result > scenario.kwargs["number_1"]
        assert scenario.result > scenario.kwargs["number_2"]
    elif scenario.kwargs["number_1"] < 0 and scenario.kwargs["number_2"] < 0:
        assert scenario.result < scenario.kwargs["number_1"]
        assert scenario.result < scenario.kwargs["number_2"]
    else:
        assert scenario.result >= min(scenario.kwargs.values())
        assert scenario.result <= max(scenario.kwargs.values())


auto_pytest_magic(my_function, auto_verify_=my_custom_verifier)
Esempio n. 3
0
from hypothesis_auto import auto_pytest_magic

from cruft.cli import _check_command_output, _link_output, _update_output

auto_pytest_magic(_check_command_output, auto_allow_exceptions_=(SystemExit, ))
auto_pytest_magic(_update_output)
auto_pytest_magic(_link_output)
Esempio n. 4
0
from hypothesis_auto import auto_pytest_magic

import isort
from isort import wrap_modes

auto_pytest_magic(wrap_modes.grid, auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.vertical, auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.hanging_indent,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.vertical_hanging_indent,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.vertical_grid,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.vertical_grid_grouped,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.vertical_grid_grouped_no_comma,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.noqa, auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.noqa,
                  auto_allow_exceptions_=(ValueError, ),
                  comments=["NOQA"])
auto_pytest_magic(wrap_modes.vertical_prefix_from_module_import,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(wrap_modes.vertical_hanging_indent_bracket,
                  auto_allow_exceptions_=(ValueError, ))
auto_pytest_magic(
    wrap_modes.vertical_hanging_indent_bracket,
    auto_allow_exceptions_=(ValueError, ),
    imports=["one", "two"],
)
auto_pytest_magic(wrap_modes.hanging_indent_with_parentheses,
Esempio n. 5
0
    "num_1, num_2, expected",
    [(3, 5, 8), (-2, -2, -4), (-1, 5, 4), (3, -5, -2), (0, 5, 5)],
)
def test__sum_buggy__with_parametrize(num_1, num_2, expected):
    """
    Test sum_buggy using parametrize.

    With parametrize looks like the sum_buggy really adds
    num_1 and num_2.
    """
    assert sum_buggy(num_1, num_2) == expected


@settings(verbosity=Verbosity.verbose)
@given(strategies.integers(), strategies.integers())
@pytest.mark.xfail(reason="Buggy logic causes fail.")
def test__sum_buggy__with_hypothesis(num_1, num_2):
    """
    Test sum_buggy using hypothesis-strategies.

    The buggy logic in sum_buggy causes fails.
    """
    assert sum_buggy(num_1, num_2) == num_1 + num_2


auto_pytest_magic(sum_typed, auto_runs_=100)
"""
This auto-generates 100 test cases (default_amount is 50) based on the
type annotations of the function sum_typed.
"""
Esempio n. 6
0
from io import StringIO
from unittest.mock import MagicMock, patch

import colorama
import pytest
from hypothesis_auto import auto_pytest_magic

import isort.format

auto_pytest_magic(isort.format.show_unified_diff,
                  auto_allow_exceptions_=(UnicodeEncodeError, ))


def test_ask_whether_to_apply_changes_to_file():
    with patch("isort.format.input", MagicMock(return_value="y")):
        assert isort.format.ask_whether_to_apply_changes_to_file("")
    with patch("isort.format.input", MagicMock(return_value="n")):
        assert not isort.format.ask_whether_to_apply_changes_to_file("")
    with patch("isort.format.input", MagicMock(return_value="q")):
        with pytest.raises(SystemExit):
            assert isort.format.ask_whether_to_apply_changes_to_file("")


def test_basic_printer(capsys):
    printer = isort.format.create_terminal_printer(color=False)
    printer.success("All good!")
    out, _ = capsys.readouterr()
    assert out == "SUCCESS: All good!\n"
    printer.error("Some error")
    _, err = capsys.readouterr()
    assert err == "ERROR: Some error\n"
Esempio n. 7
0
from unittest.mock import MagicMock

from hypothesis_auto import auto_pytest_magic

from streamdeck_ui import api, gui

gui.selected_button = MagicMock()

auto_pytest_magic(gui.update_button_text, ui=MagicMock())
auto_pytest_magic(gui.update_button_command, ui=MagicMock())
auto_pytest_magic(gui.update_button_keys, ui=MagicMock())
auto_pytest_magic(gui.update_button_write, ui=MagicMock())
auto_pytest_magic(gui.update_change_brightness, ui=MagicMock())
auto_pytest_magic(gui.change_page, ui=MagicMock())
auto_pytest_magic(gui.set_brightness,
                  ui=MagicMock(),
                  auto_allow_exceptions_=(KeyError, ))
auto_pytest_magic(gui.queue_text_change, ui=MagicMock())


def test_start():
    api.decks = {None: MagicMock()}
    api._render_key_image = MagicMock()
    gui.start(_exit=True)
Esempio n. 8
0
from hypothesis_auto import auto_pytest_magic

from isort import comments

auto_pytest_magic(comments.parse)
auto_pytest_magic(comments.add_to_line)


def test_add_to_line():
    assert comments.add_to_line([], "import os  # comment", removed=True).strip() == "import os"
Esempio n. 9
0
from hypothesis_auto import auto_pytest_magic

import tinytext


def test_something():
    # Arrange

    # Act
    tiny = tinytext.tinytext("into tinier text")

    # Assert
    assert tiny == "ᶦᶰᵗᵒ ᵗᶦᶰᶦᵉʳ ᵗᵉˣᵗ"


auto_pytest_magic(tinytext.tinytext)
Esempio n. 10
0
    pass
"""


def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        _,
        _,
        _,
        _,
        _,
        change_count,
        original_line_count,
        _,
        _,
    ) = parse.file_contents(TEST_CONTENTS, config=Config(default_section=""))
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -11
    assert original_line_count == len(in_lines)


auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)
Esempio n. 11
0
    pre: DEFAULT_RUNS,
    tok: DEFAULT_RUNS,
    rejoin: DEFAULT_RUNS,
    tok1: DEFAULT_RUNS,
    tok3: DEFAULT_RUNS,
    make_trans_table: DEFAULT_RUNS,
    get_whiteout: DEFAULT_RUNS,
    clean_text: DEFAULT_RUNS,
    pad_punctuation_w_space: DEFAULT_RUNS,
    Entropy.h: DEFAULT_RUNS,
    Entropy.h_printable: DEFAULT_RUNS,
    Entropy.h_alphanum_lower: DEFAULT_RUNS,
}

for func, runs in FUNCTIONS.items():
    auto_pytest_magic(func, auto_runs_=runs)


@given(text())
def test_split_words(text: str):
    """Test split_words function by performing identical steps."""
    new_s = " ".join(split_words(text, True))
    words = []
    for word in re.findall(r"[\w']+", text):
        for _ in word.split("_"):
            words.append(check_case(_, True))
    old_s = " ".join(words)
    assert new_s == old_s


@auto_pytest(test_split_words, auto_runs_=DEFAULT_RUNS)
Esempio n. 12
0
from hypothesis_auto import auto_pytest_magic

from streamdeck_ui import api

auto_pytest_magic(api.set_button_command)
auto_pytest_magic(api.get_button_command)
auto_pytest_magic(api.set_button_switch_page)
auto_pytest_magic(api.get_button_switch_page)
auto_pytest_magic(api.set_button_keys)
auto_pytest_magic(api.get_button_keys)
auto_pytest_magic(api.set_button_write)
auto_pytest_magic(api.get_button_write)
auto_pytest_magic(api.set_brightness, auto_allow_exceptions_=(KeyError, ))
auto_pytest_magic(api.get_brightness)
auto_pytest_magic(api.change_brightness, auto_allow_exceptions_=(KeyError, ))
auto_pytest_magic(api.set_page)
auto_pytest_magic(api.get_page)
auto_pytest_magic(api.render)
Esempio n. 13
0
    return number_1 + number_2


def test_auto_test():
    auto_test(my_function)
    auto_test(my_function, _auto_verify=lambda result: int(result))

    with pytest.raises(TypeError):
        auto_test(my_function, number_1=strategies.text())

    with pytest.raises(ValueError):
        auto_test(my_raise_function)
    auto_test(my_raise_function, _auto_allow_exceptions=(ValueError, ))


auto_pytest_magic(my_function)


@pytest.mark.parametrize("test_case", auto_test_cases(my_function))
def test_test_case_generation(test_case):
    test_case()


@auto_pytest(my_function)
def test_auto_pytest(test_case):
    test_case()


def test_auto_test_module():
    auto_test_module(example_module)
Esempio n. 14
0
from hypothesis_auto import auto_pytest_magic

from isort import output

auto_pytest_magic(output.with_comments, auto_allow_exceptions_=(ValueError, ))