Add missing error check in BMessageFormat

* Avoids a crash when an invalid format pattern is used
* Add tests exercising this with various badly formatted patterns.
This commit is contained in:
Adrien Destugues 2014-10-13 09:07:53 +02:00
parent 96ebc1d602
commit 64bda0cc91
3 changed files with 41 additions and 1 deletions

View File

@ -77,6 +77,9 @@ BMessageFormat::SetFormattingConventions(
status_t
BMessageFormat::Format(BString& output, const int32 arg) const
{
if (fInitStatus != B_OK)
return fInitStatus;
BAutolock lock(fLock);
if (!lock.IsLocked())
return B_ERROR;

View File

@ -64,6 +64,40 @@ MessageFormatTest::TestFormat()
}
void
MessageFormatTest::TestBogus()
{
struct Test {
const char* pattern;
};
static const Test tests[] = {
{ "{0, plural, one{# dog} other{# dogs}" }, // Missing closing brace
{ "{0, plural, one{# dog}, other{# dogs}}" }, // Extra comma
{ "{0, plural, one{# dog}" }, // Missing "other"
{ "{4099, plural, one{# dog} other{# dogs}}" }, // Out of bounds arg
{ "{0, invalid, one{# dog} other{# dogs}}" }, // Invalid rule
{ NULL }
};
for (int i = 0; tests[i].pattern != NULL; i++) {
NextSubTest();
status_t result;
BString output;
BMessageFormat formatter(tests[i].pattern);
CPPUNIT_ASSERT(formatter.InitCheck() != B_OK);
result = formatter.Format(output, 1);
CPPUNIT_ASSERT(result != B_OK);
result = formatter.Format(output, 2);
CPPUNIT_ASSERT(result != B_OK);
}
}
/*static*/ void
MessageFormatTest::AddTests(BTestSuite& parent)
{
@ -71,6 +105,8 @@ MessageFormatTest::AddTests(BTestSuite& parent)
suite.addTest(new CppUnit::TestCaller<MessageFormatTest>(
"MessageFormatTest::TestFormat", &MessageFormatTest::TestFormat));
suite.addTest(new CppUnit::TestCaller<MessageFormatTest>(
"MessageFormatTest::TestBogus", &MessageFormatTest::TestBogus));
parent.addTest("MessageFormatTest", &suite);
}

View File

@ -16,6 +16,7 @@ public:
virtual ~MessageFormatTest();
void TestFormat();
void TestBogus();
static void AddTests(BTestSuite& suite);
};