Skip to content

Commit 36b151c

Browse files
committed
test: improve coverage for ReadSingleConfig
1 parent abb0233 commit 36b151c

File tree

2 files changed

+41
-11
lines changed

2 files changed

+41
-11
lines changed

internal/fn/scanner.go

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -140,18 +140,16 @@ func ReadSingleConfig(path string) *ConfigFile {
140140
}
141141

142142
parts := strings.Fields(line)
143-
if len(parts) < 2 {
144-
continue
145-
}
146-
147-
key := strings.ToLower(parts[0])
148-
value := strings.Join(parts[1:], " ")
143+
if len(parts) == 2 {
144+
key := strings.ToLower(parts[0])
145+
value := strings.Join(parts[1:], " ")
149146

150-
if key == "host" {
151-
currentHost = value
152-
config.Hosts[currentHost] = make(map[string]string)
153-
} else if currentHost != "" {
154-
config.Hosts[currentHost][key] = value
147+
if key == "host" {
148+
currentHost = value
149+
config.Hosts[currentHost] = make(map[string]string)
150+
} else if currentHost != "" {
151+
config.Hosts[currentHost][key] = value
152+
}
155153
}
156154
}
157155

internal/fn/scanner_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package fn_test
22

33
import (
4+
"bufio"
45
"os"
56
"path/filepath"
67
"reflect"
8+
"strings"
79
"testing"
810

911
"github.com/soulteary/ssh-config/internal/fn"
@@ -411,3 +413,33 @@ Nothing to see here`,
411413
})
412414
}
413415
}
416+
417+
// TestReadSingleConfig_ScannerError tests the scanner error handling
418+
func TestReadSingleConfig_ScannerError(t *testing.T) {
419+
// 创建一个包含无效数据的文件
420+
tmpfile, err := os.CreateTemp("", "test_config_*.txt")
421+
if err != nil {
422+
t.Fatalf("Failed to create temporary file: %v", err)
423+
}
424+
defer os.Remove(tmpfile.Name())
425+
426+
// 写入一些正常数据和一个超长行来触发 scanner 错误
427+
longLine := strings.Repeat("a", bufio.MaxScanTokenSize+1)
428+
content := "Host testhost\n" + longLine
429+
430+
if _, err := tmpfile.WriteString(content); err != nil {
431+
t.Fatalf("Failed to write to temp file: %v", err)
432+
}
433+
434+
if err := tmpfile.Close(); err != nil {
435+
t.Fatalf("Failed to close temp file: %v", err)
436+
}
437+
438+
// 测试 ReadSingleConfig
439+
result := fn.ReadSingleConfig(tmpfile.Name())
440+
441+
// 验证当发生扫描错误时返回 nil
442+
if result != nil {
443+
t.Errorf("Expected nil result when scanner error occurs, got: %v", result)
444+
}
445+
}

0 commit comments

Comments
 (0)