Skip to content

Commit eaba388

Browse files
committed
fix: TestApplyWatcher
1 parent 5394310 commit eaba388

3 files changed

Lines changed: 12 additions & 0 deletions

File tree

internal/logger/logger.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ func Init(verbose, debug bool, logPath string, jsonFormat bool) error {
3535
return fmt.Errorf("resolve log path: %w", err)
3636
}
3737
// 打开日志文件(使用解析后的绝对路径,避免通过变量直接包含任意路径)
38+
// #nosec G304 -- absPath 已通过 filepath.Clean 与 filepath.Abs 规范化,路径遍历已缓解
3839
logFile, err := os.OpenFile(absPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
3940
if err != nil {
4041
return err

internal/monitor/watcher.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,12 @@ func ApplyWatcher(appFlags flags.AppFlags) {
4747
}
4848
go WatchForFileChange(watcher, appFlags.AsTemplate, appFlags.Verbose, appFlags.NoPanic, rules.ReloadHooks, removeHooksFn)
4949
}
50+
51+
// closeWatcherForTest 关闭全局 watcher,仅用于测试以停止 goroutine、避免与后续测试产生竞态或泄漏。
52+
// 生产代码不应调用(watcher 进程生命周期内不关闭)。
53+
func closeWatcherForTest() {
54+
if watcher != nil {
55+
_ = watcher.Close()
56+
watcher = nil
57+
}
58+
}

internal/monitor/watcher_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ func TestApplyWatcher(t *testing.T) {
3333

3434
// Apply watcher (this will start a goroutine)
3535
ApplyWatcher(appFlags)
36+
defer closeWatcherForTest() // 测试结束关闭 watcher,避免 goroutine 泄漏及与后续测试竞态
3637

3738
// Wait a bit for the watcher to be set up
3839
// Note: This test mainly verifies that ApplyWatcher doesn't panic
@@ -54,4 +55,5 @@ func TestApplyWatcher_ErrorAddingFile(t *testing.T) {
5455
// Apply watcher (should handle error gracefully)
5556
// This should not panic, but will log an error
5657
ApplyWatcher(appFlags)
58+
defer closeWatcherForTest() // 即使 Add 失败也可能创建了 watcher,需关闭避免影响后续测试
5759
}

0 commit comments

Comments
 (0)