-1

In my pytest file test_foo.py, I am trying to change the value of foo.path to mock_path using monkeypatch. However, when I try the following, I get an error

ERROR test_foo.py::test_foo - AttributeError: 'foo' has no attribute 'path'

What should be the correct way to make this change so that foo object in test_foo will use mock_path and pass that test?

test_foo.py:

import os
import pytest


class Foo:
    def __init__(self):
        self.path = os.path.join(os.getcwd(), "test.txt")
        
@pytest.fixture
def foo(monkeypatch):
    monkeypatch.setattr(Foo, 'path', 'mock_path')
    return Foo()

def test_foo(foo):
    assert foo.path == "mock_path"
Athena Wisdom
  • 6,101
  • 9
  • 36
  • 60

1 Answers1

1

You are trying to change the attribute on the class instead of the class instance, so the error message comes from monkeypath.setattr - Foo has indeed no attribute path, as this is an instance variable.

To fix this, patch the class instance instead:

@pytest.fixture
def foo(monkeypatch):
    inst = Foo()
    monkeypatch.setattr(inst, 'path', 'mock_path')
    return inst
MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46