Skip to content

Add warnings import for deprecated messages #668

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
5 changes: 4 additions & 1 deletion src/betterproto/plugin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,13 @@ def python_module_imports(self) -> Set[str]:
imports = set()

has_deprecated = False
# Check if any messages are marked as deprecated
if any(m.deprecated for m in self.messages):
has_deprecated = True
if any(x for x in self.messages if any(x.deprecated_fields)):
# Check if any fields in any messages are marked as deprecated
if any(any(f.deprecated for f in m.fields) for m in self.messages):
has_deprecated = True
# Check if any methods in any services are marked as deprecated
if any(
any(m.proto_obj.options.deprecated for m in s.methods)
for s in self.services
Expand Down
14 changes: 14 additions & 0 deletions tests/test_deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,17 @@ async def test_service_with_deprecated_method():
with warnings.catch_warnings():
warnings.simplefilter("error")
await stub.func(Empty())


def test_warnings_import_for_deprecated_message():
"""Verify that deprecated messages trigger the warnings import."""
with pytest.warns(DeprecationWarning):
# This should trigger the warnings import in the generated code
Message(value="test")

# Check that warnings module is properly imported in the generated file
import tests.output_betterproto.deprecated as deprecated_module

assert "warnings" in deprecated_module.__dict__, (
"warnings module should be imported for deprecated messages"
)