python - pytest 属性错误 : "function object has no attribute" when referencing fixture in Python 3

标签 python python-3.x pytest

我有一个模型和一个要测试的 Controller :

class Model:

    def __init__(self):
        self.display = ""

    def set_display(self, display):
        self.display = display

import pytest
from model import Model
from controller import Controller

@pytest.fixture
def model():
    return Model()

@pytest.fixture
def controller(model):
    return Controller(model)

def test_clear_button(controller):
    controller.button_pressed("4")
    controller.button_pressed("2")
    controller.button_pressed("C")
    assert model.display == "0"

E AttributeError: 'function' 对象没有属性 'display'

以上是我每次运行测试时遇到的错误/失败。

class Controller:

    def __init__(self, model):
        self.model = model

    def button_pressed(self, button_label):
        pass

最佳答案

根据 pytest ,通过做:

@pytest.fixture
def model():
    return Model()

然后:

@pytest.fixture
def controller(model):
    return Controller(model)

您定义了一个名为 controller 的 fixture,它引用另一个名为 model 的 fixture 来在 Controller< 的实例上定义 model/类。因此,您似乎没有正确引用 model:

def test_clear_button(controller):
    controller.button_pressed("4")
    controller.button_pressed("2")
    controller.button_pressed("C")
    assert controller.model.display == "0"

或者,或者:

def test_clear_button(controller, model):
    controller.button_pressed("4")
    controller.button_pressed("2")
    controller.button_pressed("C")
    assert model.display == "0"

关于python - pytest 属性错误 : "function object has no attribute" when referencing fixture in Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53072765/

相关文章:

python - save() 上的 Django Rest Framework 完整性错误,is_valid() 返回 true

Python HTTP 请求和调试级别记录到日志文件

python - python 3中所有导入的列表

python - pytest 不会运行子目录中的测试文件

python - 如何在没有函数的脚本上使用 pytest

python - 如何使用 "matplotlib.pyplot"在不同窗口中绘制图表?

python - 如何让 pynput 与 ubuntu 一起工作?

python - 一个Python程序,掷两个骰子并计算尝试次数,直到这两个骰子的数量都为6

python - 为什么我不能在 Python 中使用 ttk?

python - 找不到 pytest 固定装置(pytest-bdd)