How to unit test Django-CMS extensions?

前端 未结 2 1261
南方客
南方客 2021-02-19 08:55

I am trying to get some test coverage for a Django-CMS implementation I\'m working on and I\'m unsure how to unit test plugins/extensions. Has anyone done this before, and if s

相关标签:
2条回答
  • 2021-02-19 09:02

    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
    
    0 讨论(0)
  • 2021-02-19 09:28

    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

    0 讨论(0)
提交回复
热议问题