From befa2dd8b70fdf4ed808d8e52033e83efb032966 Mon Sep 17 00:00:00 2001 From: Patrick Lannigan Date: Fri, 13 Oct 2023 17:23:35 -0400 Subject: [PATCH] Validate the type of dynamic values --- CHANGELOG.md | 4 ++++ columbo/_interaction.py | 5 ++++- tests/interaction_test.py | 5 +++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b0631737..a898d883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Python version `3.12` tested during CI - Python version `3.12` added to package classifiers +### Fixed + +- Raise `ValueError` when dynamic value returns the wrong type. + ### Removed - Support for Python version `3.7`. diff --git a/columbo/_interaction.py b/columbo/_interaction.py index afd954b8..f2ba7f56 100644 --- a/columbo/_interaction.py +++ b/columbo/_interaction.py @@ -636,7 +636,10 @@ def to_value( if isinstance(value, value_type): return value if callable(value): - return value(answers) + result = value(answers) + if isinstance(result, value_type): + return result + raise ValueError(f"Invalid dynamic value: {result}") raise ValueError(f"Invalid value: {value}") diff --git a/tests/interaction_test.py b/tests/interaction_test.py index 342fab1e..bd9b262a 100644 --- a/tests/interaction_test.py +++ b/tests/interaction_test.py @@ -494,6 +494,11 @@ def test_to_value__invalid_type__exception(): to_value(object(), SOME_ANSWERS, str) # type: ignore[arg-type] +def test_to_value__invalid_dynamic_type__exception(): + with pytest.raises(ValueError): + to_value(lambda _: object(), SOME_ANSWERS, str) # type: ignore[arg-type,return-value] + + def test_to_labeled_options__invalid_type__exception(): with pytest.raises(ValueError): to_labeled_options(object(), SOME_ANSWERS) # type: ignore[arg-type]