1

I am having problem mocking an object to test a descriptor.

This is the code of the descriptor:

class Text(object):
    def __init__(self, default_value=u'', validators=[]):
        self.validators = validators
        self._value = default_value

    def __set__(self, instance, value):
         for validator in self.validators:
               validator(value).validate()

this is the test:

def test_text_validator_raises_exception(self):
   validator = Mock()
   validator.validate.side_effect = ValidationError()
   text = Text(validators=[validator])
   self.assertRaises( ValidationError, text__set__, (text, '') )

Edit: The function has () in the code I did a typo when copying the code.

The error I got was that set() takes exactly 3 arguments. But I noticed in the answers that I shouldn't pass a tuple as a last argument.

But It also isn't working when I called validator('').validate() inside the test function.

1
  • Sorry, should have been more clear. Commented Nov 12, 2010 at 22:35

3 Answers 3

3
  • validator in Text is an object factory e.g., class object
  • validator in the test_.. function is used as a concrete instance -- the product of an object factory.

You should give to Text() something that returns objects with .validate method not the objects themselves:

def test_text_validator_raises_exception(self):
    validator = Mock()
    validator.validate.side_effect = ValidationError()
    text = Text(validators=[Mock(return_value=validator)])
    self.assertRaises(ValidationError, text.__set__, text, '')
Sign up to request clarification or add additional context in comments.

3 Comments

This is actually what I was trying to ask. Was trying to figure out how to let mock return a class instead of an object. In your example doesn't Mock(return_value=validator) also return the instance of the object instead of class?
Tried it and it works, thanks a lot. Going to try and not make any questions anymore when I am in a hurry since it all got a little messy. Thanks again.
@Pickels: Consider: f = Mock(return_value=validator). Here's f is an object that returns validator when you call it e.g., f(value) == validator. f and f() are different things in Python.
1

I guess you need to put () after function name

1 Comment

Yes, def test_text_validator_raises_exception certainly needs ().
0

Maybe the best way to mock an instance is just "You call yourself an instance?"

Seriously, though, def test_text_validator_raises_exception: should be def test_text_validator_raises_exception():

But what problem are you having with it, as the first commenter asked?

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.