Skip to content

Commit

Permalink
Fix utils.get_name_from_obj proper view names (#1846)
Browse files Browse the repository at this point in the history
  • Loading branch information
leandrodesouzadev committed Oct 23, 2023
1 parent d4cfadc commit e58e78b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
16 changes: 9 additions & 7 deletions debug_toolbar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,15 @@ def get_template_source_from_exception_info(


def get_name_from_obj(obj: Any) -> str:
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__

if hasattr(obj, "__module__"):
module = obj.__module__
name = f"{module}.{name}"

return name
"""Get the best name as `str` from a view or a object."""
# This is essentially a rewrite of the `django.contrib.admindocs.utils.get_view_name`
# https://github.com/django/django/blob/9a22d1769b042a88741f0ff3087f10d94f325d86/django/contrib/admindocs/utils.py#L26-L32
if hasattr(obj, "view_class"):
klass = obj.view_class
return f"{klass.__module__}.{klass.__qualname__}"
mod_name = obj.__module__
view_name = getattr(obj, "__qualname__", obj.__class__.__name__)
return mod_name + "." + view_name


def getframeinfo(frame: Any, context: int = 1) -> inspect.Traceback:
Expand Down
2 changes: 2 additions & 0 deletions docs/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Pending
* Fixed template panel to avoid evaluating ``LazyObject`` when not already
evaluated.
* Added support for Django 5.0.
* Refactor the ``utils.get_name_from_obj`` to simulate the behavior of
``django.contrib.admindocs.utils.get_view_name``.

4.2.0 (2023-08-10)
------------------
Expand Down
12 changes: 9 additions & 3 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,24 @@ def x():
return 1

res = get_name_from_obj(x)
self.assertEqual(res, "tests.test_utils.x")
self.assertEqual(
res, "tests.test_utils.GetNameFromObjTestCase.test_func.<locals>.x"
)

def test_lambda(self):
res = get_name_from_obj(lambda: 1)
self.assertEqual(res, "tests.test_utils.<lambda>")
self.assertEqual(
res, "tests.test_utils.GetNameFromObjTestCase.test_lambda.<locals>.<lambda>"
)

def test_class(self):
class A:
pass

res = get_name_from_obj(A)
self.assertEqual(res, "tests.test_utils.A")
self.assertEqual(
res, "tests.test_utils.GetNameFromObjTestCase.test_class.<locals>.A"
)


class RenderStacktraceTestCase(unittest.TestCase):
Expand Down

0 comments on commit e58e78b

Please sign in to comment.