1

I use Pytest and I want to test a class which has a dynamic attribute set by a function

Here is an example

file_1.py

def fn():
    return 'foo'

class Cls(object):
    cls_attr = fn()

test_file_1.py

import file_1

def test_cl1(monkeypatch):
    monkeypatch.setattr('file_1.fn', lambda: 'bar')
    assert file_1.fn() == 'bar'
    cls = file_1.Cls()
    assert cls.cls_attr == 'bar' # <-- fail here

I think that python "compile"s the class before, then monkeypatch is run after.

Is there a way to "reload" the class with the monkeypatched function?

1 Answer 1

2

I don't think so... but why not monkeypatch the Cls.cls_attr instead?

ETA: Perhaps what you want to use instead of monkeypatch is mock. There is a pytest-mock plugin that may be useful with it too.

Sign up to request clarification or add additional context in comments.

2 Comments

This is an extremely simplified example. In the code I use functools.partials and some nested stuff I want to test either with this.
On reflection I think perhaps you are after mock rather than monkeypatch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.