2 # this will fail if run with bash!
4 #==================================================================================
5 # Copyright (c) 2019 Nokia
6 # Copyright (c) 2018-2019 AT&T Intellectual Property.
8 # Licensed under the Apache License, Version 2.0 (the "License");
9 # you may not use this file except in compliance with the License.
10 # You may obtain a copy of the License at
12 # http://www.apache.org/licenses/LICENSE-2.0
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS,
16 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 # See the License for the specific language governing permissions and
18 # limitations under the License.
19 #==================================================================================
23 # Mnemonic: unit_test.ksh
24 # Abstract: Execute unit test(s) in the directory and produce a more
25 # meaningful summary than gcov gives by default (exclude
26 # coverage on the unit test functions).
28 # Test files must be named *_test.c, or must explicitly be
29 # supplied on the command line. Functions in the test
30 # files will not be reported on provided that they have
31 # their prototype (all on the SAME line) as:
32 # static type name() {
34 # Functions with coverage less than 80% will be reported as
35 # [LOW] in the output. A file is considered to pass if the
36 # overall execution percentage for the file is >= 80% regardless
37 # of the number of functions that reported low.
39 # Test programmes are built prior to execution. Plan-9 mk is
40 # the preferred builder, but as it's not widly adopted (sigh)
41 # make is assumed and -M will shift to Plan-9. Use -C xxx to
42 # invoke a customised builder.
44 # For a module which does not pass, we will attempt to boost
45 # the coverage by discounting the unexecuted lines which are
46 # inside of if() statements that are checking return from
47 # (m)alloc() calls or are checking for nil pointers as these
48 # cases are likely impossible to drive. When discount testing
49 # is done both the failure message from the original analysis
50 # and a pass/fail message from the discount test are listed,
51 # but only the result of the discount test is taken into
52 # consideration with regard to overall success.
55 # By default the overall state is based only on the success
56 # or failure of the unit tests and NOT on the perceived
57 # state of coverage. If the -s (strict) option is given, then
58 # overall state will be failure if code coverage expectations
61 # Date: 16 January 2018
62 # Author: E. Scott Daniels
63 # -------------------------------------------------------------------------
66 echo "usage: $0 [-G|-M|-C custom-command-string] [-c cov-target] [-f] [-F] [-v] [-x] [files]"
67 echo " if -C is used to provide a custom build command then it must "
68 echo " contain a %s which will be replaced with the unit test file name."
69 echo ' e.g.: -C "mk -a %s"'
70 echo " -c allows user to set the target coverage for a module to pass; default is 80"
71 echo " -f forces a discount check (normally done only if coverage < target)"
72 echo " -F show only failures at the function level"
73 echo " -s strict mode; code coverage must also pass to result in a good exit code"
74 echo " -v will write additional information to the tty and save the disccounted file if discount run or -f given"
75 echo " -x generates the coverage XML files for Sonar (implies -f)"
78 # read through the given file and add any functions that are static to the
79 # ignored list. Only test and test tools files should be parsed.
81 function add_ignored_func {
88 grep "^static.*(.*).*{" $1 | awk ' # get list of test functions to ignore
100 # Merge two coverage files to preserve the total lines covered by different
104 if [[ -z $1 || -z $2 ]]
109 if [[ ! -e $1 || ! -e $2 ]]
126 if( executed[line] ) {
127 $1 = sprintf( "%9d:", executed[line] )
139 executed[line] = $1+0
146 # Parse the .gcov file and discount any unexecuted lines which are in if()
147 # blocks that are testing the result of alloc/malloc calls, or testing for
148 # nil pointers. The feeling is that these might not be possible to drive
149 # and shoudn't contribute to coverage deficiencies.
151 # In verbose mode, the .gcov file is written to stdout and any unexecuted
152 # line which is discounted is marked with ===== replacing the ##### marking
155 # The return value is 0 for pass; non-zero for fail.
156 function discount_an_checks {
159 mct=$( get_mct ${1%.gcov} ) # see if a special coverage target is defined for this
172 awk -v module_cov_target=$mct \
173 -v cfail=${cfail:-WARN} \
174 -v show_all=$show_all \
175 -v full_name="${1}" \
176 -v module="${f%.*}" \
178 -v replace_flags=$replace_flags \
180 function spit_line( ) {
186 /-:/ { # skip unexecutable lines
188 seq++ # allow blank lines in a sequence group
193 nexec++ # number of executable lines
198 if( $2+0 != seq+1 ) {
206 if( prev_if && prev_malloc ) {
208 #printf( "allow discount: %s\n", $0 )
209 if( replace_flags ) {
210 gsub( "#####", " 1", $0 )
211 //gsub( "#####", "=====", $0 )
222 /if[(].*alloc.*{/ { # if( (x = malloc( ... )) != NULL ) or if( (p = sym_alloc(...)) != NULL )
230 /if[(].* == NULL/ { # a nil check likely not easily forced if it wasnt driven
239 if( seq+1 == $2+0 && prev_malloc ) { // malloc on previous line
261 net = unexec - discount
262 orig_cov = ((nexec-unexec)/nexec)*100 # original coverage
263 adj_cov = ((nexec-net)/nexec)*100 # coverage after discount
264 pass_fail = adj_cov < module_cov_target ? cfail : "PASS"
265 rc = adj_cov < module_cov_target ? 1 : 0
266 if( pass_fail == cfail || show_all ) {
268 printf( "[%s] %s executable=%d unexecuted=%d discounted=%d net_unex=%d cov=%d%% ==> %d%% target=%d%%\n",
269 pass_fail, full_name ? full_name : module, nexec, unexec, discount, net, orig_cov, adj_cov, module_cov_target )
271 printf( "[%s] %d%% (%d%%) %s\n", pass_fail, adj_cov, orig_cov, full_name ? full_name : module )
280 # Given a file name ($1) see if it is in the ./.targets file. If it is
281 # return the coverage listed, else return (echo) the default $module_cov_target
284 typeset v=$module_cov_target
286 if [[ -f ./.targets ]]
288 grep "^$1 " ./.targets | head -1 | read junk tv
294 # Remove unneeded coverage files, then generate the xml files that can be given
295 # to sonar. gcov.xml is based on the "raw" coverage and dcov.xml is based on
296 # the discounted coverage.
299 rm -fr *_test.c.gcov test_*.c.gcov *_test.c.dcov test_*.c.dcov # we don't report on the unit test code, so ditch
300 cat *.gcov | cov2xml.ksh >gcov.xml
301 cat *.dcov | cov2xml.ksh >dcov.xml
305 # -----------------------------------------------------------------------------------------------------------------
307 # we assume that the project has been built in the ../[.]build directory
308 if [[ -d ../build/lib ]]
310 export LD_LIBRARY_PATH=../build/lib
312 if [[ -d ../.build/lib ]]
314 export LD_LIBRARY_PATH=../.build/lib
315 export C_INCLUDE_PATH=../.build/include
318 echo "[WARN] cannot find ../[.]build/lib; things might not work"
323 export C_INCLUDE_PATH="../src/common/include:$C_INCLUDE_PATH"
326 builder="make -B %s" # default to plain ole make
328 show_all=1 # show all things -F sets to show failures only
329 strict=0 # -s (strict) will set; when off, coverage state ignored in final pass/fail
330 show_output=0 # show output from each test execution (-S)
333 replace_flags=1 # replace ##### in gcov for discounted lines
335 while [[ $1 == "-"* ]]
338 -C) builder="$2"; shift;; # custom build command
339 -G) builder="gmake %s";;
340 -M) builder="mk -a %s";; # use plan-9 mk (better, but sadly not widly used)
342 -c) module_cov_target=$2; shift;;
343 -f) force_discounting=1;
344 trigger_discount_str="WARN|FAIL|PASS" # check all outcomes for each module
349 -s) strict=1;; # coverage counts toward pass/fail state
350 -S) show_output=1;; # test output shown even on success
351 -v) (( verbose++ ));;
352 -q) quiet=1;; # less chatty when spilling error log files
355 trigger_discount_str="WARN|FAIL|PASS" # check all outcomes for each module
360 --help) usage; exit 0;;
363 *) echo "unrecognised option: $1" >&2
373 if (( strict )) # if in strict mode, coverage shortcomings are failures
379 if [[ -z $trigger_discount_str ]]
381 trigger_discount_str="$cfail"
388 for tfile in *_test.c
390 if [[ $tfile != *"static_test.c" ]]
392 flist="${flist}$tfile "
400 rm *.gcov # ditch the previous coverage files
401 ut_errors=0 # unit test errors (not coverage errors)
414 echo "$tfile --------------------------------------"
415 bcmd=$( printf "$builder" "${tfile%.c}" )
416 if ! $bcmd >/tmp/PID$$.log 2>&1
418 echo "[FAIL] cannot build $tfile"
424 iflist="main sig_clean_exit " # ignore external functions from our tools
425 add_ignored_func $tfile # ignore all static functions in our test driver
426 add_ignored_func test_support.c # ignore all static functions in our test tools
427 add_ignored_func test_nng_em.c # the nng/nano emulated things
428 for f in *_static_test.c # all static modules here
433 if ! ./${tfile%.c} >/tmp/PID$$.log 2>&1
435 echo "[FAIL] unit test failed for: $tfile"
438 grep "^<" /tmp/PID$$.log # in quiet mode just dump <...> messages which are assumed from the test programme not appl
442 (( ut_errors++ )) # cause failure even if not in strict mode
443 continue # skip coverage tests for this
447 printf "\n============= test programme output =======================\n"
449 printf "===========================================================\n"
455 sed '/^#/ d; /^$/ d; s/^/TARGET: /' ./.targets
456 gcov -f ${tfile%.c} | sed "s/'//g"
459 -v show_all=$show_all \
460 -v ignore_list="$iflist" \
461 -v module_cov_target=$module_cov_target \
466 nignore = split( ignore_list, ignore, " " )
467 for( i = 1; i <= nignore; i++ ) {
471 exit_code = 0 # assume good
481 /File.*_test/ || /File.*test_/ { # dont report on test files
499 fname = "skipped: " fname # should never see and make it smell if we do
514 if( announce_target ) { # announce default once at start
516 printf( "\n[INFO] default target coverage for modules is %d%%\n", module_cov_target )
519 if( target[fname] ) {
523 mct = module_cov_target
526 if( announce_target ) { # annoucne for module if different from default
527 printf( "[INFO] target coverage for %s is %d%%\n", fname, mct )
531 printf( "[%s] %3d%% %s\n", cfail, pct, fname ) # CAUTION: write only 3 things here
534 printf( "[PASS] %3d%% %s\n", pct, fname )
540 printf( "[LOW] %3d%% %s\n", pct, fname )
543 printf( "[MARG] %3d%% %s\n", pct, fname )
546 printf( "[OK] %3d%% %s\n", pct, fname )
558 ' >/tmp/PID$$.log # capture output to run discount on failures
562 if (( rc || force_discounting )) # didn't pass, or forcing, see if discounting helps
566 echo "[INFO] checking to see if discounting improves coverage for failures listed above"
569 egrep "$trigger_discount_str" /tmp/PID$$.log | while read state junk name
571 if ! discount_an_checks $name.gcov >/tmp/PID$$.disc
576 tail -1 /tmp/PID$$.disc | grep '\['
578 if (( verbose > 1 )) # updated file was generated, keep here
580 echo "[INFO] discounted coverage info in: ${tfile##*/}.dcov"
583 mv /tmp/PID$$.disc ${name##*/}.dcov
587 for x in *.gcov # merge any previous coverage file with this one
589 if [[ -e $x && -e $x- ]]
591 merge_cov $x $x- >/tmp/PID$$.mc
599 echo "[INFO] final discount checks on merged gcov files"
603 if [[ $xx != *"test"* ]]
606 discount_an_checks $xx >$of
607 tail -1 $of | grep '\['
611 state=0 # final state
613 if (( strict )) # fail if some coverage failed too
615 if (( errors + ut_errors ))
619 else # not strict; fail only if unit tests themselves failed
629 echo "[FAIL] overall unit testing fails: coverage errors=$errors unit test errors=$ut_errors"
631 echo "[PASS] overall unit testing passes"