From cd960e414fc4a42aaa4c92b4b4e27f7d605804d1 Mon Sep 17 00:00:00 2001
From: Fabian Seidl <fabian.b.seidl@stud.h-da.de>
Date: Thu, 9 Jun 2022 12:37:10 +0000
Subject: [PATCH] Resolve "Running the test suite creates plugins which prevent
 running the test suite again"

See merge request danet/gosdn!330

Co-authored-by: Andre Sterba <andre.sterba@stud.h-da.de>
---
 controller/nucleus/initialise_test.go         | 43 +++++++++++++++++++
 .../nucleus/principalNetworkDomain_test.go    |  2 +
 2 files changed, 45 insertions(+)

diff --git a/controller/nucleus/initialise_test.go b/controller/nucleus/initialise_test.go
index cf17d49d6..ed1d2b16c 100644
--- a/controller/nucleus/initialise_test.go
+++ b/controller/nucleus/initialise_test.go
@@ -2,8 +2,12 @@ package nucleus
 
 import (
 	"context"
+	"io/fs"
+	"io/ioutil"
 	"os"
+	"path/filepath"
 	"testing"
+	"time"
 
 	"code.fbi.h-da.de/danet/gosdn/controller/interfaces/device"
 	"code.fbi.h-da.de/danet/gosdn/controller/store"
@@ -166,3 +170,42 @@ func newPnd() pndImplementation {
 		Id:                defaultPndID,
 	}
 }
+
+// removeTestPlugins removes the plugins created during running the test in the current directory based on their name consisting of a uuid
+// and the time since they`ve been created
+func removeTestPlugins() {
+	currentDirectory := "./"
+	// pattern to match plugin uuid used as dir name
+	pattern := "*-*-*-*-*"
+	// max time passed since creation in seconds
+	var seconds int64 = 10
+
+	// get all available files
+	dirs, err := ioutil.ReadDir(currentDirectory)
+	if err != nil {
+		log.Info(err)
+	}
+
+	for _, dir := range dirs {
+		if !dir.IsDir() {
+			continue
+		} else if found, _ := filepath.Match(pattern, dir.Name()); found && isDirYoungerThanSeconds(dir.Name(), seconds) {
+			log.Infof("removing: %v", dir.Name())
+			err = os.RemoveAll(dir.Name())
+			if err != nil {
+				log.Info(err)
+			}
+		}
+	}
+}
+
+// isDirYoungerThanSeconds returns true if the provided dir is younger than the given amount in seconds
+// and therefore was created as part of the test suite
+func isDirYoungerThanSeconds(dirName string, seconds int64) bool {
+	fileInfo, err := os.Stat(dirName)
+	if err != nil {
+		log.Info(err)
+	}
+
+	return fs.FileInfo.ModTime(fileInfo).Unix() > (time.Now().Unix() - seconds)
+}
diff --git a/controller/nucleus/principalNetworkDomain_test.go b/controller/nucleus/principalNetworkDomain_test.go
index 62da66887..907e027ab 100644
--- a/controller/nucleus/principalNetworkDomain_test.go
+++ b/controller/nucleus/principalNetworkDomain_test.go
@@ -1095,6 +1095,8 @@ func Test_pndImplementation_ConfirmedChanges(t *testing.T) {
 }
 
 func Test_pndImplementation_saveGoStructsToFile(t *testing.T) {
+	defer removeTestPlugins()
+
 	type genericGoStructClientArg struct {
 		fn    string
 		rtrn  []interface{}
-- 
GitLab