curiousgeorge
curiousgeorge

Reputation: 121

Pytest fixture returning multiples

Is it possible to have a fixture that returns a dictionary and dataframe?

import somefile
import pytest

@pytest.fixture()
def setup():
    dictionary, dataframe = somefile.get_Di_And_Df()
    return(dictionary, dataframe)

def test_check(setup):
    assert dictionary['movie']['action'] == 'Avengers'
    assert dataframe.shape[0] == 5

Upvotes: 3

Views: 6322

Answers (3)

probhonjon
probhonjon

Reputation: 311

you could mock the called method

@patch("somefile.get_Di_And_Df", MagicMock=(return_value=(dictionary, dataframe)))
def test_check():
  _dict, _df = somefile.get_Di_And_Df()
  assert _dict['movie']['action'] == 'Avengers'
  assert _df.shape[0] == 5

Upvotes: 0

rocksportrocker
rocksportrocker

Reputation: 7419

The most readable way is to return a namedtuple in the fixture:

from collections import namedtuple

import somefile
import pytest

@pytest.fixture()
def setup():
    dictionary, dataframe = somefile.get_Di_And_Df()
    return namedtuple("Setup", "dictionary dataframe")(dictionary, dataframe)


def test_check(setup):
    assert setup.dictionary['movie']['action'] == 'Avengers'
    assert setup.dataframe.shape[0] == 5

Upvotes: 4

wim
wim

Reputation: 362716

The return value (or yield value) of the fixture is literally the object injected as a function argument during test execution:

def test_check(setup):
    dictionary, dataframe = setup
    assert dictionary['movie']['action'] == 'Avengers'
    assert dataframe.shape[0] == 5

Upvotes: 4

Related Questions