2

I'm doing unit tests. I have to test ALL possible if..else cases. But in this if statement:

int32_t i32Res = snprintf(buffer, len, "The%d_String_%d", 0, u8Idx);
if ((i32Res < 0) || (i32Res >= len))
{
    return enuErrVal;
}

i32Res is never < 0, it always ends up having the string's size value. I can only force the buffer and len variables. I have tried with a null buffer but it crashes before actually reaching the if. I have tried with very small and very big sizes in buffer. I tried with low (2) values on len.

I know snprintf() returns -1 on encoding errors, how can I force this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ivan
  • 1,352
  • 2
  • 13
  • 31

3 Answers3

1

From https://support.sas.com/documentation/onlinedoc/sasc/doc700/html/lr1/z2056522.htm#z2056525:

The snprintf function returns an integer value that equals, in magnitude, the number of characters written to the area addressed by dest. If the value returned is negative, then either the maxlen character limit was reached or some other error, such as an invalid format specification, has occurred. The one exception to this is if an error occurs before any characters are stored, snprintf returns INT_MIN (-2**31) .

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Joe Davis
  • 333
  • 1
  • 8
  • 2
    Thank you, but this doesn't help. I wrote I tried to hace wrong values of `len` . and I also can't just force an error "before any characters are stored" – Ivan Oct 28 '20 at 08:42
1

Probably the best way to get test coverage for code like this is to use an interposer library. This is a shared library that goes between your code and the system C library. Some of them have function calls for testing which can command it to do things like return NULL for the next malloc call.

There's this closed question which still has some good info it seems: Unit Testing C Code

You'll have to search around to find a good testing library layer. I've used one, but it was 15 years ago and I don't quite remember what its name was.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
0

This is a clash between a requirement which is unreasonable - 100% code coverage in unit tests - and actual real-life programming languages and libraries (or APIs). Best bet is to rewrite the code so that the <0 test is separate from the >len test, then mark the <0 test as fatal/never happens in the code with, e.g., a call to abort(), and then finally write up a request for an exception to the 100% rule you're suffering with.

int32_t i32Res = snprintf(buffer, len, "The%d_String_%d", 0, u8Idx);
if (i32Res < 0)
{
    abort();
}
if (i32Res >= len)
{
    return enuErrVal;
}
davidbak
  • 5,775
  • 3
  • 34
  • 50