Pytest using tools as arguments in parameterization

I would like to use fixtures as arguments to pytest.mark.parametrize or something that will have the same results.

For instance:

 import pytest import my_package @pytest.fixture def dir1_fixture(): return '/dir1' @pytest.fixture def dir2_fixture(): return '/dir2' @pytest.parametrize('dirname, expected', [(dir1_fixture, 'expected1'), (dir2_fixture, 'expected2')] def test_directory_command(dirname, expected): result = my_package.directory_command(dirname) assert result == expected 

The problem with the instrument parameters is that each instrument parameter is launched every time it is used, but I do not want this. I want to be able to choose which devices will be used depending on the test.

+13
source share
3 answers

If you are using Pytest 3.0 or later, I think you can solve this specific scenario by writing the following:

 @pytest.fixture(params=['dir1_fixture', 'dir2_fixture']) def dirname(request): return request.getfixturevalue(request.param) 

Docs here: http://doc.pytest.org/en/latest/builtin.html#_pytest.fixtures.FixtureRequest.getfixturevalue

However, you cannot use this approach if the device that you are trying to load dynamically is parameterized.

Alternatively, you can figure out something using the pytest_generate_tests hook. However, I could not get myself to figure it out.

+8
source

This is currently not supported by pytest. There is an open function request for this: https://github.com/pytest-dev/pytest/issues/349 .

+3
source

As of now, my only solution is to create a device that returns a dictionary of devices.

 import pytest import my_package @pytest.fixture def dir1_fixture(): return '/dir1' @pytest.fixture def dir2_fixture(): return '/dir2' @pytest.fixture def dir_fixtures( dir1_fixture, dir2_fixture ): return { 'dir1_fixture': dir1_fixture, 'dir2_fixture': dir2_fixture } @pytest.mark.parametrize('fixture_name, expected', [('dir1_fixture', 'expected1'), ('dir2_fixture', 'expected2')] def test_directory_command(dir_fixtures, fixture_name, expected): dirname = dir_fixtures[fixture_name] result = my_package.directory_command(dirname) assert result == expected 

Not the best, as it does not use the solution built into pytest, but it works for me.

+2
source

Source: https://habr.com/ru/post/1263757/


All Articles