Skip to content

Commit

Permalink
Add the "named args explanation" to other relevant parametrize erro…
Browse files Browse the repository at this point in the history
…r messages. (pantsbuild#15362)

For non-string arguments, the way to use `parametrize` is still via named arguments, but we were only including that explanation on the "illegal characters in string" case.

[ci skip-rust]
[ci skip-build-wheels]
  • Loading branch information
stuhood committed May 6, 2022
1 parent ac37b12 commit 9511b32
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
16 changes: 11 additions & 5 deletions src/python/pants/engine/internals/parametrize.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@
from pants.util.strutil import bullet_list


def _named_args_explanation(arg: str) -> str:
return (
f"To use `{arg}` as a parameter, you can pass it as a keyword argument to "
f"give it an alias. For example: `parametrize(short_memorable_name={arg})`"
)


@frozen_after_init
@dataclass(unsafe_hash=True)
class Parametrize:
Expand Down Expand Up @@ -43,21 +50,20 @@ def to_parameters(self) -> dict[str, Any]:
if not isinstance(arg, str):
raise Exception(
f"In {self}:\n Positional arguments must be strings, but "
f"`{arg}` was a `{type(arg).__name__}`."
f"`{arg!r}` was a `{type(arg).__name__}`.\n\n"
+ _named_args_explanation(f"{arg!r}")
)
previous_arg = parameters.get(arg)
if previous_arg is not None:
raise Exception(
f"In {self}:\n Positional arguments cannot have the same name as "
f"keyword arguments. `{arg}` was also defined as `{arg}={previous_arg}`."
f"keyword arguments. `{arg}` was also defined as `{arg}={previous_arg!r}`."
)
banned_chars = BANNED_CHARS_IN_PARAMETERS & set(arg)
if banned_chars:
raise Exception(
f"In {self}:\n Positional argument `{arg}` contained separator characters "
f"(`{'`,`'.join(banned_chars)}`).\n\n"
f"To use `{arg}` as a parameter, you can pass it as a keyword argument to "
f"give it an alias. For example: `parametrize(short_memorable_name='{arg}')`"
f"(`{'`,`'.join(banned_chars)}`).\n\n" + _named_args_explanation(arg)
)
parameters[arg] = arg
return parameters
Expand Down
2 changes: 1 addition & 1 deletion src/python/pants/engine/internals/parametrize_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def test_to_parameters_success(
@pytest.mark.parametrize(
"exception_str,args,kwargs",
[
("Positional arguments must be strings", [1], {}),
("Positional arguments must be strings, but `[1]` was a", [[1]], {}),
(
"Positional arguments cannot have the same name as keyword arguments",
["x"],
Expand Down

0 comments on commit 9511b32

Please sign in to comment.