Skip to content

Commit 48dbd5f

Browse files
committed
chore: rewrite reporter tests to simplify
This also catches the "FormatReporter is mutating instances" issue, but a proper fix to that one is to make results immutable. Signed-off-by: Brian Harring <ferringb@gmail.com>
1 parent 4589289 commit 48dbd5f

1 file changed

Lines changed: 82 additions & 73 deletions

File tree

tests/test_reporters.py

Lines changed: 82 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import json
22
import sys
33
import typing
4-
from functools import partial
54
from textwrap import dedent
65

76
import pytest
@@ -13,46 +12,46 @@
1312

1413

1514
class BaseReporter:
16-
reporter_cls = reporters.Reporter
17-
18-
@pytest.fixture(autouse=True)
19-
def _setup(self):
20-
self.log_warning = profiles.ProfileWarning(Exception("profile warning"))
21-
self.log_error = profiles.ProfileError(Exception("profile error"))
22-
pkg = FakePkg("dev-libs/foo-0")
23-
self.commit_result = git.InvalidCommitMessage("no commit message", commit="8d86269bb4c7")
24-
self.category_result = metadata_xml.CatMissingMetadataXml("metadata.xml", pkg=pkg)
25-
self.package_result = pkgdir.InvalidPN(("bar", "baz"), pkg=pkg)
26-
self.versioned_result = metadata.BadFilename(("0.tar.gz", "foo.tar.gz"), pkg=pkg)
27-
self.line_result = codingstyle.ReadonlyVariable("P", line="P=6", lineno=7, pkg=pkg)
28-
self.lines_result = codingstyle.EbuildUnquotedVariable("D", lines=(5, 7), pkg=pkg)
29-
30-
def mk_reporter(self, **kwargs) -> reporters.Reporter:
31-
out = PlainTextFormatter(sys.stdout)
32-
return self.reporter_cls(out, **kwargs)
33-
34-
add_report_output = None
15+
reporter_cls: type[reporters.Reporter]
16+
add_report_output: typing.ClassVar[str]
17+
pkg = FakePkg("dev-libs/foo-0")
18+
19+
results: typing.Final = (
20+
profiles.ProfileWarning(Exception("profile warning")),
21+
profiles.ProfileError(Exception("profile error")),
22+
git.InvalidCommitMessage("no commit message", commit="8d86269bb4c7"),
23+
metadata_xml.CatMissingMetadataXml("metadata.xml", pkg=pkg),
24+
pkgdir.InvalidPN(("bar", "baz"), pkg=pkg),
25+
metadata.BadFilename(("0.tar.gz", "foo.tar.gz"), pkg=pkg),
26+
codingstyle.ReadonlyVariable("P", line="P=6", lineno=7, pkg=pkg),
27+
codingstyle.EbuildUnquotedVariable("D", lines=(5, 7), pkg=pkg),
28+
)
3529

36-
def test_add_report(self, capsys):
37-
with self.mk_reporter() as reporter:
38-
reporter.report(self.commit_result)
39-
reporter.report(self.log_warning)
40-
reporter.report(self.category_result)
41-
reporter.report(self.package_result)
42-
reporter.report(self.versioned_result)
43-
reporter.report(self.line_result)
44-
reporter.report(self.lines_result)
30+
def mk_reporter(self, *args, **kwargs) -> reporters.Reporter:
31+
out = PlainTextFormatter(sys.stdout)
32+
return self.reporter_cls(out, *args, **kwargs)
33+
34+
def assert_add_report(self, capsys, reporter: reporters.Reporter, expected_out: str) -> None:
35+
if reporter is None:
36+
reporter = self.mk_reporter()
37+
with reporter as report:
38+
for result in self.results:
39+
report(result)
4540
out, err = capsys.readouterr()
4641
assert not err
47-
assert out == self.add_report_output
42+
assert out == expected_out
43+
44+
def test_add_report(self, capsys):
45+
self.assert_add_report(capsys, self.mk_reporter(), self.add_report_output)
4846

4947

5048
class TestStrReporter(BaseReporter):
5149
reporter_cls = reporters.StrReporter
5250
add_report_output = dedent(
5351
"""\
54-
commit 8d86269bb4c7: no commit message
5552
profile warning
53+
profile error
54+
commit 8d86269bb4c7: no commit message
5655
dev-libs: category is missing metadata.xml
5756
dev-libs/foo: invalid package names: [ bar, baz ]
5857
dev-libs/foo-0: bad filenames: [ 0.tar.gz, foo.tar.gz ]
@@ -66,11 +65,12 @@ class TestFancyReporter(BaseReporter):
6665
reporter_cls = reporters.FancyReporter
6766
add_report_output = dedent(
6867
"""\
69-
commit
70-
InvalidCommitMessage: commit 8d86269bb4c7: no commit message
71-
7268
profiles
7369
ProfileWarning: profile warning
70+
ProfileError: profile error
71+
72+
commit
73+
InvalidCommitMessage: commit 8d86269bb4c7: no commit message
7474
7575
dev-libs
7676
CatMissingMetadataXml: category is missing metadata.xml
@@ -86,10 +86,12 @@ class TestFancyReporter(BaseReporter):
8686

8787
class TestJsonReporter(BaseReporter):
8888
reporter_cls = reporters.JsonReporter
89+
8990
add_report_output = dedent(
9091
"""\
91-
{"_style": {"InvalidCommitMessage": "commit 8d86269bb4c7: no commit message"}}
9292
{"_warning": {"ProfileWarning": "profile warning"}}
93+
{"_error": {"ProfileError": "profile error"}}
94+
{"_style": {"InvalidCommitMessage": "commit 8d86269bb4c7: no commit message"}}
9395
{"dev-libs": {"_error": {"CatMissingMetadataXml": "category is missing metadata.xml"}}}
9496
{"dev-libs": {"foo": {"_error": {"InvalidPN": "invalid package names: [ bar, baz ]"}}}}
9597
{"dev-libs": {"foo": {"0": {"_warning": {"BadFilename": "bad filenames: [ 0.tar.gz, foo.tar.gz ]"}}}}}
@@ -104,8 +106,9 @@ class TestXmlReporter(BaseReporter):
104106
add_report_output = dedent(
105107
"""\
106108
<checks>
107-
<result><class>InvalidCommitMessage</class><msg>commit 8d86269bb4c7: no commit message</msg></result>
108109
<result><class>ProfileWarning</class><msg>profile warning</msg></result>
110+
<result><class>ProfileError</class><msg>profile error</msg></result>
111+
<result><class>InvalidCommitMessage</class><msg>commit 8d86269bb4c7: no commit message</msg></result>
109112
<result><category>dev-libs</category><class>CatMissingMetadataXml</class><msg>category is missing metadata.xml</msg></result>
110113
<result><category>dev-libs</category><package>foo</package><class>InvalidPN</class><msg>invalid package names: [ bar, baz ]</msg></result>
111114
<result><category>dev-libs</category><package>foo</package><version>0</version><class>BadFilename</class><msg>bad filenames: [ 0.tar.gz, foo.tar.gz ]</msg></result>
@@ -120,8 +123,9 @@ class TestCsvReporter(BaseReporter):
120123
reporter_cls = reporters.CsvReporter
121124
add_report_output = dedent(
122125
"""\
123-
,,,commit 8d86269bb4c7: no commit message
124126
,,,profile warning
127+
,,,profile error
128+
,,,commit 8d86269bb4c7: no commit message
125129
dev-libs,,,category is missing metadata.xml
126130
dev-libs,foo,,"invalid package names: [ bar, baz ]"
127131
dev-libs,foo,0,"bad filenames: [ 0.tar.gz, foo.tar.gz ]"
@@ -132,53 +136,56 @@ class TestCsvReporter(BaseReporter):
132136

133137

134138
class TestFormatReporter(BaseReporter):
135-
reporter_cls = partial(reporters.FormatReporter, "")
139+
reporter_cls = reporters.FormatReporter
136140

137-
def test_add_report(self, capsys):
138-
for format_str, expected in (
139-
("r", "r\n" * 7),
141+
def mk_reporter(self, format_str: str, *args, **kwargs) -> reporters.FormatReporter:
142+
out = PlainTextFormatter(sys.stdout)
143+
return self.reporter_cls(format_str, out, *args, **kwargs)
144+
145+
@pytest.mark.parametrize(
146+
["format_str", "expected"],
147+
[
148+
("r", "r\n" * len(BaseReporter.results)),
140149
("{category}", "dev-libs\n" * 5),
141-
("{category}/{package}", "/\n/\ndev-libs/\n" + "dev-libs/foo\n" * 4),
150+
("{category}/{package}", "/\n/\n/\ndev-libs/\n" + "dev-libs/foo\n" * 4),
142151
(
143152
"{category}/{package}-{version}",
144-
"/-\n/-\ndev-libs/-\ndev-libs/foo-\n" + "dev-libs/foo-0\n" * 3,
145-
),
146-
(
147-
"{name}",
148-
"InvalidCommitMessage\nProfileWarning\nCatMissingMetadataXml\nInvalidPN\nBadFilename\nReadonlyVariable\nUnquotedVariable\n",
153+
"/-\n/-\n/-\ndev-libs/-\ndev-libs/foo-\n" + "dev-libs/foo-0\n" * 3,
149154
),
155+
("{name}", "\n".join(result.name for result in BaseReporter.results) + "\n"),
150156
("{foo}", ""),
151-
):
152-
self.reporter_cls = partial(reporters.FormatReporter, format_str)
153-
self.add_report_output = expected
154-
super().test_add_report(capsys)
157+
],
158+
)
159+
def test_add_report(self, capsys, format_str: str, expected: str): # pyright: ignore[reportIncompatibleMethodOverride]
160+
self.assert_add_report(capsys, self.mk_reporter(format_str), expected)
155161

156162
def test_unsupported_index(self, capsys):
157-
self.reporter_cls = partial(reporters.FormatReporter, "{0}")
158-
with self.mk_reporter() as reporter:
163+
with self.mk_reporter("{0}") as report:
159164
with pytest.raises(base.PkgcheckUserException) as excinfo:
160-
reporter.report(self.versioned_result)
165+
report(self.results[0])
161166
assert "integer indexes are not supported" in str(excinfo.value)
162167

163168

164169
class TestJsonStream(BaseReporter):
165-
reporter_cls = reporters.JsonStream
170+
reporter_cls: type[reporters.JsonStream] = reporters.JsonStream # pyright: ignore[reportIncompatibleVariableOverride]
166171

167-
def test_add_report(self, capsys):
168-
with self.mk_reporter() as reporter:
169-
for result in (
170-
self.log_warning,
171-
self.log_error,
172-
self.commit_result,
173-
self.category_result,
174-
self.package_result,
175-
self.versioned_result,
176-
):
177-
reporter.report(result)
178-
out, err = capsys.readouterr()
179-
assert not err
180-
deserialized_result = next(self.reporter_cls.from_iter([out]))
181-
assert str(deserialized_result) == str(result)
172+
add_report_output = dedent(
173+
"""\
174+
{"__class__": "ProfileWarning", "msg": "profile warning"}
175+
{"__class__": "ProfileError", "msg": "profile error"}
176+
{"__class__": "InvalidCommitMessage", "commit": "8d86269bb4c7", "error": "no commit message"}
177+
{"__class__": "CatMissingMetadataXml", "category": "dev-libs", "filename": "metadata.xml"}
178+
{"__class__": "InvalidPN", "category": "dev-libs", "package": "foo", "ebuilds": ["bar", "baz"]}
179+
{"__class__": "BadFilename", "category": "dev-libs", "package": "foo", "version": "0", "filenames": ["0.tar.gz", "foo.tar.gz"]}
180+
{"__class__": "ReadonlyVariable", "category": "dev-libs", "package": "foo", "version": "0", "line": "P=6", "lineno": 7, "variable": "P"}
181+
{"__class__": "EbuildUnquotedVariable", "category": "dev-libs", "package": "foo", "version": "0", "lines": [5, 7], "variable": "D"}
182+
"""
183+
)
184+
185+
def test_from_iter(self):
186+
assert self.results == tuple(
187+
self.reporter_cls.from_iter(x for x in self.add_report_output.split("\n") if x.strip())
188+
)
182189

183190
def test_deserialize_error(self):
184191
# deserializing non-result objects raises exception
@@ -187,7 +194,8 @@ def test_deserialize_error(self):
187194
next(self.reporter_cls.from_iter([obj]))
188195

189196
# deserializing mangled JSON result objects raises exception
190-
obj = self.reporter_cls.to_json(self.versioned_result)
197+
# TODO: remove typing.cast once to_json is refactored to use registered decoders.
198+
obj = typing.cast(dict[str, str], self.reporter_cls.to_json(self.results[0]))
191199
del obj["__class__"]
192200
json_obj = json.dumps(obj)
193201
with pytest.raises(reporters.DeserializationError, match="unknown result"):
@@ -198,13 +206,14 @@ class TestFlycheckReporter(BaseReporter):
198206
reporter_cls = reporters.FlycheckReporter
199207
add_report_output = dedent(
200208
"""\
201-
-.ebuild:0:style:InvalidCommitMessage: commit 8d86269bb4c7: no commit message
202209
-.ebuild:0:warning:ProfileWarning: profile warning
210+
-.ebuild:0:error:ProfileError: profile error
211+
-.ebuild:0:style:InvalidCommitMessage: commit 8d86269bb4c7: no commit message
203212
-.ebuild:0:error:CatMissingMetadataXml: category is missing metadata.xml
204213
foo-.ebuild:0:error:InvalidPN: invalid package names: [ bar, baz ]
205214
foo-0.ebuild:0:warning:BadFilename: bad filenames: [ 0.tar.gz, foo.tar.gz ]
206215
foo-0.ebuild:7:warning:ReadonlyVariable: read-only variable 'P' assigned, line 7: P=6
207216
foo-0.ebuild:5:warning:UnquotedVariable: unquoted variable D
208217
foo-0.ebuild:7:warning:UnquotedVariable: unquoted variable D
209-
"""
218+
"""
210219
)

0 commit comments

Comments
 (0)