Pytest fixture for a class through self not as method argument

前端 未结 2 480
庸人自扰
庸人自扰 2020-12-03 07:41

Often I\'ll write a test class that uses a pytest fixture in every method. Here\'s an example. I\'d like to be able to avoid having to write the fixture name in the signatur

2条回答
  •  执念已碎
    2020-12-03 08:21

    I had to solve a similar problem and the accepted solution didn't work for me with a class-scoped fixture.

    I wanted to call a fixture once per test class and re-use the value in test methods using self. This is actually what the OP was intending to do as well.

    You can use the request fixture to access the class that's using it (request.cls) and assign the fixture value in a class attribute. Then you can access this attribute from self. Here's the full snippet:

    from bs4 import BeautifulSoup
    import pytest
    import requests
    
    @pytest.fixture(scope="class")
    def google(request):
        request.cls.google = requests.get("https://www.google.com")
    
    
    @pytest.mark.usefixtures("google")
    class TestGoogle:
        def test_alive(self):
            assert self.google.status_code == 200
    
        def test_html_title(self):
            soup = BeautifulSoup(self.google.content, "html.parser")
            assert soup.title.text.upper() == "GOOGLE"
    

    Hope that helps anyone else coming to this question.

提交回复
热议问题