UnitTestBot / UTBotCpp

Tool that generates unit test by C/C++ source code, trying to reach all branches and maximize code coverage
Apache License 2.0
139 stars 26 forks source link

Better structure fields initialization in generated tests #253

Closed alexey-utkin closed 2 years ago

alexey-utkin commented 2 years ago

We need the option to transform initialization from initialization-list-based way

    {0, 0, 
      {1, 2}, 
      {1, 2, 3}, 
      0, 0, 0, 
      {4,5,{3,3}}}

to struct-field-based:

structA.x = 0;
structA.y = 0;
structA.subStru.m = 1;
structA.subStru.n = 2;
...

Seems like it should be a UI option in the formatting settings.

alexey-utkin commented 2 years ago

For the common case we have several limitations.

Example 1:

struct MyStruct {
    short x;
    const int a;  // <--  const !
};

struct MyStruct st = {0, 1}; // OK
struct MyStruct st; // error: call to implicitly-deleted default constructor of 'struct MyStruct'
st.x = 0;
st.a = 1; // impossible

Example 2:

struct One {
    int a;
    char str[12];
};

struct One expected;
expected.a = 1;
char __expected_str[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'}; // two lines initialization      
memcpy((void *) expected.str, __expected_str, sizeof(__expected_str));  // looks not good

It seems that line-by-line initialization with field name could be a better solution:

struct MyStruct {
    short x;
    const int a;// <--  const !
};
struct MyStruct st = {
        .x = 0,
        .a = 1};

struct One {
    int a;
    char str[12];
};
struct One expected = {
        .a = 1,
        .str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'}};

struct MyStructWithOne {
    short x;
    const int a;// <--  const !
    struct One one;
};
struct MyStructWithOne ex = {
        .x = 2,
        .a = 1,
        .one = {
                .a = 1,
                .str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'}}};

Additional info: Struct and union initialization

llmagic commented 2 years ago

It seems a good way! And seems the only condition to support this is the compiler at least support C99?

alexey-utkin commented 2 years ago

@llmagic That is right. C99 or Cpp98 are required. But it should not be a problem to comment the designation if a custom compiler does not support the option.

alexey-utkin commented 2 years ago

Fixed in PR