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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Maybe not? What would you recommend? As an aside, I had to add a message to the ValidationError('NoReverseMatch Error')
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.
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.

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.