django admin test
2020-04-25 本文已影响0人
swotpp
-
创建模型 models.py
from django.db import models class Call(models.Model): ordernum = models.CharField( "工单号", max_length=200, default="",)
-
admin.py
from django.contrib import admin from . import models def add_delete_permission(request): group_name = request.user.groups.first().name if group_name == "风控": return False return True class CallAdmin(admin.ModelAdmin): def has_add_permission(self, request): return add_delete_permission(request) def has_delete_permission(self, request, obj=None): return add_delete_permission(request) admin.site.register(models.Call, CallAdmin)
-
tests.py 使用mock来减少创建用户、组及将用户加入组中的代码
from django.test import TestCase from . import models from django.contrib.admin.sites import AdminSite from .admin import CallAdmin from unittest import mock class CallAdminTests(TestCase): def setUp(self): self.call_admin = CallAdmin(model=models.Call, admin_site=AdminSite()) self.OurRequest = mock.Mock() self.OurRequest.user.groups.first.return_value.name = '风控' def test_has_add_permission(self): self.assertEquals(self.call_admin.has_add_permission(self.OurRequest), False) def test_has_delete_permission(self): self.assertEquals(self.call_admin.has_delete_permission(self.OurRequest), False)
-
项目下 urls.py
from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ]