question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Spying on properties

See original GitHub issue

I’ve tried to use spy on object properties, but it fails with AttributeError: can't set attribute in unittest/mock.py.

I’ve started looking into adding support for (through PropertyMock), but failed to make it work without accessing/calling the property method during setup of the spy - it would be better to only call it when it’s accessed from the test.

I would appreciate any feedback / help in this regard.

Issue Analytics

  • State:open
  • Created 8 years ago
  • Reactions:1
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

12reactions
fliiiixcommented, Mar 23, 2018

Is there any progress?

4reactions
fogocommented, Mar 2, 2016

This a nice feature that I didn’t even think about because I guess never really mocked a property before.

Below it is a draft I’ve come up in a hurry that is really buggy but get the basics done:

def spy(self, obj, name):
        if isinstance(getattr(obj, name), property):
            prop = getattr(obj, name)

            class SpyPropertyMock(mock_module.PropertyMock):

                def __get__(self, obj, obj_type):
                    self()
                    return prop.__get__(obj)

                def __set__(self, obj, val):
                    self(val)
                    prop.fset(obj, val)

            result = self.patch.object(obj, name, new_callable=SpyPropertyMock)
            return result
        else:
            method = getattr(obj, name)

            autospec = inspect.ismethod(method) or inspect.isfunction(method)
            # Can't use autospec classmethod or staticmethod objects
            # see: https://bugs.python.org/issue23078
            if inspect.isclass(obj):
                # bypass class descriptor:
                # http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static
                value = obj.__getattribute__(obj, name)
                if isinstance(value, (classmethod, staticmethod)):
                    autospec = False

            result = self.patch.object(obj, name, side_effect=method,
                                       autospec=autospec)
            return result

A test using it:

def testFoo(mocker):
    mocked = mocker.spy(Foo, 'foo')

    foo = Foo()
    foo.foo = 'b'

    assert foo.foo == 'b'
    assert foo.foo != 'c'
    assert foo.foo != 'd'
    print mocked.mock_calls  #  [call(u'b'), call(), call(), call()]

With this, the mock object returned can be used to inspect mock_calls to property and property value is in fact changed.

Problems I’ve seen so far:

  • I’m unable to access Foo.foo without getting errors.
  • Different from method spies, object accessed by foo attr isn’t a mock object, so it is only possible to access mock call objects through returned object.

Anyway I have to get more used to PropertyMock before moving on, let me know more details about your problems and implementation (maybe open a PR?) because I can try to help 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Spying on properties - Jasmine Documentation
Properties are more complicated than functions. In Jasmine, you can do anything with a property spy that you can do with a function...
Read more >
How to spy on a property (getter or setter) with Jasmine
spyOnProperty is implemented with a function behind the property defined through Object.defineProperty. So, you cannot use spyOnProperty to ...
Read more >
jasmine Spy on Properties on Mock Objects | devnote
You can create a spy object with several properties on it quickly by passing an array or hash of properties as a third...
Read more >
How to spyOn a value property (rather than a method) with ...
The right way to do this is with the spy on property, it will allow you to simulate a property on an object...
Read more >
54. Spy on the getter and setter properties using ... - YouTube
In this video we will see how to spy ion the getter and setter properties using spyOnProperty method - Jasmine TestingUnit Testing with ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found