How to unit test Django-CMS extensions?

前端 未结 2 1270
南方客
南方客 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('')
    # Check that a_field.validate('') raises
    

提交回复
热议问题