response_test.go 1.32 KB
Newer Older
1 2
package commands

3
import (
Matt Bell's avatar
Matt Bell committed
4
	"fmt"
Matt Bell's avatar
Matt Bell committed
5
	"strings"
Matt Bell's avatar
Matt Bell committed
6
	"testing"
7
)
8 9

type TestOutput struct {
Matt Bell's avatar
Matt Bell committed
10 11
	Foo, Bar string
	Baz      int
12 13 14
}

func TestMarshalling(t *testing.T) {
Matt Bell's avatar
Matt Bell committed
15
	req := NewEmptyRequest()
16

Matt Bell's avatar
Matt Bell committed
17
	res := NewResponse(req)
18
	res.SetOutput(TestOutput{"beep", "boop", 1337})
19

Matt Bell's avatar
Matt Bell committed
20 21 22 23 24 25 26 27
	// get command global options so we can set the encoding option
	cmd := Command{}
	options, err := cmd.GetOptions(nil)
	if err != nil {
		t.Error(err)
	}

	_, err = res.Marshal()
Matt Bell's avatar
Matt Bell committed
28 29 30
	if err == nil {
		t.Error("Should have failed (no encoding type specified in request)")
	}
31

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32
	req.SetOption(EncShort, JSON)
33
	req.ConvertOptions(options)
Matt Bell's avatar
Matt Bell committed
34

Matt Bell's avatar
Matt Bell committed
35 36
	bytes, err := res.Marshal()
	if err != nil {
Matt Bell's avatar
Matt Bell committed
37
		t.Error(err, "Should have passed")
Matt Bell's avatar
Matt Bell committed
38 39
	}
	output := string(bytes)
Matt Bell's avatar
Matt Bell committed
40
	if removeWhitespace(output) != "{\"Foo\":\"beep\",\"Bar\":\"boop\",\"Baz\":1337}" {
Matt Bell's avatar
Matt Bell committed
41 42
		t.Error("Incorrect JSON output")
	}
43

Matt Bell's avatar
Matt Bell committed
44
	res.SetError(fmt.Errorf("Oops!"), ErrClient)
Matt Bell's avatar
Matt Bell committed
45 46 47 48 49
	bytes, err = res.Marshal()
	if err != nil {
		t.Error("Should have passed")
	}
	output = string(bytes)
Matt Bell's avatar
Matt Bell committed
50 51
	fmt.Println(removeWhitespace(output))
	if removeWhitespace(output) != "{\"Message\":\"Oops!\",\"Code\":1}" {
Matt Bell's avatar
Matt Bell committed
52 53
		t.Error("Incorrect JSON output")
	}
54
}
Matt Bell's avatar
Matt Bell committed
55 56 57 58 59 60 61

func removeWhitespace(input string) string {
	input = strings.Replace(input, " ", "", -1)
	input = strings.Replace(input, "\t", "", -1)
	input = strings.Replace(input, "\n", "", -1)
	return strings.Replace(input, "\r", "", -1)
}