diff --git a/models/commands_test.go b/models/commands_test.go index 03e1b926991b8e1b56431bda60ca04942c7241be..fb95626ca02c0bfb72038bb3b4103f23765b2afa 100644 --- a/models/commands_test.go +++ b/models/commands_test.go @@ -1,13 +1,19 @@ /* * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. - * ha-api licensed under the Mulan Permissive Software License, Version 2. + * ha-api licensed under the Mulan Permissive Software License, Version 2. * See LICENSE file for more details. * Author: bixiaoyan * Date: Tue Aug 20 16:27:26 2024 +0800 */ package models -import "testing" +import ( + "errors" + "testing" + + "gitee.com/openeuler/ha-api/utils" + "github.com/stretchr/testify/assert" +) func TestGetCommandsList(t *testing.T) { result := GetCommandsList() @@ -16,9 +22,39 @@ func TestGetCommandsList(t *testing.T) { } } -func TestRunBuiltinCommand(t *testing.T) { - _, res := RunBuiltinCommand(1) - if res != nil { - t.Fatal("Get command result failed") +func TestRunBuiltinCommand_TableDriven(t *testing.T) { + tests := []struct { + name string + cmdID int + mockOutput string + mockError error + expectError string + }{ + {"ValidCommand", 3, "config data", nil, ""}, + {"CommandError", 4, "", errors.New("timeout"), "timeout"}, + {"InvalidID", 5, "", nil, "invalid command index"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Mock 函数设置 + originalRunCommand := utils.RunCommand + defer func() { utils.RunCommand = originalRunCommand }() + + utils.RunCommand = func(cmd string) ([]byte, error) { + return []byte(tt.mockOutput), tt.mockError + } + + // 执行测试 + output, err := RunBuiltinCommand(tt.cmdID) + + // 结果验证 + if tt.expectError != "" { + assert.ErrorContains(t, err, tt.expectError) + } else { + assert.NoError(t, err) + assert.Equal(t, tt.mockOutput, output) + } + }) } }