Skip to content

Commit 8879ee1

Browse files
authored
Merge pull request #246 from 56kyle/feature/restrict-handler-registration-with-generics
Prevent registering type handlers using types that have specified generics (Dict is okay, Dict[str, int] is not)
2 parents 224e649 + 793e289 commit 8879ee1

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/pytest_static/type_handler.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from typing import TYPE_CHECKING
88
from typing import Any
99
from typing import Callable
10+
from typing import get_args
1011

1112
from pytest_static.util import get_base_type
1213

@@ -23,6 +24,12 @@ def __init__(self) -> None:
2324
self._mapping: dict[Any, list[TypeHandler]] = {}
2425
self._proxy: types.MappingProxyType[Any, list[TypeHandler]] = types.MappingProxyType(self._mapping)
2526

27+
@classmethod
28+
def _validate_has_no_generic(cls, typ: Any) -> None:
29+
"""Validates that the provided typ has no generic type."""
30+
if get_args(typ):
31+
raise TypeError(f"Cannot register a type handler type containing generics: {typ}")
32+
2633
def __getitem__(self, key: Any) -> Any:
2734
"""Returns from proxy."""
2835
return self._proxy.__getitem__(key)
@@ -47,6 +54,8 @@ def my_function_name(base_type, type_args):
4754
type_handlers.get_instances(int) => (100, 1000, 1, 2, 3, 4, 5)
4855
type_handlers.get_instances(float) => (1.0, 2.0, 3.0, 4.0, 5.0)
4956
"""
57+
for arg in args:
58+
self._validate_has_no_generic(arg)
5059

5160
def decorator(fn: TypeHandler) -> TypeHandler:
5261
for key in args:

tests/unit_tests/test_type_handler.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
from typing import Any
2+
from typing import List
3+
14
import pytest
25

6+
from pytest_static.custom_typing import T
37
from pytest_static.custom_typing import TypeHandler
48
from pytest_static.type_handler import TypeHandlerRegistry
59

@@ -37,6 +41,13 @@ def test_register_with_existing(
3741
assert type_handler_registry__basic.get(int, None) is not None
3842
assert tuple(type_handler_registry__basic.get(int, None)[0](int, ())) == (1, 2, 3)
3943

44+
@pytest.mark.parametrize("generic", [str, list[str], T])
45+
def test_register_with_generic(
46+
self, type_handler_registry__basic: TypeHandlerRegistry, basic_handler: TypeHandler, generic: Any
47+
) -> None:
48+
with pytest.raises(TypeError):
49+
type_handler_registry__basic.register(List[generic])(basic_handler)
50+
4051
def test_clear_with_unregistered(self, type_handler_registry: TypeHandlerRegistry) -> None:
4152
assert type_handler_registry.get(int, None) is None
4253
type_handler_registry.clear(int)

0 commit comments

Comments
 (0)