la10736 / rstest

Fixture-based test framework for Rust
Apache License 2.0
1.21k stars 43 forks source link

Possibility of resolving a fixture only once per test? #263

Open stevepryde opened 5 months ago

stevepryde commented 5 months ago

This might be my misunderstanding of how fixtures are supposed to work, but I would love the ability to have fixtures resolved exactly once per test.

For example, I have a mock struct (let's call it MyMock) that contains the current mocked state. In my tests I want to use this struct to add some things to the current test environment.

For example:

#[test]
fn test_thing() {
    let mock = MyMock::new();
    let foo1: Foo = mock.add_foo("foo1");
    let foo2: Foo = mock.add_foo("foo2");

    // Now run the function-to-be-tested, which also requires `&MyMock`
    let result = my_func(&mock).unwrap();
    assert_eq!(result, foo1); // I need foo1 here.
}

Can I use fixtures to get both MyMock as well as one or more Foos, created from the same instance of MyMock ?

For example, something like this?

#[fixture]
fn mock() -> MyMock {
    MyMock::new()
}

#[fixture]
fn foo(mock: &MyMock, #[default = "foo1"] name: &str) -> Foo {
    mock.add_foo(name)
}

#[rstest]
fn test_thing(mock: &MyMock, #[with("foo1")] #[from(foo)] foo1: Foo, #[with("foo2")] #[from(foo)] foo2: Foo) {
    let result = my_func(&mock).unwrap();
    assert_eq!(result, foo1);
}

Requirements:

Is this possible?

--

(as an aside, it gets tedious to write this kind of thing:

#[with("foo1")] #[from(foo)] foo1: Foo, #[with("foo2")] #[from(foo)] foo2: Foo

is there any way to improve that?)