How to unit test Django-CMS extensions?

倾然丶 夕夏残阳落幕 提交于 2019-12-04 00:05:26

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):
        self.__dict__.update(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!