Login

Automatic testing of add and changelist admin views

Author:
Taifu
Posted:
August 20, 2011
Language:
Python
Version:
1.3
Tags:
admin test automatic test
Score:
1 (after 1 ratings)

If you want to test for trivial error in your add and changelist admin views, use this snippet.

Save the snippet in admintests.py and put it anywhere in your pythonpath.

Put this code in your tests.py:

from django.test import TestCase
from admintest import adminviews_test

class TestAdminViews(TestCase):
    def test_admin_views(self):
        adminviews_test(self)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
# -*- coding: utf-8 -
#
# @contact: [email protected]
# @version: 1.0
# @license: MIT http://www.opensource.org/licenses/mit-license.php
#

from django.db.models.base import ModelBase
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib import admin
from django.contrib.auth.models import User

def adminviews_test(self, user=None, password=None):
    if user is None:
        if password is None:
            password = "test"
        user = User.objects.create_superuser('test', '[email protected]', password)
    self.client.login(username = user.username, password = password)
    pkg = self.__module__.rpartition('.')[0]
    if pkg.endswith(".tests"):
        pkg = pkg[:-6]
    models_mod = __import__(pkg + ".models")
    if not getattr(models_mod, "models", None):
        return
    for id_ in dir(models_mod.models):
        model = getattr(models_mod.models, id_)
        # Get ModelAdmin for this Model
        if isinstance(model, ModelBase) and model._meta.app_label == pkg and model in admin.site._registry:
            try:
                # Prevent error 405 if model_admin.has_add_permission always return False
                if admin.site._registry[model].has_add_permission(type("request", (), {"user": user})):
                    url = reverse("admin:%s_%s_add" % (model._meta.app_label, model._meta.module_name))
                    response = self.client.get(url, follow = True)
                    self.failUnlessEqual(response.status_code, 200,
                         "%s != %s -> %s, url: %s" % (response.status_code, 200, repr(model), url))
                    self.assertFalse("this_is_the_login_form" in response.content,
                         "login requested for %s" % str(model))
                url = reverse("admin:%s_%s_changelist" %
                        (model._meta.app_label, model._meta.module_name))
                response = self.client.get(url, follow = True)
                self.failUnlessEqual(response.status_code, 200,
                     "%s != %s -> %s, url: %s" % (response.status_code, 200, repr(model), url))
                self.assertFalse("this_is_the_login_form" in response.content,
                     "login requested for %s" % str(model))
            except NoReverseMatch:
                continue

More like this

Comments

moreno (on August 2, 2013):
<p>It doesn't work at django 1.4.5 :(</p> <p>At the top instructions it's missing a 's' at admintests:</p> <p>from admintests import adminviews_test</p>

#

bufke (on November 14, 2013):
<p>I was able to get it working in 1.6.</p> <p>You must call admin.autodiscover()</p> <p>It does not support app names like "foo.bar" but you can hack on it to make it work.</p>

#

brigantino (on March 4, 2014):
<p>It's necessary to call admin.autodiscover() to populate admin.site._registry. There's also an easier way to retrieve models, using</p> <pre>for model in models.get_models(include_auto_created=True): </pre> <p>instead of:</p> <pre>models_mod = __import__(pkg + ".models") if not getattr(models_mod, "models", None): return for id_ in dir(models_mod.models): model = getattr(models_mod.models, id_) </pre> <p>you might also need to check that pkg value is ok for this check: model._meta.app_label == pkg</p>

#

Please login first before commenting.