1

I'm new, I have a problem with unit-test using cmocka. I have the following function :

#include <string.h>
#include <stdlib.h>
#include "function.h"


void copy_ip_addr(char *ip_addr_ascii)
{
    char ip_ascii[50];
    strcpy(ip_ascii, ip_addr_ascii);
}

I want to write unit test for that function and use mock for strcpy, at here:

#include <stdio.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmocka.h"
#include <stdio.h>
#include <string.h>
#include "function.h"


char* __real_strcpy(char *dest,const char *src);
char* __wrap_strcpy(char *dest,const char *src){
    check_expected(src);
    return (char*)mock();
}

static void test_convert_ip_addr(void **state){
    (void) state; /* unused */
    expect_string(__wrap_strcpy,src,"abc"); // line 42
    will_return(__wrap_strcpy,"abc");       // line 43
}

const struct CMUnitTest test_copy_ip_addr_group[] = {
    cmocka_unit_test(test_convert_ip_addr),
};
int main()
{
    return cmocka_run_group_tests(test_copy_ip_addr_group, NULL, NULL);
}
gcc -g function.c test_function.c -Wl,--wrap=strcpy -o test -l cmocka

and the program gives error like this :

[==========] Running 1 test(s).
[ RUN      ] test_convert_ip_addr
__wrap_strcpy() has remaining non-returned values.
test_function.c:43: note: remaining item was declared here
__wrap_strcpy.src parameter still has values that haven't been checked.
test_function.c:42: note: remaining item was declared here

[  FAILED  ] test_convert_ip_addr
[==========] 1 test(s) run.
[  PASSED  ] 0 test(s).
[  FAILED  ] 1 test(s), listed below:
[  FAILED  ] test_convert_ip_addr

 1 FAILED TEST(S)

How should I fix it to get accurate results?

Ale
  • 887
  • 10
  • 14
  • 3
    How does the original function as you've posted it make any sense to begin with? – Lundin Jun 11 '21 at 09:24
  • The `__wrap_strcpy()` function doesn't seem to have been called. BTW, I'd have expected you to wrap `copy_ip_addr()`, you're not testing the C library, are you? – Ale Jun 11 '21 at 16:20

1 Answers1

2

The problem is that you didn't call function under test in your test function. You should do something like this:

static void test_convert_ip_addr(void **state){
    (void) state; /* unused */
    char* ip_addr_ascii = "abc";
    expect_string(__wrap_strcpy,src,"abc"); // line 42
    will_return(__wrap_strcpy,"abc");       // line 43
    copy_ip_addr(ip_addr_ascii);
}
adamm
  • 849
  • 1
  • 6
  • 17