Skip to content

Commit f1820e0

Browse files
authored
Attain 100% Coverage for tests/ directory (#18470)
1 parent e965837 commit f1820e0

24 files changed

+74
-219
lines changed

pyproject.toml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[tool.coverage.run]
22
branch = true
33
dynamic_context = "test_function"
4-
source = ["warehouse"]
4+
source = ["warehouse", "tests"]
55
omit = [
66
# We don't want to get coverage information for our migrations.
77
"warehouse/migrations/*",
@@ -22,10 +22,12 @@ omit = [
2222
parallel = true
2323

2424
[tool.coverage.report]
25-
exclude_lines = [
26-
"pragma: no cover",
25+
exclude_also = [
2726
"class \\w+\\(Interface\\):",
2827
"if (typing\\.)?TYPE_CHECKING:",
28+
"pytest.fail\\(", # Use for test branches that should never be reached.
29+
# Remove once resolved: https://github.com/nedbat/coveragepy/issues/1563
30+
"case _:\\n\\s*pytest\\.fail\\(",
2931
]
3032

3133
[tool.djlint]

tests/common/db/integrations.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,5 @@ class Meta:
1515
id = factory.Faker("word")
1616
source = factory.Faker("word")
1717
link = factory.Faker("uri")
18-
aliases = factory.Sequence(lambda n: "alias" + str(n))
1918
releases = factory.SubFactory(ReleaseFactory)
2019
details = factory.Faker("word")
21-
fixed_in = factory.Sequence(lambda n: str(n) + ".0")

tests/conftest.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def _event(
8989
tags=None,
9090
hostname=None,
9191
):
92-
return None
92+
return None # pragma: no cover
9393

9494

9595
@pytest.fixture
@@ -597,6 +597,7 @@ def query_recorder(app_config):
597597
yield recorder
598598
finally:
599599
event.remove(engine, "before_cursor_execute", recorder.record)
600+
recorder.clear()
600601

601602

602603
@pytest.fixture
@@ -738,7 +739,7 @@ class _MockRedis:
738739
def __init__(self, cache=None):
739740
self.cache = cache
740741

741-
if not self.cache:
742+
if not self.cache: # pragma: no cover
742743
self.cache = dict()
743744

744745
def __enter__(self):
@@ -769,7 +770,7 @@ def hget(self, hash_, key):
769770
return None
770771

771772
def hset(self, hash_, key, value, *_args, **_kwargs):
772-
if hash_ not in self.cache:
773+
if hash_ not in self.cache: # pragma: no cover
773774
self.cache[hash_] = dict()
774775
self.cache[hash_][key] = value
775776

@@ -780,7 +781,7 @@ def pipeline(self):
780781
return self
781782

782783
def register_script(self, script):
783-
return script
784+
return script # pragma: no cover
784785

785786
def scan_iter(self, search, count):
786787
del count # unused

tests/unit/accounts/test_views.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -121,15 +121,11 @@ class TestUserProfile:
121121
def test_user_redirects_username(self, db_request):
122122
user = UserFactory.create()
123123

124-
if user.username.upper() != user.username:
125-
username = user.username.upper()
126-
else:
127-
username = user.username.lower()
128-
129124
db_request.current_route_path = pretend.call_recorder(
130125
lambda username: "/user/the-redirect/"
131126
)
132-
db_request.matchdict = {"username": username}
127+
# Intentionally swap the case of the username to trigger the redirect
128+
db_request.matchdict = {"username": user.username.swapcase()}
133129

134130
result = views.profile(user, db_request)
135131

@@ -3505,7 +3501,7 @@ def find_service(iface, name=None, context=None):
35053501
return metrics
35063502
if iface is IProjectService:
35073503
return project_service
3508-
return pretend.stub()
3504+
pytest.fail(f"Unexpected service requested: {iface}")
35093505

35103506
request = pretend.stub(
35113507
find_service=pretend.call_recorder(find_service),

tests/unit/admin/views/test_organizations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -974,7 +974,7 @@ def _organization_application_routes(
974974
elif route_name == "admin.dashboard":
975975
return "/admin/"
976976
else:
977-
raise ValueError("No dummy route found")
977+
pytest.fail(f"No dummy route found for {route_name}")
978978

979979

980980
class TestOrganizationApplicationActions:

tests/unit/cli/test_cli.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,16 @@ def test_lazy_config_delays(monkeypatch):
2121
assert configure.calls == [pretend.call("thing", settings={"lol": "wat"})]
2222

2323

24+
# TODO: This test doesn't actually test anything, as the command is not registered.
25+
# The test output is effectively "command not found".
2426
def test_cli_no_settings(monkeypatch, cli):
2527
config = pretend.stub()
2628
configure = pretend.call_recorder(lambda: config)
2729
monkeypatch.setattr(warehouse.cli, "LazyConfig", configure)
2830

2931
@warehouse.cli.warehouse.command()
3032
@click.pass_obj
31-
def cli_test_command(obj):
33+
def cli_test_command(obj): # pragma: no cover
3234
assert obj is config
3335

3436
result = cli.invoke(warehouse.cli.warehouse, ["cli-test-command"])
@@ -42,11 +44,6 @@ def test_cli_help(monkeypatch, cli):
4244
configure = pretend.call_recorder(lambda: config)
4345
monkeypatch.setattr(warehouse.cli, "LazyConfig", configure)
4446

45-
@warehouse.cli.warehouse.command()
46-
@click.pass_obj
47-
def cli_test_command(obj):
48-
assert obj is config
49-
5047
result = cli.invoke(warehouse.cli.warehouse, ["db", "-h"])
5148

5249
assert result.exit_code == 0

tests/unit/email/test_init.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@ class Task:
491491
@staticmethod
492492
@pretend.call_recorder
493493
def retry(exc):
494-
raise celery.exceptions.Retry
494+
pytest.fail("retry should not be called")
495495

496496
sender, task = FakeMailSender(), Task()
497497
request = pretend.stub(find_service=lambda *a, **kw: sender)

tests/unit/forklift/test_legacy.py

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,11 @@ def test_exc_with_missing_message(self, monkeypatch):
145145

146146

147147
def test_construct_dependencies():
148-
types = {"requires": DependencyKind.requires, "provides": DependencyKind.provides}
148+
types = {
149+
"requires": DependencyKind.requires,
150+
"provides": DependencyKind.provides,
151+
"requires_dist": DependencyKind.requires_dist,
152+
}
149153

150154
meta = metadata.Metadata.from_raw(
151155
{
@@ -3064,10 +3068,7 @@ def test_upload_succeeds_pep625_normalized_filename(
30643068
@pretend.call_recorder
30653069
def storage_service_store(path, file_path, *, meta):
30663070
with open(file_path, "rb") as fp:
3067-
if file_path.endswith(".metadata"):
3068-
assert fp.read() == b"Fake metadata"
3069-
else:
3070-
assert fp.read() == filebody
3071+
assert fp.read() == filebody
30713072

30723073
storage_service = pretend.stub(store=storage_service_store)
30733074

@@ -5153,13 +5154,13 @@ def test_upload_succeeds_creates_release_metadata_2_4(
51535154
)
51545155
digest = _TAR_GZ_PKG_MD5
51555156
data = _TAR_GZ_PKG_TESTDATA
5156-
elif mimetype == "application/zip":
5157+
elif mimetype == "application/zip": # pragma: no branch
51575158
filename = "{}-{}.zip".format(
51585159
project.normalized_name.replace("-", "_"), "1.0"
51595160
)
51605161
digest = _ZIP_PKG_MD5
51615162
data = _ZIP_PKG_TESTDATA
5162-
elif filetype == "bdist_wheel":
5163+
elif filetype == "bdist_wheel": # pragma: no branch
51635164
filename = "{}-{}-py3-none-any.whl".format(
51645165
project.normalized_name.replace("-", "_"), "1.0"
51655166
)
@@ -5271,14 +5272,14 @@ def test_upload_fails_missing_license_file_metadata_2_4(
52715272
)
52725273
digest = _TAR_GZ_PKG_MD5
52735274
data = _TAR_GZ_PKG_TESTDATA
5274-
elif mimetype == "application/zip":
5275+
elif mimetype == "application/zip": # pragma: no branch
52755276
filename = "{}-{}.zip".format(
52765277
project.normalized_name.replace("-", "_"), "1.0"
52775278
)
52785279
digest = _ZIP_PKG_MD5
52795280
data = _ZIP_PKG_TESTDATA
52805281
license_filename = "fake_package-1.0/LICENSE"
5281-
elif filetype == "bdist_wheel":
5282+
elif filetype == "bdist_wheel": # pragma: no branch
52825283
filename = "{}-{}-py3-none-any.whl".format(
52835284
project.normalized_name.replace("-", "_"),
52845285
"1.0",
@@ -5475,22 +5476,6 @@ def test_upload_for_company_organization_owned_project_fails_without_subscriptio
54755476
name=project.normalized_name.replace("-", "_"), version=version
54765477
)
54775478

5478-
@pretend.call_recorder
5479-
def storage_service_store(path, file_path, *, meta):
5480-
with open(file_path, "rb") as fp:
5481-
if file_path.endswith(".metadata"):
5482-
assert fp.read() == b"Fake metadata"
5483-
else:
5484-
assert fp.read() == filebody
5485-
5486-
storage_service = pretend.stub(store=storage_service_store)
5487-
5488-
db_request.find_service = pretend.call_recorder(
5489-
lambda svc, name=None, context=None: {
5490-
IFileStorage: storage_service,
5491-
}.get(svc)
5492-
)
5493-
54945479
monkeypatch.setattr(
54955480
legacy, "_is_valid_dist_file", lambda *a, **kw: (True, None)
54965481
)

tests/unit/i18n/test_extensions.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,6 @@ def __getattribute__(self, _: str):
4343
)
4444

4545

46-
def _get_with_context(value, ctx=None):
47-
if isinstance(value, dict):
48-
return value.get(ctx, value)
49-
return value
50-
51-
5246
class TestFallbackInternationalizationExtension:
5347
@pytest.mark.parametrize(
5448
(
@@ -139,8 +133,7 @@ def test_gettext_fallback(self, translation, expected):
139133
@pass_context
140134
def gettext(context, string):
141135
language = context.get("LANGUAGE", "en")
142-
value = languages.get(language, {}).get(string, string)
143-
return _get_with_context(value)
136+
return languages.get(language, {}).get(string, string)
144137

145138
env = Environment(
146139
loader=DictLoader(templates),
@@ -214,10 +207,8 @@ def test_ngettext_fallback(
214207
def ngettext(context, s, p, n):
215208
language = context.get("LANGUAGE", "en")
216209
if n != 1:
217-
value = languages.get(language, {}).get(p, p)
218-
return _get_with_context(value)
219-
value = languages.get(language, {}).get(s, s)
220-
return _get_with_context(value)
210+
return languages.get(language, {}).get(p, p)
211+
return languages.get(language, {}).get(s, s)
221212

222213
env = Environment(
223214
loader=DictLoader(templates),

tests/unit/legacy/api/test_json.py

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -126,11 +126,7 @@ def test_normalizing_redirects(self, db_request):
126126
project = ProjectFactory.create()
127127
release = ReleaseFactory.create(project=project, version="1.0")
128128

129-
name = project.name.lower()
130-
if name == project.normalized_name:
131-
name = project.name.upper()
132-
133-
db_request.matchdict = {"name": name}
129+
db_request.matchdict = {"name": project.name.swapcase()}
134130
db_request.current_route_path = pretend.call_recorder(
135131
lambda name: "/project/the-redirect/"
136132
)
@@ -367,11 +363,7 @@ def test_normalizing_redirects(self, db_request):
367363
project = ProjectFactory.create()
368364
release = ReleaseFactory.create(project=project, version="1.0")
369365

370-
name = project.name.lower()
371-
if name == project.normalized_name:
372-
name = project.name.upper()
373-
374-
db_request.matchdict = {"name": name}
366+
db_request.matchdict = {"name": project.name.swapcase()}
375367
db_request.current_route_path = pretend.call_recorder(
376368
lambda name: "/project/the-redirect/"
377369
)
@@ -446,14 +438,12 @@ def test_lookup_release(
446438

447439
class TestJSONRelease:
448440
def test_normalizing_redirects(self, db_request):
449-
project = ProjectFactory.create()
450-
release = ReleaseFactory.create(project=project, version="3.0")
441+
release = ReleaseFactory.create(version="3.0")
451442

452-
name = release.project.name.lower()
453-
if name == release.project.normalized_name:
454-
name = release.project.name.upper()
455-
456-
db_request.matchdict = {"name": name, "version": "3.0"}
443+
db_request.matchdict = {
444+
"name": release.project.name.swapcase(),
445+
"version": "3.0",
446+
}
457447
db_request.current_route_path = pretend.call_recorder(
458448
lambda name: "/project/the-redirect/3.0/"
459449
)
@@ -744,14 +734,12 @@ def test_vulnerabilities_renders(self, pyramid_config, db_request, withdrawn):
744734

745735
class TestJSONReleaseSlash:
746736
def test_normalizing_redirects(self, db_request):
747-
project = ProjectFactory.create()
748-
release = ReleaseFactory.create(project=project, version="3.0")
749-
750-
name = release.project.name.lower()
751-
if name == release.project.normalized_name:
752-
name = release.project.name.upper()
737+
release = ReleaseFactory.create(version="3.0")
753738

754-
db_request.matchdict = {"name": name, "version": "3.0"}
739+
db_request.matchdict = {
740+
"name": release.project.name.swapcase(),
741+
"version": "3.0",
742+
}
755743
db_request.current_route_path = pretend.call_recorder(
756744
lambda name: "/project/the-redirect/3.0/"
757745
)

0 commit comments

Comments
 (0)