• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pantsbuild / pants / 18517631058

15 Oct 2025 04:18AM UTC coverage: 69.207% (-11.1%) from 80.267%
18517631058

Pull #22745

github

web-flow
Merge 642a76ca1 into 99919310e
Pull Request #22745: [windows] Add windows support in the stdio crate.

53815 of 77759 relevant lines covered (69.21%)

2.42 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

51.38
/src/python/pants/backend/python/lint/black/rules_integration_test.py
1
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
2
# Licensed under the Apache License, Version 2.0 (see LICENSE).
3

4
from __future__ import annotations
2✔
5

6
from textwrap import dedent
2✔
7

8
import pytest
2✔
9

10
from pants.backend.python import target_types_rules
2✔
11
from pants.backend.python.lint.black.rules import BlackRequest
2✔
12
from pants.backend.python.lint.black.rules import rules as black_rules
2✔
13
from pants.backend.python.lint.black.subsystem import Black, BlackFieldSet
2✔
14
from pants.backend.python.lint.black.subsystem import rules as black_subsystem_rules
2✔
15
from pants.backend.python.target_types import PythonSourcesGeneratorTarget
2✔
16
from pants.core.goals.fmt import FmtResult, Partitions
2✔
17
from pants.core.util_rules import config_files, source_files
2✔
18
from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest
2✔
19
from pants.engine.addresses import Address
2✔
20
from pants.engine.target import Target
2✔
21
from pants.testutil.python_interpreter_selection import (
2✔
22
    all_major_minor_python_versions,
23
    skip_unless_python38_present,
24
    skip_unless_python39_present,
25
)
26
from pants.testutil.python_rule_runner import PythonRuleRunner
2✔
27
from pants.testutil.rule_runner import QueryRule
2✔
28
from pants.util.resources import read_sibling_resource
2✔
29

30

31
@pytest.fixture
2✔
32
def rule_runner() -> PythonRuleRunner:
2✔
33
    return PythonRuleRunner(
2✔
34
        rules=[
35
            *black_rules(),
36
            *black_subsystem_rules(),
37
            *source_files.rules(),
38
            *config_files.rules(),
39
            *target_types_rules.rules(),
40
            QueryRule(Partitions, (BlackRequest.PartitionRequest,)),
41
            QueryRule(FmtResult, (BlackRequest.Batch,)),
42
            QueryRule(SourceFiles, (SourceFilesRequest,)),
43
        ],
44
        target_types=[PythonSourcesGeneratorTarget],
45
    )
46

47

48
GOOD_FILE = 'animal = "Koala"\n'
2✔
49
BAD_FILE = 'name=    "Anakin"\n'
2✔
50
FIXED_BAD_FILE = 'name = "Anakin"\n'
2✔
51
NEEDS_CONFIG_FILE = "animal = 'Koala'\n"  # Note the single quotes.
2✔
52

53

54
def run_black(
2✔
55
    rule_runner: PythonRuleRunner,
56
    targets: list[Target],
57
    *,
58
    expected_ics: str = Black.default_interpreter_constraints[0],
59
    extra_args: list[str] | None = None,
60
) -> FmtResult:
61
    rule_runner.set_options(
2✔
62
        ["--backend-packages=pants.backend.python.lint.black", *(extra_args or ())],
63
        # We propagate LANG and LC_ALL to satisfy click, which black depends upon. Without this we
64
        # see something like the following in CI:
65
        #
66
        # RuntimeError: Click will abort further execution because Python was configured to use
67
        # ASCII as encoding for the environment. Consult
68
        # https://click.palletsprojects.com/unicode-support/ for mitigation steps.
69
        #
70
        # This system supports the C.UTF-8 locale which is recommended. You might be able to
71
        # resolve your issue by exporting the following environment variables:
72
        #
73
        #     export LC_ALL=C.UTF-8
74
        #     export LANG=C.UTF-8
75
        #
76
        env_inherit={"PATH", "PYENV_ROOT", "HOME", "LANG", "LC_ALL"},
77
    )
78
    field_sets = [BlackFieldSet.create(tgt) for tgt in targets]
2✔
79

80
    input_sources = rule_runner.request(
2✔
81
        SourceFiles,
82
        [
83
            SourceFilesRequest(field_set.source for field_set in field_sets),
84
        ],
85
    )
86
    partitions = rule_runner.request(
2✔
87
        Partitions,
88
        [
89
            BlackRequest.PartitionRequest(tuple(field_sets)),
90
        ],
91
    )
92
    assert len(partitions) == 1
2✔
93
    partition = partitions[0]
2✔
94
    fmt_result = rule_runner.request(
2✔
95
        FmtResult,
96
        [
97
            BlackRequest.Batch(
98
                "",
99
                partition.elements,
100
                partition_metadata=partition.metadata,
101
                snapshot=input_sources.snapshot,
102
            ),
103
        ],
104
    )
105
    return fmt_result
2✔
106

107

108
@pytest.mark.platform_specific_behavior
2✔
109
@pytest.mark.parametrize(
2✔
110
    "major_minor_interpreter",
111
    all_major_minor_python_versions(Black.default_interpreter_constraints),
112
)
113
def test_passing(rule_runner: PythonRuleRunner, major_minor_interpreter: str) -> None:
2✔
114
    interpreter_constraint = (
2✔
115
        ">=3.6.2,<3.7" if major_minor_interpreter == "3.6" else f"=={major_minor_interpreter}.*"
116
    )
117
    extra_args = [f"--black-interpreter-constraints=['{interpreter_constraint}']"]
2✔
118

119
    rule_runner.write_files({"f.py": GOOD_FILE, "BUILD": "python_sources(name='t')"})
2✔
120
    if major_minor_interpreter == "3.8":
2✔
121
        lockfile_content = read_sibling_resource(__name__, "black-py38-testing.lock")
×
122
        rule_runner.write_files({"black-py38-testing.lock": lockfile_content})
×
123
        extra_args.extend(
×
124
            [
125
                "--python-resolves={'black-py38-testing': 'black-py38-testing.lock'}",
126
                "--black-install-from-resolve=black-py38-testing",
127
            ]
128
        )
129

130
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
2✔
131
    fmt_result = run_black(
2✔
132
        rule_runner,
133
        [tgt],
134
        expected_ics=interpreter_constraint,
135
        extra_args=extra_args,
136
    )
137
    assert "1 file left unchanged" in fmt_result.stderr
2✔
138
    assert fmt_result.output == rule_runner.make_snapshot({"f.py": GOOD_FILE})
2✔
139
    assert fmt_result.did_change is False
2✔
140

141

142
def test_failing(rule_runner: PythonRuleRunner) -> None:
2✔
143
    rule_runner.write_files({"f.py": BAD_FILE, "BUILD": "python_sources(name='t')"})
×
144
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
×
145
    fmt_result = run_black(rule_runner, [tgt])
×
146
    assert "1 file reformatted" in fmt_result.stderr
×
147
    assert fmt_result.output == rule_runner.make_snapshot({"f.py": FIXED_BAD_FILE})
×
148
    assert fmt_result.did_change is True
×
149

150

151
def test_multiple_targets(rule_runner: PythonRuleRunner) -> None:
2✔
152
    rule_runner.write_files(
×
153
        {"good.py": GOOD_FILE, "bad.py": BAD_FILE, "BUILD": "python_sources(name='t')"}
154
    )
155
    tgts = [
×
156
        rule_runner.get_target(Address("", target_name="t", relative_file_path="good.py")),
157
        rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.py")),
158
    ]
159
    fmt_result = run_black(rule_runner, tgts)
×
160
    assert "1 file reformatted, 1 file left unchanged" in fmt_result.stderr
×
161
    assert fmt_result.output == rule_runner.make_snapshot(
×
162
        {"good.py": GOOD_FILE, "bad.py": FIXED_BAD_FILE}
163
    )
164
    assert fmt_result.did_change is True
×
165

166

167
@pytest.mark.parametrize(
2✔
168
    "config_path,extra_args",
169
    (["pyproject.toml", []], ["custom_config.toml", ["--black-config=custom_config.toml"]]),
170
)
171
def test_config_file(
2✔
172
    rule_runner: PythonRuleRunner, config_path: str, extra_args: list[str]
173
) -> None:
174
    rule_runner.write_files(
×
175
        {
176
            "f.py": NEEDS_CONFIG_FILE,
177
            "BUILD": "python_sources(name='t')",
178
            config_path: "[tool.black]\nskip-string-normalization = 'true'\n",
179
        }
180
    )
181
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
×
182
    fmt_result = run_black(rule_runner, [tgt], extra_args=extra_args)
×
183
    assert "1 file left unchanged" in fmt_result.stderr
×
184
    assert fmt_result.output == rule_runner.make_snapshot({"f.py": NEEDS_CONFIG_FILE})
×
185
    assert fmt_result.did_change is False
×
186

187

188
def test_passthrough_args(rule_runner: PythonRuleRunner) -> None:
2✔
189
    rule_runner.write_files({"f.py": NEEDS_CONFIG_FILE, "BUILD": "python_sources(name='t')"})
×
190
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
×
191
    fmt_result = run_black(
×
192
        rule_runner, [tgt], extra_args=["--black-args='--skip-string-normalization'"]
193
    )
194
    assert "1 file left unchanged" in fmt_result.stderr
×
195
    assert fmt_result.output == rule_runner.make_snapshot({"f.py": NEEDS_CONFIG_FILE})
×
196
    assert fmt_result.did_change is False
×
197

198

199
@skip_unless_python38_present
2✔
200
def test_works_with_python38(rule_runner: PythonRuleRunner) -> None:
2✔
201
    """Black's typed-ast dependency does not understand Python 3.8, so we must instead run Black
202
    with Python 3.8 when relevant."""
203
    content = dedent(
×
204
        """\
205
        import datetime
206

207
        x = True
208
        if y := x:
209
            print("x is truthy and now assigned to y")
210

211

212
        class Foo:
213
            pass
214
        """
215
    )
216
    lockfile_content = read_sibling_resource(__name__, "black-py38-testing.lock")
×
217
    rule_runner.write_files(
×
218
        {
219
            "f.py": content,
220
            "BUILD": "python_sources(name='t', interpreter_constraints=['>=3.8'])",
221
            "black-py38-testing.lock": lockfile_content,
222
        }
223
    )
224
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
×
225
    fmt_result = run_black(
×
226
        rule_runner,
227
        [tgt],
228
        expected_ics=">=3.8",
229
        extra_args=[
230
            "--python-resolves={'black-py38-testing': 'black-py38-testing.lock'}",
231
            "--black-install-from-resolve=black-py38-testing",
232
        ],
233
    )
234
    assert "1 file left unchanged" in fmt_result.stderr
×
235
    assert fmt_result.output == rule_runner.make_snapshot({"f.py": content})
×
236
    assert fmt_result.did_change is False
×
237

238

239
@skip_unless_python39_present
2✔
240
def test_works_with_python39(rule_runner: PythonRuleRunner) -> None:
2✔
241
    """Black's typed-ast dependency does not understand Python 3.9, so we must instead run Black
242
    with Python 3.9 when relevant."""
243
    content = dedent(
×
244
        """\
245
        @lambda _: int
246
        def replaced(x: bool) -> str:
247
            return "42" if x is True else "1/137"
248
        """
249
    )
250
    rule_runner.write_files(
×
251
        {"f.py": content, "BUILD": "python_sources(name='t', interpreter_constraints=['>=3.9'])"}
252
    )
253
    tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
×
254
    fmt_result = run_black(rule_runner, [tgt], expected_ics=">=3.9")
×
255
    assert "1 file left unchanged" in fmt_result.stderr
×
256
    assert fmt_result.output == rule_runner.make_snapshot({"f.py": content})
×
257
    assert fmt_result.did_change is False
×
258

259

260
def test_stub_files(rule_runner: PythonRuleRunner) -> None:
2✔
261
    rule_runner.write_files(
×
262
        {
263
            "good.pyi": GOOD_FILE,
264
            "good.py": GOOD_FILE,
265
            "bad.pyi": BAD_FILE,
266
            "bad.py": BAD_FILE,
267
            "BUILD": "python_sources(name='t')",
268
        }
269
    )
270

271
    good_tgts = [
×
272
        rule_runner.get_target(Address("", target_name="t", relative_file_path="good.pyi")),
273
        rule_runner.get_target(Address("", target_name="t", relative_file_path="good.py")),
274
    ]
275
    fmt_result = run_black(rule_runner, good_tgts)
×
276
    assert "2 files left unchanged" in fmt_result.stderr
×
277
    assert fmt_result.output == rule_runner.make_snapshot(
×
278
        {"good.pyi": GOOD_FILE, "good.py": GOOD_FILE}
279
    )
280
    assert not fmt_result.did_change
×
281

282
    bad_tgts = [
×
283
        rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.pyi")),
284
        rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.py")),
285
    ]
286
    fmt_result = run_black(rule_runner, bad_tgts)
×
287
    assert "2 files reformatted" in fmt_result.stderr
×
288
    assert fmt_result.output == rule_runner.make_snapshot(
×
289
        {"bad.pyi": FIXED_BAD_FILE, "bad.py": FIXED_BAD_FILE}
290
    )
291
    assert fmt_result.did_change
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc