Reputation: 1655
I am trying to test that a certain instance of a model will raise one of two exceptions, but I can't figure out how to get it to work. Here is what I have:
class AvailablePermissions(models.Model):
# Main Checkbox.
category = models.CharField(
max_length=100,
)
# Checkboxes under Main Checkbox.
subcategory = models.CharField(
max_length=100,
)
# The view to grant permission to.
view_name= models.CharField(
max_length=255,
unique=True,
)
def full_clean_save(self):
try:
name = resolve(reverse(f'{self.view_name}'))
self.full_clean()
self.save()
except NoReverseMatch as nrme:
raise nrme
except ValidationError as ve:
raise ve
return self
# Default permission object "(**permission)"
permission = {
'category': 'Category',
'subcategory': 'Subcategory',
'view_name': 'employee:create_profile',
}
available_permission = AvailablePermissions(**permission)
class AvailablePermissionsValidationTest(TestCase):
def test_AvailablePermissions_will_not_save_blank_permissions(self):
for field in permission:
original_value = permission[field]
permission[field] = ''
with self.assertRaises(ValidationError or NoReverseMatch):
AvailablePermissions(
**permission
).full_clean_save()
permission[field] = original_value
It throws the NoReverseMatch
error, but I can't figure out how to look for "either or" exception.
Upvotes: 2
Views: 641
Reputation: 49814
This might work:
with self.assertRaises(ValidationError):
try:
AvailablePermissions(
**permission
).full_clean_save()
except NoReverseMatch:
raise ValidationError
But do you really want to do that? Generally with unit testing the desire is to exercise all of the possible paths. This would just guarantee one of two paths were tested.
Upvotes: 2