Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock socket in C

I have a function using a socket and I would mock it but I couldn't find how to do it.

Is there a way to mock sockets in C?

Thanks

like image 432
pBouillon Avatar asked May 19 '17 14:05

pBouillon


1 Answers

Most system / library function are weak symbols. That means you can create your own implementation of them that will override the existing versions. You can then use these functions when unit testing.

Suppose you want to test the following function:

src.c:

int get_socket()
{
    int s;

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s == -1) {
        perror("socket failed");
    } else {
        printf("socket success\n");
        close(s);
    }
    return s;
}

You would then create the mock function (and any controlling variables) in a separate source file:

mock_socket.c:

int sock_rval;

int socket(int domain, int type, int protocol)
{
    printf("calling mock socket\n");
    return sock_rval;
}

Then in another file you have your test:

test_socket.c:

extern int sock_rval;
int get_socket();

int main()
{
    sock_rval = -1;
    int rval = get_socket();
    assert(rval == -1);
    sock_rval = 3;
    int rval = get_socket();
    assert(rval == 3);
    return 0;
}

You would then compile and link these three modules together. Then get_socket will call the socket function in mock_socket.c instead of the library function.

This technique works not just with socket functions, but with system / library functions in general.

like image 182
dbush Avatar answered Oct 11 '22 23:10

dbush