Kintarō
Kintarō

Reputation: 3177

How to carry over variable from pytest fixture to an actual test?

I have a pytest that rely on setup/teardown fixture to create/delete a kinesis stream:

@pytest.fixture()
def clean_up_kinesis_test():
    stream_name = uuid.uuid4().hex
    api_utils.create_kinesis_stream('us-east-1', stream_name, 1)
    assert active
    yield
    api_utils.delete_kinesis_stream('us-east-1', stream_name)

@pytest.mark.usefixtures("clean_up_kinesis_test")
def test_func1():
    # Use the stream_name from the fixture to do further testing

@pytest.mark.usefixtures("clean_up_kinesis_test")
def test_func2():
    # Use the stream_name from the fixture to do further testing

Is there a way I can pass the stream_name from the fixture to the actual test_func1 and test_func2?

I cannot use global variable as each test will need to have their own stream to do testing.

Upvotes: 1

Views: 507

Answers (1)

Jason Cook
Jason Cook

Reputation: 1501

Yield the value from the test fixture and pass the fixture as an argument into each test.

import pytest
import uuid

@pytest.fixture()
def clean_up_kinesis_test():
    stream_name = uuid.uuid4().hex
    yield stream_name

def test_func1(clean_up_kinesis_test):
    print(clean_up_kinesis_test)

def test_func2(clean_up_kinesis_test):
    print(clean_up_kinesis_test)

Upvotes: 2

Related Questions