Skip to content

Commit

Permalink
Add cli UT
Browse files Browse the repository at this point in the history
  • Loading branch information
RealAlexandreAI committed Jul 16, 2024
1 parent 83dd2dd commit de0a696
Show file tree
Hide file tree
Showing 2 changed files with 147 additions and 12 deletions.
28 changes: 16 additions & 12 deletions cli/jsonrepair-cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"os"
)

const AppVersion = "0.0.11"
const AppVersion = "0.0.12"

var (
versionFlag bool
Expand All @@ -22,7 +22,7 @@ var (
func init() {
flag.BoolVar(&versionFlag, "v", false, "Print version details")
flag.BoolVar(&helpFlag, "h", false, "Print help")
flag.StringVar(&input, "i", "{}", "String input inline")
flag.StringVar(&input, "i", "", "String input inline")
flag.StringVar(&file, "f", "", "File path")
}

Expand All @@ -41,29 +41,33 @@ func printDefaults() {
//
// @Description:
func main() {
fmt.Print(cliInner())
}

// cliInner
//
// Description:
// return string
func cliInner() string {
flag.Parse()

if versionFlag {
fmt.Println("Version:", AppVersion)
return
return fmt.Sprintf("Version: %s", AppVersion)
} else if helpFlag {
printDefaults()
return
return ""
}

switch {
case input != "":
fmt.Println(jsonrepair.MustRepairJSON(input))
return jsonrepair.MustRepairJSON(input)
case file != "":
fi, err := os.ReadFile(file)
if err != nil {
fmt.Printf("[json-repair] invalid file path: %s", file)
fmt.Println()
return
return fmt.Sprintf("[json-repair] invalid file path: %s", file)
}
fmt.Println(jsonrepair.MustRepairJSON(string(fi)))
return jsonrepair.MustRepairJSON(string(fi))
default:
fmt.Println("{}")
return ""
}

}
131 changes: 131 additions & 0 deletions cli/jsonrepair-cli_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package main

import (
"encoding/json"
"fmt"
"io/ioutil"

Check failure on line 6 in cli/jsonrepair-cli_test.go

View workflow job for this annotation

GitHub Actions / lint (1.21, macos-latest)

SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details. (staticcheck)

Check failure on line 6 in cli/jsonrepair-cli_test.go

View workflow job for this annotation

GitHub Actions / lint (1.22, macos-latest)

SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details. (staticcheck)
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)

func Test_cliInner_v(t *testing.T) {

os.Args = append(os.Args, "-v")

rst := cliInner()

if !strings.Contains(rst, "Version") {
t.Errorf("-v ut error.")
}

os.Args = os.Args[:len(os.Args)-1]
resetVars()

}

func Test_cliInner_h(t *testing.T) {

os.Args = append(os.Args, "-h")

rst := cliInner()

if rst != "" {
t.Errorf("-h ut error.")
}

os.Args = os.Args[:len(os.Args)-1]
resetVars()

}

func Test_cliInner_i(t *testing.T) {

os.Args = append(os.Args, "-i")
os.Args = append(os.Args, "{'employees':['John', 'Anna', ")

rst := cliInner()

if !jsonStringsEqual(rst, `{"employees":["John","Anna"]}`) {
t.Errorf("-i ut error.")
}

os.Args = os.Args[:len(os.Args)-2]
resetVars()

}

func Test_cliInner_f(t *testing.T) {

tmpFile := writeToTemp("{'employees':['John', 'Anna', ")

os.Args = append(os.Args, "-f")
os.Args = append(os.Args, tmpFile)

rst := cliInner()

if !jsonStringsEqual(rst, `{"employees":["John","Anna"]}`) {
t.Errorf("-i ut error.")
}

os.Args = os.Args[:len(os.Args)-2]
resetVars()
}

func Test_cliInner_i_f(t *testing.T) {

tmpFile := writeToTemp("{'employees':['John', 'Anna', ")

os.Args = append(os.Args, "-f")
os.Args = append(os.Args, tmpFile)
os.Args = append(os.Args, "-i")
os.Args = append(os.Args, "")

rst := cliInner()

if !jsonStringsEqual(rst, `{"employees":["John","Anna"]}`) {
t.Errorf("-i ut error.")
}

os.Args = os.Args[:len(os.Args)-4]
resetVars()
}

func resetVars() {
versionFlag = false
helpFlag = false
input = ""
file = ""
}

func writeToTemp(input string) string {
tempDir := os.TempDir()
timestamp := time.Now().Format("20060102150405")
fileName := fmt.Sprintf("employees_%s.json", timestamp)
filePath := filepath.Join(tempDir, fileName)
data := []byte(input)
err := ioutil.WriteFile(filePath, data, 0644)
if err != nil {
fmt.Println("Error writing to file:", err)
}
return filePath
}

func jsonStringsEqual(jsonStr1, jsonStr2 string) bool {
var jsonObj interface{}
err := json.Unmarshal([]byte(jsonStr1), &jsonObj)
if err != nil {
return false
}

var jsonObj2 interface{}
err = json.Unmarshal([]byte(jsonStr2), &jsonObj2)
if err != nil {
return false
}

return reflect.DeepEqual(jsonObj, jsonObj2)
}

0 comments on commit de0a696

Please sign in to comment.