@@ -2,6 +2,8 @@ package fn_test
2
2
3
3
import (
4
4
"bufio"
5
+ "bytes"
6
+ "io"
5
7
"os"
6
8
"path/filepath"
7
9
"reflect"
@@ -443,3 +445,79 @@ func TestReadSingleConfig_ScannerError(t *testing.T) {
443
445
t .Errorf ("Expected nil result when scanner error occurs, got: %v" , result )
444
446
}
445
447
}
448
+
449
+ func TestPrintConfigs (t * testing.T ) {
450
+ // 准备测试数据
451
+ sshConfig := & fn.SSHConfig {
452
+ Configs : map [string ]* fn.ConfigFile {
453
+ "/home/user/.ssh/config" : {
454
+ Path : "/home/user/.ssh/config" ,
455
+ Content : []string {
456
+ "Host github.com" ,
457
+ " HostName github.com" ,
458
+ " User git" ,
459
+ " IdentityFile ~/.ssh/github_rsa" ,
460
+ },
461
+ Hosts : map [string ]map [string ]string {
462
+ "github.com" : {
463
+ "HostName" : "github.com" ,
464
+ "User" : "git" ,
465
+ "IdentityFile" : "~/.ssh/github_rsa" ,
466
+ },
467
+ },
468
+ },
469
+ "/home/user/.ssh/config.d/work" : {
470
+ Path : "/home/user/.ssh/config.d/work" ,
471
+ Content : []string {
472
+ "Host work-server" ,
473
+ " HostName 192.168.1.100" ,
474
+ " User worker" ,
475
+ " Port 2222" ,
476
+ },
477
+ Hosts : map [string ]map [string ]string {
478
+ "work-server" : {
479
+ "HostName" : "192.168.1.100" ,
480
+ "User" : "worker" ,
481
+ "Port" : "2222" ,
482
+ },
483
+ },
484
+ },
485
+ },
486
+ }
487
+
488
+ // 捕获标准输出
489
+ old := os .Stdout
490
+ r , w , _ := os .Pipe ()
491
+ os .Stdout = w
492
+
493
+ // 运行要测试的函数
494
+ sshConfig .PrintConfigs ()
495
+
496
+ // 恢复标准输出并获取输出内容
497
+ w .Close ()
498
+ os .Stdout = old
499
+
500
+ var buf bytes.Buffer
501
+ io .Copy (& buf , r )
502
+ output := buf .String ()
503
+
504
+ // 验证输出内容
505
+ expectedOutputs := []string {
506
+ "=== 配置文件: /home/user/.ssh/config ===" ,
507
+ "Host github.com:" ,
508
+ " HostName = github.com" ,
509
+ " User = git" ,
510
+ " IdentityFile = ~/.ssh/github_rsa" ,
511
+ "=== 配置文件: /home/user/.ssh/config.d/work ===" ,
512
+ "Host work-server:" ,
513
+ " HostName = 192.168.1.100" ,
514
+ " User = worker" ,
515
+ " Port = 2222" ,
516
+ }
517
+
518
+ for _ , expected := range expectedOutputs {
519
+ if ! strings .Contains (output , expected ) {
520
+ t .Errorf ("Expected output to contain %q, but it didn't.\n Actual output:\n %s" , expected , output )
521
+ }
522
+ }
523
+ }
0 commit comments