How to play a socket in C

I have a function that uses 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?

thank

+3


source to share


2 answers


Most system / library functions are weak symbols . This means that you can create your own implementation that will override existing versions. Then you can use these functions in unit testing.

Let's say 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;
}

      

Then, you'll create your layout function (and any control 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 a 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;
}

      

Then you will compile and link these three modules together. get_socket

Will then call the function socket

in mock_socket.c instead of the library function.

This method works not only with socket functions, but also with system / library functions in general.

+4


source


Sockets are managed by the kernel, so there is no user-space-only mechanism for mocking them, but you can configure a genuine socket connected to the endpoint part of your test fixture.



In particular, you can use a unix domain or raw socket for this purpose, where the normally tested code has, say, a TCP socket to work with, or you can connect the socket to a local fixture test through the loopback interface. Or, although I don't know of any examples, in principle you can also find or write a driver that provides sockets for an artificial, target address family.

0


source







All Articles