Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 447 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to mock socket in C

#1
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
Reply

#2
Sockets are managed by the kernel, so there is no userspace-only mechanism for mocking them, but you can set up a genuine socket connected to an endpoint that's part of your test fixture.

In particular, you may be able to use a unix-domain or raw socket for that purpose where the code under test normally has, say, a TCP socket to work with, or you can connect a socket back to the local test fixture via the loopback interface. Or, though I am unaware of any example, in principle you could also find or write a driver that provides sockets for an artificial, for-purpose address family.
Reply

#3
Most system / library function are [weak symbols](

[To see links please register here]

). 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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through