Commit 5ba63620dc478bcdeb0e0feabc9990ac523c7643

Authored by Philip Top
Committed by GitHub
1 parent 9ec0ba78

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
... ... @@ -480,10 +480,12 @@ class Range : public Validator {
480 480 func_ = [min_val, max_val](std::string &input) {
481 481 T val;
482 482 bool converted = detail::lexical_cast(input, val);
483   - if((!converted) || (val < min_val || val > max_val))
484   - return std::string("Value ") + input + " not in range " + std::to_string(min_val) + " to " +
485   - std::to_string(max_val);
486   -
  483 + if((!converted) || (val < min_val || val > max_val)) {
  484 + std::stringstream out;
  485 + out << "Value " << input << " not in range [";
  486 + out << min_val << " - " << max_val << "]";
  487 + return out.str();
  488 + }
487 489 return std::string{};
488 490 };
489 491 }
... ...
tests/AppTest.cpp
... ... @@ -1858,6 +1858,23 @@ TEST_CASE_METHOD(TApp, &quot;RangeDouble&quot;, &quot;[app]&quot;) {
1858 1858 run();
1859 1859 }
1860 1860  
  1861 +TEST_CASE_METHOD(TApp, "NonNegative", "[app]") {
  1862 +
  1863 + std::string res;
  1864 + /// Note that this must be a double in Range, too
  1865 + app.add_option("--one", res)->check(CLI::NonNegativeNumber);
  1866 +
  1867 + args = {"--one=crazy"};
  1868 + try {
  1869 + // this should throw
  1870 + run();
  1871 + CHECK(false);
  1872 + } catch(const CLI::ValidationError &e) {
  1873 + std::string emess = e.what();
  1874 + CHECK(emess.size() < 70U);
  1875 + }
  1876 +}
  1877 +
1861 1878 TEST_CASE_METHOD(TApp, "typeCheck", "[app]") {
1862 1879  
1863 1880 /// Note that this must be a double in Range, too
... ...