测试如下所示cms/tests/plugins.py
与其说是单元测试,不如说是集成测试,这是相当重量级的,有时需要整个系统的很大一部分启动和运行(不一定是错误,只是在调试时不切实际)。
DjangoCMS 是紧密集成的,所以我这里有一些“更接近金属”的技术,而不是完整的解决方案:
你需要一个“Expando”风格的假类:
class Expando(object): # Never use in production!
def __init__(self, **kw):
self.__dict__.update(kw)
要实例化插件类的实例:
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()
健全性检查插件.render
method:
ctx = plugin.render({}, Expando(attr1='a1', attr2=123), None)
使用实际模板渲染,检查输出:
res = render_to_response(look.render_template, ctx)
# assert that attr1 exist in res if it should
# ..same for attr2
美丽汤 http://www.crummy.com/software/BeautifulSoup/在验证小 DOM 片段的内容时很方便。
使用管理表单字段间接检查模型属性是否正确运行:
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