Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest AttributeError: "function object has no attribute" when referencing fixture in Python 3

I have a model and a controller I'm trying to test:

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' object has no attribute 'display'

Above is the errors/failures I get every time I run the test.

class Controller:

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

    def button_pressed(self, button_label):
        pass
like image 893
Ankit Dwivedi Avatar asked Oct 17 '22 11:10

Ankit Dwivedi


1 Answers

According to pytest, by doing:

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

and then:

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

you define a fixture called controller that references another fixture called model to define the model on that instance of the Controller class. Therefore, it seems that you're not referencing model correctly:

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

or, alternatively:

def test_clear_button(controller, model):
    controller.button_pressed("4")
    controller.button_pressed("2")
    controller.button_pressed("C")
    assert model.display == "0"
like image 82
Woody1193 Avatar answered Oct 20 '22 22:10

Woody1193