Skip to content

Attain 100% Coverage for tests/ directory #18470

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[tool.coverage.run]
branch = true
dynamic_context = "test_function"
source = ["warehouse"]
source = ["warehouse", "tests"]
omit = [
# We don't want to get coverage information for our migrations.
"warehouse/migrations/*",
Expand All @@ -22,10 +22,12 @@ omit = [
parallel = true

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

[tool.djlint]
Expand Down
2 changes: 0 additions & 2 deletions tests/common/db/integrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,5 @@ class Meta:
id = factory.Faker("word")
source = factory.Faker("word")
link = factory.Faker("uri")
aliases = factory.Sequence(lambda n: "alias" + str(n))
releases = factory.SubFactory(ReleaseFactory)
details = factory.Faker("word")
fixed_in = factory.Sequence(lambda n: str(n) + ".0")
9 changes: 5 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def _event(
tags=None,
hostname=None,
):
return None
return None # pragma: no cover


@pytest.fixture
Expand Down Expand Up @@ -597,6 +597,7 @@ def query_recorder(app_config):
yield recorder
finally:
event.remove(engine, "before_cursor_execute", recorder.record)
recorder.clear()


@pytest.fixture
Expand Down Expand Up @@ -738,7 +739,7 @@ class _MockRedis:
def __init__(self, cache=None):
self.cache = cache

if not self.cache:
if not self.cache: # pragma: no cover
self.cache = dict()

def __enter__(self):
Expand Down Expand Up @@ -769,7 +770,7 @@ def hget(self, hash_, key):
return None

def hset(self, hash_, key, value, *_args, **_kwargs):
if hash_ not in self.cache:
if hash_ not in self.cache: # pragma: no cover
self.cache[hash_] = dict()
self.cache[hash_][key] = value

Expand All @@ -780,7 +781,7 @@ def pipeline(self):
return self

def register_script(self, script):
return script
return script # pragma: no cover

def scan_iter(self, search, count):
del count # unused
Expand Down
10 changes: 3 additions & 7 deletions tests/unit/accounts/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,11 @@ class TestUserProfile:
def test_user_redirects_username(self, db_request):
user = UserFactory.create()

if user.username.upper() != user.username:
username = user.username.upper()
else:
username = user.username.lower()

db_request.current_route_path = pretend.call_recorder(
lambda username: "/user/the-redirect/"
)
db_request.matchdict = {"username": username}
# Intentionally swap the case of the username to trigger the redirect
db_request.matchdict = {"username": user.username.swapcase()}

result = views.profile(user, db_request)

Expand Down Expand Up @@ -3505,7 +3501,7 @@ def find_service(iface, name=None, context=None):
return metrics
if iface is IProjectService:
return project_service
return pretend.stub()
pytest.fail(f"Unexpected service requested: {iface}")

request = pretend.stub(
find_service=pretend.call_recorder(find_service),
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/admin/views/test_organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -974,7 +974,7 @@ def _organization_application_routes(
elif route_name == "admin.dashboard":
return "/admin/"
else:
raise ValueError("No dummy route found")
pytest.fail(f"No dummy route found for {route_name}")


class TestOrganizationApplicationActions:
Expand Down
9 changes: 3 additions & 6 deletions tests/unit/cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ def test_lazy_config_delays(monkeypatch):
assert configure.calls == [pretend.call("thing", settings={"lol": "wat"})]


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

@warehouse.cli.warehouse.command()
@click.pass_obj
def cli_test_command(obj):
def cli_test_command(obj): # pragma: no cover
assert obj is config

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

@warehouse.cli.warehouse.command()
@click.pass_obj
def cli_test_command(obj):
assert obj is config

result = cli.invoke(warehouse.cli.warehouse, ["db", "-h"])

assert result.exit_code == 0
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/email/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ class Task:
@staticmethod
@pretend.call_recorder
def retry(exc):
raise celery.exceptions.Retry
pytest.fail("retry should not be called")

sender, task = FakeMailSender(), Task()
request = pretend.stub(find_service=lambda *a, **kw: sender)
Expand Down
35 changes: 10 additions & 25 deletions tests/unit/forklift/test_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,11 @@ def test_exc_with_missing_message(self, monkeypatch):


def test_construct_dependencies():
types = {"requires": DependencyKind.requires, "provides": DependencyKind.provides}
types = {
"requires": DependencyKind.requires,
"provides": DependencyKind.provides,
"requires_dist": DependencyKind.requires_dist,
}

meta = metadata.Metadata.from_raw(
{
Expand Down Expand Up @@ -3064,10 +3068,7 @@ def test_upload_succeeds_pep625_normalized_filename(
@pretend.call_recorder
def storage_service_store(path, file_path, *, meta):
with open(file_path, "rb") as fp:
if file_path.endswith(".metadata"):
assert fp.read() == b"Fake metadata"
else:
assert fp.read() == filebody
assert fp.read() == filebody

storage_service = pretend.stub(store=storage_service_store)

Expand Down Expand Up @@ -5153,13 +5154,13 @@ def test_upload_succeeds_creates_release_metadata_2_4(
)
digest = _TAR_GZ_PKG_MD5
data = _TAR_GZ_PKG_TESTDATA
elif mimetype == "application/zip":
elif mimetype == "application/zip": # pragma: no branch
filename = "{}-{}.zip".format(
project.normalized_name.replace("-", "_"), "1.0"
)
digest = _ZIP_PKG_MD5
data = _ZIP_PKG_TESTDATA
elif filetype == "bdist_wheel":
elif filetype == "bdist_wheel": # pragma: no branch
filename = "{}-{}-py3-none-any.whl".format(
project.normalized_name.replace("-", "_"), "1.0"
)
Expand Down Expand Up @@ -5271,14 +5272,14 @@ def test_upload_fails_missing_license_file_metadata_2_4(
)
digest = _TAR_GZ_PKG_MD5
data = _TAR_GZ_PKG_TESTDATA
elif mimetype == "application/zip":
elif mimetype == "application/zip": # pragma: no branch
filename = "{}-{}.zip".format(
project.normalized_name.replace("-", "_"), "1.0"
)
digest = _ZIP_PKG_MD5
data = _ZIP_PKG_TESTDATA
license_filename = "fake_package-1.0/LICENSE"
elif filetype == "bdist_wheel":
elif filetype == "bdist_wheel": # pragma: no branch
filename = "{}-{}-py3-none-any.whl".format(
project.normalized_name.replace("-", "_"),
"1.0",
Expand Down Expand Up @@ -5475,22 +5476,6 @@ def test_upload_for_company_organization_owned_project_fails_without_subscriptio
name=project.normalized_name.replace("-", "_"), version=version
)

@pretend.call_recorder
def storage_service_store(path, file_path, *, meta):
with open(file_path, "rb") as fp:
if file_path.endswith(".metadata"):
assert fp.read() == b"Fake metadata"
else:
assert fp.read() == filebody

storage_service = pretend.stub(store=storage_service_store)

db_request.find_service = pretend.call_recorder(
lambda svc, name=None, context=None: {
IFileStorage: storage_service,
}.get(svc)
)

monkeypatch.setattr(
legacy, "_is_valid_dist_file", lambda *a, **kw: (True, None)
)
Expand Down
15 changes: 3 additions & 12 deletions tests/unit/i18n/test_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,6 @@ def __getattribute__(self, _: str):
)


def _get_with_context(value, ctx=None):
if isinstance(value, dict):
return value.get(ctx, value)
return value


class TestFallbackInternationalizationExtension:
@pytest.mark.parametrize(
(
Expand Down Expand Up @@ -139,8 +133,7 @@ def test_gettext_fallback(self, translation, expected):
@pass_context
def gettext(context, string):
language = context.get("LANGUAGE", "en")
value = languages.get(language, {}).get(string, string)
return _get_with_context(value)
return languages.get(language, {}).get(string, string)

env = Environment(
loader=DictLoader(templates),
Expand Down Expand Up @@ -214,10 +207,8 @@ def test_ngettext_fallback(
def ngettext(context, s, p, n):
language = context.get("LANGUAGE", "en")
if n != 1:
value = languages.get(language, {}).get(p, p)
return _get_with_context(value)
value = languages.get(language, {}).get(s, s)
return _get_with_context(value)
return languages.get(language, {}).get(p, p)
return languages.get(language, {}).get(s, s)

env = Environment(
loader=DictLoader(templates),
Expand Down
36 changes: 12 additions & 24 deletions tests/unit/legacy/api/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,7 @@ def test_normalizing_redirects(self, db_request):
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project, version="1.0")

name = project.name.lower()
if name == project.normalized_name:
name = project.name.upper()

db_request.matchdict = {"name": name}
db_request.matchdict = {"name": project.name.swapcase()}
db_request.current_route_path = pretend.call_recorder(
lambda name: "/project/the-redirect/"
)
Expand Down Expand Up @@ -367,11 +363,7 @@ def test_normalizing_redirects(self, db_request):
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project, version="1.0")

name = project.name.lower()
if name == project.normalized_name:
name = project.name.upper()

db_request.matchdict = {"name": name}
db_request.matchdict = {"name": project.name.swapcase()}
db_request.current_route_path = pretend.call_recorder(
lambda name: "/project/the-redirect/"
)
Expand Down Expand Up @@ -446,14 +438,12 @@ def test_lookup_release(

class TestJSONRelease:
def test_normalizing_redirects(self, db_request):
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project, version="3.0")
release = ReleaseFactory.create(version="3.0")

name = release.project.name.lower()
if name == release.project.normalized_name:
name = release.project.name.upper()

db_request.matchdict = {"name": name, "version": "3.0"}
db_request.matchdict = {
"name": release.project.name.swapcase(),
"version": "3.0",
}
db_request.current_route_path = pretend.call_recorder(
lambda name: "/project/the-redirect/3.0/"
)
Expand Down Expand Up @@ -744,14 +734,12 @@ def test_vulnerabilities_renders(self, pyramid_config, db_request, withdrawn):

class TestJSONReleaseSlash:
def test_normalizing_redirects(self, db_request):
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project, version="3.0")

name = release.project.name.lower()
if name == release.project.normalized_name:
name = release.project.name.upper()
release = ReleaseFactory.create(version="3.0")

db_request.matchdict = {"name": name, "version": "3.0"}
db_request.matchdict = {
"name": release.project.name.swapcase(),
"version": "3.0",
}
db_request.current_route_path = pretend.call_recorder(
lambda name: "/project/the-redirect/3.0/"
)
Expand Down
7 changes: 3 additions & 4 deletions tests/unit/legacy/api/xmlrpc/test_xmlrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def view(context, request):

def test_ratelimiting_block(self, pyramid_services, pyramid_request, metrics):
def view(context, request):
return None
pytest.fail("view should not be called")

ratelimited_view = xmlrpc.ratelimit()(view)
context = pretend.stub()
Expand Down Expand Up @@ -77,7 +77,7 @@ def test_ratelimiting_block_with_hint(
self, pyramid_services, pyramid_request, metrics, resets_in_delta, expected
):
def view(context, request):
return None
pytest.fail("view should not be called")

ratelimited_view = xmlrpc.ratelimit()(view)
context = pretend.stub()
Expand Down Expand Up @@ -145,8 +145,7 @@ def test_list_packages_with_serial(db_request):
expected.setdefault(project.name, 0)
entries = JournalEntryFactory.create_batch(10, name=project.name)
for entry in entries:
if entry.id > expected[project.name]:
expected[project.name] = entry.id
expected[project.name] = entry.id
assert xmlrpc.list_packages_with_serial(db_request) == expected


Expand Down
2 changes: 1 addition & 1 deletion tests/unit/manage/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def mock_form(*args, **kwargs):

@pretend.call_recorder
def view(context, request):
return response
pytest.fail("view should not be called")

info = pretend.stub(options={}, exception_only=False)
info.options["require_reauth"] = require_reauth
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/manage/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6348,8 +6348,8 @@ def test_manage_project_oidc_publishers_prefill(

# The form data does not contain the provider, so we'll remove it from
# the prefilled data before comparing them
if "provider" in prefilled_data:
del prefilled_data["provider"]
del prefilled_data["provider"]

form = getattr(view, form_name)
assert form.data == prefilled_data

Expand Down Expand Up @@ -6431,8 +6431,8 @@ def test_manage_project_oidc_publishers_prefill_partial(

# The form data does not contain the provider, so we'll remove it from
# the prefilled data before comparing them
if "provider" in prefilled_data:
del prefilled_data["provider"]
del prefilled_data["provider"]

missing_data = {k: None for k in missing_fields}
# The expected form data is the prefilled data plus the missing fields
# (set to None) minus the extra fields
Expand Down
Loading