longganhua
2019-07-18 2fcec5d0debb4819c651e8f3b1287f18de9efee9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package command
 
import (
    "fmt"
    "testing"
)
 
type OutputTest struct {
    XMLName    string           `json:"-"`
    TestString string           `json:"test_string"`
    TestInt    int              `json:"test_int"`
    TestNil    []byte           `json:"test_nil"`
    TestNested OutputTestNested `json:"nested"`
}
 
type OutputTestNested struct {
    NestKey string `json:"nest_key"`
}
 
func (o OutputTest) String() string {
    return fmt.Sprintf("%s    %d    %s", o.TestString, o.TestInt, o.TestNil)
}
 
func TestCommandOutput(t *testing.T) {
    var formatted []byte
    result := OutputTest{
        TestString: "woooo a string",
        TestInt:    77,
        TestNil:    nil,
        TestNested: OutputTestNested{
            NestKey: "nest_value",
        },
    }
 
    json_expected := `{
  "test_string": "woooo a string",
  "test_int": 77,
  "test_nil": null,
  "nested": {
    "nest_key": "nest_value"
  }
}`
    formatted, _ = formatOutput(result, "json")
    if string(formatted) != json_expected {
        t.Fatalf("bad json:\n%s\n\nexpected:\n%s", formatted, json_expected)
    }
 
    text_expected := "woooo a string    77"
    formatted, _ = formatOutput(result, "text")
    if string(formatted) != text_expected {
        t.Fatalf("bad output:\n\"%s\"\n\nexpected:\n\"%s\"", formatted, text_expected)
    }
 
    error_expected := `Invalid output format "boo"`
    _, err := formatOutput(result, "boo")
    if err.Error() != error_expected {
        t.Fatalf("bad output:\n\"%s\"\n\nexpected:\n\"%s\"", err.Error(), error_expected)
    }
}