2

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:

Model

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

Test

# 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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Carl Brubaker
  • 1,602
  • 11
  • 26

1 Answers1

2

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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • Maybe not? What would you recommend? As an aside, I had to add a message to the `ValidationError('NoReverseMatch Error')` – Carl Brubaker Sep 08 '18 at 23:15
  • It is usually best too use two different tests for each error type and then figure out how excite the error independently. So in this case inject a view_name that will cause the appropriate error for each test. – Stephen Rauch Sep 08 '18 at 23:17
  • `def test_AvailablePermissions_only_saves_if_view_exists(self):` - To pass this test I broke the one above and couldn't figure out how to rewrite it with only a small amount of code. – Carl Brubaker Sep 08 '18 at 23:24