当使用pytest时,找不到夹具'custom_fixture'。

问题描述 投票:0回答:1

我有一个简单的夹具来设置一个自定义类的实例,在执行时得到这个错误,特别是在 ...setup of test_headers.

fixture 'slack_client' not found

夹具代码。

import os
import pytest
from api.slack import Slack #Slack is the custom class


@pytest.fixture(scope='module')
def set_up_slack_client():
    print("---Creating default instance of Slack client class---")
    BOT_O_AUTH_TOKEN = os.getenv("BOT_O_AUTH_TOKEN")
    slack_client = Slack()
    yield slack_client

还有产生错误的测试代码。

def test_headers(slack_client):
    headers_match = {"Authorization": "Bearer " + slack_client.bearer_token,
                     "content-type": slack_client.content_type}
    assert slack_client.headers() == headers_match

所有这些都在同一个 test_api.py 文件。自定义 Slack 类在其他地方,但我正在导入它。有什么建议可以告诉我,我遇到了什么问题,如何纠正它?

python unit-testing pytest fixtures
1个回答
0
投票

我想我需要咖啡...

问题是我的夹具名称与我传递给测试函数的参数名称不同,即 set_up_slack_clientslack_client. 似乎pytest寻找的是与param命名完全相同的固定装置,而不仅仅是在同一命名空间的vars、对象等。

这段代码是可行的。

import os
import pytest
from api.slack import Slack #Slack is the custom class


@pytest.fixture(scope='module')
def slack_client():                                #THIS IS WHAT CHANGED
    print("---Creating default instance of Slack client class---")
    BOT_O_AUTH_TOKEN = os.getenv("BOT_O_AUTH_TOKEN")
    slack_client = Slack()
    yield slack_client

def test_headers(slack_client):
    headers_match = {"Authorization": "Bearer " + slack_client.bearer_token,
                     "content-type": slack_client.content_type}
    assert slack_client.headers() == headers_match
© www.soinside.com 2019 - 2024. All rights reserved.