response_test.go 1.04 KB
Newer Older
1 2
package commands

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

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

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

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

Matt Bell's avatar
Matt Bell committed
19 20 21 22 23 24 25 26
	// 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
27 28 29
	if err == nil {
		t.Error("Should have failed (no encoding type specified in request)")
	}
30

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
	res.SetError(fmt.Errorf("You broke something!"), ErrClient)
Matt Bell's avatar
Matt Bell committed
44 45 46 47 48 49 50 51
	bytes, err = res.Marshal()
	if err != nil {
		t.Error("Should have passed")
	}
	output = string(bytes)
	if output != "{\"Message\":\"You broke something!\",\"Code\":1}" {
		t.Error("Incorrect JSON output")
	}
52
}