Debian Codegraph @

tests/test_concurrency_manager_shutdown.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 from concurrent.futures import ThreadPoolExecutor
5 from pathlib import Path
6 from typing import Any, Optional
7
8 import black.concurrency as concurrency
9 from black import Mode, WriteBack
10 from black.report import Report
11
12
13 class FakeManager:
14 shutdown_called: bool
15
16 def __init__(self) -> None:
17 self.shutdown_called = False
18
19 def Lock(self) -> object:
20 return object()
21
22 def shutdown(self) -> None:
23 self.shutdown_called = True
24
25
26 def test_manager_shutdown_called_for_diff(monkeypatch: Any, tmp_path: Path) -> None:
27 """
28 schedule_formatting() creates multiprocessing.Manager() for DIFF/COLOR_DIFF
29 and must shut it down deterministically.
30 """
31 fake_manager = FakeManager()
32
33 monkeypatch.setattr(concurrency, "Manager", lambda: fake_manager)
34
35 def fake_format_file_in_place(
36 src: Path,
37 fast: bool,
38 mode: Mode,
39 write_back: WriteBack,
40 lock: Optional[object],
41 ) -> bool:
42 assert lock is not None
43 return False
44
45 monkeypatch.setattr(concurrency, "format_file_in_place", fake_format_file_in_place)
46
47 src = tmp_path / "a.py"
48 src.write_text("x=1\n", encoding="utf8")
49
50 async def run() -> None:
51 loop = asyncio.get_running_loop()
52 with ThreadPoolExecutor(max_workers=1) as executor:
53 await concurrency.schedule_formatting(
54 sources={src},
55 fast=False,
56 write_back=WriteBack.DIFF,
57 mode=Mode(),
58 report=Report(),
59 loop=loop,
60 executor=executor,
61 no_cache=True,
62 )
63
64 asyncio.run(run())
65
66 assert fake_manager.shutdown_called is True