[Fixed]-How to unit test Django-CMS extensions?


Tests as shown by cms/tests/plugins.py is rather integration tests than unit tests, and that’s quite heavy-weight and requires a sometimes too large part of the entire system up and running (not neccessary wrong, just impractical when debugging).

DjangoCMS is tightly integrated so what I have here are a few techniques to get ‘closer to the metal’ rather than a complete solution:

You need an ‘Expando’ -style fake class:

class Expando(object): # Never use in production!
    def __init__(self, **kw):

To instantiate an instance of your plugin class:

from cms.plugin_pool import plugin_pool

# ..in production code: class YourPlugin(CMSPlugin)...

# This ensures that the system is aware of your plugin:
YrPluginCls = plugin_pool.plugins.get('YourPlugin', None)

# ..instantiate:
plugin = YrPluginCls()

Sanity check the plugins .render method:

ctx = plugin.render({}, Expando(attr1='a1', attr2=123), None)

Render with actual template, check output:

res = render_to_response(look.render_template, ctx)
# assert that attr1 exist in res if it should
# ..same for attr2

BeautifulSoup is handy when validating content of small DOM fragments.

Use admin form fields to indirectly check that model attributes behave correctly:

from django.test.client import RequestFactory
from django.contrib.auth.models import AnonymousUser

# ...

request = RequestFactory().get('/')
request.user = AnonymousUser()
a_field = plugin.get_form(request).base_fields['a_field']
a_field.validate('<some valid value>')
# Check that a_field.validate('<some invalid value>') raises


If I understand your question correctly, you can find examples for unit-tests for plugins in the module cms/tests/plugins.py, located in the folder holding your installation of django-cms.

Basically you subclass CMSTestCase and use the Client class from django.test.client to make requests to your CMS and check the resulting responses.

Information on how to use the client can be found on http://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client


Leave a comment