6

I am trying to figure out if there's a way to (unit test) verify that the property and the setter is actually called to set the name attribute.

class DummyName:
    def __init__(self):
        self.name = ''

    @property
    def name(self):
        return self.name

    @name.setter
    def name(self, name):
        if not isinstance(name, basestring):
            raise Exception('Name must be a string.')
        self.name = name

Trying to do something like this...

@mock.patch.object(DummyName, 'name', new_callable=PropertyMock)
def testNameProperty(self, mock_name):
    MockName = Mock()
    mock_name.return_value = MockName
    dummyName = DummyName()
    dummyName.name = 'test_name'
    # assert setter is called to set the name
    # assert name is called to get the name
    # assert name is 'test_name'

Seems like name() and setter are never accessed. the Anyone has a better idea? Thanks!

1
  • dummyName.name = 'test_name' overrides the setter field. Use different names for different methods / variables / etc Commented Aug 14, 2017 at 18:13

2 Answers 2

5

By using mocks like that you've overwritten the code you're trying to test. Mocks are for calls that are external to the code under test.

An appropriate test for this code is to assert that the exception is raised if you pass something that isn't a string.

def testNameProperty(self):
    dummyName = DummyName()
    with self.assertRaises(Exception):
        dummyName.name = 12345
Sign up to request clarification or add additional context in comments.

2 Comments

this gives AssertionError: Exception not raised error
See Cory's answer for the reasons why.
2

Your class needs to inherit from object.

class DummyName(object):
    def __init__(self):
        self._name = ''

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        if not isinstance(name, basestring):
            raise Exception('Name must be a string.')
        self._name = name

You also need to use different variables for the name inside the class, or you'll hit maximum recursion.

Comments

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.