I have a ModelForm called SignUpForm located in myproj.accounts.forms
SignUpForm overrides Django's validate_unique so that the 'email' field is excluded from 'unique' validation as required by the model's unique=True (this is dealt with later in the view). Everything works as expected.
I now want to test the code by raising a ValidationError when self.instance.validate_unique(exclude=exclude) is called.
The problem I have is how to use mock to patch the instance.validate_unique so that a ValidationError is raised.
SignUpForm's validate_unique(self) - myproj.accounts.forms
def validate_unique(self):
exclude = self._get_validation_exclusions()
exclude.add('email')
try:
self.instance.validate_unique(exclude=exclude)
except forms.ValidationError as e:
self._update_errors(e)
This test works, but it does not raise the error on the method (validate_unique) and not the instance (self.instance.validate_unique).
def test_validate_unique_raises_exception(self):
with patch.object(SignUpForm, 'validate_unique') as mock_method:
mock_method.side_effect = Exception(ValidationError)
data = {"email": 'someone@somewhere.com',
'full_name': A User,
"password": "A19A23CD",
}
form = SignUpForm(data)
self.assertRaises(ValidationError)
My question is how can I raise a ValidationError using mock when self.instance.validate_unique is called?