Skip to content

Commit 2079b91

Browse files
committed
config: move uninteresting error handling code to own functions
1 parent bf78ef3 commit 2079b91

File tree

1 file changed

+33
-25
lines changed

1 file changed

+33
-25
lines changed

src/_pytest/config/__init__.py

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,29 @@ def filter_traceback_for_conftest_import_failure(
142142
return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep)
143143

144144

145+
def print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None:
146+
exc_info = ExceptionInfo.from_exception(e.cause)
147+
tw = TerminalWriter(file)
148+
tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
149+
exc_info.traceback = exc_info.traceback.filter(
150+
filter_traceback_for_conftest_import_failure
151+
)
152+
exc_repr = (
153+
exc_info.getrepr(style="short", chain=False)
154+
if exc_info.traceback
155+
else exc_info.exconly()
156+
)
157+
formatted_tb = str(exc_repr)
158+
for line in formatted_tb.splitlines():
159+
tw.line(line.rstrip(), red=True)
160+
161+
162+
def print_usage_error(e: UsageError, file: TextIO) -> None:
163+
tw = TerminalWriter(file)
164+
for msg in e.args:
165+
tw.line(f"ERROR: {msg}\n", red=True)
166+
167+
145168
def main(
146169
args: list[str] | os.PathLike[str] | None = None,
147170
plugins: Sequence[str | _PluggyPlugin] | None = None,
@@ -167,34 +190,19 @@ def main(
167190
try:
168191
config = _prepareconfig(new_args, plugins)
169192
except ConftestImportFailure as e:
170-
exc_info = ExceptionInfo.from_exception(e.cause)
171-
tw = TerminalWriter(sys.stderr)
172-
tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
173-
exc_info.traceback = exc_info.traceback.filter(
174-
filter_traceback_for_conftest_import_failure
175-
)
176-
exc_repr = (
177-
exc_info.getrepr(style="short", chain=False)
178-
if exc_info.traceback
179-
else exc_info.exconly()
180-
)
181-
formatted_tb = str(exc_repr)
182-
for line in formatted_tb.splitlines():
183-
tw.line(line.rstrip(), red=True)
193+
print_conftest_import_error(e, file=sys.stderr)
184194
return ExitCode.USAGE_ERROR
185-
else:
195+
196+
try:
197+
ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)
186198
try:
187-
ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)
188-
try:
189-
return ExitCode(ret)
190-
except ValueError:
191-
return ret
192-
finally:
193-
config._ensure_unconfigure()
199+
return ExitCode(ret)
200+
except ValueError:
201+
return ret
202+
finally:
203+
config._ensure_unconfigure()
194204
except UsageError as e:
195-
tw = TerminalWriter(sys.stderr)
196-
for msg in e.args:
197-
tw.line(f"ERROR: {msg}\n", red=True)
205+
print_usage_error(e, file=sys.stderr)
198206
return ExitCode.USAGE_ERROR
199207
finally:
200208
if old_pytest_version is None:

0 commit comments

Comments
 (0)