From 5ba63620dc478bcdeb0e0feabc9990ac523c7643 Mon Sep 17 00:00:00 2001 From: Philip Top Date: Wed, 5 Jan 2022 12:36:15 -0800 Subject: [PATCH] fix: update the range error output (#690) * update the range error output to be able to be used by more types, and better printouts in some situations. * style: pre-commit.ci fixes * add test * style: pre-commit.ci fixes * fix the test Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- include/CLI/Validators.hpp | 10 ++++++---- tests/AppTest.cpp | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/include/CLI/Validators.hpp b/include/CLI/Validators.hpp index ba3cbe3c..63422cb7 100644 --- a/include/CLI/Validators.hpp +++ b/include/CLI/Validators.hpp @@ -480,10 +480,12 @@ class Range : public Validator { func_ = [min_val, max_val](std::string &input) { T val; bool converted = detail::lexical_cast(input, val); - if((!converted) || (val < min_val || val > max_val)) - return std::string("Value ") + input + " not in range " + std::to_string(min_val) + " to " + - std::to_string(max_val); - + if((!converted) || (val < min_val || val > max_val)) { + std::stringstream out; + out << "Value " << input << " not in range ["; + out << min_val << " - " << max_val << "]"; + return out.str(); + } return std::string{}; }; } diff --git a/tests/AppTest.cpp b/tests/AppTest.cpp index 3e39a7c9..9268925f 100644 --- a/tests/AppTest.cpp +++ b/tests/AppTest.cpp @@ -1858,6 +1858,23 @@ TEST_CASE_METHOD(TApp, "RangeDouble", "[app]") { run(); } +TEST_CASE_METHOD(TApp, "NonNegative", "[app]") { + + std::string res; + /// Note that this must be a double in Range, too + app.add_option("--one", res)->check(CLI::NonNegativeNumber); + + args = {"--one=crazy"}; + try { + // this should throw + run(); + CHECK(false); + } catch(const CLI::ValidationError &e) { + std::string emess = e.what(); + CHECK(emess.size() < 70U); + } +} + TEST_CASE_METHOD(TApp, "typeCheck", "[app]") { /// Note that this must be a double in Range, too