summaryrefslogtreecommitdiffstats
path: root/tools/lint/test/test_isort.py
blob: 180bfbebd0d5b76e0772777fbe66285ae8f1f402 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# -*- coding: utf-8 -*-

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import os

import mozunit

LINTER = "isort"
fixed = 0


def test_lint_fix(lint, create_temp_file):
    contents = """
import prova
import collections


def foobar():
    c = collections.Counter()
    prova.ciao(c)
""".lstrip()

    path = create_temp_file(contents, name="bad.py")
    results = lint([path])
    assert len(results) == 1
    assert results[0].level == "error"

    lint([path], fix=True)
    assert fixed == 1


def test_lint_excluded_file(lint, paths, config):
    # Second file is excluded from .flake8 config.
    files = paths("bad.py", "subdir/exclude/bad.py", "subdir/exclude/exclude_subdir")
    results = lint(files, config)
    assert len(results) == 1

    # First file is globally excluded, second one is from .flake8 config.
    files = paths("bad.py", "subdir/exclude/bad.py", "subdir/exclude/exclude_subdir")
    config["exclude"] = paths("bad.py")
    results = lint(files, config)
    assert len(results) == 0

    # Make sure excludes also apply when running from a different cwd.
    cwd = paths("subdir")[0]
    os.chdir(cwd)

    results = lint(paths("subdir/exclude"))
    assert len(results) == 0


def test_lint_uses_all_configs(lint, paths, tmpdir):
    myself = tmpdir.join("myself")
    myself.mkdir()

    flake8_path = tmpdir.join(".flake8")
    flake8_path.write(
        """
[flake8]
exclude =
""".lstrip()
    )

    py_path = myself.join("good.py")
    py_path.write(
        """
import os

from myself import something_else
from third_party import something


def ciao():
    pass
""".lstrip()
    )

    results = lint([py_path.strpath])
    assert len(results) == 0

    isort_cfg_path = myself.join(".isort.cfg")
    isort_cfg_path.write(
        """
[settings]
known_first_party = myself
""".lstrip()
    )

    results = lint([py_path.strpath], root=tmpdir.strpath)
    assert len(results) == 1

    py_path.write(
        """
import os

from third_party import something

from myself import something_else


def ciao():
    pass
""".lstrip()
    )

    results = lint([py_path.strpath], root=tmpdir.strpath)
    assert len(results) == 0


if __name__ == "__main__":
    mozunit.main()