Skip to content

Commit 64dd700

Browse files
authored
Merge pull request #7436 from bluetech/cleanup-lsof
pytester: slightly clean up LsofFdLeakChecker
2 parents f76ac4c + 7b1ba7c commit 64dd700

File tree

1 file changed

+23
-27
lines changed

1 file changed

+23
-27
lines changed

src/_pytest/pytester.py

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -94,21 +94,16 @@ def pytest_configure(config: Config) -> None:
9494

9595

9696
class LsofFdLeakChecker:
97-
def get_open_files(self):
98-
out = self._exec_lsof()
99-
open_files = self._parse_lsof_output(out)
100-
return open_files
101-
102-
def _exec_lsof(self):
103-
pid = os.getpid()
104-
# py3: use subprocess.DEVNULL directly.
105-
with open(os.devnull, "wb") as devnull:
106-
return subprocess.check_output(
107-
("lsof", "-Ffn0", "-p", str(pid)), stderr=devnull
108-
).decode()
109-
110-
def _parse_lsof_output(self, out):
111-
def isopen(line):
97+
def get_open_files(self) -> List[Tuple[str, str]]:
98+
out = subprocess.run(
99+
("lsof", "-Ffn0", "-p", str(os.getpid())),
100+
stdout=subprocess.PIPE,
101+
stderr=subprocess.DEVNULL,
102+
check=True,
103+
universal_newlines=True,
104+
).stdout
105+
106+
def isopen(line: str) -> bool:
112107
return line.startswith("f") and (
113108
"deleted" not in line
114109
and "mem" not in line
@@ -130,9 +125,9 @@ def isopen(line):
130125

131126
return open_files
132127

133-
def matching_platform(self):
128+
def matching_platform(self) -> bool:
134129
try:
135-
subprocess.check_output(("lsof", "-v"))
130+
subprocess.run(("lsof", "-v"), check=True)
136131
except (OSError, subprocess.CalledProcessError):
137132
return False
138133
else:
@@ -149,16 +144,17 @@ def pytest_runtest_protocol(self, item: Item) -> Generator[None, None, None]:
149144
new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
150145
leaked_files = [t for t in lines2 if t[0] in new_fds]
151146
if leaked_files:
152-
error = []
153-
error.append("***** %s FD leakage detected" % len(leaked_files))
154-
error.extend([str(f) for f in leaked_files])
155-
error.append("*** Before:")
156-
error.extend([str(f) for f in lines1])
157-
error.append("*** After:")
158-
error.extend([str(f) for f in lines2])
159-
error.append(error[0])
160-
error.append("*** function %s:%s: %s " % item.location)
161-
error.append("See issue #2366")
147+
error = [
148+
"***** %s FD leakage detected" % len(leaked_files),
149+
*(str(f) for f in leaked_files),
150+
"*** Before:",
151+
*(str(f) for f in lines1),
152+
"*** After:",
153+
*(str(f) for f in lines2),
154+
"***** %s FD leakage detected" % len(leaked_files),
155+
"*** function %s:%s: %s " % item.location,
156+
"See issue #2366",
157+
]
162158
item.warn(pytest.PytestWarning("\n".join(error)))
163159

164160

0 commit comments

Comments
 (0)