在课堂上使用 pytest 装置

sta*_*flo 6 pytest flask python-3.x

我已经开始为我的 Flask API 编写单元测试。当我在课堂外宣布时,我已经让它们开始工作了。但是,为了简单性和 OOP 限制,我尝试让所有内容都从类中运行。问题是我似乎无法将任何固定方法传递给我的测试类。我这里的代码如下:

#conftest.py

import os, json, pytest
from ..app import create_app
from flask import Flask

@pytest.fixture
def env_setup():
    env_name = os.getenv('FLASK_ENV')
    app = create_app(env_name)
    return app
Run Code Online (Sandbox Code Playgroud)

我正在尝试将 env_setup 导入以下文件。

# test_BaseURL.py
import pytest

@pytest.mark.usefixtures("env_setup")
class TestStaticPages:

    def setUp(self, env_setup):
        """
        Setup Test
        """
        self.client = env_setup.test_client()

    def test_base_route(self, env_setup):
        #client = env_setup.test_client()
        url   = '/'
        html1 = b'Welcome to the API. Please visit '
        html2 = b'https://example.com to learn more about this app.'

        response = self.client.get(url)
        assert response.get_data() == html1 + html2
        assert response.status_code == 200
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,我不断收到以下错误:

>       response = self.client.get(url)
E       AttributeError: 'TestStaticPages' object has no attribute 'client'

src/tests/test_BaseURL.py:18: AttributeError
Run Code Online (Sandbox Code Playgroud)

但是,如果我取消注释该行,client = env_setup.test_client()它就可以工作。无论出于何种原因,它似乎无法从 setUP 方法中获取设置并不断出错。

sta*_*flo 17

以下是我解决问题的方法:

#conftest.py
import os, json, pytest
from ..app import create_app
from flask import Flask

@pytest.fixture
def client():
    env_name = os.getenv('FLASK_ENV')
    app = create_app(env_name)
    client = app.test_client()
    return client
Run Code Online (Sandbox Code Playgroud)

然后我就可以像这样将客户端导入到我的其他测试类中。

#test_StaticView.py
import pytest

@pytest.mark.usefixtures("client")
class TestStaticPages:

    def test_base_route(self, client):
        url   = '/'
        html1 = b'Welcome to the API. Please visit '
        html2 = b'https://example.com to learn more about this app.'

        response = client.get(url)
        assert response.get_data() == html1 + html2
        assert response.status_code == 200
Run Code Online (Sandbox Code Playgroud)

  • 对此有一千张赞成票。上网查了2个小时。在 pytest 的类中使用固定装置让我来到这里。pytest 类必须有 `usefixtures` 装饰器! (4认同)
  • 如果我可以添加...这对我不起作用,因为我使用 `unittest.TestCase` 来定义我的类(如 `class TestMyStuff(TestCase):` 中所示,并且这是不支持的。请参阅此处的 [pytest 文档] ](https://doc.pytest.org/en/6.2.x/unittest.html#pytest-features-in-unittest-testcase-subclasses)。我删除了 TestCase,它的工作原理与此答案完全相同。 (2认同)