I am working only in C regarding this issue.
I have two function prototypes :
int pkg_permserver(const char *service, const char *protocol, int backlog, void (*errlog) (char *msg))
int pkg_permserver_ip(const char *ipOrHostname, const char *service, const char *protocol, int backlog, void (*errlog)(char *msg))
and the following segment of code :
int test_permserv(char *port) {
int return_val;
int num_port;
char *chr_port;
int nr_test_passed=0;
chr_port = (char *) bu_malloc(8 * sizeof( char), "port string");
printf("TESTING PKG_PERMSERVER.....\n PORT PARAMETER TEST: \n");
printf("TESTING VALID PORT...\n");
return_val = pkg_permserver(port ,"tcp", 0, 0);
display(return_val,1,&nr_test_passed);
printf("TESTING INVALID PORT...\n");
num_port = -1;
sprintf(chr_port, "%d", num_port);
return_val = pkg_permserver(chr_port ,"tcp", 0, 0);
display(return_val,0,&nr_test_passed);
}
I am writing a test unit. I need to test each case ( valid / invalid ) for each parameter of a function.
I cannot modify the functions stated above. pkg_permserver and pkg_permserver_ip have the exact same parameters, except pkg_permserver_ip has the IpOrHostname additionally.
if I will write another function “test_permserver_ip” I do not want to copy – paste the part from test_permserver ( because the parameters are identical ).
What I have on my mind is something like int test_permserver(char * port, int which_function);
I want to avoid copying the same code for test_permserver_ip ( for the parameters that are identical to test_permserver ones)
The testing function for pkg_permserver_ip hasn’t been written yet.
This is the code for the two above functions :
int pkg_permserver(const char *service, const char *protocol, int backlog, void (*errlog) (char *msg))
{
struct in_addr iface;
iface.s_addr = INADDR_ANY;
return _pkg_permserver_impl(iface, service, protocol, backlog, errlog);
}
int
pkg_permserver_ip(const char *ipOrHostname, const char *service, const char *protocol, int backlog, void (*errlog)(char *msg))
{
struct hostent* host;
struct in_addr iface;
/* if ipOrHostname starts with a number, it's an IP */
if (ipOrHostname) {
if (ipOrHostname[0] >= '0' && ipOrHostname[0] <= '9') {
iface.s_addr = inet_addr(ipOrHostname);
} else {
/* XXX gethostbyname is deprecated on Windows */
host = gethostbyname(ipOrHostname);
iface = *(struct in_addr*)host->h_addr;
}
return _pkg_permserver_impl(iface, service, protocol, backlog, errlog);
} else {
_pkg_perror(errlog, "pkg: ipOrHostname cannot be NULL");
return -1;
}
}
As ATaylor says, just extract the common stuff from both functions and get something like
If you don’t know how to extract the common part, post some more code for both functions and we’ll think it over.