如何单元测试Django-CMS扩展? [英] How to unit test Django-CMS extensions?
问题描述
我正在尝试为我正在开发的Django-CMS实现提供一些测试报告,我不知道如何单元测试插件/扩展。有没有人这样做过,如果是这样,怎么样?
测试如 cms / tests / plugins.py
是单元测试的集成测试,而且这个测试非常重,并且需要整个系统有时太大的一部分运行(不必要的错误,调试时不切实际)。
DjangoCMS是紧密集成的,所以我在这里有一些技术来靠近金属,而不是一个完整的解决方案:
你需要一个'Expando'风格的假类:
class Expando(object):#在生产中绝不使用!
def __init __(self,** kw):
self .__ dict __。update(kw)
要实例化一个插件类的实例:
从cms.plugin_pool import plugin_pool
#..在生产代码:class YourPlugin(CMSPlugin)...
#这确保系统知道你的插件:
YrPluginCls = plugin_pool.plugins.get(' YourPlugin',None)
#..instantiate:
plugin = YrPluginCls()
健康检查插件 .render
方法:
ctx = plugin.render({},Expando(attr1 ='a1',attr2 = 123),无)
使用实际模板呈现,检查输出:
res = render_to_response(look.render_template,ctx)
#断言attr1存在于res如果它应该
#..same for attr2
< a href =http://www.crummy.com/software/BeautifulSoup/ =nofollow> Beau tifulSoup 在验证小型DOM片段的内容时非常方便。
使用管理表单字段间接检查模型属性是否正确:
$ b $ django.contrib.auth.models中的$ 。
request = RequestFactory()。get('/')
request.user = AnonymousUser()
a_field = plugin.get_form(request).base_fields ['a_field' ]
a_field.validate('< some valid value>')
#检查a_field.validate('<一些无效值>')引发
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 so, how? Some examples would be awesome.
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
这篇关于如何单元测试Django-CMS扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!