Debian Codegraph @

debian/rust-vendor/rstest/src/lib.rs

raw
1 #![allow(clippy::test_attr_in_doctest)]
2 //! This crate will help you to write simpler tests by leveraging a software testing concept called
3 //! [test fixtures](https://en.wikipedia.org/wiki/Test_fixture#Software). A fixture is something
4 //! that you can use in your tests to encapsulate a test's dependencies.
5 //!
6 //! The general idea is to have smaller tests that only describe the thing you're testing while you
7 //! hide the auxiliary utilities your tests make use of somewhere else.
8 //! For instance, if you have an application that has many tests with users, shopping baskets, and
9 //! products, you'd have to create a user, a shopping basket, and product every single time in
10 //! every test which becomes unwieldy quickly. To cut down on that repetition, you can
11 //! instead use fixtures to declare that you need those objects for your function and the fixtures
12 //! will take care of creating those by themselves. Focus on the important stuff in your tests!
13 //!
14 //! In `rstest` a fixture is a function that can return any kind of valid Rust type. This
15 //! effectively means that your fixtures are not limited by the kind of data they can return.
16 //! A test can consume an arbitrary number of fixtures at the same time.
17 //!
18 //! ## What
19 //!
20 //! The `rstest` crate defines the following procedural macros:
21 //!
22 //! - [`[rstest]`](macro@rstest): Declare that a test or a group of tests that may take
23 //! [fixtures](attr.rstest.html#injecting-fixtures),
24 //! [input table](attr.rstest.html#test-parametrized-cases),
25 //! [list of values](attr.rstest.html#values-lists) or read data from
26 //! [files](attr.rstest.html#files-path-as-input-arguments).
27 //! - [`[fixture]`](macro@fixture): To mark a function as a fixture.
28 //!
29 //! ## Why
30 //!
31 //! Very often in Rust we write tests like this
32 //!
33 //! ```
34 //! #[test]
35 //! fn should_process_two_users() {
36 //! let mut repository = create_repository();
37 //! repository.add("Bob", 21);
38 //! repository.add("Alice", 22);
39 //!
40 //! let processor = string_processor();
41 //! processor.send_all(&repository, "Good Morning");
42 //!
43 //! assert_eq!(2, processor.output.find("Good Morning").count());
44 //! assert!(processor.output.contains("Bob"));
45 //! assert!(processor.output.contains("Alice"));
46 //! }
47 //! ```
48 //!
49 //! By making use of [`[rstest]`](macro@rstest) we can isolate the dependencies `empty_repository` and
50 //! `string_processor` by passing them as fixtures:
51 //!
52 //! ```
53 //! # use rstest::*;
54 //! #[rstest]
55 //! fn should_process_two_users(mut empty_repository: impl Repository,
56 //! string_processor: FakeProcessor) {
57 //! empty_repository.add("Bob", 21);
58 //! empty_repository.add("Alice", 22);
59 //!
60 //! string_processor.send_all("Good Morning");
61 //!
62 //! assert_eq!(2, string_processor.output.find("Good Morning").count());
63 //! assert!(string_processor.output.contains("Bob"));
64 //! assert!(string_processor.output.contains("Alice"));
65 //! }
66 //! ```
67 //!
68 //! ... or if you use `"Alice"` and `"Bob"` in other tests, you can isolate `alice_and_bob` fixture
69 //! and use it directly:
70 //!
71 //! ```
72 //! # use rstest::*;
73 //! # trait Repository { fn add(&mut self, name: &str, age: u8); }
74 //! # struct Rep;
75 //! # impl Repository for Rep { fn add(&mut self, name: &str, age: u8) {} }
76 //! # #[fixture]
77 //! # fn empty_repository() -> Rep {
78 //! # Rep
79 //! # }
80 //! #[fixture]
81 //! fn alice_and_bob(mut empty_repository: impl Repository) -> impl Repository {
82 //! empty_repository.add("Bob", 21);
83 //! empty_repository.add("Alice", 22);
84 //! empty_repository
85 //! }
86 //!
87 //! #[rstest]
88 //! fn should_process_two_users(alice_and_bob: impl Repository,
89 //! string_processor: FakeProcessor) {
90 //! string_processor.send_all("Good Morning");
91 //!
92 //! assert_eq!(2, string_processor.output.find("Good Morning").count());
93 //! assert!(string_processor.output.contains("Bob"));
94 //! assert!(string_processor.output.contains("Alice"));
95 //! }
96 //! ```
97 //! ## Features
98 //!
99 //! - `async-timeout`: `timeout` for `async` tests (Default enabled)
100 //! - `crate-name`: Import `rstest` package with different name (Default enabled)
101 //!
102 //! ## Injecting fixtures as function arguments
103 //!
104 //! `rstest` functions can receive fixtures by using them as input arguments.
105 //! A function decorated with [`[rstest]`](attr.rstest.html#injecting-fixtures)
106 //! will resolve each argument name by call the fixture function.
107 //! Fixtures should be annotated with the [`[fixture]`](macro@fixture) attribute.
108 //!
109 //! Fixtures will be resolved like function calls by following the standard resolution rules.
110 //! Therefore, an identically named fixture can be use in different context.
111 //!
112 //! ```
113 //! # use rstest::*;
114 //! # trait Repository { }
115 //! # #[derive(Default)]
116 //! # struct DataSet {}
117 //! # impl Repository for DataSet { }
118 //! mod empty_cases {
119 //! # use rstest::*;
120 //! # trait Repository { }
121 //! # #[derive(Default)]
122 //! # struct DataSet {}
123 //! # impl Repository for DataSet { }
124 //! use super::*;
125 //!
126 //! #[fixture]
127 //! fn repository() -> impl Repository {
128 //! DataSet::default()
129 //! }
130 //!
131 //! #[rstest]
132 //! fn should_do_nothing(repository: impl Repository) {
133 //! //.. test impl ..
134 //! }
135 //! }
136 //!
137 //! mod non_trivial_case {
138 //! # use rstest::*;
139 //! # trait Repository { }
140 //! # #[derive(Default)]
141 //! # struct DataSet {}
142 //! # impl Repository for DataSet { }
143 //! use super::*;
144 //!
145 //! #[fixture]
146 //! fn repository() -> impl Repository {
147 //! let mut ds = DataSet::default();
148 //! // Fill your dataset with interesting case
149 //! ds
150 //! }
151 //!
152 //! #[rstest]
153 //! fn should_notify_all_entries(repository: impl Repository) {
154 //! //.. test impl ..
155 //! }
156 //! }
157 //!
158 //! ```
159 //!
160 //! Last but not least, fixtures can be injected like we saw in `alice_and_bob` example.
161 //!
162 //! ## Creating parametrized tests
163 //!
164 //! You can use also [`[rstest]`](attr.rstest.html#test-parametrized-cases) to create
165 //! simple table-based tests. Let's see the classic Fibonacci example:
166 //!
167 //! ```
168 //! use rstest::rstest;
169 //!
170 //! #[rstest]
171 //! #[case(0, 0)]
172 //! #[case(1, 1)]
173 //! #[case(2, 1)]
174 //! #[case(3, 2)]
175 //! #[case(4, 3)]
176 //! #[case(5, 5)]
177 //! #[case(6, 8)]
178 //! fn fibonacci_test(#[case] input: u32,#[case] expected: u32) {
179 //! assert_eq!(expected, fibonacci(input))
180 //! }
181 //!
182 //! fn fibonacci(input: u32) -> u32 {
183 //! match input {
184 //! 0 => 0,
185 //! 1 => 1,
186 //! n => fibonacci(n - 2) + fibonacci(n - 1)
187 //! }
188 //! }
189 //! ```
190 //! This will generate a bunch of tests, one for every `#[case(a, b)]`.
191 //!
192 //! ## Creating a test for each combinations of given values
193 //!
194 //! In some cases you need to test your code for each combinations of some input values. In this
195 //! cases [`[rstest]`](attr.rstest.html#values-lists) give you the ability to define a list
196 //! of values (rust expressions) to use for an arguments.
197 //!
198 //! ```
199 //! # use rstest::rstest;
200 //! # #[derive(PartialEq, Debug)]
201 //! # enum State { Init, Start, Processing, Terminated }
202 //! # #[derive(PartialEq, Debug)]
203 //! # enum Event { Error, Fatal }
204 //! # impl State { fn process(self, event: Event) -> Self { self } }
205 //!
206 //! #[rstest]
207 //! fn should_terminate(
208 //! #[values(State::Init, State::Start, State::Processing)]
209 //! state: State,
210 //! #[values(Event::Error, Event::Fatal)]
211 //! event: Event
212 //! ) {
213 //! assert_eq!(State::Terminated, state.process(event))
214 //! }
215 //! ```
216 //!
217 //! This will generate a test for each combination of `state` and `event`.
218 //!
219 //! ## Magic Conversion
220 //!
221 //! If you need a value where its type implement `FromStr()` trait you
222 //! can use a literal string to build it.
223 //!
224 //! ```
225 //! # use rstest::rstest;
226 //! # use std::net::SocketAddr;
227 //! #[rstest]
228 //! #[case("1.2.3.4:8080", 8080)]
229 //! #[case("127.0.0.1:9000", 9000)]
230 //! fn check_port(#[case] addr: SocketAddr, #[case] expected: u16) {
231 //! assert_eq!(expected, addr.port());
232 //! }
233 //! ```
234 //! You can use this feature also in value list and in fixture default value.
235 //!
236
237 #[doc(hidden)]
238 pub mod magic_conversion;
239 #[doc(hidden)]
240 pub mod timeout;
241
242 #[doc(hidden)]
243 pub mod __std {
244 pub mod sync {
245 pub use std::sync::{Once, OnceLock};
246 }
247 }
248
249 mod context;
250 pub use crate::context::Context;
251
252 /// Define a fixture that you can use in all `rstest`'s test arguments. You should just mark your
253 /// function as `#[fixture]` and then use it as a test's argument. Fixture functions can also
254 /// use other fixtures.
255 ///
256 /// Let's see a trivial example:
257 ///
258 /// ```
259 /// use rstest::*;
260 ///
261 /// #[fixture]
262 /// fn twenty_one() -> i32 { 21 }
263 ///
264 /// #[fixture]
265 /// fn two() -> i32 { 2 }
266 ///
267 /// #[fixture]
268 /// fn injected(twenty_one: i32, two: i32) -> i32 { twenty_one * two }
269 ///
270 /// #[rstest]
271 /// fn the_test(injected: i32) {
272 /// assert_eq!(42, injected)
273 /// }
274 /// ```
275 ///
276 /// If the fixture function is an [`async` function](#async) your fixture become an `async`
277 /// fixture.
278 ///
279 /// # Default values
280 ///
281 /// If you need to define argument default value you can use `#[default(expression)]`
282 /// argument's attribute:
283 ///
284 /// ```
285 /// use rstest::*;
286 ///
287 /// #[fixture]
288 /// fn injected(
289 /// #[default(21)]
290 /// twenty_one: i32,
291 /// #[default(1 + 1)]
292 /// two: i32
293 /// ) -> i32 { twenty_one * two }
294 ///
295 /// #[rstest]
296 /// fn the_test(injected: i32) {
297 /// assert_eq!(42, injected)
298 /// }
299 /// ```
300 /// The `expression` could be any valid rust expression, even an `async` block if you need.
301 /// Moreover, if the type implements `FromStr` trait you can use a literal string to build it.
302 ///
303 /// ```
304 /// # use rstest::*;
305 /// # use std::net::SocketAddr;
306 /// # struct DbConnection {}
307 /// #[fixture]
308 /// fn db_connection(
309 /// #[default("127.0.0.1:9000")]
310 /// addr: SocketAddr
311 /// ) -> DbConnection {
312 /// // create connection
313 /// # DbConnection{}
314 /// }
315 /// ```
316 ///
317 /// # Async
318 ///
319 /// If you need you can write `async` fixtures to use in your `async` tests. Simply use `async`
320 /// keyword for your function and the fixture become an `async` fixture.
321 ///
322 /// ```
323 /// use rstest::*;
324 ///
325 /// #[fixture]
326 /// async fn async_fixture() -> i32 { 42 }
327 ///
328 ///
329 /// #[rstest]
330 /// #[tokio::test]
331 /// async fn the_test(#[future] async_fixture: i32) {
332 /// assert_eq!(42, async_fixture.await)
333 /// }
334 /// ```
335 /// The `#[future]` argument attribute helps to remove the `impl Future<Output = T>` boilerplate.
336 /// In this case the macro expands it in:
337 ///
338 /// ```
339 /// # use rstest::*;
340 /// # use std::future::Future;
341 /// # #[fixture]
342 /// # async fn async_fixture() -> i32 { 42 }
343 /// #[rstest]
344 /// #[tokio::test]
345 /// async fn the_test(async_fixture: impl std::future::Future<Output = i32>) {
346 /// assert_eq!(42, async_fixture.await)
347 /// }
348 /// ```
349 /// If you need, you can use `#[future]` attribute also with an implicit lifetime reference
350 /// because the macro will replace the implicit lifetime with an explicit one.
351 ///
352 /// # Rename
353 ///
354 /// Sometimes you want to have long and descriptive name for your fixture but you prefer to use a much
355 /// shorter name for argument that represent it in your fixture or test. You can rename the fixture
356 /// using `#[from(short_name)]` attribute like following example:
357 ///
358 /// ## Destructuring
359 ///
360 /// It's possible to destructure the fixture type but, in this case, your're forced to use renaming syntax
361 /// because it's not possible to guess the fixture name from this syntax:
362 ///
363 /// ```
364 /// use rstest::*;
365 /// #[fixture]
366 /// fn two_values() -> (u32, u32) { (42, 24) }
367 ///
368 /// #[rstest]
369 /// fn the_test(#[from(two_values)] (first, _): (u32, u32)) {
370 /// assert_eq!(42, first)
371 /// }
372 /// ```
373 ///
374 /// ```
375 /// use rstest::*;
376 ///
377 /// #[fixture]
378 /// fn long_and_boring_descriptive_name() -> i32 { 42 }
379 ///
380 /// #[rstest]
381 /// fn the_test(#[from(long_and_boring_descriptive_name)] short: i32) {
382 /// assert_eq!(42, short)
383 /// }
384 /// ```
385 ///
386 /// This feature can also be useful when you don't want to declare the `use` of a fixture or simple
387 /// use the fixture's path:
388 ///
389 /// ```
390 /// use rstest::*;
391 ///
392 /// # mod magic_numbers {
393 /// # use rstest::*;
394 /// # #[fixture]
395 /// # pub fn fortytwo() -> i32 { 42 }
396 /// # }
397 /// #[rstest]
398 /// fn the_test(#[from(magic_numbers::fortytwo)] x: i32) {
399 /// assert_eq!(42, x)
400 /// }
401 /// ```
402 ///
403 /// # `#[once]` Fixture
404 ///
405 /// Especially in integration tests there are cases where you need a fixture that is called just once
406 /// for every tests. `rstest` provides `#[once]` attribute for these cases.
407 ///
408 /// If you mark your fixture with this attribute, then `rstest` will compute a static reference to your
409 /// fixture result and return this reference to all your tests that need this fixture.
410 ///
411 /// In follow example all tests share the same reference to the `42` static value.
412 ///
413 /// ```
414 /// use rstest::*;
415 ///
416 /// #[fixture]
417 /// #[once]
418 /// fn once_fixture() -> i32 { 42 }
419 ///
420 /// // Take care!!! You need to use a reference to the fixture value
421 ///
422 /// #[rstest]
423 /// #[case(1)]
424 /// #[case(2)]
425 /// fn cases_tests(once_fixture: &i32, #[case] v: i32) {
426 /// // Take care!!! You need to use a reference to the fixture value
427 /// assert_eq!(&42, once_fixture)
428 /// }
429 ///
430 /// #[rstest]
431 /// fn single(once_fixture: &i32) {
432 /// assert_eq!(&42, once_fixture)
433 /// }
434 /// ```
435 ///
436 /// There are some limitations when you use `#[once]` fixture. `rstest` forbid to use once fixture
437 /// for:
438 ///
439 /// - `async` function
440 /// - Generic function (both with generic types or use `impl` trait)
441 ///
442 /// Take care that the `#[once]` fixture value will **never be dropped**.
443 ///
444 /// # Partial Injection
445 ///
446 /// You can also partially inject fixture dependency using `#[with(v1, v2, ..)]` attribute:
447 ///
448 /// ```
449 /// use rstest::*;
450 ///
451 /// #[fixture]
452 /// fn base() -> i32 { 1 }
453 ///
454 /// #[fixture]
455 /// fn first(base: i32) -> i32 { 1 * base }
456 ///
457 /// #[fixture]
458 /// fn second(base: i32) -> i32 { 2 * base }
459 ///
460 /// #[fixture]
461 /// fn injected(first: i32, #[with(3)] second: i32) -> i32 { first * second }
462 ///
463 /// #[rstest]
464 /// fn the_test(injected: i32) {
465 /// assert_eq!(-6, injected)
466 /// }
467 /// ```
468 /// Note that injected value can be an arbitrary rust expression. `#[with(v1, ..., vn)]`
469 /// attribute will inject `v1, ..., vn` expression as fixture arguments: all remaining arguments
470 /// will be resolved as fixtures.
471 ///
472 /// Sometimes the return type cannot be inferred so you must define it: For the few times you may
473 /// need to do it, you can use the `#[default(type)]`, `#[partial_n(type)]` function attribute
474 /// to define it:
475 ///
476 /// ```
477 /// use rstest::*;
478 /// # use std::fmt::Debug;
479 ///
480 /// #[fixture]
481 /// pub fn i() -> u32 {
482 /// 42
483 /// }
484 ///
485 /// #[fixture]
486 /// pub fn j() -> i32 {
487 /// -42
488 /// }
489 ///
490 /// #[fixture]
491 /// #[default(impl Iterator<Item=(u32, i32)>)]
492 /// #[partial_1(impl Iterator<Item=(I,i32)>)]
493 /// pub fn fx<I, J>(i: I, j: J) -> impl Iterator<Item=(I, J)> {
494 /// std::iter::once((i, j))
495 /// }
496 ///
497 /// #[rstest]
498 /// fn resolve_by_default(mut fx: impl Iterator<Item=(u32, i32)>) {
499 /// assert_eq!((42, -42), fx.next().unwrap())
500 /// }
501 ///
502 /// #[rstest]
503 /// fn resolve_partial(#[with(42.0)] mut fx: impl Iterator<Item=(f32, i32)>) {
504 /// assert_eq!((42.0, -42), fx.next().unwrap())
505 /// }
506 /// ```
507 /// `partial_i` is the fixture used when you inject the first `i` arguments in test call.
508 ///
509 /// # Old _compact_ syntax
510 ///
511 /// There is also a compact form for all previous features. This will maintained for a long time
512 /// but for `fixture` I strongly recommend to migrate your code because you'll pay a little
513 /// verbosity but get back a more readable code.
514 ///
515 /// Follow the previous examples in old _compact_ syntax.
516 ///
517 /// ## Default
518 /// ```
519 /// # use rstest::*;
520 /// #[fixture(twenty_one=21, two=2)]
521 /// fn injected(twenty_one: i32, two: i32) -> i32 { twenty_one * two }
522 /// ```
523 ///
524 /// ## Rename
525 /// ```
526 /// # use rstest::*;
527 /// #[fixture]
528 /// fn long_and_boring_descriptive_name() -> i32 { 42 }
529 ///
530 /// #[rstest(long_and_boring_descriptive_name as short)]
531 /// fn the_test(short: i32) {
532 /// assert_eq!(42, short)
533 /// }
534 /// ```
535 ///
536 /// ## Partial Injection
537 /// ```
538 /// # use rstest::*;
539 /// # #[fixture]
540 /// # fn base() -> i32 { 1 }
541 /// #
542 /// # #[fixture]
543 /// # fn first(base: i32) -> i32 { 1 * base }
544 /// #
545 /// # #[fixture]
546 /// # fn second(base: i32) -> i32 { 2 * base }
547 /// #
548 /// #[fixture(second(-3))]
549 /// fn injected(first: i32, second: i32) -> i32 { first * second }
550 /// ```
551 /// ## Partial Type Injection
552 /// ```
553 /// # use rstest::*;
554 /// # use std::fmt::Debug;
555 /// #
556 /// # #[fixture]
557 /// # pub fn i() -> u32 {
558 /// # 42
559 /// # }
560 /// #
561 /// # #[fixture]
562 /// # pub fn j() -> i32 {
563 /// # -42
564 /// # }
565 /// #
566 /// #[fixture(::default<impl Iterator<Item=(u32, i32)>>::partial_1<impl Iterator<Item=(I,i32)>>)]
567 /// pub fn fx<I, J>(i: I, j: J) -> impl Iterator<Item=(I, J)> {
568 /// std::iter::once((i, j))
569 /// }
570 /// ```
571 pub use rstest_macros::fixture;
572
573 /// The attribute that you should use for your tests. Your
574 /// annotated function's arguments can be
575 /// [injected](attr.rstest.html#injecting-fixtures) with
576 /// [`fixture`](macro@fixture)s, provided by
577 /// [parametrized cases](attr.rstest.html#test-parametrized-cases)
578 /// or by [value lists](attr.rstest.html#values-lists).
579 ///
580 /// `rstest` attribute can be applied to _any_ function and you can customize its
581 /// parameters by using function and arguments attributes.
582 ///
583 /// Your test function can use generics, `impl` or `dyn` and like any kind of rust tests:
584 ///
585 /// - return results
586 /// - marked by `#[should_panic]` attribute
587 ///
588 /// In the function signature, where you define your tests inputs, you can also destructuring
589 /// the values like any other rust function.
590 ///
591 /// If the test function is an [`async` function](#async) `rstest` will run all cases as `async`
592 /// tests. However, async tests must supply either an [explicit test attribute](#explicit-test-attributes)
593 /// or an [implicit test attribute](#implicit-test-attributes).
594 ///
595 /// In your test function you can:
596 ///
597 /// - [inject fixtures](#injecting-fixtures)
598 /// - Generate [parametrized test cases](#test-parametrized-cases)
599 /// - Generate tests for each combination of [value lists](#values-lists)
600 /// - Feed variables from [files](#files-path-as-input-arguments)
601 ///
602 /// Additional Attributes:
603 ///
604 /// - Function Attributes:
605 /// - [`#[case]`](#test-parametrized-cases) define a parametrized test case
606 /// - [`#[awt]`](#async) await all your future test function's inputs
607 /// - [`#[timeout(...)]`](#test-timeout) define a test timeout
608 /// - [`#[trace]`](#trace-input-arguments) tracing input arguments
609 /// - [`#[test_attr(...)]`](#explicit-test-attr) define an explicit test attribute
610 /// - Arguments Attributes:
611 /// - [`#[case]`](#test-parametrized-cases) define an argument parametrized by test cases
612 /// - [`#[values(...)]`](#values-lists) define an argument that can be a list of values
613 /// - [`#[files(...)]`-`#[exclude(...)]`-`#[base_dir = ... ]`-`#[mode = ...]`](#files-path-as-input-arguments)
614 /// define an argument that can be a list of path based on a glob pattern
615 /// - [`#[from(...)]`-`#[with(...)]`](#injecting-fixtures) handling injected fixture
616 /// - [`#[future]`](#async) implement future boilerplate argument
617 /// - [`#[context]`](#test-context-object) Some metadata test information
618 /// - [`#[by_ref]`](#local-lifetime-and-by_ref-attribute) define a local lifetime
619 /// - [`#[ignore]`](#ignoring-arguments) ignore an argument used by a custom test function
620 /// - [`#[notrace]`](#trace-input-arguments) disable trace
621 ///
622 /// ## Injecting Fixtures
623 ///
624 /// The simplest case is write a test that can be injected with
625 /// [`[fixture]`](macro@fixture)s. You can just declare all used fixtures by passing
626 /// them as a function's arguments. This can help your test to be neat
627 /// and make your dependency clear.
628 ///
629 /// ```
630 /// use rstest::*;
631 ///
632 /// #[fixture]
633 /// fn injected() -> i32 { 42 }
634 ///
635 /// #[rstest]
636 /// fn the_test(injected: i32) {
637 /// assert_eq!(42, injected)
638 /// }
639 /// ```
640 ///
641 /// [`[rstest]`](macro@rstest) procedural macro will desugar it to something that isn't
642 /// so far from
643 ///
644 /// ```
645 /// #[test]
646 /// fn the_test() {
647 /// let injected=injected();
648 /// assert_eq!(42, injected)
649 /// }
650 /// ```
651 ///
652 /// If you want to use long and descriptive names for your fixture but prefer to use
653 /// shorter names inside your tests you use rename feature described in
654 /// [fixture rename](attr.fixture.html#rename):
655 ///
656 /// ```
657 /// use rstest::*;
658 ///
659 /// #[fixture]
660 /// fn long_and_boring_descriptive_name() -> i32 { 42 }
661 ///
662 /// #[rstest]
663 /// fn the_test(#[from(long_and_boring_descriptive_name)] short: i32) {
664 /// assert_eq!(42, short)
665 /// }
666 /// ```
667 ///
668 /// The use of `#[from(...)]` attribute is mandatory if you need to destructure the value:
669 ///
670 /// ```
671 /// use rstest::*;
672 ///
673 /// #[fixture]
674 /// fn tuple() -> (u32, f32) { (42, 42.0) }
675 ///
676 /// #[rstest]
677 /// fn the_test(#[from(tuple)] (u, _): (u32, f32)) {
678 /// assert_eq!(42, u)
679 /// }
680 /// ```
681 ///
682 /// Sometimes is useful to have some parameters in your fixtures but your test would
683 /// override the fixture's default values in some cases. Like in
684 /// [fixture partial injection](attr.fixture.html#partial-injection) you use `#[with]`
685 /// attribute to indicate some fixture's arguments also in `rstest`.
686 ///
687 /// ```
688 /// # struct User(String, u8);
689 /// # impl User { fn name(&self) -> &str {&self.0} }
690 /// use rstest::*;
691 ///
692 /// #[fixture]
693 /// fn user(
694 /// #[default("Alice")] name: impl AsRef<str>,
695 /// #[default(22)] age: u8
696 /// ) -> User { User(name.as_ref().to_owned(), age) }
697 ///
698 /// #[rstest]
699 /// fn check_user(#[with("Bob")] user: User) {
700 /// assert_eq("Bob", user.name())
701 /// }
702 /// ```
703 ///
704 /// ## Test Parametrized Cases
705 ///
706 /// If you would execute your test for a set of input data cases
707 /// you can define the arguments to use and the cases list. Let see
708 /// the classical Fibonacci example. In this case we would give the
709 /// `input` value and the `expected` result for a set of cases to test.
710 ///
711 /// ```
712 /// use rstest::rstest;
713 ///
714 /// #[rstest]
715 /// #[case(0, 0)]
716 /// #[case(1, 1)]
717 /// #[case(2, 1)]
718 /// #[case(3, 2)]
719 /// #[case(4, 3)]
720 /// fn fibonacci_test(#[case] input: u32,#[case] expected: u32) {
721 /// assert_eq!(expected, fibonacci(input))
722 /// }
723 ///
724 /// fn fibonacci(input: u32) -> u32 {
725 /// match input {
726 /// 0 => 0,
727 /// 1 => 1,
728 /// n => fibonacci(n - 2) + fibonacci(n - 1)
729 /// }
730 /// }
731 /// ```
732 ///
733 /// `rstest` will produce 5 independent tests and not just one that
734 /// check every case. Every test can fail independently and `cargo test`
735 /// will give follow output:
736 ///
737 /// ```text
738 /// running 5 tests
739 /// test fibonacci_test::case_1 ... ok
740 /// test fibonacci_test::case_2 ... ok
741 /// test fibonacci_test::case_3 ... ok
742 /// test fibonacci_test::case_4 ... ok
743 /// test fibonacci_test::case_5 ... ok
744 ///
745 /// test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
746 /// ```
747 ///
748 /// The cases input values can be arbitrary Rust expressions that return the
749 /// argument type.
750 ///
751 /// ```
752 /// use rstest::rstest;
753 ///
754 /// fn sum(a: usize, b: usize) -> usize { a + b }
755 ///
756 /// #[rstest]
757 /// #[case("foo", 3)]
758 /// #[case(String::from("foo"), 2 + 1)]
759 /// #[case(format!("foo"), sum(2, 1))]
760 /// fn test_len(#[case] s: impl AsRef<str>,#[case] len: usize) {
761 /// assert_eq!(s.as_ref().len(), len);
762 /// }
763 /// ```
764 /// ### Feature flagged cases
765 ///
766 /// In case you want certain test cases to only be present if a certain feature is
767 /// enabled, use `#[cfg_attr(feature = …, case(…))]`:
768 ///
769 /// ```
770 /// use rstest::rstest;
771 ///
772 /// #[rstest]
773 /// #[case(2, 2)]
774 /// #[cfg_attr(feature = "frac", case(4/2, 2))]
775 /// fn it_works(#[case] a: u32, #[case] b: u32) {
776 /// assert!(a == b);
777 /// }
778 /// ```
779 ///
780 /// This also works with [`rstest_reuse`](https://crates.io/crates/rstest_reuse).
781 ///
782 /// ### Magic Conversion
783 ///
784 /// You can use the magic conversion feature every time you would define a variable
785 /// where its type define `FromStr` trait: test will parse the string to build the value.
786 ///
787 /// ```
788 /// # use rstest::rstest;
789 /// # use std::path::PathBuf;
790 /// # fn count_words(path: PathBuf) -> usize {0}
791 /// #[rstest]
792 /// #[case("resources/empty", 0)]
793 /// #[case("resources/divine_comedy", 101.698)]
794 /// fn test_count_words(#[case] path: PathBuf, #[case] expected: usize) {
795 /// assert_eq!(expected, count_words(path))
796 /// }
797 /// ```
798 ///
799 /// ### Optional case description
800 ///
801 /// Optionally you can give a _description_ to every case simple by follow `case`
802 /// with `::my_case_description` where `my_case_description` should be a a valid
803 /// Rust ident.
804 ///
805 /// ```
806 /// # use rstest::*;
807 /// #[rstest]
808 /// #[case::zero_base_case(0, 0)]
809 /// #[case::one_base_case(1, 1)]
810 /// #[case(2, 1)]
811 /// #[case(3, 2)]
812 /// fn fibonacci_test(#[case] input: u32,#[case] expected: u32) {
813 /// assert_eq!(expected, fibonacci(input))
814 /// }
815 ///
816 /// # fn fibonacci(input: u32) -> u32 {
817 /// # match input {
818 /// # 0 => 0,
819 /// # 1 => 1,
820 /// # n => fibonacci(n - 2) + fibonacci(n - 1)
821 /// # }
822 /// # }
823 /// ```
824 ///
825 /// Output will be
826 /// ```text
827 /// running 4 tests
828 /// test fibonacci_test::case_1_zero_base_case ... ok
829 /// test fibonacci_test::case_2_one_base_case ... ok
830 /// test fibonacci_test::case_3 ... ok
831 /// test fibonacci_test::case_4 ... ok
832 ///
833 /// test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
834 /// ```
835 ///
836 /// ### Use specific `case` attributes
837 ///
838 /// Every function's attributes that preceding a `#[case]` attribute will
839 /// be used in this test case and all function's attributes that follow the
840 /// last `#[case]` attribute will mark all test cases.
841 ///
842 /// This feature can be use to mark just some cases as `should_panic`
843 /// and choose to have a fine grain on expected panic messages.
844 ///
845 /// In follow example we run 3 tests where the first pass without any
846 /// panic, in the second we catch a panic but we don't care about the message
847 /// and in the third one we also check the panic message.
848 ///
849 /// ```
850 /// use rstest::rstest;
851 ///
852 /// #[rstest]
853 /// #[case::no_panic(0)]
854 /// #[should_panic]
855 /// #[case::panic(1)]
856 /// #[should_panic(expected="expected")]
857 /// #[case::panic_with_message(2)]
858 /// fn attribute_per_case(#[case] val: i32) {
859 /// match val {
860 /// 0 => assert!(true),
861 /// 1 => panic!("No catch"),
862 /// 2 => panic!("expected"),
863 /// _ => unreachable!(),
864 /// }
865 /// }
866 /// ```
867 ///
868 /// Output:
869 ///
870 /// ```text
871 /// running 3 tests
872 /// test attribute_per_case::case_1_no_panic ... ok
873 /// test attribute_per_case::case_3_panic_with_message ... ok
874 /// test attribute_per_case::case_2_panic ... ok
875 ///
876 /// test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
877 /// ```
878 ///
879 /// To mark all your tests as `#[should_panic]` use:
880 ///
881 /// ```
882 /// # use rstest::rstest;
883 /// #[rstest]
884 /// #[case(1)]
885 /// #[case(2)]
886 /// #[case(3)]
887 /// #[should_panic]
888 /// fn fail(#[case] v: u32) { assert_eq!(0, v) }
889 /// ```
890 ///
891 /// ## Values Lists
892 ///
893 /// Another useful way to write a test and execute it for some values
894 /// is to use the values list syntax. This syntax can be useful both
895 /// for a plain list and for testing all combination of input arguments.
896 ///
897 /// ```
898 /// # use rstest::*;
899 /// # fn is_valid(input: &str) -> bool { true }
900 ///
901 /// #[rstest]
902 /// fn should_be_valid(
903 /// #[values("John", "alice", "My_Name", "Zigy_2001")]
904 /// input: &str
905 /// ) {
906 /// assert!(is_valid(input))
907 /// }
908 /// ```
909 ///
910 /// or
911 ///
912 /// ```
913 /// # use rstest::*;
914 /// # fn valid_user(name: &str, age: u8) -> bool { true }
915 ///
916 /// #[rstest]
917 /// fn should_accept_all_corner_cases(
918 /// #[values("J", "A", "A________________________________________21")]
919 /// name: &str,
920 /// #[values(14, 100)]
921 /// age: u8
922 /// ) {
923 /// assert!(valid_user(name, age))
924 /// }
925 /// ```
926 /// where `cargo test` output is
927 ///
928 /// ```text
929 /// test should_accept_all_corner_cases::name_1___J__::age_2_100 ... ok
930 /// test should_accept_all_corner_cases::name_2___A__::age_1_14 ... ok
931 /// test should_accept_all_corner_cases::name_2___A__::age_2_100 ... ok
932 /// test should_accept_all_corner_cases::name_3___A________________________________________21__::age_2_100 ... ok
933 /// test should_accept_all_corner_cases::name_3___A________________________________________21__::age_1_14 ... ok
934 /// test should_accept_all_corner_cases::name_1___J__::age_1_14 ... ok
935 ///
936 /// test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
937 /// ```
938 /// Note that the test names contains the given expression sanitized into
939 /// a valid Rust identifier name. This should help to identify which case fails.
940 ///
941 /// If you prefer to provide an explicit name you can use doc comments before
942 /// each value inside the `#[values(...)]` attribute:
943 ///
944 /// ```
945 /// # use rstest::rstest;
946 /// #[rstest]
947 /// fn describe_values(
948 /// #[values(
949 /// /// short_value
950 /// 42,
951 /// /// long_value
952 /// 100,
953 /// )]
954 /// value: u32,
955 /// ) {
956 /// assert!(value > 0);
957 /// }
958 /// ```
959 ///
960 /// The generated tests will be named `value_1_short_value` and
961 /// `value_2_long_value` instead of using the raw expression text.
962 ///
963 ///
964 /// Also value list implements the magic conversion feature: every time the value type
965 /// implements `FromStr` trait you can use a literal string to define it.
966 ///
967 /// ```
968 /// # use rstest::rstest;
969 /// # use std::net::SocketAddr;
970 /// #[rstest]
971 /// fn given_port(#[values("1.2.3.4:8000", "4.3.2.1:8000", "127.0.0.1:8000")] addr: SocketAddr) {
972 /// assert_eq!(8000, addr.port())
973 /// }
974 /// ```
975 ///
976 /// ## Destructuring inputs
977 ///
978 /// Both parametrized case and values can be destructured:
979 ///
980 /// ```
981 /// # use rstest::*;
982 /// struct S {
983 /// first: u32,
984 /// second: u32,
985 /// }
986 ///
987 /// struct T(i32);
988 ///
989 /// #[rstest]
990 /// #[case(S{first: 21, second: 42})]
991 /// fn some_test(#[case] S{first, second} : S, #[values(T(-1), T(1))] T(t): T) {
992 /// assert_eq!(1, t * t);
993 /// assert_eq!(2 * first, second);
994 /// }
995 /// ```
996 ///
997 /// ## Files path as input arguments
998 ///
999 /// If you need to create a test for each file in a given location you can use
1000 /// `#[files("glob path syntax")]` attribute to generate a test for each file that
1001 /// satisfy the given glob path.
1002 ///
1003 /// ```
1004 /// # use rstest::rstest;
1005 /// # use std::path::{Path, PathBuf};
1006 /// # fn check_file(path: &Path) -> bool { true };
1007 /// #[rstest]
1008 /// fn for_each_file(#[files("src/**/*.rs")] #[exclude("test")] path: PathBuf) {
1009 /// assert!(check_file(&path))
1010 /// }
1011 /// ```
1012 ///
1013 /// The default behavior is to ignore the files that start with `"."`, but you can
1014 /// modify this by use `#[include_dot_files]` attribute. The `files` attribute can be
1015 /// used more than once on the same variable, and you can also create some custom
1016 /// exclusion rules with the `#[exclude("regex")]` attributes that filter out all
1017 /// paths that verify the regular expression.
1018 ///
1019 /// Sometime is useful to have test files in a workspace folder to share them between the
1020 /// crates in your workspace. You can do that by use the usual parent folders `..` in
1021 /// the glob path. In this case the test names will be the relative path from the crate root
1022 /// where the parent folder components are replaced by `_UP`: for instance if you have a
1023 /// `valid_call.yaml` in the folder `../test_cases` (from your crate root) a test name could be
1024 /// `path_1__UP_test_cases_valid_call_yaml`.
1025 ///
1026 /// If you want to change the base path for the test files. You can do that by using
1027 /// `#[base_dir = "..."]` attribute. The `base_dir` is resolved relative to the crate root
1028 /// (similar to the `files` attribute without `base_dir`). If you want to use an absolute
1029 /// path you can use `#[base_dir = "/path/to/your/files"]`.
1030 ///
1031 /// Both `files` and `base_dir` attributes can use environment variables using the syntax
1032 /// `$VAR` or `${VAR}`. If the environment variable is not set, the attribute will cause
1033 /// an error. This can be ignored using the `#[ignore_missing_env_vars]` attribute. A
1034 /// default value can be provided for the environment variable using the syntax
1035 /// `${VAR:-default}` (similar to bash). This can be really useful when you want to override
1036 /// the cargo root on some environments: use `#[base_dir = "BASE_TEST_DIR:-"]` do the trick.
1037 ///
1038 /// The `#[files(...)]` attribute ignores matched directory paths by default,
1039 /// returning only file paths. If you need the test cases to include directories
1040 /// found by the glob pattern, use the `#[dirs]` attribute in conjunction with `#[files(...)]`.
1041 ///
1042 /// Finally, often you would to recompile tests sources when file the folders or the
1043 /// environment variables changed. In this case you should provide a `build.rs` script file
1044 /// that tell to the compiler what to look in order to recompile the tests. For instance
1045 /// follow a simple example:
1046 ///
1047 /// ```ignore
1048 /// pub fn main() {
1049 /// println!("cargo::rerun-if-changed=tests/resources");
1050 /// println!("cargo::rerun-if-env-changed=BASE_TEST_DIR");
1051 /// }
1052 /// ```
1053 ///
1054 /// ### `#[mode = ...]`
1055 ///
1056 /// Using the `#[mode = ...]` attribute on an argument tagged with
1057 /// `#[files(...)]` and friends will set the way the file is passed as an argument.
1058 /// It accepts the following arguments with the following behaviour:
1059 ///
1060 /// - `path`: the default behaviour, passes each file path as a [PathBuf][std::path::PathBuf].
1061 /// - `str`: passes the contents of each file as a [&str][str] using [include_str].
1062 /// - `bytes`: passes the contents of each files as a `&[u8]` using [include_bytes].
1063 ///
1064 /// Trying to pass directories as arguments will cause a compile error when using `str` and
1065 /// `bytes`.
1066 ///
1067 /// ```
1068 /// # use rstest::rstest;
1069 /// # use std::path::PathBuf;
1070 /// # use std::fs::read_to_string;
1071 /// #[rstest]
1072 /// fn for_each_path(
1073 /// #[files("src/**/*.rs")] #[exclude("test")] #[mode = path] path: PathBuf
1074 /// ) {
1075 /// let contents = read_to_string(path).unwrap();
1076 /// assert!(contents.len() >= 0)
1077 /// }
1078 ///
1079 /// #[rstest]
1080 /// fn for_each_txt_file(
1081 /// #[files("src/**/*.rs")] #[exclude("test")] #[mode = str] contents: &str
1082 /// ) {
1083 /// assert!(contents.len() >= 0)
1084 /// }
1085 ///
1086 /// #[rstest]
1087 /// fn for_each_bin_file(
1088 /// #[files("src/**/*.rs")] #[exclude("test")] #[mode = bytes] contents: &[u8]
1089 /// ) {
1090 /// assert!(contents.len() >= 0)
1091 /// }
1092 /// ```
1093 ///
1094 /// ## Use Parametrize definition in more tests
1095 ///
1096 /// If you need to use a test list for more than one test you can use
1097 /// [`rstest_reuse`](https://crates.io/crates/rstest_reuse) crate.
1098 /// With this helper crate you can define a template and use it everywhere.
1099 ///
1100 /// ```rust,ignore
1101 /// use rstest::rstest;
1102 /// use rstest_reuse::{self, *};
1103 ///
1104 /// #[template]
1105 /// #[rstest]
1106 /// #[case(2, 2)]
1107 /// #[case(4/2, 2)]
1108 /// fn two_simple_cases(#[case] a: u32, #[case] b: u32) {}
1109 ///
1110 /// #[apply(two_simple_cases)]
1111 /// fn it_works(#[case] a: u32,#[case] b: u32) {
1112 /// assert_eq!(a, b);
1113 /// }
1114 /// ```
1115 ///
1116 /// See [`rstest_reuse`](https://crates.io/crates/rstest_reuse) for more details.
1117 ///
1118 /// ## Async
1119 ///
1120 /// `rstest` supports async tests, but makes no assumptions about what
1121 /// async runtime you are using. Async tests require either an
1122 /// [explicit test attribute](#explicit-test-attributes) or an
1123 /// [implicit test attribute](#implicit-test-attributes).
1124 ///
1125 /// You are responsible for providing any appropriate peer dependencies to run your async tests.
1126 ///
1127 /// If your test input is an async value (fixture or test parameter) you can use `#[future]`
1128 /// attribute to remove `impl Future<Output = T>` boilerplate and just use `T`:
1129 ///
1130 /// ```
1131 /// use rstest::*;
1132 /// #[fixture]
1133 /// async fn base() -> u32 { 42 }
1134 ///
1135 /// #[rstest]
1136 /// #[case(21, async { 2 })]
1137 /// #[case(6, async { 7 })]
1138 /// #[tokio::test]
1139 /// async fn my_async_test(#[future] base: u32, #[case] expected: u32, #[future] #[case] div: u32) {
1140 /// assert_eq!(expected, base.await / div.await);
1141 /// }
1142 /// ```
1143 ///
1144 /// As you noted you should `.await` all _future_ values and this some times can be really boring.
1145 /// In this case you can use `#[future(awt)]` to _awaiting_ an input or annotating your function
1146 /// with `#[awt]` attributes to globally `.await` all your _future_ inputs. Previous code can be
1147 /// simplified like follow:
1148 ///
1149 /// ```
1150 /// use rstest::*;
1151 /// # #[fixture]
1152 /// # async fn base() -> u32 { 42 }
1153 ///
1154 /// #[rstest]
1155 /// #[case(21, async { 2 })]
1156 /// #[case(6, async { 7 })]
1157 /// #[tokio::test]
1158 /// #[awt]
1159 /// async fn global(#[future] base: u32, #[case] expected: u32, #[future] #[case] div: u32) {
1160 /// assert_eq!(expected, base / div);
1161 /// }
1162 ///
1163 /// #[rstest]
1164 /// #[case(21, async { 2 })]
1165 /// #[case(6, async { 7 })]
1166 /// #[tokio::test]
1167 /// async fn single(#[future] base: u32, #[case] expected: u32, #[future(awt)] #[case] div: u32) {
1168 /// assert_eq!(expected, base.await / div);
1169 /// }
1170 /// ```
1171 ///
1172 /// ### Test `#[timeout()]`
1173 ///
1174 /// You can define an execution timeout for your tests with `#[timeout(<duration>)]` attribute. Timeout
1175 /// works both for sync and async tests and is runtime agnostic. `#[timeout(<duration>)]` take an
1176 /// expression that should return a `std::time::Duration`. Follow a simple async example:
1177 ///
1178 /// ```rust
1179 /// use rstest::*;
1180 /// use std::time::Duration;
1181 ///
1182 /// async fn delayed_sum(a: u32, b: u32,delay: Duration) -> u32 {
1183 /// async_std::task::sleep(delay).await;
1184 /// a + b
1185 /// }
1186 ///
1187 /// #[rstest]
1188 /// #[timeout(Duration::from_millis(80))]
1189 /// #[async_std::test]
1190 /// async fn single_pass() {
1191 /// assert_eq!(4, delayed_sum(2, 2, ms(10)).await);
1192 /// }
1193 /// ```
1194 /// In this case test pass because the delay is just 10 milliseconds and timeout is
1195 /// 80 milliseconds.
1196 ///
1197 /// You can use `timeout` attribute like any other attribute in your tests, and you can
1198 /// override a group timeout with a test specific one. In the follow example we have
1199 /// 3 tests where first and third use 100 milliseconds but the second one use 10 milliseconds.
1200 /// Another valuable point in this example is to use an expression to compute the
1201 /// duration.
1202 ///
1203 /// ```rust
1204 /// # use rstest::*;
1205 /// # use std::time::Duration;
1206 /// #
1207 /// # async fn delayed_sum(a: u32, b: u32,delay: Duration) -> u32 {
1208 /// # async_std::task::sleep(delay).await;
1209 /// # a + b
1210 /// # }
1211 /// fn ms(ms: u32) -> Duration {
1212 /// Duration::from_millis(ms.into())
1213 /// }
1214 ///
1215 /// #[rstest]
1216 /// #[case::pass(ms(1), 4)]
1217 /// #[timeout(ms(10))]
1218 /// #[case::fail_timeout(ms(60), 4)]
1219 /// #[case::fail_value(ms(1), 5)]
1220 /// #[timeout(ms(100))]
1221 /// #[async_std::test]
1222 /// async fn group_one_timeout_override(#[case] delay: Duration, #[case] expected: u32) {
1223 /// assert_eq!(expected, delayed_sum(2, 2, delay).await);
1224 /// }
1225 /// ```
1226 ///
1227 /// If you want to use `timeout` for `async` test you need to use `async-timeout`
1228 /// feature (enabled by default).
1229 ///
1230 /// ### Default timeout
1231 ///
1232 /// You can set a default timeout for test using the `RSTEST_TIMEOUT` environment variable.
1233 /// The value is in seconds and is evaluated on test compile time.
1234 ///
1235 /// ## Test Attributes
1236 ///
1237 /// ### Explicit Test Attributes
1238 ///
1239 /// If your test contains an attribute `#[test_attr(...)]`, this is an explicit test attribute declaration.
1240 /// The contents of the parentheses will be inserted as an attribute of your test. This allows for arbitrary
1241 /// test attribute syntax.
1242 ///
1243 /// For instance, if you want to test an async function with [`smol_macros::test`](https://docs.rs/smol-macros/0.1.1/smol_macros/macro.test.html),
1244 /// you can write
1245 ///
1246 /// ```rust
1247 /// use rstest::*;
1248 /// use macro_rules_attribute::apply;
1249 /// use smol_macros::test;
1250 /// use std::future::Future;
1251 ///
1252 /// #[rstest]
1253 /// #[case(2, async { 4 })]
1254 /// #[case(21, async { 42 })]
1255 /// #[test_attr(apply(test))]
1256 /// async fn my_async_test(#[case] a: u32, #[case] #[future] result: u32) {
1257 /// assert_eq!(2 * a, result.await);
1258 /// }
1259 /// ```
1260 ///
1261 /// ### Implicit Test Attributes
1262 ///
1263 /// If your test contains an attribute whose path ends in `test`, this is treated
1264 /// as an implicit test attribute, and replaces the default `#[test]` attribute.
1265 /// Simply including the attribute in your test's attribute list is all that is required.
1266 ///
1267 /// For instance, if you want to test an async function with the `actix_rt::test` attribute, you can just write:
1268 ///
1269 /// ```rust
1270 /// use rstest::*;
1271 /// use actix_rt;
1272 /// use std::future::Future;
1273 ///
1274 /// #[rstest]
1275 /// #[case(2, async { 4 })]
1276 /// #[case(21, async { 42 })]
1277 /// #[actix_rt::test]
1278 /// async fn my_async_test(#[case] a: u32, #[case] #[future] result: u32) {
1279 /// assert_eq!(2 * a, result.await);
1280 /// }
1281 /// ```
1282 ///
1283 /// Implicit test attributes have a lower priority than [`explicit test attributes`](#explicit-test-attribute).
1284 /// If you have an unrelated attribute whose path ends in `test`, you should declare an explicit test attribute
1285 /// for deconfliction.
1286 ///
1287 /// ### Default Test Attributes
1288 ///
1289 /// Synchronous tests use `#[test]` as the default test attribute if nothing else is supplied explicitly or implicitly.
1290 ///
1291 /// Asynchronous tests will fail to compile if no test attribute is specified explicitly or implicitly.
1292 ///
1293 /// ## Test `Context` object
1294 ///
1295 /// You can have a [`Context`] object for your test by annotating an argument by `#[context]` attribute.
1296 /// This object contains some useful information both to implement simple logics and debugging stuff.
1297 ///
1298 /// ```
1299 /// use rstest::{rstest, Context};
1300 ///
1301 /// #[rstest]
1302 /// #[case::a_description(42)]
1303 /// fn my_test(#[context] ctx: Context, #[case] _c: u32) {
1304 /// assert_eq!("my_test", ctx.name);
1305 /// assert_eq!(Some("a_description"), ctx.description);
1306 /// assert_eq!(Some(0), ctx.case);
1307 ///
1308 /// std::thread::sleep(std::time::Duration::from_millis(100));
1309 /// assert!(ctx.start.elapsed() >= std::time::Duration::from_millis(100));
1310 /// }
1311 ///
1312 /// ```
1313 ///
1314 /// ## Local lifetime and `#[by_ref]` attribute
1315 ///
1316 /// In some cases you may want to use a local lifetime for some arguments of your test.
1317 /// In these cases you can use the `#[by_ref]` attribute then use the reference instead
1318 /// the value.
1319 ///
1320 /// ```rust
1321 /// # use std::cell::Cell;
1322 /// # use rstest::*;
1323 /// # #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1324 /// enum E<'a> {
1325 /// A(bool),
1326 /// B(&'a Cell<E<'a>>),
1327 /// }
1328 ///
1329 /// fn make_e_from_bool<'a>(_bump: &'a (), b: bool) -> E<'a> {
1330 /// E::A(b)
1331 /// }
1332 ///
1333 /// #[fixture]
1334 /// fn bump() -> () {}
1335 ///
1336 /// #[rstest]
1337 /// #[case(true, E::A(true))]
1338 /// fn it_works<'a>(#[by_ref] bump: &'a (), #[case] b: bool, #[case] expected: E<'a>) {
1339 /// let actual = make_e_from_bool(&bump, b);
1340 /// assert_eq!(actual, expected);
1341 /// }
1342 /// ```
1343 ///
1344 /// You can use `#[by_ref]` attribute for all arguments of your test and not just for fixture
1345 /// but also for cases, values and files.
1346 ///
1347 /// ## Putting all Together
1348 ///
1349 /// All these features can be used together with a mixture of fixture variables,
1350 /// fixed cases and bunch of values. For instance, you might need two
1351 /// test cases which test for panics, one for a logged in user and one for a guest user.
1352 ///
1353 /// ```rust
1354 /// # enum User { Guest, Logged, }
1355 /// # impl User { fn logged(_n: &str, _d: &str, _w: &str, _s: &str) -> Self { Self::Logged } }
1356 /// # struct Item {}
1357 /// # trait Repository { fn find_items(&self, user: &User, query: &str) -> Result<Vec<Item>, String> { Err("Invalid query error".to_owned()) } }
1358 /// # #[derive(Default)] struct InMemoryRepository {}
1359 /// # impl Repository for InMemoryRepository {}
1360 ///
1361 /// use rstest::*;
1362 ///
1363 /// #[fixture]
1364 /// fn repository() -> InMemoryRepository {
1365 /// let mut r = InMemoryRepository::default();
1366 /// // fill repository with some data
1367 /// r
1368 /// }
1369 ///
1370 /// #[fixture]
1371 /// fn alice() -> User {
1372 /// User::logged("Alice", "2001-10-04", "London", "UK")
1373 /// }
1374 ///
1375 /// #[rstest]
1376 /// #[case::authorized_user(alice())] // We can use `fixture` also as standard function
1377 /// #[case::guest(User::Guest)] // We can give a name to every case : `guest` in this case
1378 /// #[should_panic(expected = "Invalid query error")] // We would test a panic
1379 /// fn should_be_invalid_query_error(
1380 /// repository: impl Repository,
1381 /// #[case] user: User,
1382 /// #[values(" ", "^%$some#@invalid!chars", ".n.o.d.o.t.s.")] query: &str,
1383 /// query: &str
1384 /// ) {
1385 /// repository.find_items(&user, query).unwrap();
1386 /// }
1387 /// ```
1388 ///
1389 /// ## Ignoring Arguments
1390 ///
1391 /// Sometimes, you may want to inject and use fixtures not managed by rstest
1392 /// (e.g. db connection pools for sqlx tests).
1393 ///
1394 /// In these cases, you can use the `#[ignore]` attribute to ignore the additional
1395 /// parameter and let another crate take care of it:
1396 ///
1397 /// ```rust, ignore
1398 /// use rstest::*;
1399 /// use sqlx::*;
1400 ///
1401 /// #[fixture]
1402 /// fn my_fixture() -> i32 { 42 }
1403 ///
1404 /// #[rstest]
1405 /// #[sqlx::test]
1406 /// async fn test_db(my_fixture: i32, #[ignore] pool: PgPool) {
1407 /// assert_eq!(42, injected);
1408 /// // do stuff with the connection pool
1409 /// }
1410 /// ```
1411 ///
1412 ///
1413 /// ## Trace Input Arguments
1414 ///
1415 /// Sometimes can be very helpful to print all test's input arguments. To
1416 /// do it you can use the `#[trace]` function attribute that you can apply
1417 /// to all cases or just to some of them.
1418 ///
1419 /// ```
1420 /// use rstest::*;
1421 ///
1422 /// #[fixture]
1423 /// fn injected() -> i32 { 42 }
1424 ///
1425 /// #[rstest]
1426 /// #[trace]
1427 /// fn the_test(injected: i32) {
1428 /// assert_eq!(42, injected)
1429 /// }
1430 /// ```
1431 ///
1432 /// Will print an output like
1433 ///
1434 /// ```bash
1435 /// Testing started at 14.12 ...
1436 /// ------------ TEST ARGUMENTS ------------
1437 /// injected = 42
1438 /// -------------- TEST START --------------
1439 ///
1440 ///
1441 /// Expected :42
1442 /// Actual :43
1443 /// ```
1444 /// But
1445 /// ```
1446 /// # use rstest::*;
1447 /// #[rstest]
1448 /// #[case(1)]
1449 /// #[trace]
1450 /// #[case(2)]
1451 /// fn the_test(#[case] v: i32) {
1452 /// assert_eq!(0, v)
1453 /// }
1454 /// ```
1455 /// will trace just `case_2` input arguments.
1456 ///
1457 /// If you want to trace input arguments but skip some of them that don't
1458 /// implement the `Debug` trait, you can also use the
1459 /// `#[notrace]` argument attribute to skip them:
1460 ///
1461 /// ```
1462 /// # use rstest::*;
1463 /// # struct Xyz;
1464 /// # struct NoSense;
1465 /// #[rstest]
1466 /// #[trace]
1467 /// fn the_test(injected: i32, #[notrace] xyz: Xyz, #[notrace] have_no_sense: NoSense) {
1468 /// assert_eq!(42, injected)
1469 /// }
1470 /// ```
1471 /// # Old _compact_ syntax
1472 ///
1473 /// `rstest` support also a syntax where all options and configuration can be write as
1474 /// `rstest` attribute arguments. This syntax is a little less verbose but make
1475 /// composition harder: for instance try to add some cases to a `rstest_reuse` template
1476 /// is really hard.
1477 ///
1478 /// So we'll continue to maintain the old syntax for a long time but we strongly encourage
1479 /// to switch your test in the new form.
1480 ///
1481 /// Anyway, here we recall this syntax and rewrite the previous example in the _compact_ form.
1482 ///
1483 /// ```text
1484 /// rstest(
1485 /// arg_1,
1486 /// ...,
1487 /// arg_n[,]
1488 /// [::attribute_1[:: ... [::attribute_k]]]
1489 /// )
1490 /// ```
1491 /// Where:
1492 ///
1493 /// - `arg_i` could be one of the follow
1494 /// - `ident` that match to one of function arguments for parametrized cases
1495 /// - `case[::description](v1, ..., vl)` a test case
1496 /// - `fixture(v1, ..., vl) [as argument_name]` where fixture is the injected
1497 /// fixture and argument_name (default use fixture) is one of function arguments
1498 /// that and `v1, ..., vl` is a partial list of fixture's arguments
1499 /// - `ident => [v1, ..., vl]` where `ident` is one of function arguments and
1500 /// `v1, ..., vl` is a list of values for ident
1501 /// - `attribute_j` a test attribute like `trace` or `notrace`
1502 ///
1503 /// ## Fixture Arguments
1504 ///
1505 /// ```
1506 /// # struct User(String, u8);
1507 /// # impl User { fn name(&self) -> &str {&self.0} }
1508 /// # use rstest::*;
1509 /// #
1510 /// # #[fixture]
1511 /// # fn user(
1512 /// # #[default("Alice")] name: impl AsRef<str>,
1513 /// # #[default(22)] age: u8
1514 /// # ) -> User { User(name.as_ref().to_owned(), age) }
1515 /// #
1516 /// #[rstest(user("Bob"))]
1517 /// fn check_user(user: User) {
1518 /// assert_eq("Bob", user.name())
1519 /// }
1520 /// ```
1521 ///
1522 /// ## Fixture Rename
1523 /// ```
1524 /// # use rstest::*;
1525 /// #[fixture]
1526 /// fn long_and_boring_descriptive_name() -> i32 { 42 }
1527 ///
1528 /// #[rstest(long_and_boring_descriptive_name as short)]
1529 /// fn the_test(short: i32) {
1530 /// assert_eq!(42, short)
1531 /// }
1532 /// ```
1533 ///
1534 /// ## Parametrized
1535 ///
1536 /// ```
1537 /// # use rstest::*;
1538 /// #[rstest(input, expected,
1539 /// case::zero_base_case(0, 0),
1540 /// case::one_base_case(1, 1),
1541 /// case(2, 1),
1542 /// case(3, 2),
1543 /// #[should_panic]
1544 /// case(4, 42)
1545 /// )]
1546 /// fn fibonacci_test(input: u32, expected: u32) {
1547 /// assert_eq!(expected, fibonacci(input))
1548 /// }
1549 ///
1550 /// # fn fibonacci(input: u32) -> u32 {
1551 /// # match input {
1552 /// # 0 => 0,
1553 /// # 1 => 1,
1554 /// # n => fibonacci(n - 2) + fibonacci(n - 1)
1555 /// # }
1556 /// # }
1557 /// ```
1558 ///
1559 /// ## Values Lists
1560 ///
1561 /// ```
1562 /// # use rstest::*;
1563 /// # fn is_valid(input: &str) -> bool { true }
1564 ///
1565 /// #[rstest(
1566 /// input => ["John", "alice", "My_Name", "Zigy_2001"]
1567 /// )]
1568 /// fn should_be_valid(input: &str) {
1569 /// assert!(is_valid(input))
1570 /// }
1571 /// ```
1572 ///
1573 /// ## `trace` and `notrace`
1574 ///
1575 /// ```
1576 /// # use rstest::*;
1577 /// # struct Xyz;
1578 /// # struct NoSense;
1579 /// #[rstest(::trace::notrace(xzy, have_no_sense))]
1580 /// fn the_test(injected: i32, xyz: Xyz, have_no_sense: NoSense) {
1581 /// assert_eq!(42, injected)
1582 /// }
1583 /// ```
1584 ///
1585 pub use rstest_macros::rstest;