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]