Skip to content

Commit

Permalink
website for our cnf (#1544)
Browse files Browse the repository at this point in the history
* website for our cnf

to run need to call  ./run-cnf-suites.sh -l lifecycle -s true
-s new filed mean if i want to run that from the website

* a few changes(add upload file) and added the -s for server

* change folder name

* Delete index.html

* added new function and rename names

* add new file for html function

* fix for saving the log to be in a bif and not in a file

* add bufer implemntation fir logs

* update the flag

* few changes for linter

* Update run-cnf-suites.sh

* udpate typos

* david comments

* update the flag

* website for our cnf

to run need to call  ./run-cnf-suites.sh -l lifecycle -s true
-s new filed mean if i want to run that from the website

* a few changes(add upload file) and added the -s for server

* change folder name

* Delete index.html

* added new function and rename names

* add new file for html function

* fix for saving the log to be in a bif and not in a file

* add bufer implemntation fir logs

* update the flag

* few changes for linter

* Update run-cnf-suites.sh

* udpate typos

* david comments

* update the flag
  • Loading branch information
aabughosh authored Nov 9, 2023
1 parent 78adf87 commit 3ed0838
Show file tree
Hide file tree
Showing 9 changed files with 646 additions and 25 deletions.
168 changes: 146 additions & 22 deletions cnf-certification-test/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,17 @@
package suite

import (
"bytes"
_ "embed"
"encoding/json"
"flag"
"fmt"
"io"
rlog "log"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand All @@ -45,6 +52,7 @@ import (
_ "github.com/test-network-function/cnf-certification-test/cnf-certification-test/performance"
_ "github.com/test-network-function/cnf-certification-test/cnf-certification-test/platform"
_ "github.com/test-network-function/cnf-certification-test/cnf-certification-test/preflight"
"github.com/test-network-function/cnf-certification-test/cnf-certification-test/webserver"
"github.com/test-network-function/cnf-certification-test/internal/clientsholder"
"github.com/test-network-function/cnf-certification-test/pkg/configuration"
"github.com/test-network-function/cnf-certification-test/pkg/diagnostics"
Expand All @@ -56,8 +64,10 @@ const (
defaultClaimPath = ".."
defaultCliArgValue = ""
junitFlagKey = "junit"
serverModeFlag = "serverMode"
TNFReportKey = "cnf-certification-test"
extraInfoKey = "testsExtraInfo"
defaultServerMode = false
)

var (
Expand All @@ -77,13 +87,15 @@ var (
// ClaimFormat is the current version for the claim file format to be produced by the TNF test suite.
// A client decoding this claim file must support decoding its specific version.
ClaimFormatVersion string
serverMode *bool
)

func init() {
claimPath = flag.String(claimPathFlagKey, defaultClaimPath,
"the path where the claimfile will be output")
junitPath = flag.String(junitFlagKey, defaultCliArgValue,
"the path for the junit format report")
serverMode = flag.Bool("serverMode", defaultServerMode, "run test with webserver")
}

// setLogLevel sets the log level for logrus based on the "TNF_LOG_LEVEL" environment variable
Expand Down Expand Up @@ -126,8 +138,7 @@ func getGitVersion() string {
return gitDisplayRelease + " ( " + GitCommit + " )"
}

// TestTest invokes the CNF Certification Test Suite.
func TestTest(t *testing.T) {
func PreRun(t *testing.T) (claimData *claim.Claim, claimRoot *claim.Root) {
// When running unit tests, skip the suite
if os.Getenv("UNIT_TEST") != "" {
t.Skip("Skipping test suite when running unit tests")
Expand All @@ -147,20 +158,13 @@ func TestTest(t *testing.T) {
log.Infof("Claim Format Version: %s", ClaimFormatVersion)
log.Infof("Ginkgo Version : %v", ginkgo.GINKGO_VERSION)
log.Infof("Labels filter : %v", ginkgoConfig.LabelFilter)

// Diagnostic functions will run when no labels are provided.
var diagnosticMode bool
if ginkgoConfig.LabelFilter == "" {
log.Infof("TNF will run in diagnostic mode so no test case will be launched.")
diagnosticMode = true
}

log.Infof("run test with webserver : %v", *serverMode)
// Set clientsholder singleton with the filenames from the env vars.
_ = clientsholder.GetClientsHolder(getK8sClientsConfigFileNames()...)

// Initialize the claim with the start time, tnf version, etc.
claimRoot := claimhelper.CreateClaimRoot()
claimData := claimRoot.Claim
claimRoot = claimhelper.CreateClaimRoot()
claimData = claimRoot.Claim
claimData.Configurations = make(map[string]interface{})
claimData.Nodes = make(map[string]interface{})
incorporateVersions(claimData)
Expand All @@ -170,21 +174,42 @@ func TestTest(t *testing.T) {
log.Errorf("Configuration node missing because of: %s", err)
t.FailNow()
}

claimData.Nodes = claimhelper.GenerateNodes()
claimhelper.UnmarshalConfigurations(configurations, claimData.Configurations)
return claimData, claimRoot
}

// TestTest invokes the CNF Certification Test Suite.
func TestTest(t *testing.T) {
ginkgoConfig, _ := ginkgo.GinkgoConfiguration()
if !*serverMode {
claimData, claimRoot := PreRun(t)
var diagnosticMode bool
// Diagnostic functions will run when no labels are provided.

if ginkgoConfig.LabelFilter == "" {
log.Infof("TNF will run in diagnostic mode so no test case will be launched.")
diagnosticMode = true
}

// initialize abort flag
testhelper.AbortTrigger = ""
// initialize abort flag
testhelper.AbortTrigger = ""

// Run tests specs only if not in diagnostic mode, otherwise all TSs would run.
var env provider.TestEnvironment
if !diagnosticMode {
env.SetNeedsRefresh()
env = provider.GetTestEnvironment()
ginkgo.RunSpecs(t, CnfCertificationTestSuiteName)
// Run tests specs only if not in diagnostic mode, otherwise all TSs would run.
var env provider.TestEnvironment
if !diagnosticMode {
env.SetNeedsRefresh()
env = provider.GetTestEnvironment()
ginkgo.RunSpecs(t, CnfCertificationTestSuiteName)
}
ContinueRun(diagnosticMode, &env, claimData, claimRoot)
} else {
go StartServer()
select {}
}
}

func ContinueRun(diagnosticMode bool, env *provider.TestEnvironment, claimData *claim.Claim, claimRoot *claim.Root) {
endTime := time.Now()
claimData.Metadata.EndTime = endTime.UTC().Format(claimhelper.DateTimeFormatDirective)

Expand All @@ -211,7 +236,7 @@ func TestTest(t *testing.T) {

// Send claim file to the collector if specified by env var
if configuration.GetTestParameters().EnableDataCollection {
err = collector.SendClaimFileToCollector(env.CollectorAppEndPoint, claimOutputFile, env.ExecutedBy, env.PartnerName, env.CollectorAppPassword)
err := collector.SendClaimFileToCollector(env.CollectorAppEndPoint, claimOutputFile, env.ExecutedBy, env.PartnerName, env.CollectorAppPassword)
if err != nil {
log.Errorf("Failed to send post request to the collector: %v", err)
}
Expand Down Expand Up @@ -264,3 +289,102 @@ func incorporateVersions(claimData *claim.Claim) {
ClaimFormat: ClaimFormatVersion,
}
}
func StartServer() {
server := &http.Server{
Addr: ":8084", // Server address
ReadTimeout: 10 * time.Second, // Maximum duration for reading the entire request
WriteTimeout: 10 * time.Second, // Maximum duration for writing the entire response
IdleTimeout: 120 * time.Second, // Maximum idle duration before closing the connection
}
webserver.HandlereqFunc()

http.HandleFunc("/runFunction", RunHandler)

fmt.Println("Server is running on :8084...")
if err := server.ListenAndServe(); err != nil {
panic(err)
}
}

// Define an HTTP handler that triggers Ginkgo tests
func RunHandler(w http.ResponseWriter, r *http.Request) {
webserver.Buf = bytes.NewBufferString("")
log.SetOutput(webserver.Buf)
rlog.SetOutput(webserver.Buf)

jsonData := r.FormValue("jsonData") // "jsonData" is the name of the JSON input field
log.Info(jsonData)
var data webserver.RequestedData
if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
fmt.Println("Error:", err)
}
var flattenedOptions []string
flattenedOptions = webserver.FlattenData(data.SelectedOptions, flattenedOptions)

// Get the file from the request
file, handler, err := r.FormFile("kubeConfigPath") // "fileInput" is the name of the file input field
if err != nil {
http.Error(w, "Unable to retrieve file from form", http.StatusBadRequest)
return
}
defer file.Close()

// Create a new file on the server to store the uploaded content
uploadedFile, err := os.Create(handler.Filename)
if err != nil {
http.Error(w, "Unable to create file for writing", http.StatusInternalServerError)
return
}
defer uploadedFile.Close()

// Copy the uploaded file's content to the new file
_, err = io.Copy(uploadedFile, file)
if err != nil {
http.Error(w, "Unable to copy file", http.StatusInternalServerError)
return
}

// Copy the uploaded file to the server file

os.Setenv("KUBECONFIG", handler.Filename)
log.Infof("KUBECONFIG : %v", handler.Filename)

log.Infof("Labels filter : %v", flattenedOptions)
t := testing.T{}
claimData, claimRoot := PreRun(&t)
var env provider.TestEnvironment
env.SetNeedsRefresh()
env = provider.GetTestEnvironment()

// fetch the current config
suiteConfig, reporterConfig := ginkgo.GinkgoConfiguration()
// adjust it
suiteConfig.SkipStrings = []string{"NEVER-RUN"}
reporterConfig.FullTrace = true
reporterConfig.JUnitReport = "cnf-certification-tests_junit.xml"
// pass it in to RunSpecs
suiteConfig.LabelFilter = strings.Join(flattenedOptions, "")
ginkgo.RunSpecs(&t, CnfCertificationTestSuiteName, suiteConfig, reporterConfig)

ContinueRun(false, &env, claimData, claimRoot)
// Return the result as JSON
response := struct {
Message string `json:"Message"`
}{
Message: fmt.Sprintf("Sucsses to run %s", strings.Join(flattenedOptions, "")),
}
// Serialize the response data to JSON
jsonResponse, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Set the Content-Type header to specify that the response is JSON
w.Header().Set("Content-Type", "application/json")
// Write the JSON response to the client
_, err = w.Write(jsonResponse)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
Loading

0 comments on commit 3ed0838

Please sign in to comment.