Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: chore: add cli tester #1204

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,4 @@ mgc/spec_manipulator/cli_specs/specs.go.tmp
terraform.tfstate
terraform.tfstate.backup
terraform.tfstate.d
mgc/cli_tester/cli_tester
1 change: 1 addition & 0 deletions go.work
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ go 1.23.0

use (
./mgc/cli
./mgc/cli_tester
./mgc/codegen
./mgc/core
./mgc/lib
Expand Down
50 changes: 50 additions & 0 deletions mgc/cli_tester/cmd/add.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package cmd

import (
"fmt"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func add(cmd *cobra.Command, args []string) {
var toSave []commandsList

module := strings.Split(args[0], " ")[1]
if module == "" {
fmt.Println(`fail! Command syntax eg.: "mgc auth login"`)
return
}
toSave = append(toSave, commandsList{Command: args[0], Module: module})

currentConfig, err := loadList()
if err != nil {
fmt.Println(err)
return
}

for _, x := range currentConfig {
if x.Command == args[0] {
fmt.Println(`fail! command already exists`)
return
}
}

toSave = append(toSave, currentConfig...)
viper.Set("commands", toSave)
err = viper.WriteConfigAs(VIPER_FILE)
if err != nil {
fmt.Println(err)
}
fmt.Println("done")
}

var addCommandCmd = &cobra.Command{
Use: "add [command]",
Short: "Add new command",
Example: "specs add 'mgc auth login'",
Args: cobra.MinimumNArgs(1),
Hidden: false,
Run: add,
}
148 changes: 148 additions & 0 deletions mgc/cli_tester/cmd/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package cmd

import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/spf13/viper"
)

type commandsList struct {
Module string `yaml:"module"`
Command string `yaml:"command"`
}

func interfaceToMap(i interface{}) (map[string]interface{}, bool) {
mapa, ok := i.(map[string]interface{})
if !ok {
fmt.Println("A interface não é um mapa ou mapa de interfaces.")
return nil, false
}
return mapa, true
}

func loadList() ([]commandsList, error) {
var currentConfig []commandsList
config := viper.Get("commands")

if config != nil {
for _, v := range config.([]interface{}) {
vv, ok := interfaceToMap(v)
if !ok {
return currentConfig, fmt.Errorf("fail to load current config")
}
currentConfig = append(currentConfig, commandsList{
Module: vv["module"].(string),
Command: vv["command"].(string),
})
}

}
return currentConfig, nil
}

func ensureDirectoryExists(dirPath string) error {
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
return os.MkdirAll(dirPath, 0755)
}
return nil
}

func createFile(content []byte, dir, filePath string) error {
return os.WriteFile(filepath.Join(dir, filePath), content, 0644)
}

func loadFile(dir, filePath string) ([]byte, error) {
return os.ReadFile(filepath.Join(dir, filePath))
}

func writeSnapshot(output []byte, dir string, id string) error {
_ = createFile(output, dir, fmt.Sprintf("%s.cli", id))
return nil
}

func compareBytes(expected, actual []byte, ignoreDateUUID bool) error {
if bytes.Equal(expected, actual) {
return nil
}

allEqual := true

expectedLines := strings.Split(string(expected), "\n")
actualLines := strings.Split(string(actual), "\n")

var diff strings.Builder
diff.WriteString("\nDiferenças encontradas:\n")

dateRegex := regexp.MustCompile(`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z`)
uuidRegex := regexp.MustCompile(`[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`)

i, j := 0, 0
for i < len(expectedLines) && j < len(actualLines) {
expectedLine := expectedLines[i]
actualLine := actualLines[j]

if ignoreDateUUID {
expectedLine = dateRegex.ReplaceAllString(expectedLine, "DATE")
expectedLine = uuidRegex.ReplaceAllString(expectedLine, "UUID")
actualLine = dateRegex.ReplaceAllString(actualLine, "DATE")
actualLine = uuidRegex.ReplaceAllString(actualLine, "UUID")
}

if expectedLine == actualLine {
diff.WriteString(" " + expectedLines[i] + "\n")
i++
j++
} else {
allEqual = false
diff.WriteString("- " + expectedLines[i] + "\n")
diff.WriteString("+ " + actualLines[j] + "\n")
i++
j++
}
}

for ; i < len(expectedLines); i++ {
diff.WriteString("- " + expectedLines[i] + "\n")
}
for ; j < len(actualLines); j++ {
diff.WriteString("+ " + actualLines[j] + "\n")
}

if allEqual {
return nil
}

return fmt.Errorf("%s", diff.String())
}

func compareSnapshot(output []byte, dir string, id string) error {
snapContent, err := loadFile(dir, fmt.Sprintf("%s.cli", id))
if err == nil {
return compareBytes(snapContent, output, true)
}

if errors.Is(err, os.ErrNotExist) {
_ = writeSnapshot(output, dir, id)
return nil
}

return fmt.Errorf("Diosmio")
}

func normalizeCommandToFile(input string) string {
words := strings.Fields(input)
var filteredWords []string
for _, word := range words {
if !strings.HasPrefix(word, "--") {
filteredWords = append(filteredWords, word)
}
}
result := strings.Join(filteredWords, "-")
return result
}
28 changes: 28 additions & 0 deletions mgc/cli_tester/cmd/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package cmd

import (
"fmt"

"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)

var lisCommandsCmd = &cobra.Command{
Use: "list",
Short: "List all available commands",
Hidden: true,
Run: func(cmd *cobra.Command, args []string) {
currentCommands, err := loadList()

if err != nil {
fmt.Println(err)
return
}

out, err := yaml.Marshal(currentCommands)
if err == nil {
fmt.Println(string(out))
}

},
}
16 changes: 16 additions & 0 deletions mgc/cli_tester/cmd/mock/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package mock

import (
"fmt"

"github.com/spf13/cobra"
)

var mockCreateCmd = &cobra.Command{
Use: "create",
Short: "create",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("xpto")

},
}
16 changes: 16 additions & 0 deletions mgc/cli_tester/cmd/mock/group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package mock

import "github.com/spf13/cobra"

func MockCmd() *cobra.Command {

mockCmd := &cobra.Command{
CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
Use: "mock",
Short: "Mock",
}

mockCmd.AddCommand(mockCreateCmd)

return mockCmd
}
62 changes: 62 additions & 0 deletions mgc/cli_tester/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package cmd

import (
"fmt"
"os"
"path/filepath"

mock "magalu.cloud/cli_tester/cmd/mock"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
rootCmd = &cobra.Command{
CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
Use: "cli_tester",
Short: "Utilitário para auxiliar nos testes da CLI",
}
)

const (
VIPER_FILE = "commands.yaml"
SNAP_DIR = "snapshot"
)

var currentDir = func() string {
ex, err := os.Executable()
if err != nil {
panic(err)
}
return filepath.Dir(ex)
}

func Execute() error {
return rootCmd.Execute()
}

func init() {
cobra.OnInitialize(initConfig)
rootCmd.AddCommand(lisCommandsCmd)
rootCmd.AddCommand(addCommandCmd)
rootCmd.AddCommand(runTestsCmd)
rootCmd.AddCommand(mock.MockCmd())
}

func initConfig() {

ex, err := os.Executable()
home := filepath.Dir(ex)
cobra.CheckErr(err)

viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(VIPER_FILE)

viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Command list at file:", viper.ConfigFileUsed())
}

}
Loading