From 1fbf794dff88e2b8d64e6daf2fa6cd32215c16b9 Mon Sep 17 00:00:00 2001 From: michele Date: Sat, 27 Nov 2021 17:13:38 +0100 Subject: [PATCH] #119 Docs --- README.md | 20 ++++++++++++++++++++ src/lib.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/README.md b/README.md index dd69367..a694361 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,26 @@ async fn my_async_test(#[case] a: u32, result: #[case] #[future] u32) { ``` Just the attributes that ends with `test` (last path segment) can be injected. +### Use `#[once]` Fixture + +If you need to a fixture that should be inizialized just once for all tests +you can use `#[once]` attribute. `rstest` call your fixture function just once and +return a reference to your function result to all your tests: + +```rust +#[fixture] +#[once] +fn once_fixture() -> i32 { 42 } + +#[rstest] +fn single(once_fixture: &i32) { + // All tests that use once_fixture will share the same reference to once_fixture() + // function result. + assert_eq!(&42, once_fixture) +} +``` + + ## Complete Example All these features can be used together with a mixture of fixture variables, diff --git a/src/lib.rs b/src/lib.rs index 0baf01e..64e70a0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -366,6 +366,47 @@ use quote::ToTokens; /// } /// ``` /// +/// # `#[once]` Fixture +/// +/// Expecially in integration tests there are cases where you need a fixture that is called just once +/// for every tests. `rstest` provides `#[once]` attribute for these cases. +/// +/// If you mark your fixture with this attribute and `rstest` will compute a static reference to your +/// fixture result and return this reference to all your tests that need this fixture. +/// +/// In follow example all tests share the same reference to the `42` static value. +/// +/// ``` +/// use rstest::*; +/// +/// #[fixture] +/// #[once] +/// fn once_fixture() -> i32 { 42 } +/// +/// // Take care!!! You need tu use a reference to fixture value +/// +/// #[rstest] +/// #[case(1)] +/// #[case(2)] +/// fn cases_tests(once_fixture: &i32, #[case] v: i32) { +/// // Take care!!! You need tu use a reference to fixture value +/// assert_eq!(&42, once_fixture) +/// } +/// +/// #[rstest] +/// fn single(once_fixture: &i32) { +/// assert_eq!(&42, once_fixture) +/// } +/// ``` +/// +/// There are some limitations when you use `#[once]` fixture. `rstest` forbid to use once fixture +/// for: +/// +/// - `async` function +/// - Generic function (both with generic types or use `impl` trait) +/// +/// Take care that the `#[once]` fixture value will **never dropped**. +/// /// # Partial Injection /// /// You can also partialy inject fixture dependency using `#[with(v1, v2, ..)]` attribute: