Switch to new test harness

This commit is contained in:
2025-10-09 15:37:17 +02:00
parent 170a038612
commit fd55412020
8 changed files with 567 additions and 304 deletions

View File

@@ -1,10 +1,109 @@
package protocol
import (
"errors"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"testing"
)
type testCase struct {
Name string
Direction Direction
Data []byte
SrcPort int
DstPort int
WantProto string
WantConfidence float64
WantError error
}
func testRunner(t *testing.T, tests []*testCase) {
t.Helper()
for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
if test.SrcPort == 0 {
test.SrcPort = 1024 + rand.Intn(65535-1024)
}
if test.DstPort == 0 {
test.DstPort = 1024 + rand.Intn(65535-1024)
}
proto, confidence, err := Detect(test.Direction, test.Data, test.SrcPort, test.DstPort)
// Process error first
if err != nil {
if test.WantError == nil {
t.Fatalf("unexpected error: %v", err)
} else if !errors.Is(err, test.WantError) {
t.Fatalf("Detect(%s, %s, %d, %d) returned error %q, expected %q",
test.Direction, testBytesSample(test.Data, 8), test.SrcPort, test.DstPort,
err, test.WantError)
} else {
t.Logf("Detect(%s, %s, %d, %d) returned error %q as expected",
test.Direction, testBytesSample(test.Data, 8), test.SrcPort, test.DstPort,
err)
}
return
} else if test.WantError != nil {
t.Fatalf("Detect(%s, %s, %d, %d) returned protocol %q version %s, expected error %q",
test.Direction, testBytesSample(test.Data, 8), test.SrcPort, test.DstPort,
proto.Name, proto.Version, test.WantError)
return
}
// Process protocol
if proto == nil {
t.Fatalf("Detect(%s, %s, %d, %d) returned nil, expected protocol %q",
test.Direction, testBytesSample(test.Data, 8), test.SrcPort, test.DstPort,
test.WantProto)
return
}
t.Logf("Detect(%s, %s, %d, %d) returned protocol %q version %s with confidence %g%%",
test.Direction, testBytesSample(test.Data, 4), test.SrcPort, test.DstPort,
proto.Name, proto.Version, confidence*100)
if proto.Name != test.WantProto {
t.Errorf("Expected protocol %q", test.WantProto)
}
if !testAlmostEqual(confidence, test.WantConfidence) {
t.Errorf("Expected confidence %g%%", test.WantConfidence*100)
}
})
}
}
func testBytesSample(b []byte, n int) string {
if b == nil {
return "<nil>"
}
var (
hex []string
etc string
)
for i, l := 0, len(b); i < l && i < n; i++ {
if strconv.IsPrint(rune(b[i])) {
hex = append(hex, fmt.Sprintf("%c", b[i]))
} else {
hex = append(hex, fmt.Sprintf("\\x%02X", b[i]))
}
if i == (n-1) && l > (n-1) {
etc = fmt.Sprintf(" … (%d more)", l-n)
}
}
return fmt.Sprintf(`"%s"%s`, strings.Join(hex, ""), etc)
}
func testAlmostEqual(a, b float64) bool {
const e = 1e-9
return math.Abs(a-b) < e
}
func TestCompareFloats(t *testing.T) {
tests := []struct {
name string