Debian Codegraph @

third_party/rust/failspot/src/lib.rs

raw
1 //! A testing library that makes it easy(ish) to add intentional errors to a program
2 //!
3 //! When testing error-handling codepaths, it is often useful to programmatically tell parts of the
4 //! code to fail. This crate provides the [`failspot!()`][failspot] macro, which can be used
5 //! to mark a spot in the codepath where an intentional failure can be toggled on and off
6 //! from testing code.
7 //!
8 //! Adding it to code is fairly simple:
9 //!
10 //! ```no_run
11 //! # use {failspot::failspot, std::{error::Error, fs, io, path::Path}};
12 //! # failspot::failspot_name! { pub enum FailSpotName { FailDataRead } }
13 //! # fn main() {
14 //! # read_data_file("/tmp/foo".as_ref());
15 //! # }
16 //! fn read_data_file(path: &Path) -> Result<Vec<u8>, Box<dyn Error>> {
17 //! // `FailDataRead` is a variant of an enum that was declared in our crate
18 //! // `bail` returns `Err` and does type conversion on the error type
19 //! failspot!(FailDataRead bail(io::Error::other("failed due to test config")));
20 //! Ok(fs::read(path)?)
21 //! }
22 //! ```
23 //!
24 //! The [`failspot_name!()`][failspot_name] macro is used to declare an enum that can be used
25 //! to name a failspot. Its syntax is identical to a regular enum declaration:
26 //!
27 //! ```no_run
28 //! # use failspot::failspot_name;
29 //! failspot_name! {
30 //! pub enum FailSpotName {
31 //! StuffWentWrong,
32 //! }
33 //! }
34 //! ```
35 //!
36 //! # Syntaxes
37 //!
38 //! The [`failspot!()`][failspot] macro has **four main syntaxes**. Each takes either a
39 //! **long form** or a **short form**.
40 //!
41 //! The **long form** explicitly contains the path to the enum containing the failspot names. This
42 //! is useful if there are multiple enums with different failspot names, or if the enum is only
43 //! accessible at a non-standard name or path.
44 //!
45 //! If the enum can be reached at the name `crate::FailSpotName` (either because it was declared in
46 //! the crate root or re-exported there), the **short form** versions of these macros
47 //! can be used. The examples below make this clear:
48 //!
49 //! ## "if-else" syntax (long form)
50 //!
51 //! Useful when standard if-else behavior is desired:
52 //!
53 //! ```
54 //! # use {failspot::failspot};
55 //! # pub mod my_module {
56 //! # failspot::failspot_name! { pub enum MyFailName { FailDataRead } }
57 //! # }
58 //! # fn main() {
59 //! // In "long form", the entire path to the enum must be spelled out
60 //! let _enabled = failspot!(if <crate::my_module::MyFailName>::FailDataRead {
61 //! println!("Data read failure enabled");
62 //! true
63 //! } else {
64 //! println!("Data read failure disabled");
65 //! false
66 //! });
67 //! # }
68 //! ```
69 //!
70 //! When the `enabled` feature is not on, the compiler will see the second block verbatim.
71 //!
72 //! ### The same code with the short-form
73 //!
74 //! If an enum named `FailSpotName` is reachable at the crate root, like this:
75 //!
76 //! ```
77 //! # use failspot::failspot_name;
78 //! // lib.rs
79 //! failspot_name! {
80 //! pub enum FailSpotName {
81 //! FailDataRead,
82 //! }
83 //! }
84 //! ```
85 //!
86 //! The short form can be used, like this:
87 //!
88 //! ```
89 //! # use failspot::{failspot, failspot_name};
90 //! # failspot_name! { pub enum FailSpotName { FailDataRead } }
91 //! # fn main() {
92 //! let _enabled = failspot!(if FailDataRead {
93 //! println!("Data read failure enabled");
94 //! true
95 //! } else {
96 //! println!("Data read failure disabled");
97 //! false
98 //! });
99 //! # }
100 //! ```
101 //!
102 //! ## "quick expression" syntax
103 //!
104 //! Useful when a short block of syntax should be evaluated when the failspot is enabled:
105 //!
106 //! ```
107 //! # use {failspot::failspot};
108 //! # failspot::failspot_name! { pub enum FailSpotName { FailDataRead } }
109 //! # fn main() {
110 //! failspot!(FailDataRead println!("Data read failure enabled"));
111 //!
112 //! // Also good for panicking
113 //! failspot!(FailDataRead panic!());
114 //!
115 //! // Or for just early returning
116 //! failspot!(FailDataRead return);
117 //!
118 //! // Multiple statements can be run, but use sparingly as things start to get ugly.
119 //! failspot!(FailDataRead println!("Data read failure enabled"); return);
120 //! # }
121 //! ```
122 //!
123 //! When the `enabled` feature is not on, the macro will evaluate to the empty block, `{}`.
124 //!
125 //! ## "bail" syntax
126 //!
127 //! Useful for returning an `Err` with error-type conversion:
128 //!
129 //! ```
130 //! # use {failspot::failspot, std::error::Error};
131 //! # failspot::failspot_name! { pub enum FailSpotName { FailDataRead } }
132 //! fn main() -> Result<(), Box<dyn Error>> {
133 //! failspot!(FailDataRead bail(std::io::Error::other("Data read failure enabled")));
134 //! Ok(())
135 //! }
136 //! ```
137 //!
138 //! When the `enabled` feature is not on, the macro will evaluate to the empty block, `{}`.
139 //!
140 //! ## "bool" syntax
141 //!
142 //! Useful to just evaluate whether the failspot is enabled or not:
143 //!
144 //! ```
145 //! # use {failspot::failspot, std::error::Error};
146 //! # failspot::failspot_name! { pub enum FailSpotName { FailDataRead } }
147 //! # fn main() {
148 //! # let bytes_to_read = 5;
149 //! let fail_the_read = bytes_to_read > 5000 || failspot!(FailDataRead);
150 //! # }
151 //! ```
152 //!
153 //! When the `enabled` feature is not on, the macro will evaluate to the token `false`.
154
155 #![cfg_attr(
156 feature = "enabled",
157 doc = r#"
158 # Testing code
159
160 Testing code should see the documentation for the [testing] module."#
161 )]
162 #![forbid(missing_docs)]
163
164 #[cfg(feature = "enabled")]
165 pub mod testing;
166
167 /// Declares a spot that can trigger intentional failures
168 ///
169 /// See the [crate-level docs][crate] for details.
170 #[cfg(feature = "enabled")]
171 #[allow(clippy::crate_in_macro_def)]
172 #[macro_export]
173 macro_rules! failspot {
174 (
175 if <$e: ty>::$n: ident {
176 $($enabled: tt)*
177 } $(else {
178 $($disabled: tt)*
179 })?
180 ) => {{
181 if $crate::failspot!(<$e>::$n) {
182 $($enabled)*
183 } $(else {
184 $($disabled)*
185 })?
186 }};
187
188 (
189 if $n: ident {
190 $($enabled: tt)*
191 } $(else {
192 $($disabled: tt)*
193 })?
194 ) => {
195 $crate::failspot!(
196 if <crate::FailSpotName>::$n {
197 $($enabled)*
198 } $(else {
199 $($disabled)*
200 })?
201 )
202 };
203
204 (<$e: ty>::$n: ident bail($err: expr)) => {{
205 if $crate::failspot!(<$e>::$n) {
206 return Err($err.into());
207 }
208 }};
209 ($n: ident bail($err: expr)) => {
210 $crate::failspot!(<crate::FailSpotName>::$n bail($err))
211 };
212 (<$e: ty>::$n: ident) => {{
213 <$e>::enabled(<$e>::$n)
214 }};
215 ($n: ident) => {
216 $crate::failspot!(<crate::FailSpotName>::$n)
217 };
218 (<$e: ty>::$n: ident $($enabled: tt)+) => {{
219 if $crate::failspot!(<$e>::$n) {
220 $($enabled)+
221 }
222 }};
223 ($n: ident $($enabled: tt)+) => {
224 $crate::failspot!(<crate::FailSpotName>::$n $($enabled)+)
225 }}
226
227 /// Declares a spot that can trigger intentional failures
228 ///
229 /// See the [crate-level docs][crate] for details.
230 #[cfg(not(feature = "enabled"))]
231 #[allow(clippy::crate_in_macro_def)]
232 #[macro_export]
233 macro_rules! failspot {
234 (
235 if <$e: ty>::$n: ident {
236 $($enabled: tt)*
237 } $(else {
238 $($disabled: tt)*
239 })?
240 ) => {{$($($disabled)*)?}};
241
242 (
243 if $n: ident {
244 $($enabled: tt)*
245 } $(else {
246 $($disabled: tt)*
247 })?
248 ) => {
249 $crate::failspot!(
250 if <crate::FailSpotName>::$n {
251 $($enabled)*
252 } $(else {
253 $($disabled)*
254 })?
255 )
256 };
257 (<$e: ty>::$n: ident bail($err: expr)) => {{}};
258 ($n: ident bail($err: expr)) => {
259 $crate::failspot!(<crate::FailSpotName>::$n bail($err))
260 };
261 (<$e: ty>::$n: ident) => {false};
262 ($n: ident) => {
263 $crate::failspot!(<crate::FailSpotName>::$n)
264 };
265 (<$e: ty>::$n: ident $($enabled: tt)+) => {{}};
266 ($n: ident $($enabled: tt)+) => {
267 $crate::failspot!(<crate::FailSpotName>::$n $($enabled)+)
268 }}
269
270 /// Declares an enum that can be used as a name for a [failspot]
271 ///
272 /// When feature `enabled` is off, this macro does nothing.
273 ///
274 /// See the [crate-level docs][crate] for details.
275 #[cfg(feature = "enabled")]
276 #[macro_export]
277 macro_rules! failspot_name {{
278 $(#[$m:meta])*
279 $p:vis enum $n:ident {
280 $(
281 $(#[$a:meta])*
282 $k:ident
283 ),+ $(,)*
284 }
285 } => {
286 $crate::flagset::flags! {
287 $(#[$m])*
288 $p enum $n: usize {
289 $(
290 $(#[$a])*
291 $k
292 ),+
293 }
294 }
295 $crate::failspot_global!($n);
296 }}
297
298 /// Declares an enum that can be used as a name for a [failspot]
299 ///
300 /// When feature `enabled` is off, this macro does nothing.
301 ///
302 /// See the [crate-level docs][crate] for details.
303 #[cfg(not(feature = "enabled"))]
304 #[macro_export]
305 macro_rules! failspot_name(($($t: tt)*) => ());
306
307 #[doc(hidden)]
308 #[macro_export]
309 macro_rules! failspot_global(($n: ident) => {
310 impl $n {
311 pub fn enabled(name: Self) -> bool {
312 Self::global_config().enabled(name)
313 }
314 pub fn testing_client() -> $crate::testing::Client<'static, $n> {
315 Self::global_config().client()
316 }
317 fn global_config() -> &'static $crate::testing::Config<$n> {
318 static GLOBAL: std::sync::LazyLock<$crate::testing::Config<$n>> =
319 std::sync::LazyLock::new($crate::testing::Config::default);
320 &GLOBAL
321 }
322 }
323 });
324
325 #[cfg(feature = "enabled")]
326 #[doc(hidden)]
327 pub use flagset;