Skip to content

Commit

Permalink
fix: Don't crash when rendering the source of an object whose lineno …
Browse files Browse the repository at this point in the history
…is none

Issue-163: #163
  • Loading branch information
pawamoy committed May 22, 2024
1 parent 0b8a3a9 commit 64df00b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ Context:
{{ init.relative_filepath }}
{%- endif -%}
</code></summary>
{{ init.source|highlight(language="python", linestart=init.lineno, linenums=True) }}
{{ init.source|highlight(language="python", linestart=init.lineno or 0, linenums=True) }}
</details>
{% endwith %}
{% endif %}
Expand All @@ -170,7 +170,7 @@ Context:
{{ class.relative_filepath }}
{%- endif -%}
</code></summary>
{{ class.source|highlight(language="python", linestart=class.lineno, linenums=True) }}
{{ class.source|highlight(language="python", linestart=class.lineno or 0, linenums=True) }}
</details>
{% endif %}
{% endif %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ Context:
{{ function.relative_filepath }}
{%- endif -%}
</code></summary>
{{ function.source|highlight(language="python", linestart=function.lineno, linenums=True) }}
{{ function.source|highlight(language="python", linestart=function.lineno or 0, linenums=True) }}
</details>
{% endif %}
{% endblock source %}
Expand Down
28 changes: 28 additions & 0 deletions tests/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

import os
from glob import glob
from textwrap import dedent
from typing import TYPE_CHECKING

import pytest
from griffe.docstrings.dataclasses import DocstringSectionExamples, DocstringSectionKind
from griffe.tests import temporary_visited_module

from mkdocstrings_handlers.python.handler import CollectionError, PythonHandler, get_handler

Expand Down Expand Up @@ -145,3 +147,29 @@ def test_extension_paths(tmp_path: Path, expect_change: bool, extension: str | d
raise ValueError("Normalization must not change extension items type")
else:
assert normalized == extension


def test_rendering_object_source_without_lineno(handler: PythonHandler) -> None:
"""Test rendering objects without a line number."""
code = dedent(
"""
'''Module docstring.'''
class Class:
'''Class docstring.'''
def function(self):
'''Function docstring.'''
attribute = 0
'''Attribute docstring.'''
""",
)
with temporary_visited_module(code) as module:
# TODO: Remove once Griffe does that automatically.
module.lines_collection[module.filepath] = code.splitlines() # type: ignore[index]

module["Class"].lineno = None
module["Class.function"].lineno = None
module["attribute"].lineno = None
assert handler.render(module, {"show_source": True})

0 comments on commit 64df00b

Please sign in to comment.