I am trying to find out the best way for testing admin.ModelAdmin
in admin.py
. Specifically I am overriding the save_model()
function which I want to test. From the research I have done, the only solution I have found was writing a request/response test and then query the database.
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- How to replace file-access references for a module
- How to mock methods return object with deleted cop
- What is a good way of cleaning up after a unit tes
-
EF6 DbSet
returns null in Moq - Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
I had a similar problem so I wrote a tiny little helper here: https://github.com/metzlar/djest
As suggested in Udi's answer, we can study Django's own ModelAdmin tests, to determine the basic ingredients for a
ModelAdmin
test. Here's a summary:Basic ingredients
In addition to the Django
TestCase
stuff, the basic ingredients are:An instance of
AdminSite
:Your model class and corresponding
ModelAdmin
(sub)class:Optionally, depending on your needs, a (mock) request and/or form.
Recipe
The first two ingredients are required to create an instance of your (custom)
ModelAdmin
:Based on the ModelAdmin source, the default
save_model
implementation only requires an instance of your model, so it can be called, for example, as follows:It all depends on what your
save_model
does, and what you want to test. Suppose yoursave_model
checks user permissions, then you would need to pass a request (i.e. the third ingredient) with a valid user, in addition to the model instance:An example of the
MockRequest
is defined below. Based on the Django test source, a minimalrequest
consists of a Pythonobject
with auser
attribute. Theuser
attribute may refer to a mock user, or an actual instance of yourAUTH_USER_MODEL
, depending on your needs.This basic approach applies to the other
ModelAdmin
methods as well.You can specify custom modelform for modeladmin then simply test this modelform ;)
https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
forms
admin
tests
Check out Django's
ModelAdminTests
for examples.