How to reference one of two parameters from test on fixtures? #10040
-
I have the following code sample to reproduce the behavior I need: @pytest.fixture
def mocker_search_posts(mocker):
post = Post(
id=1,
title='Title',
body='Body',
tags=['tag A']
)
patch = mocker.patch('path.to.search_posts', return_value=[post])
return [post, patch]
@pytest.fixture
def mocker_create_post(mocker, request):
post = Post(
id=0,
title='New Post Title',
body='Body',
tags=request.node.funcargs['tags']
)
return mocker.patch('path.to.create_post', return_value=post)
@pytest.fixture
def mocker_search_comments(mocker, request):
comment = Comment(
id=1,
content='Comment content',
moderation_date: request.node.funcargs['date']
)
patch = mocker.patch('path.to.search_comments', return_value=[comment])
return [comment, patch]
@pytest.mark.parametrize("tags",
[["tag A"], ["tag A", "tag B"]],
indirect=True)
@pytest.mark.parametrize("date",
[datetime.now(pytz.utc), datetime.now(pytz.utc) - timedelta(minutes=26)],
indirect=True)
@pytest.mark.usefixtures("mocker_search_comments")
def test_row_creation(mocker_search_posts, mocker_create_post):
pass # just for the sake of clarity As you may check, I defined two parametrize on The example above gives the error "KeyError: 'date' at moderation_date: request.node.funcargs['date']" This is so I can have a more generic fixture and add the scenarios using two parametrize in my test. If you know a more apropriate way to achieve it, it will be certainly welcome too. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi @julianonunes, You should use the same name of the fixtures that you want the pass the parameters to, and also access the parametrization value using Updated your example (only the relevant parts): @pytest.fixture
def mocker_create_post(mocker, request):
post = Post(
id=0,
title='New Post Title',
body='Body',
tags=request.param
)
return mocker.patch('path.to.create_post', return_value=post)
@pytest.fixture
def mocker_search_comments(mocker, request):
comment = Comment(
id=1,
content='Comment content',
moderation_date=request.param
)
patch = mocker.patch('path.to.search_comments', return_value=[comment])
return [comment, patch]
@pytest.mark.parametrize("mocker_create_post",
[["tag A"], ["tag A", "tag B"]],
indirect=True)
@pytest.mark.parametrize("mocker_search_comments",
[datetime.now(pytz.utc), datetime.now(pytz.utc) - timedelta(minutes=26)],
indirect=True)
@pytest.mark.usefixtures("mocker_search_comments")
def test_row_creation(mocker_search_posts, mocker_create_post):
pass # just for the sake of clarity |
Beta Was this translation helpful? Give feedback.
Hi @julianonunes,
You should use the same name of the fixtures that you want the pass the parameters to, and also access the parametrization value using
request.param
, see Indirect parametrization in the documentation.Updated your example (only the relevant parts):