Debian Codegraph @

assert/assert.go

raw
1 //go:build !no_antithesis_sdk
2
3 // Package assert enables defining [test properties] about your program or [workload]. It is part of the [Antithesis Go SDK], which enables Go applications to integrate with the [Antithesis platform].
4 //
5 // Code that uses this package should be instrumented with the [antithesis-go-generator] utility. This step is required for the Always, Sometime, and Reachable methods. It is not required for the Unreachable and AlwaysOrUnreachable methods, but it will improve the experience of using them.
6 //
7 // These functions are no-ops with minimal performance overhead when called outside of the Antithesis environment. However, if the environment variable ANTITHESIS_SDK_LOCAL_OUTPUT is set, these functions will log to the file pointed to by that variable using a structured JSON format defined [here]. This allows you to make use of the Antithesis assertions package in your regular testing, or even in production. In particular, very few assertions frameworks offer a convenient way to define [Sometimes assertions], but they can be quite useful even outside Antithesis.
8 //
9 // Each function in this package takes a parameter called message, which is a human readable identifier used to aggregate assertions. Antithesis generates one test property per unique message and this test property will be named "<message>" in the [triage report]. Message must be provided as a string literal.
10 //
11 // This test property either passes or fails, which depends upon the evaluation of every assertion that shares its message. Different assertions in different parts of the code should have different message, but the same assertion should always have the same message even if it is moved to a different file.
12 //
13 // Each function also takes a parameter called details, which is a key-value map of optional additional information provided by the user to add context for assertion failures. The information that is logged will appear in the [triage report], under the details section of the corresponding property. Normally the values passed to details are evaluated at runtime.
14 //
15 // [Antithesis Go SDK]: https://antithesis.com/docs/using_antithesis/sdk/go/
16 // [Antithesis platform]: https://antithesis.com
17 // [test properties]: https://antithesis.com/docs/properties_assertions/properties/
18 // [workload]: https://antithesis.com/docs/test_templates/first_test/
19 // [antithesis-go-generator]: https://antithesis.com/docs/using_antithesis/sdk/go/instrumentor/
20 // [triage report]: https://antithesis.com/docs/reports/
21 // [here]: https://antithesis.com/docs/using_antithesis/sdk/fallback/
22 // [Sometimes assertions]: https://antithesis.com/docs/best_practices/sometimes_assertions/
23 //
24 // [details]: https://antithesis.com/docs/reports/
25 package assert
26
27 import (
28 "encoding/json"
29 "fmt"
30 )
31
32 type assertInfo struct {
33 Location *locationInfo `json:"location"`
34 Details map[string]any `json:"details"`
35 AssertType string `json:"assert_type"`
36 DisplayType string `json:"display_type"`
37 Message string `json:"message"`
38 Id string `json:"id"`
39 Hit bool `json:"hit"`
40 MustHit bool `json:"must_hit"`
41 Condition bool `json:"condition"`
42 }
43
44 // Create a custom json marshaler for assertInfo so that we can force Errors to be marshaled with their error details.
45 // Without this, custom errors are marshaled as an empty object because the default json marshaler doesn't include the error
46 // (because it's a method - not an exported struct field).
47 func (f assertInfo) MarshalJSON() ([]byte, error) {
48 type alias assertInfo // prevent infinite recursion
49 a := alias(f)
50 if a.Details != nil {
51 a.Details = normalizeMap(a.Details)
52 }
53 return json.Marshal(a)
54 }
55
56 type jsonError struct {
57 innerError error
58 }
59
60 func (e jsonError) MarshalJSON() ([]byte, error) {
61 // Marshal this as the debug output string instead of e.Error(). These should be equivalent, but Sprintf correctly
62 // handles nil values for us (which otherwise are annoying to defend against due to this - https://go.dev/doc/faq#nil_error)
63 return json.Marshal(fmt.Sprintf("%+v", e.innerError))
64 }
65
66 // Recursively replace any `error` with jsonError while doing a deep copy.
67 // Most of the logic is in the normalize method below. This method exists to localize the type assertions
68 // and provide a function that takes in/out a map instead of any.
69 func normalizeMap(v map[string]any) map[string]any {
70 return normalize(v).(map[string]any)
71 }
72
73 func normalize(input any) any {
74 // This switch will miss some cases (pointers, structs, non-any types), but should catch a very large proportion of real error interfaces
75 // in real details objects. We can augment this if we find other cases common enough to support.
76 switch inputTyped := input.(type) {
77 case error:
78 // Check if the underlying error implements json.Marshaler, so that if the error
79 // already knows who to marshal itself, we don't override that.
80 if _, ok := inputTyped.(json.Marshaler); ok {
81 return inputTyped
82 } else {
83 return jsonError{inputTyped}
84 }
85 case map[string]any:
86 out := make(map[string]any, len(inputTyped))
87 for k, v := range inputTyped {
88 out[k] = normalize(v)
89 }
90 return out
91 case []any:
92 out := make([]any, len(inputTyped))
93 for i := range inputTyped {
94 out[i] = normalize(inputTyped[i])
95 }
96 return out
97 default:
98 return input
99 }
100 }
101
102 type wrappedAssertInfo struct {
103 A *assertInfo `json:"antithesis_assert"`
104 }
105
106 // --------------------------------------------------------------------------------
107 // Assertions
108 // --------------------------------------------------------------------------------
109 const (
110 wasHit = true
111 mustBeHit = true
112 optionallyHit = false
113 expectingTrue = true
114 )
115
116 const (
117 universalTest = "always"
118 existentialTest = "sometimes"
119 reachabilityTest = "reachability"
120 )
121
122 const (
123 alwaysDisplay = "Always"
124 alwaysOrUnreachableDisplay = "AlwaysOrUnreachable"
125 sometimesDisplay = "Sometimes"
126 reachableDisplay = "Reachable"
127 unreachableDisplay = "Unreachable"
128 )
129
130 // Always asserts that condition is true every time this function is called, and that it is called at least once. The corresponding test property will be viewable in the Antithesis SDK: Always group of your triage report.
131 func Always(condition bool, message string, details map[string]any) {
132 if trackerEmitted(message, condition) {
133 return
134 }
135 locationInfo := newLocationInfo(offsetAPICaller)
136 id := makeKey(message, locationInfo)
137 assertImpl(condition, message, details, locationInfo, wasHit, mustBeHit, universalTest, alwaysDisplay, id)
138 }
139
140 // AlwaysOrUnreachable asserts that condition is true every time this function is called. The corresponding test property will pass if the assertion is never encountered (unlike Always assertion types). This test property will be viewable in the “Antithesis SDK: Always” group of your triage report.
141 func AlwaysOrUnreachable(condition bool, message string, details map[string]any) {
142 if trackerEmitted(message, condition) {
143 return
144 }
145 locationInfo := newLocationInfo(offsetAPICaller)
146 id := makeKey(message, locationInfo)
147 assertImpl(condition, message, details, locationInfo, wasHit, optionallyHit, universalTest, alwaysOrUnreachableDisplay, id)
148 }
149
150 // Sometimes asserts that condition is true at least one time that this function was called. (If the assertion is never encountered, the test property will therefore fail.) This test property will be viewable in the “Antithesis SDK: Sometimes” group.
151 func Sometimes(condition bool, message string, details map[string]any) {
152 if trackerEmitted(message, condition) {
153 return
154 }
155 locationInfo := newLocationInfo(offsetAPICaller)
156 id := makeKey(message, locationInfo)
157 assertImpl(condition, message, details, locationInfo, wasHit, mustBeHit, existentialTest, sometimesDisplay, id)
158 }
159
160 // Unreachable asserts that a line of code is never reached. The corresponding test property will fail if this function is ever called. (If it is never called the test property will therefore pass.) This test property will be viewable in the “Antithesis SDK: Reachablity assertions” group.
161 func Unreachable(message string, details map[string]any) {
162 if trackerEmitted(message, false) {
163 return
164 }
165 locationInfo := newLocationInfo(offsetAPICaller)
166 id := makeKey(message, locationInfo)
167 assertImpl(false, message, details, locationInfo, wasHit, optionallyHit, reachabilityTest, unreachableDisplay, id)
168 }
169
170 // Reachable asserts that a line of code is reached at least once. The corresponding test property will pass if this function is ever called. (If it is never called the test property will therefore fail.) This test property will be viewable in the “Antithesis SDK: Reachablity assertions” group.
171 func Reachable(message string, details map[string]any) {
172 if trackerEmitted(message, true) {
173 return
174 }
175 locationInfo := newLocationInfo(offsetAPICaller)
176 id := makeKey(message, locationInfo)
177 assertImpl(true, message, details, locationInfo, wasHit, mustBeHit, reachabilityTest, reachableDisplay, id)
178 }
179
180 // AssertRaw is a low-level method designed to be used by third-party frameworks. Regular users of the assert package should not call it.
181 func AssertRaw(cond bool, message string, details map[string]any,
182 classname, funcname, filename string, line int, column int,
183 hit bool, mustHit bool,
184 assertType string, displayType string,
185 id string,
186 ) {
187 assertImpl(cond, message, details,
188 &locationInfo{classname, funcname, filename, line, column},
189 hit, mustHit,
190 assertType, displayType,
191 id)
192 }
193
194 func assertImpl(cond bool, message string, details map[string]any,
195 loc *locationInfo,
196 hit bool, mustHit bool,
197 assertType string, displayType string,
198 id string,
199 ) {
200 trackerEntry := getTrackerEntry(id, loc.Filename, loc.Classname)
201
202 // Always grab the Filename and Classname captured when the trackerEntry was established
203 // This provides the consistency needed between instrumentation-time and runtime
204 if loc.Filename != trackerEntry.Filename {
205 loc.Filename = trackerEntry.Filename
206 }
207
208 if loc.Classname != trackerEntry.Classname {
209 loc.Classname = trackerEntry.Classname
210 }
211
212 aI := &assertInfo{
213 Hit: hit,
214 MustHit: mustHit,
215 AssertType: assertType,
216 DisplayType: displayType,
217 Message: message,
218 Condition: cond,
219 Id: id,
220 Location: loc,
221 Details: details,
222 }
223
224 trackerEntry.emit(aI)
225 }
226
227 func makeKey(message string, _ *locationInfo) string {
228 return message
229 }