This commit is contained in:
admju 2024-09-10 13:05:48 +00:00
parent 13025746e6
commit 75b7b94a50
10 changed files with 277 additions and 37 deletions

17
src/helm/helm_test.go Normal file
View File

@ -0,0 +1,17 @@
package helm
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHelm(t *testing.T) {
cmd := HelmCommand{}
cmd.New()
assert.NotNilf(t, cmd.Exec, "TestHelm %s", "New")
cmd.Exec("pwd")
}

View File

@ -4,15 +4,11 @@ import (
"fmt" "fmt"
"strings" "strings"
"errors" "errors"
"os/exec"
"encoding/json" "encoding/json"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
) )
// type KubeContext struct {
// Bin string // Chemin vers le binaire
// }
type kubeConfig struct { type kubeConfig struct {
CurrentContext string `json:"current-context"` CurrentContext string `json:"current-context"`
@ -43,7 +39,7 @@ type kubeConfigClusters struct {
func (this KubectlCommand) GetCurrentContext() (string, error) { func (this KubectlCommand) GetCurrentContext() (string, error) {
bin := this.Bin bin := this.Bin
msg := fmt.Sprintf("%s get config current-context", bin) msg := fmt.Sprintf("%s config current-context", bin)
log.Log().Debug().Msg(msg) log.Log().Debug().Msg(msg)
cmd_args := strings.Split(msg, " ") cmd_args := strings.Split(msg, " ")
@ -56,8 +52,7 @@ func (this KubectlCommand) GetCurrentContext() (string, error) {
return res, err return res, err
} }
// Current Context // currentContext, currentNamespace, currentServer
// namespace, server
func (this KubectlCommand) GetContext() (string, string, string, error) { func (this KubectlCommand) GetContext() (string, string, string, error) {
bin := this.Bin bin := this.Bin
@ -101,9 +96,14 @@ func (this KubectlCommand) GetContext() (string, string, string, error) {
func (this KubectlCommand) UseContext(newContext string) (error) { func (this KubectlCommand) UseContext(newContext string) (error) {
cmd := exec.Command(this.Bin, "config", "use-context", newContext) bin := this.Bin
stdout, err := cmd.CombinedOutput()
msg := fmt.Sprintf("%s config use-context %s", bin, newContext)
log.Log().Debug().Msg(msg)
cmd_args := strings.Split(msg, " ")
cmd := this.Exec(cmd_args[0], cmd_args[1:]...)
stdout, err := cmd.CombinedOutput()
if err != nil { if err != nil {
log.Log().Debug().Msg(string(stdout)) log.Log().Debug().Msg(string(stdout))
return errors.New(string(stdout)) return errors.New(string(stdout))

View File

@ -0,0 +1,86 @@
package kubectl
import (
"os"
"path/filepath"
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
var MOCK_ENABLE = true
func TestKubectCurrentContext(t *testing.T) {
cmd := getCmdKubectl(MOCK_ENABLE, "minikube")
res, err := cmd.GetCurrentContext()
assert.Nilf(t, err, "error message %s", err)
assert.Equal(t, "minikube", res, "TestKubectCurrentContext error")
}
func TestKubectContext(t *testing.T) {
fileName := filepath.Join(TEST_SRC_DIR, "context.json")
cmd_json, _ := os.ReadFile(fileName)
cmd := getCmdKubectl(MOCK_ENABLE, string(cmd_json))
currentContext, currentNamespace, currentServer, err := cmd.GetContext()
assert.Nilf(t, err, "error message %s", err)
assert.Equal(t, "minikube", currentContext, "TestKubectContext error")
assert.Equal(t, "default", currentNamespace, "TestKubectContext error")
assert.Equal(t, "https://127.0.0.1:38039", currentServer, "TestKubectContext error")
}
func TestKubectUseContext(t *testing.T) {
cmd := getCmdKubectl(MOCK_ENABLE, `Switched to context "minikube".`)
err := cmd.UseContext("minikube")
assert.Nilf(t, err, "error message %s", err)
}
func TestKubectUseContextErr(t *testing.T) {
error := errors.New("exit 1")
cmd := getCmdKubectlError(MOCK_ENABLE, `error: no context exists with the name: "minikube2"`, error)
err := cmd.UseContext("minikube2")
assert.NotNilf(t, err, "error message %s", err)
}
func TestKubectCheck(t *testing.T) {
cmd_txt := `
Kubernetes control plane is running at https://127.0.0.1:38039
CoreDNS is running at https://127.0.0.1:38039/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
`
// error := errors.New("exit 1")
cmd := getCmdKubectl(MOCK_ENABLE, cmd_txt)
err := cmd.Check()
assert.Nilf(t, err, "error message %s", err)
}
func TestKubectCheckErr(t *testing.T) {
cmd_txt := ""
error := errors.New("exit 1")
cmd := getCmdKubectlError(MOCK_ENABLE, cmd_txt, error)
err := cmd.Check()
assert.NotNilf(t, err, "error message %s", "TestKubectCheckErr")
}

View File

@ -0,0 +1,17 @@
package kubectl
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestKubectl(t *testing.T) {
cmd := KubectlCommand{}
cmd.New()
assert.NotNilf(t, cmd.Exec, "TestKubectl %s", "New")
cmd.Exec("pwd")
}

View File

@ -30,15 +30,16 @@ type MockCommandExecutor struct {
// Used to stub the return of the Output method // Used to stub the return of the Output method
// Could add other properties depending on testing needs // Could add other properties depending on testing needs
output string output string
err error
} }
// Implements the commandExecutor interface // Implements the commandExecutor interface
func (m *MockCommandExecutor) Output() ([]byte, error) { func (m *MockCommandExecutor) Output() ([]byte, error) {
return []byte(m.output), nil return []byte(m.output), m.err
} }
func (m *MockCommandExecutor) CombinedOutput() ([]byte, error) { func (m *MockCommandExecutor) CombinedOutput() ([]byte, error) {
return []byte(m.output), nil return []byte(m.output), m.err
} }
// //
@ -74,7 +75,26 @@ func getCmdsKubectl(mock bool, outputs map[string]string) (KubectlCommand) {
cmd := KubectlCommand{Bin: "mock", Exec: mock} cmd := KubectlCommand{Bin: "mock", Exec: mock}
return cmd return cmd
} else { } else {
bin := filepath.Join(TEST_BIN_DIR, "Kubectl") bin := filepath.Join(TEST_BIN_DIR, "kubectl")
os.Chmod(bin, 0700)
cmd := KubectlCommand{Bin: bin}
cmd.New()
return cmd
}
}
func getCmdKubectlError(mock bool, output string, err error) (KubectlCommand) {
if mock == true {
mock := func(name string, args ...string) commandExecutor {
return &MockCommandExecutor{output: output, err: err}
}
cmd := KubectlCommand{Bin: "mock", Exec: mock}
return cmd
} else {
bin := filepath.Join(TEST_BIN_DIR, "kubectl")
os.Chmod(bin, 0700) os.Chmod(bin, 0700)
cmd := KubectlCommand{Bin: bin} cmd := KubectlCommand{Bin: bin}

View File

@ -1,9 +1,9 @@
package kubectl package kubectl
import ( import (
"fmt" "fmt"
"time" "time"
"errors" "errors"
log "oc-deploy/log_wrapper" log "oc-deploy/log_wrapper"
) )
@ -20,14 +20,14 @@ type getOutput struct {
} }
type getStatusOutput struct { type getStatusOutput struct {
Replicas int `json:"replicas"` Replicas int `json:"replicas"`
UnavailableReplicas int `json:"unavailableReplicas"` UnavailableReplicas int `json:"unavailableReplicas"`
} }
func (this KubectlCommand) Get(data KubectlObject) (map[string]any, error) { func (this KubectlCommand) Get(data KubectlObject) (map[string]any, error) {
if data.Kind == "Deployment" {return this.getDeployment(data)} if data.Kind == "Deployment" {return this.getDeployment(data)}
if data.Kind == "StatefulSet" {return this.getStatefulSet(data)} if data.Kind == "StatefulSet" {return this.getStatefulSet(data)}
return make(map[string]any), fmt.Errorf("Kind %s inconnu", data.Kind) return make(map[string]any), fmt.Errorf("Kind %s inconnu", data.Kind)
} }
func (this KubectlCommand) Wait(data KubectlObject) (error) { func (this KubectlCommand) Wait(data KubectlObject) (error) {
@ -35,22 +35,22 @@ func (this KubectlCommand) Wait(data KubectlObject) (error) {
boucle := 10 boucle := 10
sleep := 10000 * time.Millisecond sleep := 10000 * time.Millisecond
for _ = range boucle { for _ = range boucle {
log.Log().Debug().Msg(fmt.Sprintf("Check Deployement %s", data.Name)) log.Log().Debug().Msg(fmt.Sprintf("Check Deployement %s", data.Name))
m, err := this.Get(data) m, err := this.Get(data)
if err != nil { if err != nil {
return err return err
} }
ko := m["UnavailableReplicas"].(int) ko := m["UnavailableReplicas"].(int)
if ko == 0 { if ko == 0 {
return nil return nil
} }
log.Log().Info().Msg(fmt.Sprintf(" >> %s (Unavailable : %d)...", data.Name, ko)) log.Log().Info().Msg(fmt.Sprintf(" >> %s (Unavailable : %d)...", data.Name, ko))
time.Sleep(sleep) time.Sleep(sleep)
} }
return errors.New("Temps d'attente dépassé") return errors.New("Temps d'attente dépassé")
} }

View File

@ -3,7 +3,9 @@ package log_wrapper
// https://github.com/rs/zerolog/issues/150 // https://github.com/rs/zerolog/issues/150
import ( import (
"fmt"
"os" "os"
"path/filepath"
"github.com/rs/zerolog" "github.com/rs/zerolog"
) )
@ -28,9 +30,11 @@ func Log() *zerolog.Logger {
return &mainLogVar return &mainLogVar
} }
func InitLog(serverName string) bool { func InitLog(filename string) bool {
fAll, _ := os.OpenFile("./" + serverName + ".log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644) ficlog := filepath.Join(filename + ".log")
fAll, _ := os.OpenFile(ficlog, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
fmt.Println("ficlog", ficlog)
output := zerolog.ConsoleWriter{Out: os.Stdout} output := zerolog.ConsoleWriter{Out: os.Stdout}
writerInfo := zerolog.MultiLevelWriter(output) writerInfo := zerolog.MultiLevelWriter(output)

View File

@ -0,0 +1,21 @@
package log_wrapper
import (
// "os"
"path/filepath"
// "errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLogWrapper(t *testing.T) {
ficlog := filepath.Join(TEST_DEST_DIR, "test")
InitLog(ficlog)
Log().Info().Msg("KKK")
Log().Error().Msg("KKK")
assert.FileExists(t, ficlog + ".log", "TestLogWrapper")
}

View File

@ -0,0 +1,21 @@
package log_wrapper
import (
"os"
"testing"
)
var TEST_DEST_DIR = "../wrk_log"
func TestMain(m *testing.M) {
folderPath := TEST_DEST_DIR
os.RemoveAll(folderPath)
os.MkdirAll(folderPath, os.ModePerm)
// call flag.Parse() here if TestMain uses flags
exitCode := m.Run()
os.RemoveAll(folderPath)
os.Exit(exitCode)
}

54
test/kubectl/context.json Normal file
View File

@ -0,0 +1,54 @@
{
"kind": "Config",
"apiVersion": "v1",
"preferences": {},
"clusters": [
{
"name": "minikube",
"cluster": {
"server": "https://127.0.0.1:38039",
"certificate-authority": "/home/admeju/.minikube/ca.crt",
"extensions": [
{
"name": "cluster_info",
"extension": {
"last-update": "Tue, 10 Sep 2024 10:32:04 UTC",
"provider": "minikube.sigs.k8s.io",
"version": "v1.33.1"
}
}
]
}
}
],
"users": [
{
"name": "minikube",
"user": {
"client-certificate": "/home/admeju/.minikube/profiles/minikube/client.crt",
"client-key": "/home/admeju/.minikube/profiles/minikube/client.key"
}
}
],
"contexts": [
{
"name": "minikube",
"context": {
"cluster": "minikube",
"user": "minikube",
"namespace": "default",
"extensions": [
{
"name": "context_info",
"extension": {
"last-update": "Tue, 10 Sep 2024 10:32:04 UTC",
"provider": "minikube.sigs.k8s.io",
"version": "v1.33.1"
}
}
]
}
}
],
"current-context": "minikube"
}