【问题标题】:Fixture not found pytest找不到夹具 pytest
【发布时间】:2022-01-21 13:20:34
【问题描述】:

嘿,我得到了一个简单的测试,没有找到修复程序。我正在写 vsc 并使用 windows cmd 运行 pytest。

def test_graph_add_node(test_graph):
E       fixture 'test_graph' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

这是我得到的错误,这是测试代码:

import pytest
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'giddeon1.settings')
import django
django.setup()

from graphs.models import Graph, Node, Tag


@pytest.fixture
def test_graph():
    graph = Graph.objects.get(pk='74921f18-ed5f-4759-9f0c-699a51af4307')
    return graph

def test_graph():
    new_graph = Graph()
    assert new_graph

def test_graph_add_node(test_graph):
    assert test_graph.name == 'Test1'

我使用 python 3.9.2,pytest 6.2.5。 我见过一些类似的问题,但它们都处理更广泛或更大的问题。

【问题讨论】:

    标签: python-3.x django pytest


    【解决方案1】:

    您似乎定义了两次test_graph,这意味着第二个定义将覆盖第一个。并且您在使用 test_ 方法时添加了 @pytest.fixture,但应将 @pytest.fixture 添加到非测试方法中,以便测试可以使用该夹具。以下是代码的外观:

    import pytest
    import os
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'giddeon1.settings')
    import django
    django.setup()
    
    from graphs.models import Graph, Node, Tag
    
    
    @pytest.fixture
    def graph():
        graph = Graph.objects.get(pk='74921f18-ed5f-4759-9f0c-699a51af4307')
        return graph
    
    def test_graph():
        new_graph = Graph()
        assert new_graph
    
    def test_graph_add_node(graph):
        assert graph.name == 'Test1'
    

    上面,第一个方法已重命名为graph,因此下一个方法不会覆盖它(现在@pytest.fixture 应用于非测试方法)。然后,第三种方法使用graph 夹具。根据需要进行任何其他更改。

    【讨论】:

    • 说得对,谢谢!
    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 2022-01-21
    • 2016-07-27
    • 1970-01-01
    • 2021-08-30
    • 2021-10-01
    • 2021-03-13
    • 2019-07-17
    相关资源
    最近更新 更多