Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions cmd/base/list_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,3 +341,48 @@ func (o *BandwidthTypeOption[T]) ApplyToCollection(collection serverscom.Collect
collection.SetParam("type", o.bandwidthType)
}
}

type HasRaidControllerOption[T any] struct {
hasRaidController bool
}

func (o *HasRaidControllerOption[T]) AddFlags(cmd *cobra.Command) {
cmd.Flags().BoolVar(&o.hasRaidController, "has-raid-controller", false,
"Filter only servers with RAID controller")
}

func (o *HasRaidControllerOption[T]) ApplyToCollection(collection serverscom.Collection[T]) {
if o.hasRaidController {
collection.SetParam("has_raid_controller", "true")
}
}

type DriveMediaTypeOption[T any] struct {
mediaType string
}

func (o *DriveMediaTypeOption[T]) AddFlags(cmd *cobra.Command) {
cmd.Flags().StringVar(&o.mediaType, "media-type", "",
"Filter drives by media type (HDD, SSD")
}

func (o *DriveMediaTypeOption[T]) ApplyToCollection(collection serverscom.Collection[T]) {
if o.mediaType != "" {
collection.SetParam("media_type", o.mediaType)
}
}

type DriveInterfaceOption[T any] struct {
iface string
}

func (o *DriveInterfaceOption[T]) AddFlags(cmd *cobra.Command) {
cmd.Flags().StringVar(&o.iface, "interface", "",
"Filter drives by interface (SATA1, SATA2, SATA3, SAS, NVMe-PCIe)")
}

func (o *DriveInterfaceOption[T]) ApplyToCollection(collection serverscom.Collection[T]) {
if o.iface != "" {
collection.SetParam("interface", o.iface)
}
}
38 changes: 38 additions & 0 deletions cmd/entities/drivemodels/drivemodels.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package drivemodels

import (
"log"

serverscom "github.com/serverscom/serverscom-go-client/pkg"
"github.com/serverscom/srvctl/cmd/base"
"github.com/serverscom/srvctl/internal/output/entities"
"github.com/spf13/cobra"
)

func NewCmd(cmdContext *base.CmdContext) *cobra.Command {
driveEntity, err := entities.Registry.GetEntityFromValue(serverscom.DriveModel{})
if err != nil {
log.Fatal(err)
}
entitiesMap := make(map[string]entities.EntityInterface)
entitiesMap["drive-models"] = driveEntity
cmd := &cobra.Command{
Use: "drive-models",
Short: "Manage drive models",
PersistentPreRunE: base.CombinePreRunE(
base.CheckFormatterFlags(cmdContext, entitiesMap),
base.CheckEmptyContexts(cmdContext),
),
Args: base.NoArgs,
Run: base.UsageRun,
}

cmd.AddCommand(
newListCmd(cmdContext),
newGetCmd(cmdContext),
)

base.AddFormatFlags(cmd)

return cmd
}
251 changes: 251 additions & 0 deletions cmd/entities/drivemodels/drivemodels_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
package drivemodels

import (
"errors"
"fmt"
"path/filepath"
"testing"

. "github.com/onsi/gomega"
serverscom "github.com/serverscom/serverscom-go-client/pkg"
"github.com/serverscom/srvctl/cmd/testutils"
"github.com/serverscom/srvctl/internal/mocks"
"go.uber.org/mock/gomock"
)

var (
fixtureBasePath = filepath.Join("..", "..", "..", "testdata", "entities", "drive-models")
testDriveModelID = int64(10)
testLocationID = int64(1)
testServerModelID = int64(100)
testDriveModelOption = serverscom.DriveModel{
ID: testDriveModelID,
Name: "ssd-model-749",
Capacity: 100,
Interface: "SATA3",
FormFactor: "2.5",
MediaType: "SSD",
}
)

func TestGetDriveModelOptionCmd(t *testing.T) {
testCases := []struct {
name string
id int64
output string
flags []string
expectedOutput []byte
expectError bool
}{
{
name: "get drive model in default format",
id: testDriveModelID,
flags: []string{"--location-id", fmt.Sprint(testLocationID), "--server-model-id", fmt.Sprint(testServerModelID)},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "get.txt")),
},
{
name: "get drive model in JSON format",
id: testDriveModelID,
output: "json",
flags: []string{"--location-id", fmt.Sprint(testLocationID), "--server-model-id", fmt.Sprint(testServerModelID)},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "get.json")),
},
{
name: "get drive model in YAML format",
id: testDriveModelID,
output: "yaml",
flags: []string{"--location-id", fmt.Sprint(testLocationID), "--server-model-id", fmt.Sprint(testServerModelID)},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "get.yaml")),
},
{
name: "get drive model with service error",
id: testDriveModelID,
flags: []string{"--location-id", fmt.Sprint(testLocationID), "--server-model-id", fmt.Sprint(testServerModelID)},
expectError: true,
},
{
name: "get drive model missing required flags",
id: testDriveModelID,
expectError: true,
},
}

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()

locationsServiceHandler := mocks.NewMockLocationsService(mockCtrl)

scClient := serverscom.NewClientWithEndpoint("", "")
scClient.Locations = locationsServiceHandler

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
g := NewWithT(t)

var err error
if tc.expectError && len(tc.flags) > 0 {
err = errors.New("some error")
}

if len(tc.flags) > 0 {
locationsServiceHandler.EXPECT().
GetDriveModelOption(gomock.Any(), testLocationID, testServerModelID, tc.id).
Return(&testDriveModelOption, err)
}

testCmdContext := testutils.NewTestCmdContext(scClient)
driveCmd := NewCmd(testCmdContext)

args := []string{"drive-models", "get", fmt.Sprint(tc.id)}
if len(tc.flags) > 0 {
args = append(args, tc.flags...)
}
if tc.output != "" {
args = append(args, "--output", tc.output)
}

builder := testutils.NewTestCommandBuilder().
WithCommand(driveCmd).
WithArgs(args)

cmd := builder.Build()

execErr := cmd.Execute()

if tc.expectError {
g.Expect(execErr).To(HaveOccurred())
} else {
g.Expect(execErr).To(BeNil())
g.Expect(builder.GetOutput()).To(BeEquivalentTo(string(tc.expectedOutput)))
}
})
}
}

func TestListDriveModelOptionsCmd(t *testing.T) {
d1 := testDriveModelOption
d2 := testDriveModelOption
d2.ID = testDriveModelID + 1
d2.Name = "hdd-model-741"
d2.MediaType = "HDD"

testCases := []struct {
name string
output string
args []string
expectedOutput []byte
expectError bool
configureMock func(*mocks.MockCollection[serverscom.DriveModel])
}{
{
name: "list all drive models",
output: "json",
args: []string{"-A", "--location-id", "1", "--server-model-id", "100"},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "list_all.json")),
configureMock: func(mock *mocks.MockCollection[serverscom.DriveModel]) {
mock.EXPECT().
Collect(gomock.Any()).
Return([]serverscom.DriveModel{d1, d2}, nil)
},
},
{
name: "list drive models",
output: "json",
args: []string{"--location-id", "1", "--server-model-id", "100"},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "list.json")),
configureMock: func(mock *mocks.MockCollection[serverscom.DriveModel]) {
mock.EXPECT().
List(gomock.Any()).
Return([]serverscom.DriveModel{d1}, nil)
},
},
{
name: "list drive models with template",
args: []string{"--template", "{{range .}}ID: {{.ID}} MediaType: {{.MediaType}}\n{{end}}", "--location-id", "1", "--server-model-id", "100"},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "list_template.txt")),
configureMock: func(mock *mocks.MockCollection[serverscom.DriveModel]) {
mock.EXPECT().
List(gomock.Any()).
Return([]serverscom.DriveModel{d1, d2}, nil)
},
},
{
name: "list drive models with pageView",
args: []string{"--page-view", "--location-id", "1", "--server-model-id", "100"},
expectedOutput: testutils.ReadFixture(filepath.Join(fixtureBasePath, "list_pageview.txt")),
configureMock: func(mock *mocks.MockCollection[serverscom.DriveModel]) {
mock.EXPECT().
List(gomock.Any()).
Return([]serverscom.DriveModel{d1, d2}, nil)
},
},
{
name: "list drive models with error",
args: []string{"--location-id", "1", "--server-model-id", "100"},
expectError: true,
configureMock: func(mock *mocks.MockCollection[serverscom.DriveModel]) {
mock.EXPECT().
List(gomock.Any()).
Return(nil, errors.New("some error"))
},
},
{
name: "list drive models missing required flags",
expectError: true,
},
}

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()

locationsServiceHandler := mocks.NewMockLocationsService(mockCtrl)
collectionHandler := mocks.NewMockCollection[serverscom.DriveModel](mockCtrl)

locationsServiceHandler.EXPECT().
DriveModelOptions(gomock.Any(), gomock.Any()).
Return(collectionHandler).
AnyTimes()

collectionHandler.EXPECT().
SetParam(gomock.Any(), gomock.Any()).
Return(collectionHandler).
AnyTimes()

scClient := serverscom.NewClientWithEndpoint("", "")
scClient.Locations = locationsServiceHandler

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
g := NewWithT(t)

if tc.configureMock != nil {
tc.configureMock(collectionHandler)
}

testCmdContext := testutils.NewTestCmdContext(scClient)
driveCmd := NewCmd(testCmdContext)

args := []string{"drive-models", "list"}
if len(tc.args) > 0 {
args = append(args, tc.args...)
}
if tc.output != "" {
args = append(args, "--output", tc.output)
}

builder := testutils.NewTestCommandBuilder().
WithCommand(driveCmd).
WithArgs(args)

cmd := builder.Build()
err := cmd.Execute()

if tc.expectError {
g.Expect(err).To(HaveOccurred())
} else {
g.Expect(err).To(BeNil())
g.Expect(builder.GetOutput()).To(BeEquivalentTo(string(tc.expectedOutput)))
}
})
}
}
54 changes: 54 additions & 0 deletions cmd/entities/drivemodels/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package drivemodels

import (
"fmt"
"strconv"

"github.com/serverscom/srvctl/cmd/base"
"github.com/spf13/cobra"
)

func newGetCmd(cmdContext *base.CmdContext) *cobra.Command {
var locationID int64
var serverModelID int64

cmd := &cobra.Command{
Use: "get <id>",
Short: "Get a drive model for a server model",
Long: "Get a drive model for a server model by id",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
manager := cmdContext.GetManager()

ctx, cancel := base.SetupContext(cmd, manager)
defer cancel()

base.SetupProxy(cmd, manager)

scClient := cmdContext.GetClient().SetVerbose(manager.GetVerbose(cmd)).GetScClient()

driveModelID, err := strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("drive model id should be integer")
}

model, err := scClient.Locations.GetDriveModelOption(ctx, locationID, serverModelID, int64(driveModelID))
if err != nil {
return err
}

if model != nil {
formatter := cmdContext.GetOrCreateFormatter(cmd)
return formatter.Format(model)
}
return nil
},
}

cmd.Flags().Int64Var(&locationID, "location-id", 0, "Location id (int, required)")
cmd.Flags().Int64Var(&serverModelID, "server-model-id", 0, "Server model id (int, required)")
_ = cmd.MarkFlagRequired("location-id")
_ = cmd.MarkFlagRequired("server-model-id")

return cmd
}
Loading
Loading