pytest.fixture functions cannot use ``yield``. Instead write and return an inner function/generator and let the consumer call and iterate over it.:
Asked Answered
K

1

5

I am trying to run selenium with pytest for my Django project and execute the fixture setup/teardown.

I have tried to follow the best practice using yield but I am getting an error :

--- ERROR at setup of test_browsing_check --- 
pytest.fixture functions cannot use ``yield``. Instead write and return an inner function/generator and let the consumer call and iterate over it.:

@pytest.fixture(scope="module")
def browser(request):
    selenium = webdriver.Firefox()
    selenium .implicitly_wait(3)
    yield selenium
    selenium.quit()

Do you know why it is not working ?

Then later on I have used another code that works well

@pytest.fixture(scope="module")
def browser(request):
    selenium = webdriver.Firefox()
    selenium.implicitly_wait(3)
    def teardown():
        selenium.quit()
    request.addfinalizer(teardown)
    return selenium

But this method is not recommended:

This method is still fully supported, but yield is recommended from 2.10 onward because it is considered simpler and better describes the natural code flow.

Note about versions:

$ python -V
$ Python 3.5.2 :: Anaconda 4.2.0 (64-bit)

$ django-admin version
$ 1.10.3

$ pip show pytest
$ Name: pytest
$ Version: 2.9.2
Kawai answered 4/3, 2017 at 5:36 Comment(5)
According to the docs: Prior to version 2.10, in order to use a yield statement to execute teardown code one had to mark a fixture using the yield_fixture marker. From 2.10 onward, normal fixtures can use yield directly so the yield_fixture decorator is no longer needed and considered deprecated.Bolton
@FrancoSolleza good answer! Please add as an answer, and I'll give it my up vote!Remmer
Yes. Indeed. Test it and it works. Thank you.Kawai
@DavorCubranic answered.Bolton
Samir, can you accept @FrancoSolleza's answer?Remmer
B
9

According to the docs: Prior to version 2.10, in order to use a yield statement to execute teardown code one had to mark a fixture using the yield_fixture marker. From 2.10 onward, normal fixtures can use yield directly so the yield_fixture decorator is no longer needed and considered deprecated.

Bolton answered 11/3, 2017 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.