Skip to content

Commit 0b8dcfc

Browse files
authored
Fix mypy test temporary config file creation (#13620)
1 parent 5c85697 commit 0b8dcfc

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

tests/mypy_test.py

+23-2
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55

66
import argparse
77
import concurrent.futures
8+
import functools
89
import os
910
import subprocess
1011
import sys
1112
import tempfile
1213
import time
1314
from collections import defaultdict
15+
from collections.abc import Generator
1416
from dataclasses import dataclass
1517
from enum import Enum
1618
from itertools import product
@@ -44,6 +46,24 @@
4446
print_error("Cannot import mypy. Did you install it?")
4547
sys.exit(1)
4648

49+
# We need to work around a limitation of tempfile.NamedTemporaryFile on Windows
50+
# For details, see https://github.com/python/typeshed/pull/13620#discussion_r1990185997
51+
# Python 3.12 added a workaround with `tempfile.NamedTemporaryFile("w+", delete_on_close=False)`
52+
if sys.platform != "win32":
53+
_named_temporary_file = functools.partial(tempfile.NamedTemporaryFile, "w+")
54+
else:
55+
from contextlib import contextmanager
56+
57+
@contextmanager
58+
def _named_temporary_file() -> Generator[tempfile._TemporaryFileWrapper[str]]: # pyright: ignore[reportPrivateUsage]
59+
temp = tempfile.NamedTemporaryFile("w+", delete=False) # noqa: SIM115
60+
try:
61+
yield temp
62+
finally:
63+
temp.close()
64+
os.remove(temp.name)
65+
66+
4767
SUPPORTED_VERSIONS = ["3.13", "3.12", "3.11", "3.10", "3.9"]
4868
SUPPORTED_PLATFORMS = ("linux", "win32", "darwin")
4969
DIRECTORIES_TO_TEST = [STDLIB_PATH, STUBS_PATH]
@@ -214,7 +234,8 @@ def run_mypy(
214234
env_vars = dict(os.environ)
215235
if mypypath is not None:
216236
env_vars["MYPYPATH"] = mypypath
217-
with tempfile.NamedTemporaryFile("w+") as temp:
237+
238+
with _named_temporary_file() as temp:
218239
temp.write("[mypy]\n")
219240
for dist_conf in configurations:
220241
temp.write(f"[mypy-{dist_conf.module_name}]\n")
@@ -290,7 +311,7 @@ def add_third_party_files(
290311
if name.startswith("."):
291312
continue
292313
add_files(files, (root / name), args)
293-
add_configuration(configurations, distribution)
314+
add_configuration(configurations, distribution)
294315

295316

296317
class TestResult(NamedTuple):

0 commit comments

Comments
 (0)