Can I parameterize a pytest fixture with other fixtures?

2024/10/15 16:26:09

I have a python test that uses a fixture for credentials (a tuple of userid and password)

def test_something(credentials)(userid, password) = credentialsprint("Hello {0}, welcome to my test".format(userid))

and I have pytest fixture for credentials:

@pytest.fixture()
def credentials():return ("my_userid", "my_password")

It works great

Now I want to extend this for multiple credentials (say staging and production) so that my test will run twice (once each for staging and production).

I thought that parameterization was the answer, but it seems I can't parameterize with fixtures.

I would love to do something like this:

@pytest.fixture(params=[staging_credentials, production_credentials])
def credentials(request):return request.param

where staging_credentials and production_credentials are all fixtures:

@pytest.fixture()
def staging_credentials():return ("staging_userid", "staging_password")@pytest.fixture()
def production_credentials():return ("prod_userid", "prod_password")

but apparently parameters to the fixture can't be other fixtures.

Any suggestions on how to elegantly handle this? I've looked at https://docs.pytest.org/en/latest/proposals/parametrize_with_fixtures.html but that seems a but too brute force.

Thanks! Steve

Answer

Indirect parametrization is the answer. So, the parameters to the fixtures CAN be other fixtures (by their name/code).

import pytestall_credentials = {'staging': ('user1', 'pass1'),'prod': ('user2', 'pass2'),
}@pytest.fixture
def credentials(request):return all_credentials[request.param]@pytest.mark.parametrize('credentials', ['staging', 'prod'], indirect=True)
def test_me(credentials):pass

Technically, you can not only get a dict value by its key, but generate the credentials result based on request.param, and this param will be the value passed to the same-name parameter of the test.

If you want other fixtures to be used (probably because of the setup/teardown stages, as this is the only reason to do so):

import pytest@pytest.fixture
def credentials(request):return request.getfuncargvalue(request.param)@pytest.fixture()
def staging_credentials():return ("staging_userid", "staging_password")@pytest.fixture()
def production_credentials():return ("prod_userid", "prod_password")@pytest.mark.parametrize('credentials', ['staging_credentials', 'production_credentials'], indirect=True)
def test_me(credentials):pass

Here, request.getfuncargvalue(...) will return a fixture value by the fixture name, dynamically.

https://en.xdnf.cn/q/69265.html

Related Q&A

fit method in python sklearn

I am asking myself various questions about the fit method in sklearn.Question 1: when I do:from sklearn.decomposition import TruncatedSVD model = TruncatedSVD() svd_1 = model.fit(X1) svd_2 = model.fit(…

Django 1.9 JSONField update behavior

Ive recently updated to Django 1.9 and tried updating some of my model fields to use the built-in JSONField (Im using PostgreSQL 9.4.5). As I was trying to create and update my objects fields, I came a…

Using Tweepy to search for tweets with API 1.1

Ive been trying to get tweepy to search for a sring without success for the past 3 hours. I keep getting replied it should use api 1.1. I thought that was implemented... because I can post with tweepy.…

Retrieving my own data via FaceBook API

I am building a website for a comedy group which uses Facebook as one of their marketing platforms; one of the requirements for the new site is to display all of their Facebook events on a calendar.Cur…

Python -- Optimize system of inequalities

I am working on a program in Python in which a small part involves optimizing a system of equations / inequalities. Ideally, I would have wanted to do as can be done in Modelica, write out the equation…

Pandas side-by-side stacked bar plot

I want to create a stacked bar plot of the titanic dataset. The plot needs to group by "Pclass", "Sex" and "Survived". I have managed to do this with a lot of tedious nump…

Turn off list reflection in Numba

Im trying to accelerate my code using Numba. One of the arguments Im passing into the function is a mutable list of lists. When I try changing one of the sublists, I get this error: Failed in nopython …

Identifying large bodies of text via BeautifulSoup or other python based extractors

Given some random news article, I want to write a web crawler to find the largest body of text present, and extract it. The intention is to extract the physical news article on the page. The original p…

Pandas reindex and interpolate time series efficiently (reindex drops data)

Suppose I wish to re-index, with linear interpolation, a time series to a pre-defined index, where none of the index values are shared between old and new index. For example# index is all precise times…

How do you set the box width in a plotly box in python?

I currently have the following;y = time_h time_box = Box(y=y,name=Time (hours),boxmean=True,marker=Marker(color=green),boxpoints=all,jitter=0.5,pointpos=-2.0 ) layout = Layout(title=Time Box, ) fig = F…