2

I'm trying to pass values to a fixture because I basically have the same code for many tests but only some values changing, for what I understand pytest fixtures don't accept that but not really sure how to solve this , for example I have this:

import pytest


@pytest.fixture
def option_a():
    a = 1
    b = 2
    return print(a + b)


@pytest.fixture
def option_b():
    a = 5
    b = 3
    return print(a + b)


def test_foo(option_b):
    pass

instead of choosing between fixture option a or option b , both do adding and the only thing that changes is the values , can I have one fixture where I can set which values I want to run on test_foo?

thanks in advance.

user964503
  • 91
  • 1
  • 13

1 Answers1

2

The example you gave is so simple that you don't need fixtures. You'd just do:

import pytest

@pytest.mark.parametrize("a,b,expected", [
    (1,2,3),
    (5,3,8),
])
def test_foo(a, b, expected):
    assert a + b == expected

See https://docs.pytest.org/en/3.6.1/parametrize.html for details

However, I'm going to assume, you just simplified it that much as part of making an MCVE. In that case, you'd do the following:

@pytest.fixture(params=[(1 , 2, "three"), (5,3,"eight")])
def option_a_and_b(request):
    a, b, word = request.param
    return a + b, word

def test_foo(option_a_and_b):
    total, word = option_a_and_b
    if total == 3:
        assert word == "three"
    elif total == 8:
        assert word == "eight"
    else:
        assert False

def test_bar(option_a_and_b):
    pass

If you run this code you'll note 4 passing tests because every test that gets that fixture will be run for each param.

See https://docs.pytest.org/en/3.6.1/fixture.html#fixture-parametrize for details.

Zev
  • 3,423
  • 1
  • 20
  • 41
  • thanks Zev, your code is easy to understand , I just have a question , if I just want to use the second param (5,3,"eight"] on test_foo without removing the first param on fixture option_a_and_b (1 , 2, "three"),how can I do that? I'm trying this because my fixture contains code that can be used for many tests but the only thing that changes is the values , thanks – user964503 Jun 08 '18 at 20:09
  • Do you mean something like [fixture of fixtures]( https://stackoverflow.com/questions/35777854/pytest-fixture-of-fixtures) or [indirect parameterization?](https://stackoverflow.com/questions/42228895/how-to-parametrize-a-pytest-fixture)? Without understanding better (seeing code) what you are looking for, I don't know. If you have a specific issue you are stuck on and can post the relevant parts of your actual code (rather than a simple example like this) you may get more specific and relevant help. – Zev Jun 08 '18 at 20:35