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

fix: update annotation name extraction logic and add unit tests #320

Merged
merged 4 commits into from
Oct 30, 2023
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
10 changes: 3 additions & 7 deletions docfx_yaml/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -747,17 +747,13 @@ def _extract_type_name(annotation: Any) -> str:
Returns:
The extracted type hint in human-readable string format.
"""
type_name = ""
# Extract names for simple types.
try:

annotation_dir = dir(annotation)
if '__args__' not in annotation_dir:
return annotation.__name__
except AttributeError:
pass

# Try to extract names for more complicated types.
type_name = str(annotation)
if not annotation.__args__:
return type_name

# If ForwardRef references are found, recursively remove them.
prefix_to_remove_start = "ForwardRef('"
Expand Down
56 changes: 56 additions & 0 deletions tests/test_inspect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Tests for various inspect related utils."""
from docfx_yaml import extension

import inspect
import unittest
from parameterized import parameterized

from typing import Any, Optional, Union


class TestGenerate(unittest.TestCase):

types_to_test = [
[
# Test for a simple type without __args__.
str,
'str',
],
[
# Test for a more complex type without forward reference.
list[str],
'list[str]',
],
[
# Test for imported type, without forward reference.
dict[str, Any],
'dict[str, typing.Any]',
],
[
# Test for forward reference.
Optional["ForwardClass"],
'typing.Optional[ForwardClass]'
],
[
# Test for multiple forward references.
Union["ForwardClass", "ForwardClass2"],
'typing.Union[ForwardClass, ForwardClass2]'
],
]
@parameterized.expand(types_to_test)
def test_extracts_annotations(self, type_to_test, expected_type_name):
"""Extracts annotations from test method, compares to expected name."""
def test_method(name: type_to_test):
pass

annotations = inspect.getfullargspec(test_method).annotations
annotation_to_use = annotations['name']

extracted_annotation_name = extension._extract_type_name(
annotation_to_use)

self.assertEqual(extracted_annotation_name, expected_type_name)


if __name__ == '__main__':
unittest.main()