| 1 |
import ast |
| 2 |
import glob |
| 3 |
import os |
| 4 |
import re |
| 5 |
import sys |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from flake8_import_order.checker import ImportOrderChecker |
| 10 |
from flake8_import_order.styles import lookup_entry_point |
| 11 |
|
| 12 |
ERROR_RX = re.compile("# ((I[0-9]{3} ?)+) ?.*$") |
| 13 |
|
| 14 |
|
| 15 |
def _extract_expected_errors(data): |
| 16 |
lines = data.splitlines() |
| 17 |
expected_codes = [] |
| 18 |
for line in lines: |
| 19 |
match = ERROR_RX.search(line) |
| 20 |
if match is not None: |
| 21 |
codes = match.group(1).split() |
| 22 |
expected_codes.extend(codes) |
| 23 |
return expected_codes |
| 24 |
|
| 25 |
|
| 26 |
def _load_test_cases(): |
| 27 |
base_path = os.path.dirname(__file__) |
| 28 |
test_cases = [] |
| 29 |
test_case_path = os.path.join(base_path, "test_cases") |
| 30 |
wildcard_path = os.path.join(test_case_path, "*.py") |
| 31 |
|
| 32 |
for filename in glob.glob(wildcard_path): |
| 33 |
# The namespace.py test only works with Python3 |
| 34 |
if filename.endswith("namespace.py") and sys.version_info.major < 3: |
| 35 |
continue |
| 36 |
fullpath = os.path.join(test_case_path, filename) |
| 37 |
with open(fullpath) as file_: |
| 38 |
data = file_.read() |
| 39 |
styles = data.splitlines()[0].lstrip("#").strip().split() |
| 40 |
codes = _extract_expected_errors(data) |
| 41 |
tree = ast.parse(data, fullpath) |
| 42 |
for style_name in styles: |
| 43 |
style_entry_point = lookup_entry_point(style_name) |
| 44 |
test_cases.append((filename, tree, style_entry_point, codes)) |
| 45 |
|
| 46 |
return test_cases |
| 47 |
|
| 48 |
|
| 49 |
def _checker(filename, tree, style_entry_point): |
| 50 |
options = { |
| 51 |
"application_import_names": [ |
| 52 |
"flake8_import_order", |
| 53 |
"namespace.package_b", |
| 54 |
"tests", |
| 55 |
], |
| 56 |
"application_package_names": ["localpackage"], |
| 57 |
"import_order_style": style_entry_point, |
| 58 |
} |
| 59 |
checker = ImportOrderChecker(filename, tree) |
| 60 |
checker.options = options |
| 61 |
return checker |
| 62 |
|
| 63 |
|
| 64 |
@pytest.mark.parametrize( |
| 65 |
"filename, tree, style, expected_codes", |
| 66 |
_load_test_cases(), |
| 67 |
) |
| 68 |
def test_styles(filename, tree, style, expected_codes): |
| 69 |
checker = _checker(filename, tree, style) |
| 70 |
codes = [ |
| 71 |
(filename, error.lineno, error.code) |
| 72 |
for error in checker.check_order() |
| 73 |
] |
| 74 |
assert [i[2] for i in codes] == expected_codes, codes |
| 75 |
|
| 76 |
|
| 77 |
def test_unknown_style(): |
| 78 |
with pytest.raises(LookupError): |
| 79 |
lookup_entry_point("Unknown") |