Files
steampipe/cmd/root_test.go
Nathan Wallace 46809b7982 Fix #4708: Thread-safe AddCommands/ResetCommands with mutex (#4904)
* Add test demonstrating race condition in AddCommands/ResetCommands

Added TestAddCommands_Concurrent which exposes data races when
AddCommands() and ResetCommands() are called concurrently.
Running with -race flag shows multiple race condition warnings.

This test demonstrates bug #4708 where these functions are not
thread-safe. While not a practical issue (only called during
single-threaded CLI initialization), proper synchronization
should be added.

Related to #4708

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix race condition in AddCommands/ResetCommands with mutex

Added thread-safe synchronization to AddCommands() and created a
new thread-safe ResetCommands() wrapper using a shared mutex.

The underlying cobra.Command methods are not thread-safe, causing
data races when called concurrently. While these functions are
typically only called during single-threaded CLI initialization,
adding proper synchronization ensures correctness and allows for
safe concurrent usage in tests.

Changes:
- Added commandMutex to protect concurrent access to rootCmd
- Updated AddCommands() with mutex lock/unlock
- Created ResetCommands() wrapper with mutex protection
- Updated test to use the new thread-safe ResetCommands()

Test now passes with -race flag with no warnings.

Fixes #4708

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-17 04:04:22 -05:00

39 lines
987 B
Go

package cmd
import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
// TestHideRootFlags_NonExistentFlag tests that hideRootFlags handles non-existent flags gracefully
// Bug #4707: hideRootFlags panics when called with a flag that doesn't exist
func TestHideRootFlags_NonExistentFlag(t *testing.T) {
// Initialize the root command
InitCmd()
// Test that calling hideRootFlags with a non-existent flag should NOT panic
assert.NotPanics(t, func() {
hideRootFlags("non-existent-flag")
}, "hideRootFlags should handle non-existent flags without panicking")
}
// TestAddCommands_Concurrent tests that AddCommands is thread-safe
// Bug #4708: AddCommands/ResetCommands not thread-safe (data races detected)
func TestAddCommands_Concurrent(t *testing.T) {
var wg sync.WaitGroup
// Run AddCommands concurrently to expose race conditions
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
ResetCommands()
AddCommands()
}()
}
wg.Wait()
}