Skip to content

Commit

Permalink
test(ipaddress): validate list JSON output is a list
Browse files Browse the repository at this point in the history
  • Loading branch information
kangasta committed Oct 17, 2023
1 parent 5ac8438 commit b9c2fc2
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/commands/ipaddress/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (s *listCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Ou
}

return output.MarshaledWithHumanOutput{
Value: ips.IPAddresses,
Value: ips,
Output: output.Table{
Columns: []output.TableColumn{
{
Expand Down
46 changes: 46 additions & 0 deletions internal/commands/ipaddress/list_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package ipaddress

import (
"testing"

"github.com/UpCloudLtd/upcloud-cli/v2/internal/commands"
"github.com/UpCloudLtd/upcloud-cli/v2/internal/config"
smock "github.com/UpCloudLtd/upcloud-cli/v2/internal/mock"
"github.com/UpCloudLtd/upcloud-cli/v2/internal/mockexecute"
"github.com/UpCloudLtd/upcloud-cli/v2/internal/testutils"
"github.com/stretchr/testify/assert"

"github.com/UpCloudLtd/upcloud-go-api/v6/upcloud"
)

func TestList_MarshaledOutput(t *testing.T) {
ipAddress := upcloud.IPAddress{
Address: "94.237.117.150",
Access: "public",
Family: "IPv4",
PartOfPlan: upcloud.FromBool(true),
PTRRecord: "94-237-117-150.fi-hel1.upcloud.host",
ServerUUID: "005ab220-7ff6-42c9-8615-e4c02eb4104e",
MAC: "ee:1b:db:ca:6b:80",
Floating: upcloud.FromBool(false),
Zone: "fi-hel1",
}
ipAddresses := upcloud.IPAddresses{
IPAddresses: []upcloud.IPAddress{
ipAddress,
},
}

mService := smock.Service{}
mService.On("GetIPAddresses").Return(&ipAddresses, nil)

conf := config.New()
conf.Viper().Set(config.KeyOutput, config.ValueOutputJSON)

command := commands.BuildCommand(ListCommand(), nil, conf)

output, err := mockexecute.MockExecute(command, &mService, conf)

assert.Nil(t, err)
testutils.AssertOutputHasType(t, output, &upcloud.IPAddressSlice{})
}
26 changes: 26 additions & 0 deletions internal/testutils/json_output.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package testutils

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"
)

func AssertOutputHasType(t *testing.T, output string, expected interface{}) {
t.Helper()

err := json.Unmarshal([]byte(output), expected)
if typeError, ok := err.(*json.UnmarshalTypeError); ok {
assert.Nil(t, err, "Expected %t, got %s: %s", expected, typeError.Value, output)
} else {
assert.Nil(t, err)
}
}

func AssertOutputIsList(t *testing.T, output string) {
t.Helper()

list := make([]interface{}, 0)
AssertOutputHasType(t, output, &list)
}

0 comments on commit b9c2fc2

Please sign in to comment.