how to get data from fixture to parametrize with @parametrize ? (with repository example)
I created this repository to demonstrate the problem
https://github.com/andreabisello/pytest-fixture-as-parameter
there are a fixture and three test.
import pytest
import requests
@pytest.mark.parametrize('endpoint', [
"https://www.google.it",
"https://www.google.com"
])
def test_parametrized(endpoint):
"""
this will create two tests, one for every value of the endpoint parameter
"""
print("checking : " + endpoint)
assert requests.get(endpoint).status_code == 200
@pytest.fixture(scope="session")
def get_endpoints():
return [
"https://www.google.it",
"https://www.google.com"
]
def test_using_fixture(get_endpoints):
"""this will assert the result of the fixture"""
assert get_endpoints == [
"https://www.google.it",
"https://www.google.com"
]
@pytest.mark.parametrize('endpoint', get_endpoints)
def test_parametrizing_using_fixture(endpoint):
"""
this should load data from get_endpoints fixture and pass every value of
get_endpoints as endpoint value
"""
print("checking : " + endpoint)
assert requests.get(endpoint).status_code == 200
a test is using @mark.parametrize and it works.
a test is using the fixture and it works.
a test is trying to use the fixture as values for the @mark.parametrize and it cannot works.
but i would like to load the @mark.parametrize values from a fixture.
It looks like you probably want https://docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures - does that solve your problem?
@JoshKarpel no. this is needed to parametrize a fixture. and i use this : i have a fixture that generate something based on a parameter. my need is the opposite : i need to use the results of a fixture to parametrize a test.
A parametrized fixture indirectly parametrizes all of the fixtures/tests that depend on it, without needing to explicitly use @parametrize on the tests:
import pytest
import requests
@pytest.fixture(scope = "session", params = [
"https://www.google.it",
"https://www.google.com"
])
def endpoint(request):
return request.param
def test_parametrizing_using_fixture(endpoint):
print("checking : " + endpoint)
assert requests.get(endpoint).status_code == 200
Running pytest -v to see what tests are generated:
$ pytest -v
===== test session starts =====
platform linux -- Python 3.7.5, pytest-5.3.2, py-1.8.0, pluggy-0.13.1 --
cachedir: .pytest_cache
rootdir:
collected 2 items
test_req.py::test_parametrizing_using_fixture[https://www.google.it] PASSED
test_req.py::test_parametrizing_using_fixture[https://www.google.com] PASSED
===== 2 passed in 0.91s =====
If this isn't what you want, could you provide an example that's closer to your real code?
@JoshKarpel thanks, my code in on my work computer, i will try next monday and i'll return a feedback.
Thanks @JoshKarpel - I think that should do it :smile:
@JoshKarpel @Zac-HD my need is a little different. thanks for your help.
the problem is related to the fact i cannot hardcode
params = [
"https://www.google.it",
"https://www.google.com"
])
because this needs to be returned by a fixture,
i give you the context.
my testsuite needs to be executed in 4 different environments ( staging , quality, pre production , production ) and the configuration for every environment is stored in a json file . due some environments share some configuration values, configuration file is splitted in several files : one with username and passwords, one with assets links, one with endpoints and so on. when i need to change environment, i change files and i re run the suite.
now, i want to parametrize the choose of the file on the pytest command line.
to obtain this is used pytest_addoption(parser) in conftest.py like this
def pytest_addoption(parser):
parser.addoption("--users", action="store", default="test", help="file contenente username e password. senza .json")
parser.addoption("--endpoints", action="store", default="integration")
parser.addoption("--assets", action="store", default="test")
parser.addoption("--environment", action="store", default="test")
i permit to choose what file to load, and fixtures load the configuration from the file e.g.
@pytest.fixture(scope="session")
def users(request):
users = None
users = request.config.getoption("--users")
with open('configurations/users-'+users+'.json', 'r') as f:
users = json.load(f)
return users
and this works, every test class have a fixture with autouse used to load required parameters from the loaded json files
class TestServizi():
@pytest.fixture(autouse=True)
def init(self, users, endpoints, assets, environment):
self.username = users['userServizi']
self.password = bytes(users['passwordUserServizi'],"utf-8")
self.client = Client(endpoints["solutionUpdate"])
i use the autouse fixture to avoid loading fixture in every single test, due the test class use everytime the same parameter.
it works good.
one of the test, check if every of the 11 endpoints returns http status 200 ok.
sure, i can create 11 tests, or i can create a test looping to the array of 11 endpoints, but i would like to use parametrize to create 11 tests.
and this is my initial approach
def test_using_fixture(get_endpoints):
"""this will assert the result of the fixture"""
assert get_endpoints == [
"https://www.google.it",
"https://www.google.com"
]
@pytest.mark.parametrize('endpoint', get_endpoints)
def test_parametrizing_using_fixture(endpoint):
"""
this should load data from get_endpoints fixture and pass every value of
get_endpoints as endpoint value
"""
print("checking : " + endpoint)
assert requests.get(endpoint).status_code == 200
but you teached me to use this snipped
@pytest.fixture(scope = "session", params = [
"https://www.google.it",
"https://www.google.com"
])
def endpoint(request):
return request.param
def test_parametrizing_using_fixture(endpoint):
print("checking : " + endpoint)
assert requests.get(endpoint).status_code == 200
the problem is related to the fact i cannot hardcode
params = [
"https://www.google.it",
"https://www.google.com"
])
because this needs to be returned by the fixture.
so i tried something like this
@pytest.fixture(scope="session", params = endpoints['provisioning'])
def provisioning_endpoint(request):
return request.param
where endpoints is a fixture that return a dictionary and provisioning in a keys of this dictionary containing the array of the url i need to check
def test_endpoints_from_fixture(provisioning_endpoint):
print(provisioning_endpoint)
but i obtain this error loading the conftest.py
TypeError: 'function' object is not subscriptable
Sounds like you might need https://docs.pytest.org/en/latest/parametrize.html#basic-pytest-generate-tests-example
Building off the example there, you would keep your pytest_addoption as is. Then in pytest_generate tests, you would check for the "fixture" named endpoint and manually parametrize its value based on the endpoint list. There is no actual endpoint fixture function, and get_endpoints can just be a plain function instead of a fixture. You'll probably want to cache the file reads, because pytest_generate_tests will fire for every test in your suite.
@JoshKarpel thanks again. i'm stalled at the same problem : i don't want to hardcode data. so for example this works
#test_something.py
def test_loading_endpoints_from_pytest_generate_tests(provisioning_endpoints):
print(provisioning_endpoints)
#conftest.py
def pytest_generate_tests(metafunc):
if "provisioning_endpoints" in metafunc.fixturenames:
metafunc.parametrize("provisioning_endpoints", ["https://www.google.it","https://www.google.com"])
it will generate two tests, but this code
def pytest_generate_tests(metafunc):
if "provisioning_endpoints" in metafunc.fixturenames:
metafunc.parametrize("provisioning_endpoints", endpoints["provisioning"])
has the same problem
metafunc.parametrize("provisioning_endpoints", endpoints["provisioning"]) E TypeError: 'function' object is not subscriptable
you say get_endpoints can just be a plain function, but how this plain function can understand what file to load, if it cannot access pytest test configuration?
i tried these other ways
- use a fixture with params=a_function_who_load_data())
but a_function_who_load_data needs to know what environment is going to be loaded and outside from the pytest context you cannot get references to the request.config.getoption paramer (https://stackoverflow.com/questions/43172467/pytest-how-to-access-command-line-arguments-outside-of-a-test)
-
use a fixture inside use a_function_who_load_data to get the data, but you can't use fixture outside a test run (https://stackoverflow.com/questions/57072380/how-to-use-pytest-fixture-outside-test-run).
-
use a fixture that store data in a module variable , so create a fixture parametrized with the data stored from the first fixture, so use a test that use the parametrid fixture, but there fixture called by the test was launched before the fixture use to store data in the module variable even playing with the scopes (https://docs.pytest.org/en/latest/fixture.html#order-higher-scoped-fixtures-are-instantiated-first) and this approach is only a patch.
you say get_endpoints can just be a plain function, but how this plain function can understand what file to load, if it cannot access pytest test configuration?
You can access the pytest config in pytest_generate_tests, so you just need to write a normal function which is passed information by pytest_generate_tests. I haven't tested the below, but something like this...
def pytest_addoption(parser):
parser.addoption("--endpoints", action = "store", default = "integration")
def get_endpoints(endpoints):
with open('configurations/endpoints-' + endpoints + '.json', 'r') as f:
users = json.load(f)
return users
def pytest_generate_tests(metafunc):
if "endpoint" in metafunc.fixturenames:
metafunc.parametrize("endpoint", get_endpoints(metafunc.config.getoption("endpoints")))
def test_endpoints(endpoint):
print("checking : " + endpoint)
assert requests.get(endpoint).status_code == 200
As I mentioned above, you'll probably want to put a functools.lru_cache on get_endpoints to speed collection up (https://docs.python.org/3/library/functools.html#functools.lru_cache).
@JoshKarpel thanks, it works. i also used lru_cache, thanks for the suggestion.
maybe you think in a future release of pytest a fixture can be used as arguments of parametrize ?
fixtures can not be used as parameterization without some new kind of scope and/or breaking changes to pytest (as parametrization happens before fixtures can be instantiated atm
@andreabisello have you solve this issue? I am meeting the same issue, how to get the parameter from a fixture
@tingtingjin-1024 no. i removed the fixtures used to parametrize tests.
how to parametrize the test case then?
获取 Outlook for iOShttps://aka.ms/o0ukef
发件人: Andrea Bisello [email protected] 发送时间: Thursday, December 3, 2020 11:52:14 PM 收件人: pytest-dev/pytest [email protected] 抄送: Tingting Jin [email protected]; Mention [email protected] 主题: Re: [pytest-dev/pytest] how to get data from fixture to parametrize with @parametrize ? (with repository example) (#6374)
@tingtingjin-1024https://urldefense.com/v3/__https://github.com/tingtingjin-1024__;!!PA7sDg!TiggTkx0Q3Vc-4CXG7hA4JvsSON-7tKrU5OyRjntR8qG3MQKPuP-UTeVpPaJOBMV$ no. i removed the fixtures used to parametrize tests.
― You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://urldefense.com/v3/__https://github.com/pytest-dev/pytest/issues/6374*issuecomment-738094942__;Iw!!PA7sDg!TiggTkx0Q3Vc-4CXG7hA4JvsSON-7tKrU5OyRjntR8qG3MQKPuP-UTeVpMglxFnY$, or unsubscribehttps://urldefense.com/v3/__https://github.com/notifications/unsubscribe-auth/AR6RXD7W2LK6BBZQRD2SRYDSS6X25ANCNFSM4J76ODGA__;!!PA7sDg!TiggTkx0Q3Vc-4CXG7hA4JvsSON-7tKrU5OyRjntR8qG3MQKPuP-UTeVpMGybHtV$.
Hi @tingtingjin-1024 @andreabisello , I have just been banging my head on this and I think I have two ways forward.
Simple way
You can call the underlying function of a fixture with __wrapped__:
@pytest.mark.parametrize('endpoint', get_endpoints.__wrapped__())
def test_parametrizing_using_fixture(endpoint):
However, __wrapped__ doesn't get any of the pytest framework - if your real get_endpoints itself calls fixtures, you're probably out of luck. Although, see https://stackoverflow.com/questions/55413277/can-pytest-hooks-use-fixtures/55416498
Using pytest hooks
Pytest defines a number of hooks which you can use to modify behaviour. You might find pytest_generate_tests relevant.
I'm assuming your test.py still looks like this:
@pytest.fixture(scope="session")
def get_endpoints():
return [
"https://www.google.it",
"https://www.google.com"
]
def test_parametrizing_using_fixture(endpoint):
assert requests.get(endpoint).status_code == 200
Create a conftest.py file:
def pytest_generate_tests(metafunc):
if metafunc.function.__name__ == "test_parametrizing_using_fixture" and "get_endpoints" in dir(metafunc.module):
metafunc.parametrize("endpoint", metafunc.module.get_endpoints.__wrapped__())
Again, I don't think it's possible to call get_endpoints as a fixture, so you can't automatically get cascading fixtures. You would have to manually call the __wrapped__ of each fixture as the args to your call.
Dirty hack
One final possibility is to iterate over the fixture:
# no mark.parametrize
def test_parametrizing_using_fixture(get_endpoints):
for endpoint in get_endpoints:
assert requests.get(endpoint).status_code == 200
@fsackur The Dirty hack looks good but chances are that some endpoints will not be checked if the assertion failed early.
@fsackur The Dirty hack looks good but chances are that some endpoints will not be checked if the assertion failed early.
Can be used https://pypi.org/project/pytest-check/