HBat
HBat

Reputation: 5702

Checking the existence of a permission object in Django unit test

Suppose that I want to write a test to make sure that a permission does not exist. I want the following test to pass (instead it gives an error):

from django.test import TestCase
from django.contrib.auth.models import Permission

class TestPermission(TestCase):
  def test_existence_of_permission(self):
    self.assertIsNone(Permission.objects.get(codename='a_non_existant_permission'))

This gives me the following error:

django.contrib.auth.models.DoesNotExist: Permission matching query does not exist.

How can I test the non-existence of this permission?

Upvotes: 3

Views: 1718

Answers (1)

HBat
HBat

Reputation: 5702

I figured this out:

I should have treatead Permission as a regular Django model.

from django.test import TestCase
from django.contrib.auth.models import Permission

class TestPermission(TestCase):
  def test_existence_of_permission(self):
    self.assertFalse(Permission.objects.filter(
      codename='a_non_existant_permission').exists())

Upvotes: 4

Related Questions