Updates to the affinity router test framework as
well as bug fixes to the affinity router found by
the test framework.

Change-Id: I90e6baa9e9ee11bd8034498b8651e9e14512e528
diff --git a/tests/afrouter/templates/client.go b/tests/afrouter/templates/client.go
index 8cd3330..db34efd 100644
--- a/tests/afrouter/templates/client.go
+++ b/tests/afrouter/templates/client.go
@@ -99,7 +99,7 @@
 			// value.
 			if resS,err := json.Marshal(res); err == nil {
 				if string(resS) != expect {
-					resFile.testLog("Unexpected result returned\n")
+					stats.testLog("Unexpected result returned expected '%s' got '%s'\n", expect, string(resS))
 					return errors.New("Unexpected result on method {{.Name}}")
 				}
 			} else {
@@ -109,11 +109,11 @@
 			for k,v := range expectMeta {
 				if rv,ok := hdr[k]; ok == true {
 					if rv[0] != v[0] {
-						resFile.testLog("Mismatch on returned metadata for key '%s' expected '%s' and got '%s'\n", k, v, rv)
+						stats.testLog("Mismatch on returned metadata for key '%s' expected '%s' and got '%s'\n", k, v, rv)
 						err = errors.New("Failure on returned metadata")
 					}
 				} else {
-					resFile.testLog("Returned metadata missing key '%s'; expected value '%s' at that key\n", k, v)
+					stats.testLog("Returned metadata missing key '%s'; expected value '%s' at that key\n", k, v)
 					err = errors.New("Failure on returned metadata")
 				}
 			}
diff --git a/tests/afrouter/templates/main.go b/tests/afrouter/templates/main.go
index c2fddb9..0361460 100644
--- a/tests/afrouter/templates/main.go
+++ b/tests/afrouter/templates/main.go
@@ -21,74 +21,15 @@
 
 import (
 	"os"
-	"fmt"
 	"time"
 	"os/exec"
 	"strings"
 	"context"
-	slog "log"
-	"io/ioutil"
-	"encoding/json"
-	"google.golang.org/grpc/grpclog"
+	//slog "log"
+	//"google.golang.org/grpc/grpclog"
 	"github.com/opencord/voltha-go/common/log"
 )
 
-type TestCase struct {
-	Title string `json:"title"`
-	Result bool `json:"result"`
-	Info []string `json:"info"`
-}
-
-type TestSuite struct {
-	Name string `json:"name"`
-	TestCases []TestCase `json:"testCases"`
-}
-
-type TestRun struct {
-	TestSuites []TestSuite
-}
-
-var resFile *tstLog
-type tstLog struct {
-	fp * os.File
-	fn string
-}
-
-func (tr * tstLog) testLog(format string, a ...interface{}) {
-	var err error
-	if tr.fp == nil {
-		if tr.fp, err = os.OpenFile(tr.fn, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil {
-			log.Errorf("Could not append to the results file")
-			tr.fp = nil
-		}
-	}
-	if tr.fp != nil {
-		tr.fp.Write([]byte(fmt.Sprintf(format, a...)))
-	}
-}
-
-func (tr * tstLog) testLogOnce(format string, a ...interface{}) {
-	var err error
-	if tr.fp == nil {
-		if tr.fp, err = os.OpenFile(tr.fn, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil {
-			log.Errorf("Could not append to the results file")
-			tr.fp = nil
-		}
-	}
-	if tr.fp != nil {
-		tr.fp.Write([]byte(fmt.Sprintf(format, a...)))
-	}
-	tr.fp.Close()
-	tr.fp = nil
-}
-
-func (tr * tstLog) close() {
-	if tr.fp != nil {
-		tr.fp.Close()
-	}
-}
-
-
 func startSut(cmdStr string) (*exec.Cmd, context.CancelFunc, error) {
 	var err error = nil
 
@@ -109,58 +50,35 @@
 
 func cleanUp(cmd *exec.Cmd, cncl context.CancelFunc) {
 	cncl()
-	cmd.Wait() // This seems to hang
-	// Give the child processes time to terminate
-	//time.Sleep(1 * time.Second)
+	cmd.Wait()
 }
 
-func readStats(stats * TestRun) () {
-	// Check if the  stats file exists
-	if _,err := os.Stat("stats.json"); err != nil {
-		// Nothing to do, just return
-		return
-	}
-	// The file is there, read it an unmarshal it into the stats struct
-	if statBytes, err := ioutil.ReadFile("stats.json"); err != nil {
-		log.Error(err)
-		return
-	} else if err := json.Unmarshal(statBytes, stats); err != nil {
-		log.Error(err)
-		return
-	}
-}
-
-func writeStats(stats * TestRun) () {
-	// Check if the  stats file exists
-	// The file is there, read it an unmarshal it into the stats struct
-	if statBytes, err := json.MarshalIndent(stats, "","    "); err != nil {
-		log.Error(err)
-		return
-	} else if err := ioutil.WriteFile("stats.json.new", statBytes, 0644); err != nil {
-		log.Error(err)
-		return
-	}
-	os.Rename("stats.json", "stats.json~")
-	os.Rename("stats.json.new", "stats.json")
-}
-var stats TestRun
-
 func main() {
 	var err error
 
 	// Setup logging
-	if _, err = log.SetDefaultLogger(log.JSON, 0, nil); err != nil {
+	if _, err = log.SetDefaultLogger(log.JSON, 1, nil); err != nil {
 		log.With(log.Fields{"error": err}).Fatal("Cannot setup logging")
 	}
 	defer log.CleanUp()
 
-	readStats(&stats)
+	if len(os.Args) < 2 {
+		log.Fatalf("Stat file name parameter missing for %s. Aborting...", os.Args[0])
+	} else {
+		statFn = os.Args[1]
+	}
 
+	if stats,err = readStats(statFn); err != nil {
+		log.Error(err)
+		return
+	}
+	defer writeStats(statFn, stats)
 
-	grpclog.SetLogger(slog.New(os.Stderr, "grpc: ", slog.LstdFlags))
+	// Add a stat entry for this run
 
-	resFile = &tstLog{fn:os.Args[1]}
-	defer resFile.close()
+	stats.appendNew()
+	tsIdx :=  len(stats.TestSuites) - 1
+	stats.TestSuites[tsIdx].Name = os.Args[0]
 
 
 	// Initialize the servers
@@ -186,7 +104,8 @@
 
 	// Run all the test cases now
 	log.Infof("Executing tests")
+
+	//log.Infof("Stats struct: %v", stats)
 	runTests()
-	writeStats(&stats)
 
 }
diff --git a/tests/afrouter/templates/runAll.go b/tests/afrouter/templates/runAll.go
index 03cdab1..5b02376 100644
--- a/tests/afrouter/templates/runAll.go
+++ b/tests/afrouter/templates/runAll.go
@@ -28,44 +28,6 @@
 	"github.com/opencord/voltha-go/common/log"
 )
 
-type tstLog struct {
-	fp * os.File
-	fn string
-}
-
-func (tr * tstLog) testLog(format string, a ...interface{}) {
-	var err error
-	if tr.fp == nil {
-		if tr.fp, err = os.OpenFile(tr.fn, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil {
-			log.Errorf("Could not append to the results file")
-			tr.fp = nil
-		}
-	}
-	if tr.fp != nil {
-		tr.fp.Write([]byte(fmt.Sprintf(format, a...)))
-	}
-}
-
-func (tr * tstLog) testLogOnce(format string, a ...interface{}) {
-	var err error
-	if tr.fp == nil {
-		if tr.fp, err = os.OpenFile(tr.fn, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil {
-			log.Errorf("Could not append to the results file")
-			tr.fp = nil
-		}
-	}
-	if tr.fp != nil {
-		tr.fp.Write([]byte(fmt.Sprintf(format, a...)))
-	}
-	tr.fp.Close()
-	tr.fp = nil
-}
-
-func (tr * tstLog) close() {
-	if tr.fp != nil {
-		tr.fp.Close()
-	}
-}
 
 func main() {
 	var cmd *exec.Cmd
@@ -77,17 +39,23 @@
 
 	defer log.CleanUp()
 
+	statFn = "stats.json"
+
 	log.Info("Running tests")
 	if err:= os.Chdir(os.Args[1]); err != nil {
 		log.Error("Could not change directory to %s: %v", os.Args[1], err)
 	}
-	tl := &tstLog{fn:"results.txt"}
+
+	if err := initStats(statFn); err != nil {
+		log.Error(err)
+		return
+	}
+
 	{{range .}}
 	cmdStr =  "./"+"{{.}}"+".e"
-	tl.testLogOnce("Running test suite '%s'\n", cmdStr[2:])
 
 	log.Infof("Running test suite %s",cmdStr)
-	cmd = exec.Command(cmdStr, "results.txt")
+	cmd = exec.Command(cmdStr, statFn)
 	cmd.Stdin = os.Stdin
 	cmd.Stdout = os.Stdout
 	cmd.Stderr = os.Stderr
@@ -96,10 +64,36 @@
 	}
 	{{end}}
 	// Open the results file and output it.
-	if resFile, err := ioutil.ReadFile("results.txt"); err == nil {
+	if s,err := readStats(statFn); err != nil {
+		log.Error(err)
+		return
+	} else {
+		stats = s
+	}
+
+	//log.Infof("Stats are: %v", stats)
+	if resFile, err := ioutil.ReadFile(statFn); err == nil {
 		fmt.Println(string(resFile))
 	} else {
-		log.Error("Could not load the results file 'results.txt'")
+		log.Error("Could not load the stats file 'stats.json'")
+	}
+	fmt.Println("Test result summary")
+	for _,v := range stats.TestSuites {
+		fmt.Printf("Test suite: %s\n", v.Name[2:len(v.Name)-2])
+		pass := 0
+		fail := 0
+		total := 0
+		for _,v1 := range v.TestCases {
+			total++
+			if v1.Result == true {
+				pass++
+			} else {
+				fail++
+			}
+		}
+		fmt.Printf("\tTotal test cases: %d\n", total)
+		fmt.Printf("\t\tTotal passed test cases: %d\n", pass)
+		fmt.Printf("\t\tTotal failed test cases: %d\n", fail)
 	}
 	log.Info("Tests complete")
 }
diff --git a/tests/afrouter/templates/runTests.go b/tests/afrouter/templates/runTests.go
index 61ba5eb..ac58220 100644
--- a/tests/afrouter/templates/runTests.go
+++ b/tests/afrouter/templates/runTests.go
@@ -18,6 +18,7 @@
 package main
 
 import (
+{{if .HasFuncs}}
 	"fmt"
 	"time"
 	"errors"
@@ -26,14 +27,22 @@
 	//"golang.org/x/net/context"
 	"google.golang.org/grpc/metadata"
 	"github.com/opencord/voltha-go/common/log"
+{{end}}
 	{{range .Imports}}
-	_ "{{.}}"
+	{{if .Used}}
+	"{{.Package}}"
+	{{end}}
 	{{end}}
 	{{range .ProtoImports}}
+	{{if .Used}}
 	{{.Short}} "{{.Package}}"
 	{{end}}
+	{{end}}
 )
 
+
+{{if .FileNum}}
+{{else}}
 var glCtx context.Context
 
 func resetChannels() {
@@ -54,70 +63,148 @@
 	}
 }
 
-func runTests() {
-	{{range $k,$v := .Tests}}
-	if err := test{{$k}}(); err == nil {
-		resFile.testLog("\tTest Successful\n")
-	} else {
-		resFile.testLog("\tTest Failed\n")
-	}
-	//resetChannels()
-	{{end}}
+type testData struct {
+	function func(int, string, string, []string,[]string,[]string,
+				  map[string][]string,interface{}, interface{}) error
+	testNum int
+	testName string
+	sendClient string
+	srvrs []string
+	sendMeta []string
+	expectMeta []string // Send Meta
+	srvMeta map[string][]string
+	parm interface{}
+	ret interface{}
 }
 
-{{range $k,$v := .Tests}}
-func test{{$k}}() error {
+func addTestSlot(stats * TestRun) {
+	tsIdx := len(stats.TestSuites) - 1
+	stats.TestSuites[tsIdx].TestCases =
+			append(stats.TestSuites[tsIdx].TestCases, TestCase{Info:[]string{}})
+}
+{{end}}
+
+{{if .FileNum}}
+func runTests{{.FileNum}}() {
+{{else}}
+func runTests() {
+{{end}}
+	tsIdx := len(stats.TestSuites) - 1
+	tests := []testData {
+	{{$ofs := .Offset}}
+	{{range $k,$v := .Tests}}
+	testData {
+		{{$v.Send.Method}}_test,
+		{{$k}} + {{$ofs}},
+		"{{$v.Name}}",
+		"{{$v.Send.Client}}",
+		[]string{ {{range $sk,$sv := $v.Srvr}} "{{$sv.Name}}",{{end}} },
+		[]string{ {{range $mk,$mv := $v.Send.MetaData}}"{{$mv.Key}}","{{$mv.Val}}",{{end}} },
+		[]string{ {{range $mk,$mv := $v.Send.ExpectMeta}}"{{$mv.Key}}","{{$mv.Val}}",{{end}} },
+		map[string][]string {
+		{{range $sk,$sv := $v.Srvr}}
+			"{{$sv.Name}}":[]string {
+			{{range $mk, $mv := $sv.Meta}}
+				 "{{$mv.Key}}","{{$mv.Val}}",
+			{{end}}
+			},
+		{{end}}
+		},
+		&{{$v.Send.ParamType}}{{$v.Send.Param}},
+		&{{$v.Send.ExpectType}}{{$v.Send.Expect}},
+	},
+	{{end}}
+	}
+
+	for _,v := range tests {
+		addTestSlot(stats)
+		stats.TestSuites[tsIdx].TestCases[v.testNum].Title = v.testName
+		if err := v.function(
+			v.testNum,
+			v.testName,
+			v.sendClient,
+			v.srvrs,
+			v.sendMeta,
+			v.expectMeta,
+			v.srvMeta,
+			v.parm,
+			v.ret); err != nil {
+			stats.TestSuites[tsIdx].TestCases[v.testNum].Result = false
+		} else {
+			stats.TestSuites[tsIdx].TestCases[v.testNum].Result = true
+		}
+	}
+	{{if .FileNum}}
+	{{else}}
+	{{range $k,$v := .RunTestsCallList}}
+	{{$v}}()
+	{{end}}
+	{{end}}
+	return
+	//resetChannels()
+}
+
+{{range $k,$v := .Funcs }}
+{{if $v.CodeGenerated}}
+{{else}}
+func {{$k}}_test(testNum int, testName string, sendClient string, srvrs []string,
+				 sendMeta []string, expectMeta []string, srvrMeta map[string][]string,
+				 parm interface{}, ret interface{}) error {
+
 	var rtrn error = nil
 	var cancel context.CancelFunc
+	var repl *reply
 
+	log.Debug("Running Test %d",testNum)
 	glCtx, cancel = context.WithTimeout(context.Background(), 900*time.Millisecond)
 	defer cancel()
-	// Announce the test being run
-	resFile.testLog("******************** Running test case ({{$k}}): {{$v.Name}}\n")
-	// Acquire the client used to run the test
-	cl := clients["{{$v.Send.Client}}"]
+
+	cl := clients[sendClient]
 	// Create the server's reply data structure
-	repl := &reply{repl:&{{$v.Send.ExpectType}}{{$v.Send.Expect}}}
-	// Send the reply data structure to each of the servers
-	{{range $s := .Srvr}}
-	if servers["{{$s.Name}}"] == nil {
-		err := errors.New("Server '{{$s.Name}}' is nil")
-		log.Error(err)
-		return err
+	switch r := ret.(type) {
+	case *{{$v.ReturnType}}:
+		repl = &reply{repl:r}
+	default:
+		log.Errorf("Invalid type in call to {{$k}}_test expecting {{$v.ReturnType}} got %T", ret)
 	}
-	// Start a go routine to send the the reply data to the
-	// server. The go routine blocks until the server picks
-	// up the data or the timeout is exceeded.
-	go func (ctx context.Context) {
-		select {
-		case servers["{{$s.Name}}"].replyData <- repl:
-		case <-ctx.Done():
-			rtrn := errors.New("Could not provide server {{$s.Name}} with reply data")
-			log.Error(rtrn)
-			resFile.testLog("%s\n", rtrn.Error())
+	// Send the reply data structure to each of the servers
+	for _,v := range srvrs {
+		if servers[v] == nil {
+			err := errors.New(fmt.Sprintf("Server %s is nil", v))
+			log.Error(err)
+			return err
 		}
-	}(glCtx)
-	{{end}}
+		// Start a go routine to send the the reply data to the
+		// server. The go routine blocks until the server picks
+		// up the data or the timeout is exceeded.
+		go func (ctx context.Context, srv string) {
+			select {
+			case servers[srv].replyData <- repl:
+			case <-ctx.Done():
+				rtrn := errors.New(fmt.Sprintf("Could not provide server %s with reply data",srv))
+				log.Error(rtrn)
+				stats.testLog("%s\n", rtrn.Error())
+			}
+		}(glCtx,v)
+	}
 
 	// Now call the RPC with the data provided
 	if expct,err := json.Marshal(repl.repl); err != nil {
-		log.Errorf("Marshaling the reply for test {{$v.Name}}: %v",err)
+		log.Errorf("Marshaling the reply for test %s: %v",testName, err)
 	} else {
 		// Create the context for the call
 		ctx := context.Background()
-		{{range $m := $v.Send.MetaData}}
-		ctx = metadata.AppendToOutgoingContext(ctx, "{{$m.Key}}", "{{$m.Val}}")
-		{{end}}
+		for i:=0; i<len(sendMeta); i += 2 {
+			ctx = metadata.AppendToOutgoingContext(ctx, sendMeta[i], sendMeta[i+1])
+		}
 		var md map[string]string = make(map[string]string)
-		{{range $m := $v.Send.ExpectMeta}}
-			md["{{$m.Key}}"] = "{{$m.Val}}"
-		{{end}}
+		for i:=0; i<len(expectMeta); i+=2 {
+			md[expectMeta[i]] = expectMeta[i+1]
+		}
 		expectMd := metadata.New(md)
-		if err := cl.send("{{$v.Send.Method}}", ctx,
-							&{{$v.Send.ParamType}}{{$v.Send.Param}},
-							string(expct), expectMd); err != nil {
-			log.Errorf("Test case {{$v.Name}} failed!: %v", err)
-
+		if err := cl.send("{{$k}}", ctx, parm, string(expct), expectMd); err != nil {
+			log.Errorf("Test case %s failed!: %v", testName, err)
+			rtrn = err
 		}
 	}
 
@@ -125,39 +212,38 @@
 	var s *serverCtl
 	var payload string
 	var i *incoming
-	if pld, err := json.Marshal(&{{$v.Send.ParamType}}{{$v.Send.Param}}); err != nil {
-		log.Errorf("Marshaling paramter for test {{$v.Name}}: %v", err)
+	if pld, err := json.Marshal(parm); err != nil {
+		log.Errorf("Marshaling paramter for test %s: %v", testName, err)
 	} else {
 		payload = string(pld)
 	}
-	{{range $s := .Srvr}}
-	s = servers["{{$s.Name}}"]
-	// Oddly sometimes the data isn't in the channel yet when we come to read it.
-	select {
-	case i = <-s.incmg:
-		if i.payload != payload {
-			rtrn = errors.New(fmt.Sprintf("Mismatched payload expected '%s', got '%s'", payload, i.payload))
-			log.Error(rtrn.Error())
-			resFile.testLog("%s\n", rtrn.Error())
-		}
-		{{range $m := $s.Meta}}
-		if mv,ok := i.meta["{{$m.Key}}"]; ok == true {
-			if "{{$m.Val}}" != mv[0] {
-				rtrn=errors.New(fmt.Sprintf("Mismatched metadata on server '%s' expected '%s', got '%s'", "{{$s.Name}}", "{{$m.Val}}", mv[0]))
+	for _,v := range srvrs {
+		s = servers[v]
+		// Oddly sometimes the data isn't in the channel yet when we come to read it.
+		select {
+		case i = <-s.incmg:
+			if i.payload != payload {
+				rtrn = errors.New(fmt.Sprintf("Mismatched payload expected '%s', got '%s'", payload, i.payload))
 				log.Error(rtrn.Error())
-				resFile.testLog("%s\n", rtrn.Error())
+				stats.testLog("%s\n", rtrn.Error())
 			}
+			for j:=0; j<len(srvrMeta[v]); j+=2 {
+				if mv,ok := i.meta[srvrMeta[v][j]]; ok == true {
+					if srvrMeta[v][j+1] != mv[0] {
+						rtrn=errors.New(fmt.Sprintf("Mismatched metadata on server '%s' expected '%s', got '%s'", srvrMeta[v][j], srvrMeta[v][j+1], mv[0]))
+						log.Error(rtrn.Error())
+						stats.testLog("%s\n", rtrn.Error())
+					}
+				}
+			}
+		case <-glCtx.Done():
+			rtrn = errors.New(fmt.Sprintf("Timeout: no response data available for server %s", testName))
+			stats.testLog("%s\n", rtrn.Error())
+			log.Error(rtrn)
 		}
-		{{end}}
-	case <-glCtx.Done():
-		rtrn = errors.New("Timeout: no response data available for server {{$s.Name}}")
-		resFile.testLog("%s\n", rtrn.Error())
-		log.Error(rtrn)
 	}
-	{{end}}
 
 	return rtrn
 }
 {{end}}
-
-
+{{end}}
diff --git a/tests/afrouter/templates/server.go b/tests/afrouter/templates/server.go
index ffea3d5..0f9ed48 100644
--- a/tests/afrouter/templates/server.go
+++ b/tests/afrouter/templates/server.go
@@ -123,7 +123,7 @@
 {{else}}
 func  (ts {{$.Name}}TestServer) {{.Name}}(ctx context.Context, in *{{.Param}}) (*{{.Rtrn}}, error) {
 	var r * incoming = &incoming{}
-	log.Debug("Serving {{$.Name}}")
+	//log.Debug("Serving {{$.Name}}")
 	// Read the metadata
 	if md,ok := metadata.FromIncomingContext(ctx); ok == false {
 		log.Error("Getting matadata during call to {{.Name}}")
diff --git a/tests/afrouter/templates/stats.go b/tests/afrouter/templates/stats.go
new file mode 100644
index 0000000..958bea7
--- /dev/null
+++ b/tests/afrouter/templates/stats.go
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+
+ * 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.
+ */
+// The template for the tester.
+// This template is filled in by the
+// test driver based on the configuration.
+
+package main
+
+import (
+	"os"
+	"fmt"
+	//slog "log"
+	"io/ioutil"
+	"encoding/json"
+	//"google.golang.org/grpc/grpclog"
+	"github.com/opencord/voltha-go/common/log"
+)
+
+type TestCase struct {
+	Title string `json:"title"`
+	Result bool `json:"passed"`
+	Info []string `json:"info"`
+}
+
+type TestSuite struct {
+	Name string `json:"name"`
+	Info []string `json:"info"`
+	TestCases []TestCase `json:"testCases"`
+}
+
+type TestRun struct {
+	TestSuites []TestSuite
+}
+
+func (tr * TestRun) testLog(format string, a ...interface{}) {
+
+	tridx := len(tr.TestSuites) - 1
+	tcidx := len(tr.TestSuites[tridx].TestCases) - 1
+
+	tr.TestSuites[tridx].TestCases[tcidx].Info =
+			append(tr.TestSuites[tridx].TestCases[tcidx].Info, fmt.Sprintf(format, a...))
+
+}
+
+func (tr * TestRun) suiteLog(format string, a ...interface{}) {
+
+	tridx := len(tr.TestSuites) - 1
+
+	tr.TestSuites[tridx].Info =
+			append(tr.TestSuites[tridx].Info, fmt.Sprintf(format, a...))
+
+}
+
+func readStats(statFn string) (*TestRun, error) {
+	// Check if the  stats file exists
+	if _,err := os.Stat(statFn); err != nil {
+		// Nothing to do, just return
+		return &TestRun{}, nil
+	}
+	rtrn := &TestRun{}
+	// The file is there, read it an unmarshal it into the stats struct
+	if statBytes, err := ioutil.ReadFile(statFn); err != nil {
+		log.Error(err)
+		return nil, err
+	} else if err := json.Unmarshal(statBytes, rtrn); err != nil {
+		log.Error(err)
+		return nil, err
+	}
+	return rtrn, nil
+}
+
+func writeStats(statFn string, stats * TestRun) error {
+	// Check if the  stats file exists
+	// The file is there, read it an unmarshal it into the stats struct
+	if statBytes, err := json.MarshalIndent(stats, "","    "); err != nil {
+		log.Error(err)
+		return err
+	} else if err := ioutil.WriteFile(statFn+".new", statBytes, 0644); err != nil {
+		log.Error(err)
+		return err
+	}
+	if err := os.Rename(statFn, statFn+"~"); err != nil {
+		log.Error(err)
+		return err
+	}
+	if err := os.Rename(statFn+".new", statFn); err != nil {
+		log.Error(err)
+		return err
+	}
+	return nil
+}
+
+func (tr * TestRun) appendNew() {
+	tr.TestSuites = append(tr.TestSuites, TestSuite{})
+}
+
+func initStats(statFn string) error {
+	s := &TestRun{}
+
+	if statBytes, err := json.MarshalIndent(s, "","    "); err != nil {
+		log.Error(err)
+		return err
+	} else if err := ioutil.WriteFile(statFn, statBytes, 0644); err != nil {
+		log.Error(err)
+		return err
+	}
+
+	return nil
+}
+
+
+var statFn string
+var stats *TestRun