Pytest - Fixture introspect on function level

我与影子孤独终老i 提交于 2019-12-10 09:39:01

问题


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?


回答1:


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. :)




回答2:


Explicitly binding the local variable to the test function resulted in my IDE complaining about an Unresolved reference. What else do we need to know to make this work?

In the example given, when I write test_create_table.table_name = "Fancy Table", the test_create_table part is the part my IDE complains has an Unresolved reference. So given I am receiving the Unresolved reference error, how can I successfully explicitly bind the local variable?



来源:https://stackoverflow.com/questions/33548835/pytest-fixture-introspect-on-function-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!