Files
backup/cmd/root_test.go
T
wt f854cbace5
Go Build and Test / build-and-test (push) Successful in 25s
added more tests
2025-08-12 16:55:55 +07:00

68 lines
1.5 KiB
Go

package cmd
import (
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
)
// Вспомогательная структура для перехвата вызовов osExit
type exitCapture struct {
code int
called bool
}
func (e *exitCapture) capture(code int) {
e.code = code
e.called = true
}
func TestExecute_Success(t *testing.T) {
// Сохраняем оригинальный osExit
originalExit := osExit
defer func() { osExit = originalExit }()
// Настраиваем перехват
capture := &exitCapture{}
osExit = capture.capture
// Запускаем выполнение
Execute()
// Проверяем, что выход не вызывался
if capture.called {
t.Errorf("osExit called with code %d, expected no call", capture.code)
}
}
func TestExecute_Error(t *testing.T) {
originalExit := osExit
defer func() { osExit = originalExit }()
capture := &exitCapture{}
osExit = capture.capture
// Подменяем rootCmd на команду, возвращающую ошибку
originalCmd := rootCmd
defer func() { rootCmd = originalCmd }()
rootCmd = &cobra.Command{
Use: "error-cmd",
RunE: func(cmd *cobra.Command, args []string) error {
return assert.AnError // Имитация ошибки
},
}
// Вызываем Execute
Execute()
// Проверяем, что osExit вызван с кодом 1
if !capture.called {
t.Fatal("osExit not called")
}
if capture.code != 1 {
t.Errorf("expected exit code 1, got %d", capture.code)
}
}