Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest - Fixture introspect on function level

I've got a fixture that requires a variable from the test function. Using introspection and declaring the variable in the function namespace/context should work if introspection on function level works, as it does for module level, but each time I run the code I end up with None instead of the string "Fancy Table".

In the fixture I set the scope to 'function' and then introspect via getattr and request.function:

#conftest.py
@pytest.fixture(scope='function')
def table(request):
    from data_setup import create_table
    table_name = getattr(request.function, "table_name", None)
    create_table(request, table_name)

I declare the variable table_name in the test function:

#test_file.py
class TestTable():

    @pytest.mark.tags("table")
    def test_create_table(self, test_db):
        table_name = "Fancy Table"
        current_page = TablePage(self.test_driver, test_db)
        current_page.go_to_kitchen("Eva", "Evas Kitchen")
        current_page.create_first_table(expected_table_name)
        Validation.assert_equal(expected_table_name, current_page.get_name(), "Table had the wrong name!")

Doing this on a module level has worked, as has class but as soon as I attempt to do so on a function level the fixture spits out None again. Am I using fixture introspection on a function level wrong? How is it used if not like this?

like image 441
Mayestril Avatar asked Mar 17 '26 04:03

Mayestril


1 Answers

Function variables are local and are destroyed after the function returns, they are not bound the function object in any way... this is how Python works and not related to py.test.

Your example will work if you bind the table_name local variable explicitly to the test function, effectively letting it outlive its usual life-time:

@pytest.mark.tags("table")
def test_create_table(self, test_db):
    test_create_table.table_name = "Fancy Table"

On the other hand, wouldn't be simpler to just pass the table_name to TablePage explicitly? It would be simpler, straightforward and, well, explicit. :)

like image 103
Bruno Oliveira Avatar answered Mar 18 '26 16:03

Bruno Oliveira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!