devfund-website/blender_notes/tests.py

90 lines
3.1 KiB
Python

from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django.urls import reverse
from . import models
class NotesAPITest(TestCase):
fixtures = ['gateways', 'devfund']
def setUp(self):
super().setUp()
self.user = User.objects.create_user('harry', 'harry@blender.org')
self.user_ctype = ContentType.objects.get_for_model(User)
self.view_kwargs = {
'app_label': self.user_ctype.app_label,
'model_name': self.user_ctype.model,
'object_id': self.user.pk}
self.url = reverse('notes:for-object', kwargs=self.view_kwargs)
def grant(self, user: User, permission_name: str):
from django.contrib.auth.models import Permission
content_type = ContentType.objects.get_for_model(models.Note)
permission = Permission.objects.get(content_type=content_type, codename=permission_name)
user.user_permissions.add(permission)
def test_get_anonymous(self):
resp = self.client.get(self.url)
self.assertEqual(403, resp.status_code)
def test_get_no_permission(self):
self.client.force_login(self.user)
resp = self.client.get(self.url)
self.assertEqual(403, resp.status_code)
def test_get_with_permission(self):
self.grant(self.user, 'view_note')
self.client.force_login(self.user)
resp = self.client.get(self.url)
self.assertEqual(200, resp.status_code)
def test_post_with_only_view_permission(self):
self.grant(self.user, 'view_note')
self.client.force_login(self.user)
resp = self.client.post(self.url, data={'note': '1234'})
self.assertEqual(403, resp.status_code)
self.assertEqual(0, models.Note.objects.count())
def test_post_with_only_add_permission(self):
self.grant(self.user, 'add_note')
self.client.force_login(self.user)
resp = self.client.post(self.url, data={'note': '1234'})
self.assertEqual(200, resp.status_code)
self.assertEqual(1, models.Note.objects.count())
def test_delete_with_only_add_permission(self):
self.grant(self.user, 'add_note')
self.client.force_login(self.user)
delete_url = self._create_note()
resp = self.client.post(delete_url)
self.assertEqual(403, resp.status_code)
self.assertEqual(1, models.Note.objects.count())
def test_delete_with_only_delete_permission(self):
self.grant(self.user, 'delete_note')
self.client.force_login(self.user)
delete_url = self._create_note()
resp = self.client.post(delete_url)
self.assertEqual(302, resp.status_code)
self.assertEqual(0, models.Note.objects.count())
def _create_note(self) -> str:
note = models.Note.objects.create(
content_type=self.user_ctype,
object_id=self.user.pk,
note='123123',
)
delete_url = reverse('notes:delete-note', kwargs={'note_id': note.pk, **self.view_kwargs})
return delete_url