|
| 1 | +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 2 | +// or more contributor license agreements. Licensed under the Elastic License 2.0; |
| 3 | +// you may not use this file except in compliance with the Elastic License 2.0. |
| 4 | + |
| 5 | +package cmd |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "os" |
| 11 | + "syscall" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/stretchr/testify/assert" |
| 16 | + "github.com/stretchr/testify/require" |
| 17 | + |
| 18 | + "github.com/elastic/elastic-agent/pkg/core/logger/loggertest" |
| 19 | +) |
| 20 | + |
| 21 | +func Test_watchLoop(t *testing.T) { |
| 22 | + |
| 23 | + t.Run("watchloop returns when context expires - no error", func(t *testing.T) { |
| 24 | + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) |
| 25 | + defer cancel() |
| 26 | + log, _ := loggertest.New(t.Name()) |
| 27 | + signals := make(chan os.Signal, 1) |
| 28 | + errChan := make(chan error, 1) |
| 29 | + graceTimer := make(chan time.Time, 1) |
| 30 | + err := watchLoop(ctx, log, signals, errChan, graceTimer) |
| 31 | + require.NoError(t, err) |
| 32 | + }) |
| 33 | + |
| 34 | + t.Run("watchloop returns when grace timer triggers - no error", func(t *testing.T) { |
| 35 | + log, _ := loggertest.New(t.Name()) |
| 36 | + signals := make(chan os.Signal, 1) |
| 37 | + errChan := make(chan error, 1) |
| 38 | + graceTimer := make(chan time.Time, 1) |
| 39 | + graceTimer <- time.Now() |
| 40 | + err := watchLoop(t.Context(), log, signals, errChan, graceTimer) |
| 41 | + require.NoError(t, err) |
| 42 | + }) |
| 43 | + |
| 44 | + t.Run("watchloop returns when error from AgentWatcher is received - error", func(t *testing.T) { |
| 45 | + log, _ := loggertest.New(t.Name()) |
| 46 | + signals := make(chan os.Signal, 1) |
| 47 | + errChan := make(chan error, 1) |
| 48 | + graceTimer := make(chan time.Time, 1) |
| 49 | + agentWatcherError := fmt.Errorf("some error") |
| 50 | + errChan <- agentWatcherError |
| 51 | + err := watchLoop(t.Context(), log, signals, errChan, graceTimer) |
| 52 | + require.ErrorIs(t, err, agentWatcherError) |
| 53 | + }) |
| 54 | + |
| 55 | + t.Run("watchloop returns when receiving signals - error", func(t *testing.T) { |
| 56 | + testSignals := []syscall.Signal{ |
| 57 | + syscall.SIGTERM, |
| 58 | + syscall.SIGINT, |
| 59 | + } |
| 60 | + |
| 61 | + for _, signal := range testSignals { |
| 62 | + t.Run(signal.String(), func(t *testing.T) { |
| 63 | + log, _ := loggertest.New(t.Name()) |
| 64 | + signals := make(chan os.Signal, 1) |
| 65 | + errChan := make(chan error, 1) |
| 66 | + graceTimer := make(chan time.Time, 1) |
| 67 | + signals <- signal |
| 68 | + err := watchLoop(t.Context(), log, signals, errChan, graceTimer) |
| 69 | + assert.ErrorIs(t, err, ErrWatchCancelled) |
| 70 | + }) |
| 71 | + } |
| 72 | + }) |
| 73 | +} |
0 commit comments