Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion netstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ func parseNetstat(filePath string) (NetStat, error) {
defer file.Close()

scanner := bufio.NewScanner(file)
scanner.Scan()
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return NetStat{}, err
}
return netStat, nil
}

// First string is always a header for stats
var headers []string
Expand All @@ -78,5 +83,9 @@ func parseNetstat(filePath string) (NetStat, error) {
}
}

if err := scanner.Err(); err != nil {
return NetStat{}, err
}

return netStat, nil
}
44 changes: 44 additions & 0 deletions netstat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
package procfs

import (
"bufio"
"os"
"path/filepath"
"strings"
"testing"
)

Expand Down Expand Up @@ -112,3 +116,43 @@ func TestNetStat(t *testing.T) {
}
}
}

// writeNetstatFile writes lines to a temporary file and returns its path.
func writeNetstatFile(t *testing.T, lines ...string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "stat")
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatalf("writing fixture: %v", err)
}
return path
}

func TestParseNetstatReportsScannerErrors(t *testing.T) {
// Hex tokens, so that what the scanner has already buffered still parses
// as counters and the header index is reached.
long := strings.Repeat("00000001 ", bufio.MaxScanTokenSize/9+1)

for _, tt := range []struct {
name string
lines []string
}{
{"header too long", []string{long, "00000001"}},
{"counter line too long", []string{"entries", long}},
} {
t.Run(tt.name, func(t *testing.T) {
if _, err := parseNetstat(writeNetstatFile(t, tt.lines...)); err == nil {
t.Fatal("expected an error, got nil")
}
})
}
}

func TestParseNetstatEmptyFile(t *testing.T) {
stat, err := parseNetstat(writeNetstatFile(t))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(stat.Stats) != 0 {
t.Fatalf("expected no stats, got %d", len(stat.Stats))
}
}