Skip to content

Instantly share code, notes, and snippets.

@zhammer
Created March 30, 2018 14:42
Show Gist options
  • Save zhammer/13b6b4497bd3b0be0e334e412fb26bbe to your computer and use it in GitHub Desktop.
Save zhammer/13b6b4497bd3b0be0e334e412fb26bbe to your computer and use it in GitHub Desktop.
import pytest

def test_data_1_is_string(data_1):
    """Test that data is string"""
    assert isinstance(data_1, str)

def test_data_2_is_string(data_2):
    """Test that data is string"""
    assert isinstance(data_2, str)

@pytest.mark.parametrize(
    'data',
    [data_1, data_2]
)
def test_data_is_string_parametrized(data):
    """Parametrized test that data is string"""
    assert isinstance(data, str)

@pytest.fixture()
def data_1():
    """Data fixture for data 1."""
    return 'DATA_1'

@pytest.fixture()
def data_2():
    """Data fixture for data 2."""
    return 'DATA_2'
Zachs-MBP:test zhammer$ pytest test.py 
============================= test session starts ==============================
platform darwin -- Python 3.6.0, pytest-3.3.1, py-1.5.2, pluggy-0.6.0
rootdir: /Users/zhammer/code/test, inifile:
collected 0 items / 1 errors                                                   

==================================== ERRORS ====================================
___________________________ ERROR collecting test.py ___________________________
test.py:14: in <module>
    [data_1, data_2]
E   NameError: name 'data_1' is not defined
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.12 seconds ============================
@zhammer
Copy link
Author

zhammer commented Mar 30, 2018

I've looked into the 'parametrizing fixtures', but it seems like this syntax:

@pytest.fixture(scope=​'session'​, params=[​'tiny'​, ​'mongo'​])

doesn't support params that are fixtures.

One option is the move the fixture functions above the tests, and simple execute each function in the parametrization to get its data, but this seems ugly / anti-pytest.

import pytest

@pytest.fixture()
def data_1():
    """Data fixture for data 1."""
    return 'DATA_1'

@pytest.fixture()
def data_2():
    """Data fixture for data 2."""
    return 'DATA_2'

def test_data_1_is_string(data_1):
    """Test that data is string"""
    assert isinstance(data_1, str)

def test_data_2_is_string(data_2):
    """Test that data is string"""
    assert isinstance(data_2, str)

@pytest.mark.parametrize(
    'data',
    [data_1(), data_2()]
)
def test_data_is_string_parametrized(data):
    """Parametrized test that data is string"""
    assert isinstance(data, str)

Is there any good way to do this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment