Skip to content

Commit a2c7c18

Browse files
committed
test(coverage): 优化单元测试测试用例
1 parent 437d54e commit a2c7c18

5 files changed

Lines changed: 356 additions & 1 deletion

File tree

cmd_utils_test.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,11 @@ func TestCounterExporter_Export(t *testing.T) {
153153
exportType: "csv",
154154
wantErr: false,
155155
},
156+
{
157+
name: "Export Excel",
158+
exportType: "excel",
159+
wantErr: false,
160+
},
156161
{
157162
name: "Invalid export type",
158163
exportType: "invalid",
@@ -162,15 +167,32 @@ func TestCounterExporter_Export(t *testing.T) {
162167

163168
for _, tt := range tests {
164169
t.Run(tt.name, func(t *testing.T) {
170+
var outputPath string
171+
switch tt.exportType {
172+
case "excel":
173+
outputPath = "test_output.xlsx"
174+
case "csv":
175+
outputPath = "test_output.csv"
176+
default:
177+
outputPath = "test_output"
178+
}
179+
165180
config := wcg.ExportConfig{
166181
Type: tt.exportType,
167-
Path: "test_output",
182+
Path: outputPath,
168183
}
169184
exporter := wcg.NewCounterExporter(counter, config)
170185
err := exporter.Export()
171186
if (err != nil) != tt.wantErr {
172187
t.Errorf("CounterExporter.Export() error = %v, wantErr %v", err, tt.wantErr)
173188
}
189+
190+
// Clean up created files
191+
if !tt.wantErr && (tt.exportType == "excel" || tt.exportType == "csv") {
192+
if _, err := os.Stat(outputPath); err == nil {
193+
os.Remove(outputPath)
194+
}
195+
}
174196
})
175197
}
176198
}

dir_test.go

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,3 +369,107 @@ func TestDirCounter_GetIgnoreList(t *testing.T) {
369369
t.Errorf("DirCounter.GetIgnoreList() = %v, want %v", ignoreList, ignorePatterns)
370370
}
371371
}
372+
373+
func TestDirCounter_GetHeader(t *testing.T) {
374+
// Test GetHeader with empty DirCounter
375+
dc := wcg.NewDirCounter("nonexistent")
376+
header := dc.GetHeader()
377+
expectedHeader := wcg.Row{"File", "Lines", "ChineseChars", "NonChineseChars", "TotalChars"}
378+
if !reflect.DeepEqual(header, expectedHeader) {
379+
t.Errorf("GetHeader() for empty DirCounter = %v, want %v", header, expectedHeader)
380+
}
381+
382+
// Test GetHeader with files
383+
testDir := filepath.Join(wd, "testdata")
384+
dc = wcg.NewDirCounter(testDir)
385+
err := dc.Count()
386+
if err != nil {
387+
t.Fatalf("Failed to count: %v", err)
388+
}
389+
390+
header = dc.GetHeader()
391+
if !reflect.DeepEqual(header, expectedHeader) {
392+
t.Errorf("GetHeader() for populated DirCounter = %v, want %v", header, expectedHeader)
393+
}
394+
}
395+
396+
func TestDirCounter_ExportExcelMethod(t *testing.T) {
397+
testDir := filepath.Join(wd, "testdata")
398+
dc := wcg.NewDirCounter(testDir)
399+
err := dc.Count()
400+
if err != nil {
401+
t.Fatalf("Failed to count: %v", err)
402+
}
403+
404+
// Test Excel export
405+
excelFile := "test_dir.xlsx"
406+
err = dc.ExportExcel(excelFile)
407+
if err != nil {
408+
t.Errorf("ExportExcel failed: %v", err)
409+
}
410+
411+
// Check if file exists
412+
if _, err := os.Stat(excelFile); os.IsNotExist(err) {
413+
t.Errorf("ExportExcel did not create file")
414+
}
415+
defer os.Remove(excelFile)
416+
}
417+
418+
func TestDirCounter_IsIgnoredWithError(t *testing.T) {
419+
// Test with valid patterns first
420+
dc1 := wcg.NewDirCounter("testdata")
421+
dc1.AddIgnorePattern("*.txt")
422+
dc1.AddIgnorePattern("/specific.md")
423+
424+
tests1 := []struct {
425+
name string
426+
filename string
427+
wantIgnored bool
428+
wantError bool
429+
}{
430+
{
431+
name: "Match txt pattern",
432+
filename: "test.txt",
433+
wantIgnored: true,
434+
wantError: false,
435+
},
436+
{
437+
name: "Match specific file",
438+
filename: "specific.md",
439+
wantIgnored: true,
440+
wantError: false,
441+
},
442+
{
443+
name: "No match",
444+
filename: "test.md",
445+
wantIgnored: false,
446+
wantError: false,
447+
},
448+
}
449+
450+
for _, tt := range tests1 {
451+
t.Run(tt.name, func(t *testing.T) {
452+
ignored, err := dc1.IsIgnoredWithError(tt.filename)
453+
if (err != nil) != tt.wantError {
454+
t.Errorf("IsIgnoredWithError() error = %v, wantError %v", err, tt.wantError)
455+
}
456+
if ignored != tt.wantIgnored {
457+
t.Errorf("IsIgnoredWithError() ignored = %v, want %v", ignored, tt.wantIgnored)
458+
}
459+
})
460+
}
461+
462+
// Test with invalid pattern separately
463+
dc2 := wcg.NewDirCounter("testdata")
464+
dc2.AddIgnorePattern("[") // Invalid pattern that will cause filepath.Match to error
465+
466+
t.Run("Invalid pattern", func(t *testing.T) {
467+
ignored, err := dc2.IsIgnoredWithError("test.invalid")
468+
if err == nil {
469+
t.Errorf("Expected error when using invalid pattern, but got none")
470+
}
471+
if ignored {
472+
t.Errorf("IsIgnoredWithError() ignored = %v, want false", ignored)
473+
}
474+
})
475+
}

errors_test.go

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,36 @@ func TestWordCounterError(t *testing.T) {
3232
wantMsg: "failed to read file: /path/to/file: permission denied",
3333
wantType: wcg.ErrorTypeFileRead,
3434
},
35+
{
36+
name: "File write error",
37+
err: wcg.NewFileWriteError("/path/to/output", errors.New("disk full")),
38+
wantMsg: "failed to write file: /path/to/output: disk full",
39+
wantType: wcg.ErrorTypeFileWrite,
40+
},
41+
{
42+
name: "Invalid path error",
43+
err: wcg.NewInvalidPathError("/invalid/path", errors.New("invalid characters")),
44+
wantMsg: "invalid path: /invalid/path: invalid characters",
45+
wantType: wcg.ErrorTypeInvalidPath,
46+
},
47+
{
48+
name: "Pattern match error",
49+
err: wcg.NewPatternMatchError("*.{", errors.New("invalid regex")),
50+
wantMsg: "invalid pattern: *.{: invalid regex",
51+
wantType: wcg.ErrorTypePatternMatch,
52+
},
53+
{
54+
name: "Export error",
55+
err: wcg.NewExportError("CSV export", errors.New("encoding error")),
56+
wantMsg: "export failed: CSV export: encoding error",
57+
wantType: wcg.ErrorTypeExport,
58+
},
59+
{
60+
name: "Server error",
61+
err: wcg.NewServerError("failed to start server", errors.New("port in use")),
62+
wantMsg: "failed to start server: port in use",
63+
wantType: wcg.ErrorTypeServer,
64+
},
3565
}
3666

3767
for _, tt := range tests {
@@ -67,3 +97,52 @@ func TestWordCounterError_Unwrap(t *testing.T) {
6797
t.Errorf("Expected unwrapped error to be %v, got %v", cause, unwrapped)
6898
}
6999
}
100+
101+
func TestErrorConstructorsWithContext(t *testing.T) {
102+
tests := []struct {
103+
name string
104+
err *wcg.WordCounterError
105+
wantContext map[string]any
106+
}{
107+
{
108+
name: "File write error with path context",
109+
err: wcg.NewFileWriteError("/output/file.txt", errors.New("disk full")),
110+
wantContext: map[string]any{
111+
"path": "/output/file.txt",
112+
},
113+
},
114+
{
115+
name: "Invalid path error with path context",
116+
err: wcg.NewInvalidPathError("/invalid/path", errors.New("invalid chars")),
117+
wantContext: map[string]any{
118+
"path": "/invalid/path",
119+
},
120+
},
121+
{
122+
name: "Pattern match error with pattern context",
123+
err: wcg.NewPatternMatchError("*.{", errors.New("invalid regex")),
124+
wantContext: map[string]any{
125+
"pattern": "*.{",
126+
},
127+
},
128+
{
129+
name: "Export error with operation context",
130+
err: wcg.NewExportError("Excel export", errors.New("format error")),
131+
wantContext: map[string]any{
132+
"operation": "Excel export",
133+
},
134+
},
135+
}
136+
137+
for _, tt := range tests {
138+
t.Run(tt.name, func(t *testing.T) {
139+
for key, expectedValue := range tt.wantContext {
140+
if actualValue, exists := tt.err.Context[key]; !exists {
141+
t.Errorf("Expected context key %s to exist", key)
142+
} else if actualValue != expectedValue {
143+
t.Errorf("Expected context[%s] = %v, got %v", key, expectedValue, actualValue)
144+
}
145+
}
146+
})
147+
}
148+
}

export_test.go

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,88 @@ func TestExportToTable(t *testing.T) {
132132
t.Errorf("ExportTable result doesn't contain expected content: %v", result)
133133
}
134134
}
135+
136+
func TestExportCounterFunctions(t *testing.T) {
137+
// Test the standalone export functions
138+
testContent := "Hello 世界\nSecond line"
139+
testFile := "testdata/export_counter_test.txt"
140+
err := os.WriteFile(testFile, []byte(testContent), 0644)
141+
if err != nil {
142+
t.Fatalf("Failed to create test file: %v", err)
143+
}
144+
defer os.Remove(testFile)
145+
146+
fc := wcg.NewFileCounter(testFile)
147+
err = fc.Count()
148+
if err != nil {
149+
t.Fatalf("Failed to count: %v", err)
150+
}
151+
152+
// Test ExportCounterCSV
153+
csvResult, err := wcg.ExportCounterCSV(fc)
154+
if err != nil {
155+
t.Errorf("ExportCounterCSV failed: %v", err)
156+
}
157+
if !strings.Contains(csvResult, "File,Lines,ChineseChars,NonChineseChars,TotalChars") {
158+
t.Errorf("ExportCounterCSV result doesn't contain expected headers")
159+
}
160+
161+
// Test ExportCounterCSV with filename
162+
csvFile := "test_counter.csv"
163+
_, err = wcg.ExportCounterCSV(fc, csvFile)
164+
if err != nil {
165+
t.Errorf("ExportCounterCSV with filename failed: %v", err)
166+
}
167+
if _, err := os.Stat(csvFile); os.IsNotExist(err) {
168+
t.Errorf("ExportCounterCSV did not create file")
169+
}
170+
defer os.Remove(csvFile)
171+
172+
// Test ExportCounterExcel
173+
excelFile := "test_counter.xlsx"
174+
err = wcg.ExportCounterExcel(fc, excelFile)
175+
if err != nil {
176+
t.Errorf("ExportCounterExcel failed: %v", err)
177+
}
178+
if _, err := os.Stat(excelFile); os.IsNotExist(err) {
179+
t.Errorf("ExportCounterExcel did not create file")
180+
}
181+
defer os.Remove(excelFile)
182+
183+
// Test ExportCounterTable
184+
tableResult := wcg.ExportCounterTable(fc)
185+
if !strings.Contains(tableResult, "FILE") || !strings.Contains(tableResult, "LINES") {
186+
t.Errorf("ExportCounterTable result doesn't contain expected content")
187+
}
188+
}
189+
190+
func TestExportErrorHandling(t *testing.T) {
191+
// Test export to invalid path for Excel
192+
testContent := "Hello world"
193+
testFile := "testdata/export_error_test.txt"
194+
err := os.WriteFile(testFile, []byte(testContent), 0644)
195+
if err != nil {
196+
t.Fatalf("Failed to create test file: %v", err)
197+
}
198+
defer os.Remove(testFile)
199+
200+
fc := wcg.NewFileCounter(testFile)
201+
err = fc.Count()
202+
if err != nil {
203+
t.Fatalf("Failed to count: %v", err)
204+
}
205+
206+
// Test Excel export to invalid directory
207+
invalidPath := "/invalid/directory/test.xlsx"
208+
err = wcg.ExportCounterExcel(fc, invalidPath)
209+
if err == nil {
210+
t.Errorf("Expected error when exporting to invalid path, but got none")
211+
}
212+
213+
// Test CSV export to invalid directory
214+
invalidCSVPath := "/invalid/directory/test.csv"
215+
_, err = wcg.ExportCounterCSV(fc, invalidCSVPath)
216+
if err == nil {
217+
t.Errorf("Expected error when exporting CSV to invalid path, but got none")
218+
}
219+
}

0 commit comments

Comments
 (0)