Initial commit of RMR Library

Change-Id: Ic4c998b056e8759f4a47a9a8c50c77e88df0f325
Signed-off-by: Ashwin Sridharan <hiltunen@att.com>
diff --git a/test/.gitignore b/test/.gitignore
new file mode 100644
index 0000000..6770301
--- /dev/null
+++ b/test/.gitignore
@@ -0,0 +1,4 @@
+*.gcov
+*.dcov
+*.gcno
+*.gcda
diff --git a/test/.targets b/test/.targets
new file mode 100644
index 0000000..0825648
--- /dev/null
+++ b/test/.targets
@@ -0,0 +1,6 @@
+
+# Coverage target values for modules which are not expected to meet the
+# default standard. Lines are <module-name> <target-pct> with module name
+# starting in column 0; e.g.   ../src/common/src/foo.c 65
+
+# there are no alternate coverage targets at the moment
diff --git a/test/Makefile b/test/Makefile
new file mode 100644
index 0000000..20d461e
--- /dev/null
+++ b/test/Makefile
@@ -0,0 +1,24 @@
+
+
+CC = gcc
+coverage_opts = -ftest-coverage -fprofile-arcs
+
+libs = ../build/librmr_nng.a -L ../build/lib -lnng -lpthread -lm
+
+%.o:: %.c
+	$(CC) -g $< -c 
+
+%:: %.c
+	$(CC) $(coverage_opts) -fPIC -g $< -o $@  $(libs)
+
+# catch all 
+all:
+	echo "run unit_test.ksh to make and run things here"
+
+# remove intermediates
+clean:
+	rm -f *.gcov *.gcda *.dcov *.gcno
+
+# remove anything that can be builts
+nuke: clean
+	rm -f ring_test symtab_test 
diff --git a/test/README b/test/README
new file mode 100644
index 0000000..85f96ed
--- /dev/null
+++ b/test/README
@@ -0,0 +1,82 @@
+
+Unit test
+
+The means to unit testing the RMr library is contained in
+this directory.  It is somewhat difficult to accurately generate
+coverage information for parts of the library because the library
+is a fair amount of static functions (to keep them from being
+visible to the user programme).  
+
+To run the tests:
+	ksh unit_test.sh [specific-test]
+
+If a specific test (e.g. ring_test.c) is not given on the command line,
+all *_test.c files are sussed out and an attempt to build and run them
+is made by the script. 
+
+Output is an interpretation of the resulting gcov output (in more useful
+and/or easier to read format).  For example:
+
+unit_test.ksh ring_test.c
+ring_test.c --------------------------------------
+[OK]   100% uta_ring_insert
+[OK]   100% uta_ring_extract
+[OK]   100% uta_ring_free
+[LOW]   76% uta_mk_ring
+[PASS]  91% ../src/common/src/ring_static.c
+
+
+The output shows, for each function, the coverage (column 2) and an 
+interpretation (ok or low) wthin an overall pass or fail.
+
+
+File Names
+The unit test script will find all files named *_test.c and assume that
+they can be compiled and executed using the local Makefile. Files
+which are needed by these programmes (e.g. common functions) are expected
+to reside in this directory as test_*.c and test_*.h files and should 
+be directly included by the test programmes (not built and linked). This 
+allows the unit test script to isngore the functions, and files, when 
+generating coverage reports. 
+
+
+Discounting
+The unit test script makes a discount pass on low coverage files in
+attempt to discount the coverage rate by ignoring what are considered
+to be difficult to reach blocks in the code.  Currently, these blocks
+are limited to what appear to be tests for memory allocation, failure
+and/or nil pointer handling.  If code blocks of this sort are found,
+they are not counted against the coverage for the module.  If the -v
+option is given, an augmented coverage listing is saved in .dcov which
+shows the discounted lines with a string of equal signs (====) rather
+than the gcov hash string (###).
+
+The discount check is applied only if an entire module has a lower 
+than accepted coverage rate, and can be forced for all modules with 
+the -f option.
+
+To illustrate, the following code checks the return from the system
+library strdup() call which is very unlikely to fail under test without
+going to extremes and substituting for the system lib.  Thus, the 
+block which checks for a nil pointer has been discounted:
+
+     -:  354:
+     1:  355:    dbuf = strdup( buf );
+     1:  356:    if( dbuf == NULL  ) {
+ =====:  357:        errno = ENOMEM;
+ =====:  358:        return 0;
+     -:  359:    }
+
+
+Target Coverage
+By default, a target coverage of 80% is used. For some modules this may
+be impossible to achieve, so to prevent always failing these modules 
+may be listed in the .targets file with their expected minimum coverage.
+Module names need to be qualified (e.g. ../src/common/src/foo.c.
+
+
+-----------------------------------------------------------------------
+A note about ksh (A.K.A Korn shell, or kshell)
+Ksh is preferred for more complex scripts such as the unit test 
+script as it does not have some of the limitations that bash
+(and other knock-offs) have. 
diff --git a/test/ring_test.c b/test/ring_test.c
new file mode 100644
index 0000000..331f976
--- /dev/null
+++ b/test/ring_test.c
@@ -0,0 +1,159 @@
+// : vi ts=4 sw=4 noet :
+/*
+==================================================================================
+        Copyright (c) 2019 Nokia 
+        Copyright (c) 2018-2019 AT&T Intellectual Property.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================================
+*/
+
+/*
+	Mmemonic:	ring_test.c
+	Abstract:	Test the ring funcitons.
+	Author:		E. Scott Daniels
+	Date:		31 July 2017
+*/
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <strings.h>
+#include <errno.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "../src/common/include/rmr.h"
+#include "../src/common/include/rmr_agnostic.h"
+#include "../src/common/src/ring_static.c"
+
+
+/*
+	Conduct a series of interleaved tests inserting i-factor 
+	values before beginning to pull values (i-factor must be
+	size - 2 smaller than the ring. 
+	Returns 0 on success, 1 on insert failure and 2 on pull failure.
+*/
+static int ie_test( void* r, int i_factor, long inserts ) {
+	int i;
+	int* dp;
+	int data[29];
+
+	for( i = 0; i < inserts; i++ ) {
+		data[i%29] = i;
+		if( ! uta_ring_insert( r, &data[i%29] ) ) {
+			fprintf( stderr, "[FAIL] interleaved insert failed on ifactor=%d i=%d\n", i_factor, i );
+			return 1;
+		}
+		if( i > i_factor-1 ) {
+			dp = uta_ring_extract( r );
+			if( *dp != data[(i-i_factor)%29] ) {
+				fprintf( stderr, "[FAIL] interleaved exctract failed on ifactor=%d i=%d expected=%d got=%d\n", i_factor, i, data[(i-i_factor)%29], *dp );
+				return 2;
+			}
+		}
+	}
+	//fprintf( stderr, "[OK]   interleaved insert/extract test passed for insert factor %d\n", i_factor );
+
+	return 0;
+}
+
+int main( void  ) {
+	void* r;
+	int i;
+	int j;
+	int	data[20];
+	int*	dp;
+	int size = 18;
+
+	r = uta_mk_ring( 0 );			// should return nil
+	if( r != NULL ) {
+		fprintf( stderr, "[FAIL] attempt to make a ring with size 0 returned a pointer\n" );
+		exit( 1 );
+	}
+	r = uta_mk_ring( -1 );			// should also return nil
+	if( r != NULL ) {
+		fprintf( stderr, "[FAIL] attempt to make a ring with size <0 returned a pointer\n" );
+		exit( 1 );
+	}
+
+	r = uta_mk_ring( 18 );
+	if( r == NULL ) {
+		fprintf( stderr, "[FAIL] unable to make ring with 17 entries\n" );
+		exit( 1 );
+	}
+
+	for( i = 0; i < 20; i++ ) {		// test to ensure it reports full when head/tail start at 0
+		data[i] = i;
+		if( ! uta_ring_insert( r, &data[i] ) ) {
+			break;
+		}
+	}
+
+	if( i > size ) {
+		fprintf( stderr, "[FAIL] didn not report table full: i=%d\n", i );
+		exit( 1 );
+	}
+
+	fprintf( stderr, "[OK]   reported table full at i=%d as expected\n", i );
+
+
+	for( i = 0; i < size + 3; i++ ) {								// ensure they all come back in order, and we don't get 'extras'
+		if( (dp = uta_ring_extract( r )) == NULL ) {
+			if( i < size-1 ) {
+				fprintf( stderr, "[FAIL] nil pointer at i=%d\n", i );
+				exit( 1 );
+			} else {
+				break;
+			}
+		}	
+
+		if( *dp != i ) {
+			fprintf( stderr, "[FAIL] data at i=% isnt right; expected %d got %d\n", i, i, *dp );
+		}
+	}
+	if( i > size ) {
+		fprintf( stderr, "[FAIL] got too many values on extract: %d\n", i );
+		exit( 1 );
+	}
+	fprintf( stderr, "[OK]   extracted values were sane, got: %d\n", i-1 );
+		
+	uta_ring_free( NULL );							// ensure this doesn't blow up
+	uta_ring_free( r );
+	for( i = 2; i < 15; i++ ) {
+		r = uta_mk_ring( 16 );
+		if( ie_test( r, i, 101 ) != 0 ) {			// modest number of inserts
+			exit( 1 );
+		}
+
+		uta_ring_free( r );
+	}
+	fprintf( stderr, "[OK]   all modest insert/exctract tests pass\n" );
+
+	size = 5;
+	for( j = 0; j < 20; j++ ) {
+		for( i = 2; i < size - 2; i++ ) {
+			r = uta_mk_ring( size );
+			if( ie_test( r, i, 66000 ) != 0 ) {			// should force the 16bit head/tail indexes to roll over
+				exit( 1 );
+			}
+	
+			uta_ring_free( r );
+		}
+		fprintf( stderr, "[OK]   all large insert/exctract tests pass ring size=%d\n", size );
+
+		size++;
+	}
+
+	return 0;
+}
diff --git a/test/symtab_test.c b/test/symtab_test.c
new file mode 100644
index 0000000..76b2765
--- /dev/null
+++ b/test/symtab_test.c
@@ -0,0 +1,139 @@
+/*
+==================================================================================
+        Copyright (c) 2019 Nokia 
+        Copyright (c) 2018-2019 AT&T Intellectual Property.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================================
+*/
+
+
+/*
+	Mnemonic:	symtab_test.c
+	Abstract:	This is the unit test module that will drive tests against
+				the symbol table portion of RMr.  Run with: 
+					ksh unit_test.ksh symtab_test.c
+	Date:		1 April 2019
+	Author: 	E. Scott Daniels
+*/
+
+#include "../src/common/include/rmr_symtab.h"
+#include "../src/common/src/symtab.c"
+
+#include "test_support.c"
+
+int state = GOOD;							// overall pass/fail state 0==fail
+int counter;								// global counter for for-each tests
+
+
+
+static void fetch( void* st, char* key, int class, int expected ) {
+	char* val;
+
+	val = rmr_sym_get( st, key, class );
+	if( val ) {
+		fprintf( stderr, "[%s] get returns key=%s val=%s\n",  !expected ? "FAIL" : "OK", key, val );
+		if( !expected ) {
+			state = BAD;
+		}
+		
+	} else {
+		fprintf( stderr, "[%s] string key fetch return nil\n", expected ? "FAIL" : "OK" );
+		if( expected ) {
+			state = BAD;
+		}
+	}
+}
+
+static void nfetch( void* st, int key, int expected ) {
+	char* val;
+
+	val = rmr_sym_pull( st, key );
+	if( val ) {
+		fprintf( stderr, "[%s] get returns key=%d val=%s\n", !expected ? "FAIL" : "OK", key, val );
+		if( !expected )  {
+			state = BAD;
+		}
+	} else {
+		fprintf( stderr, "[%s] get return nil for key=%d\n", expected ? "FAIL" : "OK", key );
+		if( expected )  {
+			state = BAD;
+		}
+	}
+}
+
+
+/*
+	Driven by foreach class -- just incr the counter.
+*/
+static void each_counter( void* a, void* b, const char* c, void* d, void* e ) {
+	counter++;
+}
+
+int main( ) {
+    void*   st;
+    char*   foo = "foo";
+    char*   bar = "bar";
+	char*	goo = "goo";				// name not in symtab
+	int		i;
+	int		class = 1;
+	int		s;
+	void*	p;
+
+    st = rmr_sym_alloc( 10 );						// alloc with small value to force adjustment inside
+	fail_if_nil( st, "symtab pointer" );
+
+    s = rmr_sym_put( st, foo, class, bar );			// add entry with string key; returns 1 if it was inserted
+	fail_if_false( s, "insert foo existed" );
+
+    s = rmr_sym_put( st, foo, class+1, bar );		// add to table with a different class
+	fail_if_false( s, "insert foo existed" );
+
+    s = rmr_sym_put( st, foo, class, bar );			// inserted above, should return not inserted (0)
+	fail_if_true( s, "insert foo existed" );
+
+	fetch( st, foo, class, 1 );
+	fetch( st, goo, class, 0 );					// fetch non existant
+    rmr_sym_stats( st, 4 );							// early stats at verbose level 4 so chatter is minimised
+	rmr_sym_dump( st );
+
+	for( i = 2000; i < 3000; i++ ) {			// bunch of dummy things to force chains in the table
+		rmr_sym_map( st, i, foo );					// add entry with unsigned integer key
+	}
+    rmr_sym_stats( st, 0 );							// just the small facts to verify the 1000 we stuffed in
+	rmr_sym_ndel( st, 2001 );						// force a numeric key delete
+	rmr_sym_ndel( st, 12001 );						// delete numeric key not there
+
+	s = rmr_sym_map( st, 1234, foo );					// add known entries with unsigned integer key
+	fail_if_false( s, "numeric add of key 1234 should not have existed" );
+	s = rmr_sym_map( st, 2345, bar );
+	fail_if_true( s, "numeric add of key 2345 should have existed" );
+
+	counter = 0;
+	rmr_sym_foreach_class( st, 0, each_counter, NULL );
+	fail_if_false( counter, "expected counter after foreach to be non-zero" );
+
+	nfetch( st, 1234, 1 );
+	nfetch( st, 2345, 1 );
+
+
+    rmr_sym_del( st, foo, 0 );
+
+    rmr_sym_stats( st, 0 );
+
+	rmr_sym_free( NULL );			// ensure it doesn't barf when given a nil pointer
+	rmr_sym_free( st );
+
+    return state;
+}
+
diff --git a/test/test_support.c b/test/test_support.c
new file mode 100644
index 0000000..d9a5f47
--- /dev/null
+++ b/test/test_support.c
@@ -0,0 +1,134 @@
+// : vi ts=4 sw=4 noet :
+/*
+==================================================================================
+        Copyright (c) 2019 Nokia 
+        Copyright (c) 2018-2019 AT&T Intellectual Property.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================================
+*/
+
+/*
+	Mnemonic:	test_tools.c
+	Abstract:	Functions for test applications to make their life a bit easier.
+				This file is probably compiled to a .o, and then included on
+				the cc command for the test.
+	Author:		E. Scott Daniels
+	Date:		6 January 2019
+*/
+
+#include <signal.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifndef BAD
+#define BAD 1			// these are exit codes unless user overrides
+#define GOOD 0
+#endif
+
+/*
+	Snag the optional positional parameter at pp, return defval if not there.
+*/
+static char* snag_pp( int pp, int argc, char** argv, char* defval ) {
+
+	if( pp < argc ) {
+		return argv[pp];
+	}
+
+	return defval;
+}
+
+/*
+	Signal handler -- inside of the tests we will exit cleanly for hup/temp/intr
+	signals so that the coverage stuff will generate the needed data files. If
+	we inter/term the process they don't drive.
+*/
+
+void sig_clean_exit( int sign ) {
+	fprintf( stderr, "signal trapped for clean exit: %d\n", sign );
+	exit( 0 );
+}
+
+/*	
+	Setup all of the signal handling for signals that we want to force a clean exit:
+	term, intr, hup, quit, usr1/2 alarm, etc.  All others we'll let default.
+*/
+static void set_signals( void ) {
+	struct sigaction sa;
+	int	sig_list[] = { SIGINT, SIGQUIT, SIGILL, SIGALRM, SIGTERM, SIGUSR1 , SIGUSR2 };
+	int i;
+	int nele;		// number of elements in the list
+	
+	nele = (int) ( sizeof( sig_list )/sizeof( int ) );		// convert raw size to the number of elements
+	for( i = 0; i < nele; i ++ ) {
+		memset( &sa, 0, sizeof( sa ) );
+		sa.sa_handler = sig_clean_exit;
+		sigaction( sig_list[i], &sa, NULL );
+	}
+}
+
+
+static int fail_if_nil( void* p, char* what ) {
+	if( !p ) {
+		fprintf( stderr, "[FAIL] pointer to '%s' was nil\n", what );
+	}
+	return p ? GOOD : BAD;
+}
+
+static int fail_not_nil( void* p, char* what ) {
+	if( p ) {
+		fprintf( stderr, "[FAIL] pointer to '%s' was not nil\n", what );
+	}
+	return !p ? GOOD : BAD;
+}
+
+static int fail_if_false( int bv, char* what ) {
+	if( !bv ) {
+		fprintf( stderr, "[FAIL] boolean was false (%d) %s\n", bv, what );
+	}
+
+	return bv ? GOOD : BAD;
+}
+
+static int fail_if_true( int bv, char* what ) {
+	if( bv ) {
+		fprintf( stderr, "[FAIL] boolean was true (%d) %s\n", bv, what );
+	}
+	return bv ? BAD : GOOD;
+}
+
+/*
+	Same as fail_if_true(), but reads easier in the test code.
+*/
+static int fail_if( int bv, char* what ) {
+
+	if( bv ) {
+		fprintf( stderr, "[FAIL] boolean was true (%d) %s\n", bv, what );
+	}
+	return bv ? BAD : GOOD;
+}
+
+static int fail_not_equal( int a, int b, char* what ) {
+	if( a != b ) {
+		fprintf( stderr, "[FAIL] %s values were not equal a=%d b=%d\n", what, a, b );
+	}
+	return a == b ? GOOD : BAD;			// user may override good/bad so do NOT return a==b directly!
+}
+
+static int fail_if_equal( int a, int b, char* what ) {
+	if( a == b ) {
+		fprintf( stderr, "[FAIL] %s values were equal a=%d b=%d\n", what, a, b );
+	}
+	return a != b ? GOOD : BAD;			// user may override good/bad so do NOT return a==b directly!
+}
diff --git a/test/tools_test.c b/test/tools_test.c
new file mode 100644
index 0000000..786d2e6
--- /dev/null
+++ b/test/tools_test.c
@@ -0,0 +1,199 @@
+// : vi ts=4 sw=4 noet :
+/*
+==================================================================================
+        Copyright (c) 2019 Nokia 
+        Copyright (c) 2018-2019 AT&T Intellectual Property.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================================
+*/
+
+
+/*
+	Mnemonic:	tools_testh.c
+	Abstract:	Unit tests for the RMr tools module.
+	Author:		E. Scott Daniels
+	Date:		21 January 2019
+*/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <netdb.h>
+#include <errno.h>
+#include <string.h>
+#include <errno.h>
+#include <pthread.h>
+#include <ctype.h>
+
+/*
+#include <nanomsg/nn.h>
+#include <nanomsg/tcp.h>
+#include <nanomsg/pair.h>
+#include <nanomsg/pipeline.h>
+#include <nanomsg/pubsub.h>
+*/
+
+#include "../src/common/include/rmr.h"
+#include "../src/common/include/rmr_agnostic.h"
+#include "test_support.c"		// our private library of test tools
+
+// ===== dummy context for tools testing so we don't have to pull in all of the nano/nng specific stuff =====
+struct uta_ctx {
+	char*	my_name;			// dns name of this host to set in sender field of a message
+	int	shutdown;				// thread notification if we need to tell them to stop
+	int max_mlen;				// max message length payload+header
+	int	max_plen;				// max payload length
+	int	flags;					// CTXFL_ constants
+	int nrtele;					// number of elements in the routing table
+	int send_retries;			// number of retries send_msg() should attempt if eagain/timeout indicated by nng
+	//nng_socket	nn_sock;		// our general listen socket
+	route_table_t* rtable;		// the active route table
+	route_table_t* old_rtable;	// the previously used rt, sits here to allow for draining
+	route_table_t* new_rtable;	// route table under construction
+	if_addrs_t*	ip_list;		// list manager of the IP addresses that are on our known interfaces
+	void*	mring;				// ring where msgs are queued while waiting for a call response msg
+	
+	char*	rtg_addr;			// addr/port of the route table generation publisher
+	int		rtg_port;			// the port that the rtg listens on
+	
+	wh_mgt_t*	wormholes;		// management of user opened wormholes
+	//epoll_stuff_t*	eps;		// epoll information needed for the rcv with timeout call
+
+	//pthread_t	rtc_th;			// thread info for the rtc listener
+};
+
+
+#include "../src/common/src/tools_static.c"
+
+
+int main( ) {
+	int i;
+	int j;
+	int errors = 0;
+	char* tokens[127];
+	char* buf = "2,Fred,Wilma,Barney,Betty,Dino,Pebbles,Bambam,Mr. Slate,Gazoo";
+	char*	dbuf;				// duplicated buf since C marks a const string is unumtable
+	char*	hname;
+	uta_ctx_t ctx;				// context for uta_lookup test
+	void*	if_list;
+
+	
+	// ------------------ tokenise tests -----------------------------------------------------------
+	dbuf = strdup( buf );
+	i = uta_tokenise( dbuf, tokens, 127, ',' );
+	errors += fail_not_equal( i, 10, "unexpected number of tokens returned (comma sep)" );
+	for( j = 0; j < i; j++ ) {
+		//fprintf( stderr, ">>>> [%d] (%s)\n", j, tokens[j] );
+		errors += fail_if_nil( tokens[j], "token from buffer" );
+	}
+	errors += fail_not_equal( strcmp( tokens[4], "Betty" ), 0, "4th token wasn't 'Betty'" );
+
+	free( dbuf );
+	dbuf = strdup( buf );
+	i = uta_tokenise( dbuf, tokens, 127, '|' );
+	errors += fail_not_equal( i, 1, "unexpected number of tokens returned (bar sep)" );
+	free( dbuf );
+
+	// ------------ has str tests -----------------------------------------------------------------
+	j = uta_has_str( buf, "Mr. Slate", ',', 1 );			// should fail (-1) because user should use strcmp in this situation
+	errors += fail_if_true( j >= 0, "test to ensure has str rejects small max" );
+
+	j = uta_has_str( buf, "Mr. Slate", ',', 27 );
+	errors += fail_if_true( j < 0, "has string did not find Mr. Slate" );
+
+	j = uta_has_str( buf, "Mrs. Slate", ',', 27 );
+	errors += fail_if_true( j >= 0, "has string not found Mrs. Slate" );
+	
+	// ------------ host name 2 ip tests ---------------------------------------------------------
+	hname = uta_h2ip( "192.168.1.2" );
+	errors += fail_not_equal( strcmp( hname, "192.168.1.2" ), 0, "h2ip did not return IP address when given address" );
+	errors += fail_if_nil( hname, "h2ip did not return a pointer" );
+
+	hname = uta_h2ip( "yahoo.com" );
+	errors += fail_if_nil( hname, "h2ip did not return a pointer" );
+
+	hname = uta_h2ip( "yahoo.com:1234" );							// should ignore the port
+	errors += fail_if_nil( hname, "h2ip did not return a pointer" );
+
+	// ------------ rtg lookup test -------------------------------------------------------------
+	ctx.rtg_port = 0;
+	ctx.rtg_addr = NULL;
+       
+	i = uta_lookup_rtg( NULL );						// ensure it handles a nil context
+	errors += fail_if_true( i, "rtg lookup returned that it found something when not expected to (nil context)" );
+
+	setenv( "RMR_RTG_SVC", "localhost:1234", 1);
+	i = uta_lookup_rtg( &ctx );
+	errors += fail_if_false( i, "rtg lookup returned that it did not find something when expected to" );
+	errors += fail_if_nil( ctx.rtg_addr, "rtg lookup did not return a pointer (with port)" );
+	errors += fail_not_equal( ctx.rtg_port, 1234, "rtg lookup did not capture the port" );
+
+	setenv( "RMR_RTG_SVC", "localhost", 1);			// test ability to generate default port
+	uta_lookup_rtg( &ctx );
+	errors += fail_if_nil( ctx.rtg_addr, "rtg lookup did not return a pointer (no port)" );
+	errors += fail_not_equal( ctx.rtg_port, 5656, "rtg lookup did not return default port" );
+
+	unsetenv( "RMR_RTG_SVC" );						// this should fail as the default name (rtg) will be unknown during testing
+	i = uta_lookup_rtg( &ctx );
+	errors += fail_if_true( i, "rtg lookup returned that it found something when not expected to" );
+
+/*
+//==== moved out of generic tools ==========
+	// -------------- test link2 stuff ----------------------------------------------------------
+	i = uta_link2( "bad" );					// should fail
+	errors += fail_if_true( i >= 0, "uta_link2 didn't fail when given bad address" );
+
+	i = uta_link2( "nohost:-1234" );
+	errors += fail_if_true( i >= 0, "uta_link2 did not failed when given a bad (negative) port " );
+
+	i = uta_link2( "nohost:1234" );					// nn should go off and set things up, but it will never successd, but uta_ call should
+	errors += fail_if_true( i < 0, "uta_link2 failed when not expected to" );
+*/
+
+	// ------------ my ip stuff -----------------------------------------------------------------
+
+	if_list = mk_ip_list( "1235" );
+	errors += fail_if_nil( if_list, "mk_ip_list returned nil pointer" );
+
+	i = has_myip( NULL, NULL, ',', 128 );		// should be false if pointers are nil
+	errors += fail_if_true( i, "has_myip returned true when given nil buffer" );
+
+	i = has_myip( "buffer contents not valid", NULL, ',', 128 );		// should be false if pointers are nil
+	errors += fail_if_true( i, "has_myip returned true when given nil list" );
+
+	i = has_myip( "buffer contents not valid", NULL, ',', 1 );			// should be false if max < 2
+	errors += fail_if_true( i, "has_myip returned true when given small max value" );
+
+	i = has_myip( "buffer.contents.not.valid", if_list, ',', 128 );		// should be false as there is nothing valid in the list
+	errors += fail_if_true( i, "has_myip returned true when given a buffer with no valid info" );
+
+
+	setenv( "RMR_BIND_IF", "192.168.4.30", 1 );			// drive the case where we have a hard set interface; and set known interface in list
+	if_list = mk_ip_list( "1235" );
+	errors += fail_if_nil( if_list, "mk_ip_list with env set returned nil pointer" );
+
+	i = has_myip( "192.168.1.2:1235,192.168.4.30:1235,192.168.2.19:4567", if_list, ',', 128 );		// should find our ip in middle
+	errors += fail_if_false( i, "has_myip did not find IP in middle of list" );
+
+	i = has_myip( "192.168.4.30:1235,192.168.2.19:4567,192.168.2.19:2222", if_list, ',', 128 );		// should find our ip at head
+	errors += fail_if_false( i, "has_myip did not find IP at head of list" );
+
+	i = has_myip( "192.168.23.45:4444,192.168.1.2:1235,192.168.4.30:1235", if_list, ',', 128 );		// should find our ip at end
+	errors += fail_if_false( i, "has_myip did not find IP at tail of list" );
+
+	i = has_myip( "192.168.4.30:1235", if_list, ',', 128 );											// should find our ip when only in list
+	errors += fail_if_false( i, "has_myip did not find IP when only one in list" );
+
+	return errors > 0;			// overall exit code bad if errors
+}
diff --git a/test/unit_test.ksh b/test/unit_test.ksh
new file mode 100755
index 0000000..fb5fa2a
--- /dev/null
+++ b/test/unit_test.ksh
@@ -0,0 +1,416 @@
+#!/usr/bin/env ksh
+# this will fail if run with bash!
+
+#==================================================================================
+#        Copyright (c) 2019 Nokia 
+#        Copyright (c) 2018-2019 AT&T Intellectual Property.
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#==================================================================================
+
+
+#
+#	Mnemonic:	unit_test.ksh
+#	Abstract:	Execute unit test(s) in the directory and produce a more 
+#				meaningful summary than gcov gives by default (exclude
+#				coverage  on the unit test functions).
+#
+#				Test files must be named *_test.c, or must explicitly be 
+#				supplied on the command line. Functions in the test
+#				files will not be reported on provided that they have
+#				their prototype (all on the SAME line) as:
+#					static type name() {
+#
+#				Functions with coverage less than 80% will be reported as 
+#				[LOW] in the output.  A file is considered to pass if the
+#				overall execution percentage for the file is >= 80% regardless
+#				of the number of functions that reported low.
+#
+#				Test programmes are built prior to execution. Plan-9 mk is
+#				the preferred builder, but as it's not widly adopted (sigh)
+#				make is assumed and -M will shift to Plan-9. Use -C xxx to 
+#				invoke a customised builder.
+#
+#				For a module which does not pass, we will attempt to boost
+#				the coverage by discounting the unexecuted lines which are
+#				inside of if() statements that are checking return from 
+#				(m)alloc() calls or are checking for nil pointers as these
+#				cases are likely impossible to drive. When discount testing
+#				is done both the failure message from the original analysis
+#				and a pass/fail message from the discount test are listed, 
+#				but only the result of the discount test is taken into 
+#				consideration with regard to overall success.
+#
+#	Date:		16 January 2018
+#	Author:		E. Scott Daniels
+# -------------------------------------------------------------------------
+
+function usage {
+	echo "usage: $0 [-G|-M|-C custom-command-string] [-c cov-target]  [-f] [-v]  [files]"
+	echo "  if -C is used to provide a custom build command then it must "
+	echo "  contain a %s which will be replaced with the unit test file name."
+	echo '  e.g.:  -C "mk -a %s"'
+	echo "  -c allows user to set the target coverage for a module to pass; default is 80"
+	echo "  -f forces a discount check (normally done only if coverage < target)"
+	echo "  -v will write additional information to the tty and save the disccounted file if discount run or -f given"
+}
+
+# read through the given file and add any functions that are static to the 
+# ignored list.  Only test and test tools files should be parsed.
+#
+function add_ignored_func {
+	if [[ ! -r $1 ]]
+	then
+		return
+	fi
+
+	typeset f=""
+	grep "^static.*(.*).*{" $1 | awk '		# get list of test functions to ignore
+		{ 
+			gsub( "[(].*", "" )
+			print $3
+		}
+	' | while read f
+	do
+		iflist+="$f "	
+	done
+}
+
+#
+#	Parse the .gcov file and discount any unexecuted lines which are in if() 
+#	blocks that are testing the result of alloc/malloc calls, or testing for
+#	nil pointers.  The feeling is that these might not be possible to drive
+#	and shoudn't contribute to coverage deficencies.
+#
+#	In verbose mode, the .gcov file is written to stdout and any unexecuted
+#	line which is discounted is marked with ===== replacing the ##### marking
+#	that gcov wrote.
+#
+#	The return value is 0 for pass; non-zero for fail.
+function discount_an_checks {
+	typeset f="$1"
+
+	mct=$( get_mct ${1%.gcov} )			# see if a special coverage target is defined for this
+
+	if [[ ! -f $1 ]]
+	then
+		if [[ -f ${1##*/} ]]
+		then
+			f=${1##*/} 
+		else
+			echo "cant find: $f"
+			return
+		fi
+	fi
+
+	awk -v module_cov_target=$mct \
+		-v full_name="${1}"  \
+		-v module="${f%.*}"  \
+		-v chatty=$verbose \
+	'
+	function spit_line( ) {
+		if( chatty ) {
+			printf( "%s\n", $0 )
+		}
+	}
+
+	/-:/ { 				# skip unexecutable lines
+		spit_line()
+		seq++					# allow blank lines in a sequence group
+		next 
+	}
+
+	{
+		nexec++			# number of executable lines
+	}
+
+	/#####:/ {
+		unexec++;
+		if( $2+0 != seq+1 ) {
+			prev_malloc = 0
+			prev_if = 0
+			seq = 0
+			spit_line()
+			next
+		}
+
+		if( prev_if && prev_malloc ) {
+			if( prev_malloc ) {
+				#printf( "allow discount: %s\n", $0 )
+				if( chatty ) {
+					gsub( "#####", "=====", $0 )
+				}
+				discount++;
+			}
+		}
+
+		seq++;;
+		spit_line()
+		next;
+	}
+
+	/if[(].*alloc.*{/ {			# if( (x = malloc( ... )) != NULL ) or if( (p = sym_alloc(...)) != NULL )
+		seq = $2+0
+		prev_malloc = 1
+		prev_if = 1
+		spit_line()
+		next
+	}
+
+	/if[(].* == NULL/ {				# a nil check likely not easily forced if it wasnt driven
+		prev_malloc = 1
+		prev_if = 1
+		spit_line()
+		seq = $2+0
+		next
+	}
+
+	/if[(]/ {
+		if( seq+1 == $2+0 && prev_malloc ) {		// malloc on previous line
+			prev_if = 1
+		} else {
+			prev_malloc = 0
+			prev_if = 0
+		}
+		spit_line()
+		next
+	}
+
+	/alloc[(]/ {
+		seq = $2+0
+		prev_malloc = 1
+		spit_line()
+		next
+	}
+
+	{ 
+		spit_line()
+	}
+
+	END {
+		net = unexec - discount
+		orig_cov = ((nexec-unexec)/nexec)*100		# original coverage
+		adj_cov = ((nexec-net)/nexec)*100			# coverage after discount
+		pass_fail = adj_cov < module_cov_target ? "FAIL" : "PASS"
+		rc = adj_cov < module_cov_target ? 1 : 0
+		if( chatty ) {
+			printf( "[%s] %s executable=%d unexecuted=%d discounted=%d net_unex=%d  cov=%d% ==> %d%%%  target=%d%%\n", 
+				pass_fail, full_name ? full_name : module, nexec, unexec, discount, net, orig_cov, adj_cov, module_cov_target )
+		} else {
+			printf( "[%s] %d%% (%d%%) %s\n", pass_fail, adj_cov, orig_cov, full_name ? full_name : module )
+		}
+
+		exit( rc )
+	}
+	' $f
+}
+
+# Given a file name ($1) see if it is in the ./.targets file. If it is 
+# return the coverage listed, else return (echo)  the default $module_cov_target
+#
+function get_mct {
+	typeset v=$module_cov_target
+
+	if [[ -f ./.targets ]]
+	then
+		grep "^$1 " ./.targets | head -1 | read junk tv
+	fi
+
+	echo ${tv:-$v}
+}
+
+
+# ------------------------------------------------------------------------
+
+export C_INCLUDE_PATH="../src/common/include"
+
+module_cov_target=80
+builder="make -B %s"		# default to plain ole make
+verbose=0
+trigger_discount_str="FAIL"
+
+while [[ $1 == "-"* ]]
+do
+	case $1 in 
+		-C)	builder="$2"; shift;;		# custom build command
+		-G)	builder="gmake %s";;
+		-M)	builder="mk -a %s";;		# use plan-9 mk (better, but sadly not widly used)
+
+		-c)	module_cov_target=$2; shift;;
+		-f)	force_discounting=1; 
+			trigger_discount_str="FAIL|PASS"		# check all outcomes for each module
+			;;
+
+		-v)	(( verbose++ ));;
+
+		-h) 	usage; exit 0;;
+		--help) usage; exit 0;;
+		-\?) 	usage; exit 0;;
+
+		*)	echo "unrecognised option: $1" >&2
+			usage >&2
+			exit 1
+			;;
+	esac
+
+	shift
+done
+
+if [[ -z $1 ]]
+then
+	flist=""
+	for tfile in *_test.c
+	do
+		flist+="$tfile "
+	done
+else
+	flist="$@"
+fi
+
+errors=0
+for tfile in $flist
+do
+	echo "$tfile --------------------------------------"
+	bcmd=$( printf "$builder" "${tfile%.c}" )
+	if ! $bcmd >/tmp/PID$$.log 2>&1
+	then
+		echo "[FAIL] cannot build $tfile"
+		cat /tmp/PID$$.log
+		rm -f /tmp/PID$$
+		exit 1
+	fi
+
+	iflist="main sig_clean_exit "		# ignore external functions from our tools
+	add_ignored_func $tfile				# ignore all static functions in our test driver
+	add_ignored_func test_support.c		# ignore all static functions in our test tools
+	
+	if ! ${tfile%.c} >/tmp/PID$$.log 2>&1
+	then
+		echo "[FAIL] unit test failed for: $tfile"
+		cat /tmp/PID$$.log
+		continue
+	fi
+
+	(
+		touch ./.targets
+		sed '/^#/ d; /^$/ d; s/^/TARGET: /' ./.targets
+		gcov -f ${tfile%.c} | sed "s/'//g" 
+	) | awk \
+		-v ignore_list="$iflist" \
+		-v module_cov_target=$module_cov_target \
+		-v chatty=$verbose \
+		'
+		BEGIN {
+			nignore = split( ignore_list, ignore, " " )
+			for( i = 1; i <= nignore; i++ ) {
+				imap[ignore[i]] = 1
+			}
+
+			exit_code = 0		# assume good
+		}
+
+		/^TARGET:/ {
+			if( NF > 1 ) {
+				target[$2] = $NF
+			}
+			next;
+		}
+
+		/File.*_test/ || /File.*test_/ {		# dont report on test files
+			skip = 1
+			file = 1
+			fname = $2
+			next
+		}
+
+		/File/ {
+			skip = 0
+			file = 1
+			fname = $2
+			next
+		}
+
+		/Function/ {
+			fname = $2
+			file = 0
+			if( imap[fname] ) {
+				fname = "skipped: " fname		# should never see and make it smell if we do
+				skip = 1
+			} else {
+				skip = 0
+			}
+			next
+		}
+
+		skip { next }
+
+		/Lines executed/ {
+			split( $0, a, ":" )
+			pct = a[2]+0
+
+			if( file ) {
+				if( target[fname] ) {
+					mct = target[fname] 
+				} else {
+					mct = module_cov_target
+				}
+				if( chatty ) {
+					printf( "[INFO] target coverage for %s is %d%%\n", fname, mct )
+				}
+				if( pct < mct ) {
+					printf( "[FAIL] %3d%% %s\n\n", pct, fname )	# CAUTION: write only 3 things  here
+					exit_code = 1
+				} else {
+					printf( "[PASS] %3d%% %s\n\n", pct, fname )
+				}
+			} else {
+				if( pct < 80 ) {
+					printf( "[LOW]  %3d%% %s\n", pct, fname )
+				} else {
+					printf( "[OK]   %3d%% %s\n", pct, fname )
+				}
+			}
+		}
+
+		END {
+			exit( exit_code )
+		}
+	' >/tmp/PID$$.log					# capture output to run discount on failures
+	rc=$?
+	cat /tmp/PID$$.log
+	if (( rc  || force_discounting )) 	# didn't pass, or forcing, see if discounting helps
+	then
+		egrep "$trigger_discount_str"  /tmp/PID$$.log | while read state junk  name
+		do
+			echo "[INFO] checking to see if discounting improves coverage for $name"
+			if ! discount_an_checks $name.gcov >/tmp/PID$$.disc
+			then
+				(( errors++ ))
+			fi
+			tail -1 /tmp/PID$$.disc
+			if (( verbose )) 			# updated file was generated, keep here
+			then
+				echo "[INFO] discounted coverage info in: ${tfile##*/}.dcov"
+				mv /tmp/PID$$.disc ${tfile##*/}.dcov
+			fi
+		done
+	fi
+done
+
+rm -f /tmp/PID$$.*
+if (( errors ))
+then
+	exit 1
+fi
+exit 0
+