Merge pull request #29877 from cuishuang:core-reject-invalid-bool

core: reject invalid boolean values in CommandLineParser
This commit is contained in:
Alexander Smorkalov
2026-09-11 15:43:44 +03:00
committed by GitHub
3 changed files with 33 additions and 4 deletions

View File

@@ -76,9 +76,13 @@ static bool parse_bool(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), details::char_tolower);
std::istringstream is(str);
bool b;
is >> (str.size() > 1 ? std::boolalpha : std::noboolalpha) >> b;
return b;
bool value = false;
is >> (str.size() > 1 ? std::boolalpha : std::noboolalpha) >> value;
if (is.fail())
CV_Error_(Error::StsBadArg, ("can not convert: [%s] to [bool]", str.c_str()));
return value;
}
static void from_str(const String& str, Param type, void* dst)

View File

@@ -165,6 +165,28 @@ TEST(CommandLineParser, testBoolOption_FalseValues)
EXPECT_FALSE(parser.get<bool>("n"));
}
TEST(CommandLineParser, testBoolOption_InvalidValue)
{
const char* argv[] = {"<bin>", "--info=invalid"};
const int argc = 2;
cv::CommandLineParser parser(argc, argv, keys);
parser.get<bool>("info");
EXPECT_FALSE(parser.check());
}
TEST(CommandLineParser, testBoolOption_InvalidNumericValue)
{
const char* argv[] = {"<bin>", "--info=2"};
const int argc = 2;
cv::CommandLineParser parser(argc, argv, keys);
parser.get<bool>("info");
EXPECT_FALSE(parser.check());
}
static const char * const keys2 =
"{ h help | | print help }"