antithesis_sdk/assert/mod.rs
1use crate::details::Details;
2#[cfg(feature = "full")]
3use crate::internal;
4#[cfg(feature = "full")]
5use linkme::distributed_slice;
6#[cfg(feature = "full")]
7use once_cell::sync::Lazy;
8use serde::Serialize;
9#[cfg(feature = "full")]
10use serde_json::json;
11use serde_json::Value;
12use std::sync::atomic::AtomicU64;
13#[cfg(feature = "full")]
14use std::{
15 collections::HashMap,
16 sync::{atomic::Ordering, Arc, RwLock},
17};
18
19#[doc(hidden)]
20#[cfg(feature = "full")]
21pub mod guidance;
22mod macros;
23
24/// Catalog of all antithesis assertions provided
25#[doc(hidden)]
26#[distributed_slice]
27#[cfg(feature = "full")]
28pub static ANTITHESIS_CATALOG: [AssertionCatalogInfo];
29
30/// Catalog of all antithesis guidances provided
31#[doc(hidden)]
32#[distributed_slice]
33#[cfg(feature = "full")]
34pub static ANTITHESIS_GUIDANCE_CATALOG: [self::guidance::GuidanceCatalogInfo];
35
36#[cfg(feature = "full")]
37pub(crate) static INIT_CATALOG: Lazy<()> = Lazy::new(|| {
38 for event in crate::catalog::registrations() {
39 internal::dispatch_output(&event);
40 }
41});
42
43/// The catalog-registration event for one assertion declaration, emitted by
44/// both `antithesis_init()` and `catalog::write`.
45#[cfg(feature = "full")]
46pub(crate) fn catalog_event(info: &AssertionCatalogInfo) -> Value {
47 let f_name: &str = info.function.as_ref();
48 let details = json!(null);
49 let assertion = AssertionInfo::new(
50 info.assert_type,
51 info.display_type,
52 info.condition,
53 info.message,
54 info.class,
55 f_name,
56 info.file,
57 info.begin_line,
58 info.begin_column,
59 false, /* hit */
60 info.must_hit,
61 info.id,
62 &details,
63 );
64 json!({ "antithesis_assert": &assertion })
65}
66
67pub struct TrackingInfo {
68 pub pass_count: AtomicU64,
69 pub fail_count: AtomicU64,
70}
71
72impl Default for TrackingInfo {
73 fn default() -> Self {
74 Self::new()
75 }
76}
77
78impl TrackingInfo {
79 pub const fn new() -> Self {
80 TrackingInfo {
81 pass_count: AtomicU64::new(0),
82 fail_count: AtomicU64::new(0),
83 }
84 }
85}
86
87#[derive(Copy, Clone, PartialEq, Debug, Serialize)]
88#[serde(rename_all(serialize = "lowercase"))]
89pub enum AssertType {
90 Always,
91 Sometimes,
92 Reachability,
93}
94
95#[derive(Serialize, Debug)]
96struct AntithesisLocationInfo<'a> {
97 class: &'a str,
98 function: &'a str,
99 file: &'a str,
100 begin_line: u32,
101 begin_column: u32,
102}
103
104/// Internal representation for assertion catalog
105#[doc(hidden)]
106#[derive(Debug)]
107#[cfg(feature = "full")]
108pub struct AssertionCatalogInfo {
109 pub assert_type: AssertType,
110 pub display_type: &'static str,
111 pub condition: bool,
112 pub message: &'static str,
113 pub class: &'static str,
114 pub function: &'static Lazy<&'static str>,
115 pub file: &'static str,
116 pub begin_line: u32,
117 pub begin_column: u32,
118 pub must_hit: bool,
119 pub id: &'static str,
120}
121
122#[derive(Serialize)]
123struct AssertionInfo<'a> {
124 assert_type: AssertType,
125 display_type: &'a str,
126 condition: bool,
127 message: &'a str,
128 location: AntithesisLocationInfo<'a>,
129 hit: bool,
130 must_hit: bool,
131 id: &'a str,
132 // Serialized separately so declarations never evaluate the details serializer.
133 #[serde(skip)]
134 details: &'a dyn Details,
135}
136
137impl<'a> AssertionInfo<'a> {
138 #[allow(clippy::too_many_arguments)]
139 pub fn new(
140 assert_type: AssertType,
141 display_type: &'a str,
142 condition: bool,
143 message: &'a str,
144 class: &'a str,
145 function: &'a str,
146 file: &'a str,
147 begin_line: u32,
148 begin_column: u32,
149 hit: bool,
150 must_hit: bool,
151 id: &'a str,
152 details: &'a dyn Details,
153 ) -> Self {
154 let location = AntithesisLocationInfo {
155 class,
156 function,
157 file,
158 begin_line,
159 begin_column,
160 };
161
162 AssertionInfo {
163 assert_type,
164 display_type,
165 condition,
166 message,
167 location,
168 hit,
169 must_hit,
170 id,
171 details,
172 }
173 }
174}
175
176#[cfg(feature = "full")]
177impl AssertionInfo<'_> {
178 // AssertionInfo::track_entry() determines if the assertion should
179 // actually be emitted:
180 //
181 // [X] If this is an assertion catalog
182 // registration (assertion.hit == false) then it is emitted.
183 //
184 // [X] if `condition` is true increment the tracker_entry.pass_count,
185 // otherwise increment the tracker_entry.fail_count.
186 //
187 // [X] if `condition` is true and tracker_entry_pass_count == 1 then
188 // actually emit the assertion.
189 //
190 // [X] if `condition` is false and tracker_entry_fail_count == 1 then
191 // actually emit the assertion.
192
193 fn track_entry(&self, info: Option<&TrackingInfo>) {
194 // Requirement: Catalog entries must always will emit()
195 if !self.hit {
196 self.emit();
197 return;
198 }
199
200 // Record the condition in the associated TrackingInfo entry,
201 // and emit the assertion when first seeing a condition
202 let emitting = match (info, self.condition) {
203 (None, _) => true,
204 (Some(info), true) => {
205 let prior_value = info.pass_count.fetch_add(1, Ordering::SeqCst);
206 prior_value == 0
207 }
208 (Some(info), false) => {
209 let prior_value = info.fail_count.fetch_add(1, Ordering::SeqCst);
210 prior_value == 0
211 }
212 };
213 if emitting {
214 Lazy::force(&INIT_CATALOG);
215 self.emit();
216 }
217 }
218
219 fn emit(&self) {
220 let mut assertion = serde_json::to_value(self).unwrap();
221 if self.hit {
222 if let Some(details) = self.details.object(self.id) {
223 assertion["details"] = Value::Object(details);
224 }
225 }
226 let json_event = json!({ "antithesis_assert": assertion });
227 internal::dispatch_output(&json_event)
228 }
229}
230
231#[cfg(not(feature = "full"))]
232impl AssertionInfo<'_> {
233 fn track_entry(&self, _info: Option<&TrackingInfo>) {
234 return;
235 }
236}
237
238/// This is a low-level method designed to be used by third-party frameworks.
239/// Regular users of the assert package should not call it.
240///
241/// This is primarily intended for use by adapters from other diagnostic tools
242/// that intend to output Antithesis-style assertions.
243///
244/// Be certain to provide an assertion catalog entry for each assertion issued
245/// with ``assert_raw()``. Assertion catalog entries are also created using
246/// ``assert_raw()``, by setting the value of the ``hit`` parameter to false.
247///
248/// Details may be any borrowed value implementing `Serialize`, handled as
249/// the assertion macros handle theirs: objects are preserved, other non-null
250/// values are wrapped under `"value"`, `&Value::Null` means no details, and
251/// a serialization error emits an `antithesis_error` naming the assertion
252/// `id` while the assertion itself is still emitted without details.
253/// Catalog entries (`hit == false`) never serialize details.
254///
255/// Please refer to the general Antithesis documentation regarding the use of
256/// the
257/// [Fallback SDK](https://antithesis.com/docs/using_antithesis/sdk/fallback/assert/)
258/// for additional information.
259///
260///
261///
262/// # Example
263///
264/// ```
265/// use serde_json::{json};
266/// use antithesis_sdk::{assert, random};
267///
268/// struct Votes {
269/// num_voters: u32,
270/// candidate_1: u32,
271/// candidate_2: u32,
272/// }
273///
274/// fn main() {
275/// establish_catalog();
276///
277/// let mut all_votes = Votes {
278/// num_voters: 0,
279/// candidate_1: 0,
280/// candidate_2: 0,
281/// };
282///
283/// for _voter in 0..100 {
284/// tally_vote(&mut all_votes, random_bool(), random_bool());
285/// }
286/// }
287///
288/// fn random_bool() -> bool {
289/// let v1 = random::get_random() % 2;
290/// v1 == 1
291/// }
292///
293/// fn establish_catalog() {
294/// assert::assert_raw(
295/// false, /* condition */
296/// "Never extra votes".to_owned(), /* message */
297/// &json!({}), /* details */
298/// "mycrate::stuff".to_owned(), /* class */
299/// "mycrate::tally_vote".to_owned(), /* function */
300/// "src/voting.rs".to_owned(), /* file */
301/// 20, /* line */
302/// 3, /* column */
303/// false, /* hit */
304/// true, /* must_hit */
305/// assert::AssertType::Always, /* assert_type */
306/// "Always".to_owned(), /* display_type */
307/// "42-1005".to_owned() /* id */
308/// );
309/// }
310///
311/// fn tally_vote(votes: &mut Votes, candidate_1: bool, candidate_2: bool) {
312/// if candidate_1 || candidate_2 {
313/// votes.num_voters += 1;
314/// }
315/// if candidate_1 {
316/// votes.candidate_1 += 1;
317/// };
318/// if candidate_2 {
319/// votes.candidate_2 += 1;
320/// };
321///
322/// let num_votes = votes.candidate_1 + votes.candidate_2;
323/// assert::assert_raw(
324/// num_votes == votes.num_voters, /* condition */
325/// "Never extra votes".to_owned(), /* message */
326/// &json!({ /* details */
327/// "votes": num_votes,
328/// "voters": votes.num_voters
329/// }),
330/// "mycrate::stuff".to_owned(), /* class */
331/// "mycrate::tally_vote".to_owned(), /* function */
332/// "src/voting.rs".to_owned(), /* file */
333/// 20, /* line */
334/// 3, /* column */
335/// true, /* hit */
336/// true, /* must_hit */
337/// assert::AssertType::Always, /* assert_type */
338/// "Always".to_owned(), /* display_type */
339/// "42-1005".to_owned() /* id */
340/// );
341/// }
342///
343/// // Run example with output to /tmp/x7.json
344/// // ANTITHESIS_SDK_LOCAL_OUTPUT=/tmp/x7.json cargo test --doc
345/// //
346/// // Example output from /tmp/x7.json
347/// // Contents may vary due to use of random::get_random()
348/// //
349/// // {"antithesis_sdk":{"language":{"name":"Rust","version":"1.69.0"},"sdk_version":"0.1.2","protocol_version":"1.0.0"}}
350/// // {"assert_type":"always","display_type":"Always","condition":false,"message":"Never extra votes","location":{"class":"mycrate::stuff","function":"mycrate::tally_vote","file":"src/voting.rs","begin_line":20,"begin_column":3},"hit":false,"must_hit":true,"id":"42-1005"}
351/// // {"assert_type":"always","display_type":"Always","condition":true,"message":"Never extra votes","location":{"class":"mycrate::stuff","function":"mycrate::tally_vote","file":"src/voting.rs","begin_line":20,"begin_column":3},"hit":true,"must_hit":true,"id":"42-1005","details":{"voters":1,"votes":1}}
352/// // {"assert_type":"always","display_type":"Always","condition":false,"message":"Never extra votes","location":{"class":"mycrate::stuff","function":"mycrate::tally_vote","file":"src/voting.rs","begin_line":20,"begin_column":3},"hit":true,"must_hit":true,"id":"42-1005","details":{"voters":3,"votes":4}}
353/// ```
354#[allow(clippy::too_many_arguments)]
355#[cfg(feature = "full")]
356pub fn assert_raw<T: Details>(
357 condition: bool,
358 message: String,
359 details: &T,
360 class: String,
361 function: String,
362 file: String,
363 begin_line: u32,
364 begin_column: u32,
365 hit: bool,
366 must_hit: bool,
367 assert_type: AssertType,
368 display_type: String,
369 id: String,
370) {
371 // Only this thin shim is generic (and so compiled into the caller's
372 // crate); the tracker lookup and everything downstream are erased
373 // behind `dyn Details` and compiled once, here.
374 let info = raw_tracker_entry(&id);
375 assert_impl(
376 assert_type,
377 display_type.as_str(),
378 condition,
379 message.as_str(),
380 class.as_str(),
381 function.as_str(),
382 file.as_str(),
383 begin_line,
384 begin_column,
385 hit,
386 must_hit,
387 id.as_str(),
388 details,
389 Some(&*info),
390 )
391}
392
393// The per-id tracking entries of raw assertions (the macros hold theirs in
394// a static per call site).
395#[cfg(feature = "full")]
396fn raw_tracker_entry(id: &str) -> Arc<TrackingInfo> {
397 static ASSERT_TRACKER: Lazy<RwLock<HashMap<String, Arc<TrackingInfo>>>> =
398 Lazy::new(|| RwLock::new(HashMap::new()));
399
400 // The read guard must drop before the write lock is taken.
401 let existing = ASSERT_TRACKER.read().unwrap().get(id).cloned();
402 match existing {
403 Some(info) => info,
404 None => ASSERT_TRACKER
405 .write()
406 .unwrap()
407 .entry(id.to_owned())
408 .or_default()
409 .clone(),
410 }
411}
412
413#[allow(clippy::too_many_arguments)]
414#[cfg(not(feature = "full"))]
415pub fn assert_raw<T: Details>(
416 condition: bool,
417 message: String,
418 details: &T,
419 class: String,
420 function: String,
421 file: String,
422 begin_line: u32,
423 begin_column: u32,
424 hit: bool,
425 must_hit: bool,
426 assert_type: AssertType,
427 display_type: String,
428 id: String,
429) {
430 assert_impl(
431 assert_type,
432 display_type.as_str(),
433 condition,
434 message.as_str(),
435 class.as_str(),
436 function.as_str(),
437 file.as_str(),
438 begin_line,
439 begin_column,
440 hit,
441 must_hit,
442 id.as_str(),
443 details,
444 None,
445 )
446}
447
448#[doc(hidden)]
449#[allow(clippy::too_many_arguments)]
450pub fn assert_impl<'a>(
451 assert_type: AssertType,
452 display_type: &'a str,
453 condition: bool,
454 message: &'a str,
455 class: &'a str,
456 function: &'a str,
457 file: &'a str,
458 begin_line: u32,
459 begin_column: u32,
460 hit: bool,
461 must_hit: bool,
462 id: &'a str,
463 details: &dyn Details,
464 info: Option<&TrackingInfo>,
465) {
466 let assertion = AssertionInfo::new(
467 assert_type,
468 display_type,
469 condition,
470 message,
471 class,
472 function,
473 file,
474 begin_line,
475 begin_column,
476 hit,
477 must_hit,
478 id,
479 details,
480 );
481
482 let _ = &assertion.track_entry(info);
483}