1
0
Fork 0
mirror of https://github.com/postmannen/ctrl.git synced 2024-12-15 17:51:15 +00:00

moved hello test to request testing

This commit is contained in:
postmannen 2022-05-23 12:57:07 +02:00
parent 444c04ac3b
commit e6006b44d3
3 changed files with 51 additions and 135 deletions

View file

@ -123,7 +123,7 @@ func (s *server) readStartupFolder() {
func (s *server) getFilePaths(dirName string) ([]string, error) { func (s *server) getFilePaths(dirName string) ([]string, error) {
dirPath, err := os.Executable() dirPath, err := os.Executable()
dirPath = filepath.Dir(dirPath) dirPath = filepath.Dir(dirPath)
fmt.Printf(" * DEBUG: %v\n", dirPath) fmt.Printf(" * DEBUG: dirPath=%v\n", dirPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("error: startup folder: unable to get the working directory %v: %v", dirPath, err) return nil, fmt.Errorf("error: startup folder: unable to get the working directory %v: %v", dirPath, err)
} }

View file

@ -3,6 +3,8 @@ package steward
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"io"
"log"
"net" "net"
"net/http" "net/http"
"path/filepath" "path/filepath"
@ -12,10 +14,10 @@ import (
natsserver "github.com/nats-io/nats-server/v2/server" natsserver "github.com/nats-io/nats-server/v2/server"
) )
func newServerForTesting(t *testing.T, addressAndPort string) (*server, *Configuration) { func newServerForTesting(t *testing.T, addressAndPort string, testFolder string) (*server, *Configuration) {
//if !*logging { if !*logging {
// log.SetOutput(io.Discard) log.SetOutput(io.Discard)
//} }
// Start Steward instance // Start Steward instance
// --------------------------------------- // ---------------------------------------
@ -27,11 +29,11 @@ func newServerForTesting(t *testing.T, addressAndPort string) (*server, *Configu
conf.BrokerAddress = addressAndPort conf.BrokerAddress = addressAndPort
conf.NodeName = "central" conf.NodeName = "central"
conf.CentralNodeName = "central" conf.CentralNodeName = "central"
conf.ConfigFolder = "tmp" conf.ConfigFolder = testFolder
conf.SubscribersDataFolder = "tmp" conf.SubscribersDataFolder = testFolder
conf.SocketFolder = "tmp" conf.SocketFolder = testFolder
conf.SubscribersDataFolder = "tmp" conf.SubscribersDataFolder = testFolder
conf.DatabaseFolder = "tmp" conf.DatabaseFolder = testFolder
conf.StartSubREQErrorLog = true conf.StartSubREQErrorLog = true
stewardServer, err := NewServer(&conf, "test") stewardServer, err := NewServer(&conf, "test")
@ -106,7 +108,8 @@ func TestRequest(t *testing.T) {
} }
defer ns.Shutdown() defer ns.Shutdown()
srv, conf := newServerForTesting(t, "127.0.0.1:42222") tempdir := t.TempDir()
srv, conf := newServerForTesting(t, "127.0.0.1:42222", tempdir)
srv.Start() srv.Start()
defer srv.Stop() defer srv.Stop()
@ -123,6 +126,21 @@ func TestRequest(t *testing.T) {
} }
tests := []test{ tests := []test{
{
info: "REQHello test",
message: Message{
ToNode: "central",
FromNode: "central",
Method: REQHello,
MethodArgs: []string{},
MethodTimeout: 5,
// ReplyMethod: REQTest,
Directory: "test",
FileName: "hello.results",
}, want: []byte("Received hello from \"central\""),
containsOrEquals: fileContains,
viaSocketOrCh: viaCh,
},
{ {
info: "REQCliCommand test, echo gris", info: "REQCliCommand test, echo gris",
message: Message{ message: Message{
@ -207,6 +225,7 @@ func TestRequest(t *testing.T) {
}, },
} }
// Range over the tests defined, and execute them, one at a time.
for _, tt := range tests { for _, tt := range tests {
switch tt.viaSocketOrCh { switch tt.viaSocketOrCh {
case viaCh: case viaCh:
@ -249,8 +268,8 @@ func TestRequest(t *testing.T) {
case fileContains: case fileContains:
resultFile := filepath.Join(conf.SubscribersDataFolder, tt.message.Directory, string(tt.message.FromNode), tt.message.FileName) resultFile := filepath.Join(conf.SubscribersDataFolder, tt.message.Directory, string(tt.message.FromNode), tt.message.FileName)
_, err := findStringInFileTest(string(tt.want), resultFile, conf, t) found, err := findStringInFileTest(string(tt.want), resultFile, conf, t)
if err != nil { if err != nil || found == false {
t.Fatalf(" \U0001F631 [FAILED] : %v: %v\n", tt.info, err) t.Fatalf(" \U0001F631 [FAILED] : %v: %v\n", tt.info, err)
} }

View file

@ -33,30 +33,31 @@ func TestStewardServer(t *testing.T) {
// log.SetOutput(io.Discard) // log.SetOutput(io.Discard)
// } // }
t.Logf("--------------- 1\n")
ns := newNatsServerForTesting(t, 40222) ns := newNatsServerForTesting(t, 40222)
if err := natsserver.Run(ns); err != nil { if err := natsserver.Run(ns); err != nil {
natsserver.PrintAndDie(err.Error()) natsserver.PrintAndDie(err.Error())
} }
defer ns.Shutdown() defer ns.Shutdown()
srv, conf := newServerForTesting(t, "127.0.0.1:40222") t.Logf("--------------- 2\n")
tempDir := t.TempDir()
srv, conf := newServerForTesting(t, "127.0.0.1:40222", tempDir)
srv.Start() srv.Start()
defer srv.Stop() defer srv.Stop()
t.Logf("--------------- 3\n")
// Run the message tests // Run the message tests
// //
// --------------------------------------- // ---------------------------------------
type testFunc func(*server, *Configuration, *testing.T) error type testFunc func(*server, *Configuration, *testing.T, string) error
// Specify all the test funcs to run in the slice. // Specify all the test funcs to run in the slice.
funcs := []testFunc{ funcs := []testFunc{
checkREQCliCommandTest,
checkREQCliCommandContTest,
// checkREQToConsoleTest(conf, t), NB: No tests will be made for console ouput.
// checkREQToFileAppendTest(conf, t), NB: Already tested via others
// checkREQToFileTest(conf, t), NB: Already tested via others
checkREQHelloTest,
checkREQErrorLogTest, checkREQErrorLogTest,
checkREQTailFileTest, checkREQTailFileTest,
checkErrorKernelMalformedJSONtest, checkErrorKernelMalformedJSONtest,
@ -64,7 +65,7 @@ func TestStewardServer(t *testing.T) {
} }
for _, f := range funcs { for _, f := range funcs {
err := f(srv, conf, t) err := f(srv, conf, t, tempDir)
if err != nil { if err != nil {
t.Errorf("%v\n", err) t.Errorf("%v\n", err)
} }
@ -76,88 +77,8 @@ func TestStewardServer(t *testing.T) {
// Check REQ types // Check REQ types
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Sending of CLI Commands.
func checkREQCliCommandTest(stewardServer *server, conf *Configuration, t *testing.T) error {
m := `[
{
"directory":"commands-executed",
"fileName":"fileName.result",
"toNode": "central",
"methodArgs": ["bash","-c","echo apekatt"],
"replyMethod":"REQToFileAppend",
"method":"REQCliCommand",
"ACKTimeout":3,
"retries":3,
"methodTimeout": 10
}
]`
writeToSocketTest(conf, m, t)
resultFile := filepath.Join(conf.SubscribersDataFolder, "commands-executed", "central", "fileName.result")
_, err := findStringInFileTest("apekatt", resultFile, conf, t)
if err != nil {
return fmt.Errorf(" \U0001F631 [FAILED] : checkREQCliCommandTest: %v", err)
}
t.Logf(" \U0001f600 [SUCCESS] : checkREQCliCommandTest\n")
return nil
}
// The continous non-sequential sending of CLI Commands.
func checkREQCliCommandContTest(stewardServer *server, conf *Configuration, t *testing.T) error {
m := `[
{
"directory":"commands-executed",
"fileName":"fileName.result",
"toNode": "central",
"methodArgs": ["bash","-c","echo apekatt && sleep 5 && echo gris"],
"replyMethod":"REQToFileAppend",
"method":"REQCliCommandCont",
"ACKTimeout":3,
"retries":3,
"methodTimeout": 5
}
]`
writeToSocketTest(conf, m, t)
resultFile := filepath.Join(conf.SubscribersDataFolder, "commands-executed", "central", "fileName.result")
_, err := findStringInFileTest("apekatt", resultFile, conf, t)
if err != nil {
return fmt.Errorf(" \U0001F631 [FAILED] : checkREQCliCommandContTest: %v", err)
}
t.Logf(" \U0001f600 [SUCCESS] : checkREQCliCommandContTest\n")
return nil
}
// Sending of Hello.
func checkREQHelloTest(stewardServer *server, conf *Configuration, t *testing.T) error {
m := `[
{
"directory":"commands-executed",
"fileName":"fileName.result",
"toNode": "central",
"data": [],
"method":"REQHello"
}
]`
writeToSocketTest(conf, m, t)
resultFile := filepath.Join(conf.SubscribersDataFolder, "commands-executed", "central", "fileName.result")
_, err := findStringInFileTest("Received hello from", resultFile, conf, t)
if err != nil {
return fmt.Errorf(" \U0001F631 [FAILED] : checkREQHelloTest: %v", err)
}
t.Logf(" \U0001f600 [SUCCESS] : checkREQHelloTest\n")
return nil
}
// Check the error logger type. // Check the error logger type.
func checkREQErrorLogTest(stewardServer *server, conf *Configuration, t *testing.T) error { func checkREQErrorLogTest(stewardServer *server, conf *Configuration, t *testing.T, tempDir string) error {
m := Message{ m := Message{
ToNode: "somenode", ToNode: "somenode",
} }
@ -177,9 +98,10 @@ func checkREQErrorLogTest(stewardServer *server, conf *Configuration, t *testing
} }
// Check the tailing of files type. // Check the tailing of files type.
func checkREQTailFileTest(stewardServer *server, conf *Configuration, t *testing.T) error { func checkREQTailFileTest(stewardServer *server, conf *Configuration, t *testing.T, tmpDir string) error {
// Create a file with some content. // Create a file with some content.
fh, err := os.OpenFile("tmp/test.file", os.O_APPEND|os.O_RDWR|os.O_CREATE|os.O_SYNC, 0600) fp := filepath.Join(tmpDir, "test.file")
fh, err := os.OpenFile(fp, os.O_APPEND|os.O_RDWR|os.O_CREATE|os.O_SYNC, 0600)
if err != nil { if err != nil {
return fmt.Errorf(" * failed: unable to open temporary file: %v", err) return fmt.Errorf(" * failed: unable to open temporary file: %v", err)
} }
@ -208,20 +130,12 @@ func checkREQTailFileTest(stewardServer *server, conf *Configuration, t *testing
} }
}() }()
wd, err := os.Getwd()
if err != nil {
cancel()
return fmt.Errorf(" \U0001F631 [FAILED] : checkREQTailFileTest: : getting current working directory: %v", err)
}
file := filepath.Join(wd, "tmp/test.file")
s := `[ s := `[
{ {
"directory": "tail-files", "directory": "tail-files",
"fileName": "fileName.result", "fileName": "fileName.result",
"toNode": "central", "toNode": "central",
"methodArgs": ["` + file + `"], "methodArgs": ["` + fp + `"],
"method":"REQTailFile", "method":"REQTailFile",
"ACKTimeout":5, "ACKTimeout":5,
"retries":3, "retries":3,
@ -266,7 +180,7 @@ func checkREQTailFileTest(stewardServer *server, conf *Configuration, t *testing
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Check errorKernel // Check errorKernel
func checkErrorKernelMalformedJSONtest(stewardServer *server, conf *Configuration, t *testing.T) error { func checkErrorKernelMalformedJSONtest(stewardServer *server, conf *Configuration, t *testing.T, tempDir string) error {
// JSON message with error, missing brace. // JSON message with error, missing brace.
m := `[ m := `[
@ -328,7 +242,7 @@ func checkErrorKernelMalformedJSONtest(stewardServer *server, conf *Configuratio
} }
} }
func checkMetricValuesTest(stewardServer *server, conf *Configuration, t *testing.T) error { func checkMetricValuesTest(stewardServer *server, conf *Configuration, t *testing.T, tempDir string) error {
mfs, err := stewardServer.metrics.promRegistry.Gather() mfs, err := stewardServer.metrics.promRegistry.Gather()
if err != nil { if err != nil {
return fmt.Errorf("error: promRegistry.gathering: %v", mfs) return fmt.Errorf("error: promRegistry.gathering: %v", mfs)
@ -426,7 +340,8 @@ func findStringInFileTest(want string, fileName string, conf *Configuration, t *
return false, fmt.Errorf(" * failed: could not read result file: %v", err) return false, fmt.Errorf(" * failed: could not read result file: %v", err)
} }
if !strings.Contains(string(result), want) { found := strings.Contains(string(result), want)
if !found {
return false, nil return false, nil
} }
@ -447,21 +362,3 @@ func writeToSocketTest(conf *Configuration, messageText string, t *testing.T) {
} }
} }
// Start up the nats-server message broker.
func startNatsServerTest(t *testing.T) {
// Start up the nats-server message broker.
nsOpt := &natsserver.Options{
Host: "127.0.0.1",
Port: 40222,
}
ns, err := natsserver.NewServer(nsOpt)
if err != nil {
t.Fatalf(" * failed: could not start the nats-server %v\n", err)
}
if err := natsserver.Run(ns); err != nil {
natsserver.PrintAndDie(err.Error())
}
}