Domanda

Does anyone know a mocking- or stubbing-framework which allows stubbing properties or even classproperties like this decorator does?

class classproperty:
    """
    Decorator to  read-only static properties
    """
    def __init__(self, getter):
        self.getter = getter
    def __get__(self, instance, owner):
        return self.getter(owner)

class Foo:
    _name = "Name"
    @classproperty
    def foo(cls):
        return cls._name

I'm currently using mockito, but this doesn't allow stubbing of properties.

È stato utile?

Soluzione

Using unittest.mock.PropertyMock (available since Python 3.3):

from unittest import mock
with mock.patch.object(Foo, 'foo', new_callable=mock.PropertyMock) as m:
    m.return_value = 'nAME'
    assert Foo.foo == 'nAME'

NOTE: If you use Python version lower than 3.3, use mock.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top