0
def fixed_given(self):
    return @given(
        test_df=data_frames(
            columns=columns(
                ["float_col1"],
                dtype=float,
            ),
            rows=tuples(
                floats(allow_nan=True, allow_infinity=True)),
        )
    )(self)

@pytest.fixture()
@fixed_given
def its_a_fixture(test_df):
      obj = its_an_class(test_df)
      return obj

@pytest.fixture()
@fixed_given
def test_1(test_df):
      #use returned object from my fixture here

@pytest.fixture()
@fixed_given
def test_2(test_df):
      #use returned object from my fixture here
  • Here, I am creating my test dataframe in a seperate function to use it commonly across all functions.
  • And then creating a pytest fixture to instantiate a class by passing the test dataframe generated by a fixed given function.
  • I am finding a way to get a return value from this fixture.
  • But the problem i am using a given decorator, its doesn't allow return values.
  • is there a way to return even after using given decorator?

1 Answers1

1

It's not clear what you're trying to acheive here, but reusing inputs generated by Hypothsis gives up most of the power of the framework (including minimal examples, replaying failures, settings options, etc.).

Instead, you can define a global variable for your strategy - or write a function that returns a strategy with @st.composite - and use that in each of your tests, e.g.

MY_STRATEGY = data_frames(columns=[
    column(name="float_col1", elements=floats(allow_nan=True, allow_infinity=True))
])

@given(MY_STRATEGY)
def test_foo(df): ...

@given(MY_STRATEGY)
def test_bar(df): ...

Specifically to answer the question you asked, you cannot get a return value from a function decorated with @given.

Instead of using fixtures to instantiate your class, try using the .map method of a strategy (in this case data_frames(...).map(its_an_class)), or the builds() strategy (i.e. builds(my_class, data_frames(...), ...)).

Zac Hatfield-Dodds
  • 2,455
  • 6
  • 19
  • I am already reusing my inputs generated from the fixed_given function in all my test functions. The idea behind my question is to reuse the class object that is being created in its_my_fixture function and reuse it in all my test_functions. I've also updated my code snippet. It may help you to better understand the Scenario. Thanks ! – Lakshmana Perumal Mar 16 '20 at 07:01
  • Instead of reusing the object, generate a new one! That's the Hypothesis way :-) – Zac Hatfield-Dodds Mar 17 '20 at 07:33