Skip to content

Commit a6beae3

Browse files
committed
Report data file errors in more detail: include file and directory paths, and make helpful suggestions
1 parent 5c70761 commit a6beae3

13 files changed

+182
-32
lines changed

Diff for: coverage/cmdline.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import sys
1414
import textwrap
1515
import traceback
16+
from contextlib import suppress
1617

1718
from typing import cast, Any, NoReturn
1819

@@ -24,7 +25,8 @@
2425
from coverage.control import DEFAULT_DATAFILE
2526
from coverage.data import combinable_files, debug_data_file
2627
from coverage.debug import info_header, short_stack, write_formatted_info
27-
from coverage.exceptions import _BaseCoverageException, _ExceptionDuringRun, NoSource
28+
from coverage.exceptions import _BaseCoverageException, _ExceptionDuringRun, NoSource, \
29+
NoDataFilesFoundError
2830
from coverage.execfile import PyRunner
2931
from coverage.results import display_covered, should_fail_under
3032
from coverage.version import __url__
@@ -882,9 +884,10 @@ def do_debug(self, args: list[str]) -> int:
882884
print(info_header("data"))
883885
data_file = self.coverage.config.data_file
884886
debug_data_file(data_file)
885-
for filename in combinable_files(data_file):
886-
print("-----")
887-
debug_data_file(filename)
887+
with suppress(NoDataFilesFoundError):
888+
for filename in combinable_files(data_file):
889+
print("-----")
890+
debug_data_file(filename)
888891
elif args[0] == "config":
889892
write_formatted_info(print, "config", self.coverage.config.debug_info())
890893
elif args[0] == "premain":

Diff for: coverage/data.py

+15-8
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
import glob
1616
import hashlib
1717
import os.path
18-
1918
from typing import Callable, Iterable
2019

21-
from coverage.exceptions import CoverageException, NoDataError
20+
from coverage.exceptions import CoverageException, DataFileOrDirectoryNotFoundError, \
21+
NoDataFilesFoundError, UnusableDataFilesError
2222
from coverage.files import PathAliases
2323
from coverage.misc import Hasher, file_be_gone, human_sorted, plural
2424
from coverage.sqldata import CoverageData
@@ -82,12 +82,17 @@ def combinable_files(data_file: str, data_paths: Iterable[str] | None = None) ->
8282
pattern = glob.escape(os.path.join(os.path.abspath(p), local)) +".*"
8383
files_to_combine.extend(glob.glob(pattern))
8484
else:
85-
raise NoDataError(f"Couldn't combine from non-existent path '{p}'")
85+
raise DataFileOrDirectoryNotFoundError.new_for_data_file_or_directory(
86+
p, is_combining=True
87+
)
8688

8789
# SQLite might have made journal files alongside our database files.
8890
# We never want to combine those.
8991
files_to_combine = [fnm for fnm in files_to_combine if not fnm.endswith("-journal")]
9092

93+
if not files_to_combine:
94+
raise NoDataFilesFoundError.new_for_data_directory(data_dir)
95+
9196
# Sorting isn't usually needed, since it shouldn't matter what order files
9297
# are combined, but sorting makes tests more predictable, and makes
9398
# debugging more understandable when things go wrong.
@@ -129,10 +134,12 @@ def combine_parallel_data(
129134
`message` is a function to use for printing messages to the user.
130135
131136
"""
132-
files_to_combine = combinable_files(data.base_filename(), data_paths)
133-
134-
if strict and not files_to_combine:
135-
raise NoDataError("No data to combine")
137+
try:
138+
files_to_combine = combinable_files(data.base_filename(), data_paths)
139+
except NoDataFilesFoundError:
140+
if strict:
141+
raise
142+
return
136143

137144
file_hashes = set()
138145
combined_any = False
@@ -190,7 +197,7 @@ def combine_parallel_data(
190197
file_be_gone(f)
191198

192199
if strict and not combined_any:
193-
raise NoDataError("No usable data files")
200+
raise UnusableDataFilesError.new_for_data_files(*files_to_combine)
194201

195202

196203
def debug_data_file(filename: str) -> None:

Diff for: coverage/exceptions.py

+60
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@
55

66
from __future__ import annotations
77

8+
import os.path
9+
10+
11+
def _message_append_combine_hint(message: str, is_combining: bool) -> str:
12+
"""Append information about the combine command to error messages."""
13+
if not is_combining:
14+
message += " Perhaps `coverage combine` must be run first."
15+
return message
16+
17+
818
class _BaseCoverageException(Exception):
919
"""The base-base of all Coverage exceptions."""
1020
pass
@@ -24,11 +34,61 @@ class DataError(CoverageException):
2434
"""An error in using a data file."""
2535
pass
2636

37+
2738
class NoDataError(CoverageException):
2839
"""We didn't have data to work with."""
2940
pass
3041

3142

43+
class DataFileOrDirectoryNotFoundError(NoDataError):
44+
"""A data file or data directory could be found."""
45+
@classmethod
46+
def new_for_data_file_or_directory(
47+
cls, data_file_or_directory_path: str, *, is_combining: bool = False
48+
) -> 'DataFileOrDirectoryNotFoundError':
49+
"""
50+
Create a new instance.
51+
"""
52+
message = (
53+
f"The data file or directory `{os.path.abspath(data_file_or_directory_path)}` could not"
54+
" be found."
55+
)
56+
return cls(_message_append_combine_hint(message, is_combining))
57+
58+
59+
class NoDataFilesFoundError(NoDataError):
60+
"""No data files could be found in a data directory."""
61+
@classmethod
62+
def new_for_data_directory(
63+
cls, data_directory_path: str, *, is_combining: bool = False
64+
) -> 'NoDataFilesFoundError':
65+
"""
66+
Create a new instance.
67+
"""
68+
message = (
69+
f"The data directory `{os.path.abspath(data_directory_path)}` does not contain any data"
70+
" files."
71+
)
72+
return cls(_message_append_combine_hint(message, is_combining))
73+
74+
75+
class UnusableDataFilesError(NoDataError):
76+
"""The given data files are unusable."""
77+
@classmethod
78+
def new_for_data_files(cls, *data_file_paths: str) -> 'UnusableDataFilesError':
79+
"""
80+
Create a new instance.
81+
"""
82+
message = (
83+
"The following data files are unusable, perhaps because they do not contain valid"
84+
" coverage information:"
85+
)
86+
for data_file_path in data_file_paths:
87+
message += f"\n- `{os.path.abspath(data_file_path)}`"
88+
89+
return cls(message)
90+
91+
3292
class NoSource(CoverageException):
3393
"""We couldn't find the source for a module."""
3494
pass

Diff for: coverage/html.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
import coverage
2121
from coverage.data import CoverageData, add_data_to_hash
22-
from coverage.exceptions import NoDataError
22+
from coverage.exceptions import DataFileOrDirectoryNotFoundError
2323
from coverage.files import flat_rootname
2424
from coverage.misc import (
2525
ensure_dir, file_be_gone, Hasher, isolate_module, format_local_datetime,
@@ -317,7 +317,9 @@ def report(self, morfs: Iterable[TMorf] | None) -> float:
317317
file_be_gone(os.path.join(self.directory, ftr.html_filename))
318318

319319
if not have_data:
320-
raise NoDataError("No data to report.")
320+
raise DataFileOrDirectoryNotFoundError.new_for_data_file_or_directory(
321+
os.path.dirname(self.coverage.get_data().base_filename())
322+
)
321323

322324
self.make_directory()
323325
self.make_local_static_report_files()

Diff for: coverage/report.py

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

66
from __future__ import annotations
77

8+
import os
89
import sys
910

1011
from typing import Any, IO, Iterable, TYPE_CHECKING
1112

12-
from coverage.exceptions import ConfigError, NoDataError
13+
from coverage.exceptions import ConfigError, DataFileOrDirectoryNotFoundError
1314
from coverage.misc import human_sorted_items
1415
from coverage.plugin import FileReporter
1516
from coverage.report_core import get_analysis_to_report
@@ -182,7 +183,9 @@ def report(self, morfs: Iterable[TMorf] | None, outfile: IO[str] | None = None)
182183
self.report_one_file(fr, analysis)
183184

184185
if not self.total.n_files and not self.skipped_count:
185-
raise NoDataError("No data to report.")
186+
raise DataFileOrDirectoryNotFoundError.new_for_data_file_or_directory(
187+
os.path.dirname(self.coverage.get_data().base_filename())
188+
)
186189

187190
if self.output_format == "total":
188191
self.write(self.total.pc_covered_str)

Diff for: coverage/report_core.py

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

66
from __future__ import annotations
77

8+
import os
89
import sys
910

1011
from typing import (
1112
Callable, Iterable, Iterator, IO, Protocol, TYPE_CHECKING,
1213
)
1314

14-
from coverage.exceptions import NoDataError, NotPython
15+
from coverage.exceptions import NotPython, DataFileOrDirectoryNotFoundError
1516
from coverage.files import prep_patterns, GlobMatcher
1617
from coverage.misc import ensure_dir_for_file, file_be_gone
1718
from coverage.plugin import FileReporter
@@ -93,7 +94,9 @@ def get_analysis_to_report(
9394
fr_morfs = [(fr, morf) for (fr, morf) in fr_morfs if not matcher.match(fr.filename)]
9495

9596
if not fr_morfs:
96-
raise NoDataError("No data to report.")
97+
raise DataFileOrDirectoryNotFoundError.new_for_data_file_or_directory(
98+
os.path.dirname(coverage.get_data().base_filename())
99+
)
97100

98101
for fr, morf in sorted(fr_morfs):
99102
try:

Diff for: tests/test_api.py

+22-4
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,13 @@ def test_empty_reporting(self) -> None:
300300
# empty summary reports raise exception, just like the xml report
301301
cov = coverage.Coverage()
302302
cov.erase()
303-
with pytest.raises(NoDataError, match="No data to report."):
303+
with pytest.raises(
304+
NoDataError,
305+
match=(
306+
r"^The data file or directory `(.+?)` could not be found\. Perhaps `coverage "
307+
r"combine` must be run first\.$"
308+
)
309+
):
304310
cov.report()
305311

306312
def test_completely_zero_reporting(self) -> None:
@@ -446,7 +452,13 @@ def test_combining_twice(self) -> None:
446452
self.assert_exists(".coverage")
447453

448454
cov2 = coverage.Coverage()
449-
with pytest.raises(NoDataError, match=r"No data to combine"):
455+
with pytest.raises(
456+
NoDataError,
457+
match=(
458+
r"^The data directory `(.+?)` does not contain any data files. Perhaps `coverage "
459+
r"combine` must be run first.$"
460+
)
461+
):
450462
cov2.combine(strict=True, keep=False)
451463

452464
cov3 = coverage.Coverage()
@@ -1326,7 +1338,7 @@ def test_combine_parallel_data(self) -> None:
13261338
# Running combine again should fail, because there are no parallel data
13271339
# files to combine.
13281340
cov = coverage.Coverage()
1329-
with pytest.raises(NoDataError, match=r"No data to combine"):
1341+
with pytest.raises(NoDataError):
13301342
cov.combine(strict=True)
13311343

13321344
# And the originally combined data is still there.
@@ -1376,7 +1388,13 @@ def test_combine_no_usable_files(self) -> None:
13761388
# Combine the parallel coverage data files into .coverage, but nothing is readable.
13771389
cov = coverage.Coverage()
13781390
with pytest.warns(Warning) as warns:
1379-
with pytest.raises(NoDataError, match=r"No usable data files"):
1391+
with pytest.raises(
1392+
NoDataError,
1393+
match=(
1394+
r"^The following data files are unusable, perhaps because they do not contain "
1395+
r"valid coverage information:\n- `(.+?)`\n- `(.+?)`$"
1396+
)
1397+
):
13801398
cov.combine(strict=True)
13811399

13821400
warn_rx = re.compile(

Diff for: tests/test_coverage.py

+21-3
Original file line numberDiff line numberDiff line change
@@ -1635,19 +1635,37 @@ class ReportingTest(CoverageTest):
16351635
def test_no_data_to_report_on_annotate(self) -> None:
16361636
# Reporting with no data produces a nice message and no output
16371637
# directory.
1638-
with pytest.raises(NoDataError, match="No data to report."):
1638+
with pytest.raises(
1639+
NoDataError,
1640+
match=(
1641+
r"^The data file or directory `(.+?)` could not be found\. Perhaps `coverage "
1642+
r"combine` must be run first\.$"
1643+
)
1644+
):
16391645
self.command_line("annotate -d ann")
16401646
self.assert_doesnt_exist("ann")
16411647

16421648
def test_no_data_to_report_on_html(self) -> None:
16431649
# Reporting with no data produces a nice message and no output
16441650
# directory.
1645-
with pytest.raises(NoDataError, match="No data to report."):
1651+
with pytest.raises(
1652+
NoDataError,
1653+
match=(
1654+
r"^The data file or directory `(.+?)` could not be found\. Perhaps `coverage "
1655+
r"combine` must be run first\.$"
1656+
)
1657+
):
16461658
self.command_line("html -d htmlcov")
16471659
self.assert_doesnt_exist("htmlcov")
16481660

16491661
def test_no_data_to_report_on_xml(self) -> None:
16501662
# Reporting with no data produces a nice message.
1651-
with pytest.raises(NoDataError, match="No data to report."):
1663+
with pytest.raises(
1664+
NoDataError,
1665+
match=(
1666+
r"^The data file or directory `(.+?)` could not be found\. Perhaps `coverage "
1667+
r"combine` must be run first\.$"
1668+
)
1669+
):
16521670
self.command_line("xml")
16531671
self.assert_doesnt_exist("coverage.xml")

Diff for: tests/test_data.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -915,7 +915,7 @@ def test_combining_from_files(self) -> None:
915915

916916
def test_combining_from_nonexistent_directories(self) -> None:
917917
covdata = DebugCoverageData()
918-
msg = "Couldn't combine from non-existent path 'xyzzy'"
918+
msg = r"^The data file or directory `(.+?)` could not be found.$"
919919
with pytest.raises(NoDataError, match=msg):
920920
combine_parallel_data(covdata, data_paths=['xyzzy'])
921921

Diff for: tests/test_html.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,13 @@ def test_dothtml_not_python(self) -> None:
426426
self.make_file("innocuous.html", "<h1>This isn't python at all!</h1>")
427427
cov = coverage.Coverage()
428428
cov.load()
429-
with pytest.raises(NoDataError, match="No data to report."):
429+
with pytest.raises(
430+
NoDataError,
431+
match=(
432+
r"^The data file or directory `(.+?)` could not be found\. Perhaps `coverage "
433+
r"combine` must be run first\.$"
434+
)
435+
):
430436
cov.html_report()
431437

432438
def test_execed_liar_ignored(self) -> None:

Diff for: tests/test_process.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1143,7 +1143,13 @@ class FailUnderNoFilesTest(CoverageTest):
11431143
def test_report(self) -> None:
11441144
self.make_file(".coveragerc", "[report]\nfail_under = 99\n")
11451145
st, out = self.run_command_status("coverage report")
1146-
assert 'No data to report.' in out
1146+
assert re.match(
1147+
(
1148+
r"The data file or directory `([^`]+?)` could not be found\. Perhaps `coverage "
1149+
r"combine` must be run first\."
1150+
),
1151+
out
1152+
)
11471153
assert st == 1
11481154

11491155

0 commit comments

Comments
 (0)