Debian Codegraph @

trace/trace_fuzz_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package trace
5
6 import (
7 "regexp"
8 "testing"
9 )
10
11 func FuzzTraceIDFromHex(f *testing.F) {
12 // Seed corpus with valid and edge-case examples.
13 f.Add("00000000000000000000000000000001") // Lowest valid (non-zero).
14 f.Add("0123456789abcdef0123456789abcdef")
15 f.Add("ffffffffffffffffffffffffffffffff") // Highest valid.
16 f.Add("0123456789abcdefabcdefabcdefabcd")
17 f.Add("invalidhexstringnot32chars") // Invalid.
18
19 validTraceIDRe := regexp.MustCompile(`^[0-9a-f]{32}$`)
20
21 f.Fuzz(func(t *testing.T, s string) {
22 id, err := TraceIDFromHex(s)
23
24 // OTel-valid TraceIDs: 32 lowercase hex chars, not all zeros.
25 validTraceID := validTraceIDRe.MatchString(s) && s != "00000000000000000000000000000000"
26 if validTraceID && err != nil {
27 t.Fatalf("expected no error for valid hex input: %q, got err: %v", s, err)
28 }
29 if !validTraceID && err == nil {
30 t.Fatalf("expected error for invalid input: %q", s)
31 }
32 if err != nil {
33 return
34 }
35
36 got := id.String()
37 if got != s {
38 t.Errorf("roundtrip mismatch: in=%q out=%q", s, got)
39 }
40 })
41 }
42
43 func FuzzSpanIDFromHex(f *testing.F) {
44 // Seed corpus with valid and edge-case examples.
45 f.Add("0000000000000001") // Lowest valid (non-zero).
46 f.Add("0123456789abcdef")
47 f.Add("ffffffffffffffff") // Highest valid.
48 f.Add("abcdefabcdefabcd")
49 f.Add("invalidhex") // Invalid.
50
51 validSpanIDRe := regexp.MustCompile(`^[0-9a-f]{16}$`)
52
53 f.Fuzz(func(t *testing.T, s string) {
54 id, err := SpanIDFromHex(s)
55
56 // OTel-valid SpanIDs: 16 lowercase hex chars, not all zeros.
57 validSpanID := validSpanIDRe.MatchString(s) && s != "0000000000000000"
58 if validSpanID && err != nil {
59 t.Fatalf("expected no error for valid hex input: %q, got err: %v", s, err)
60 }
61 if !validSpanID && err == nil {
62 t.Fatalf("expected error for invalid input: %q", s)
63 }
64 if err != nil {
65 return
66 }
67
68 got := id.String()
69 if got != s {
70 t.Errorf("roundtrip mismatch: in=%q out=%q", s, got)
71 }
72 })
73 }