Skip to content

Commit

Permalink
Allow ConfigSet.add_config to receive parameterized generics for `o…
Browse files Browse the repository at this point in the history
…f_type`. (#3288)

* Allow use of list[str] inside plugins

Fixes: #3287

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
ssbarnea and pre-commit-ci[bot] authored May 31, 2024
1 parent 406f808 commit 7317225
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
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

0 comments on commit 7317225

Please sign in to comment.