Skip to content
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

Add __str__ and __repr__ to Sanic and Blueprint #2043

Merged
merged 2 commits into from
Mar 3, 2021
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
6 changes: 5 additions & 1 deletion sanic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,8 @@ class BaseSanic(
ExceptionMixin,
metaclass=Base,
):
...
def __str__(self) -> str:
return f"<{self.__class__.__name__} {self.name}>"

def __repr__(self) -> str:
return f'{self.__class__.__name__}(name="{self.name}")'
17 changes: 17 additions & 0 deletions sanic/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,23 @@ def __init__(
self.version = version
self.strict_slashes = strict_slashes

def __repr__(self) -> str:
args = ", ".join(
[
f'{attr}="{getattr(self, attr)}"'
if isinstance(getattr(self, attr), str)
else f"{attr}={getattr(self, attr)}"
for attr in (
"name",
"url_prefix",
"host",
"version",
"strict_slashes",
)
]
)
return f"Blueprint({args})"

def route(self, *args, **kwargs):
kwargs["apply"] = False
return super().route(*args, **kwargs)
Expand Down
43 changes: 43 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import pytest

from sanic import Blueprint, Sanic


@pytest.fixture
def app():
return Sanic("my_app")


@pytest.fixture
def bp(app):
return Blueprint("my_bp")


def test_app_str(app):
assert str(app) == "<Sanic my_app>"


def test_app_repr(app):
assert repr(app) == 'Sanic(name="my_app")'


def test_bp_str(bp):
assert str(bp) == "<Blueprint my_bp>"


def test_bp_repr(bp):
assert repr(bp) == (
'Blueprint(name="my_bp", url_prefix=None, host=None, '
"version=None, strict_slashes=None)"
)


def test_bp_repr_with_values(bp):
bp.host = "example.com"
bp.url_prefix = "/foo"
bp.version = 3
bp.strict_slashes = True
assert repr(bp) == (
'Blueprint(name="my_bp", url_prefix="/foo", host="example.com", '
"version=3, strict_slashes=True)"
)