Question

I am new to py.test and I am using funargs to generate some test data before the tests get executed. I want to have pytest_generate hook use the funcargs value and pass it to the test function. For e.g. I have a function "do_something" which queries a database for a given set of arguments and sets user's enviroment accordingly. Considering that we have a multi site setup, I want to ensure that the database has the entries against which the test is performed, before the test gets executed.

def pytest_funcarg__data(request):
    # Ensure test data exist in the data base
    # Perform all the checks
    # Final values
    values = [['option1', 'option2', 'option3'],
              ['option1', 'option2'],
              ['option2', 'option3']]
    # Expected result 
    results = [['output1'],
               ['output2'],
               ['output3']]

    return (values, results)

def test_do_something(value, result):       
    assert do_something(value) == result

Ideally. I want to iterate though the values and pass them to my test function. How can I do that?

Currently I am doing this:

def pytest_funcarg__data(request):
    #same as above

def pytest_funcarg__pass_data(request):
    data = request.getfuncargvalue("data")
    return (data[0][request.param],
                data[1][request.param])

def pytest_generate_tests(metafunc):
    if 'pass_data' in metafunc.funcargnames:
        # If number of test cases change the change needs to made here too
        metafunc.parametrize("pass_data", [0, 1, 2], indirect=True)

def test_do_something(pass_data):
    assert do_something(pass_data[0] == pass_data[1]

Now, this works. But everytime I add a test case, I need to update the generate_test hook. I am thinking there might be a simpler way to do this ?

Was it helpful?

Solution

the pytest_generate_tests hook is executed when tests are collected. The pytest_funcarg__data factory is called when the test is executed. Test execution happens after test collection so there is no way you could call something like "getfuncargvalue" during collection.

However, it's not clear from your example why you want to use both - here is a generate_tests that should work directly with your example test:

def pytest_generate_tests(metafunc):
    params = [("input", "output")]
    metafunc.parametrize(("test_case", "result"), params)

HTH. holger

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top