How do I run a fixture twice in a test case using pytest?
Here I am using this device to create obj network with iprange. Although in some cases I need to create 2 different networks in one test.
@pytest.fixture(scope="function")
def fixture_user_create_network_with_iprange(get_user_token,
fixture_user_create_network,
fixture_user_create_iprange,
request):
token = get_user_token
network_uuid = fixture_user_create_network
iprange_uuid = fixture_user_create_iprange
add_ipranges_to_networks(token,network_uuid,iprange_uuid)
return network_uuid
But in the same test, the device can only work once. I am creating another device named , this is a copy of the original device, but a different name.fixture_user_create_
2nd
_network_with_iprange
Interaction with these 2 devices are also used fixture_user_create_network
, fixture_user_create_iprange
which are executed only once in the test. I only have one obj network.
So I want to know
- if I can get the appliances to work twice in the test, or
- if I can call the device at any time in a test case on demand.
source to share
You cannot start one device twice. This is contrary to the concept of luminaires.
However, you can extract network_uuid
into a function (function only) and declare 2+ fixtures that call it.
You can also call lights dynamically:
@pytest.fixture
def fixt1(request):
return 'hello'
@pytest.fixture
def fixt2(request):
return request.getfuncargvalue('fixt1')
def test_me(fixt2):
assert fixt2 == 'hello'
But still, only once per test.
If you want a dynamic number of similar fixtures, you can generate them:
import pytest
# Just for proper var closures:
def _make_fixt_fn(i):
@pytest.fixture
def fixt_fn(....):
return 'fixt{}'.format(i)
return fixt_fn
# The fixtures must reside in the module namespace. The decorator is just a mark.
for i in range(1, 4):
name = 'dyn_fixt_{}'.format(i)
global()[name] = _make_fixt_fn(i)
def test_dyn(dyn_fixt_1, dyn_fixt_2, dyn_fixt_3):
pass
Lets check:
$ pytest test_dyn.py --fixtures
...
------- fixtures defined from test_dyn ----------
dyn_fixt_1
test_dyn.py:6: no docstring available
dyn_fixt_2
test_dyn.py:6: no docstring available
dyn_fixt_3
test_dyn.py:6: no docstring available
source to share
You can use mark.parametrize with an "indirect" switch to allow a power parameter to be passed to your fixture and then simply return that number of copies:
@pytest.fixture
def data_repeated(request):
return [deepcopy({'a': 1, 'b': 2}) for _ in range(request.param)]
@pytest.mark.parametrize('data_repeated', [3], indirect=['data_repeated'])
def test(data_repeated):
assert data_repeated == [
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2}]
source to share