Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Allow ConfigSet.add_config to receive parameterized generics for of_type. #3288

Merged
merged 2 commits into from
May 31, 2024
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
1 change: 1 addition & 0 deletions docs/changelog/3288.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow ``ConfigSet.add_config`` to receive parameterized generics for ``of_type``.
5 changes: 5 additions & 0 deletions src/tox/config/loader/convert.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import typing
from abc import ABC, abstractmethod
from collections import OrderedDict
from pathlib import Path
Expand Down Expand Up @@ -39,6 +40,10 @@ def to(self, raw: T, of_type: type[V], factory: Factory[V]) -> V: # noqa: PLR09
return self.to_env_list(raw) # type: ignore[return-value]
if issubclass(of_type, str):
return self.to_str(raw) # type: ignore[return-value]
# python does not allow use of parametrized generics with isinstance,
# so we need to check for them.
if hasattr(typing, "GenericAlias") and isinstance(of_type, typing.GenericAlias):
return list(self.to_list(raw, of_type=of_type)) # type: ignore[return-value]
if isinstance(raw, of_type): # already target type no need to transform it
# do it this late to allow normalization - e.g. string strip
return raw
Expand Down
15 changes: 15 additions & 0 deletions tests/config/loader/test_str_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,21 @@ def test_str_convert_ok(raw: str, value: Any, of_type: type[Any]) -> None:
assert result == value


# Tests that can work only with py39 or newer due to type not being subscriptible before
if sys.version_info >= (3, 9):

@pytest.mark.parametrize(
("raw", "value", "of_type"),
[
("", None, Optional[list[str]]),
("1,2", ["1", "2"], Optional[list[str]]),
],
)
def test_str_convert_ok_py39(raw: str, value: Any, of_type: type[Any]) -> None:
result = StrConvert().to(raw, of_type, None)
assert result == value


@pytest.mark.parametrize(
("raw", "of_type", "exc_type", "msg"),
[
Expand Down
Loading