4

我正在为一些包编写测试,我需要验证是否正确注册了一些静态资源。

在 Plone 5 之前,我可以通过访问资源注册表来做到这一点,如下所示:

self.portal.portal_javascripts.getResourceIds()
self.portal.portal_css.getResourceIds()

如何在 Plone 5 中完成该任务?

4

2 回答 2

1

看来这个问题的答案在于Products.CMFPlone 中的资源测试

具体来说,在该文件中的测试用例中,有许多测试使用配置注册表来访问已注册的包和资源,如下所示:

from Products.CMFPlone.interfaces import IBundleRegistry
from Products.CMFPlone.interfaces import IResourceRegistry
from plone.registry.interfaces import IRegistry
from zope.component import getUtility

resources = getUtility(IRegistry).collectionOfInterface(
    IResourceRegistry, prefix="plone.resources"
)
bundles = getUtility(IRegistry).collectionOfInterface(
    IBundleRegistry, prefix="plone.bundles"
)

这些调用的返回值是类似字典的对象,它们包含指向已使用registry.xml通用设置导入步骤注册的捆绑包或资源的配置注册表条目的指针。

因此,例如,如果您使用以下 xml 在您的产品中注册了一个捆绑包:

<records prefix="plone.bundles/my-product"
        interface='Products.CMFPlone.interfaces.IBundleRegistry'>
 <value key="resources">
  <element>my-resource</element>
 </value>
 <value key="enabled">True</value>
 <value key="jscompilation">++plone++static/my-compiled.js</value>
 <value key="csscompilation">++plone++static/my-compiled.css</value>
 <value key="last_compilation">2014-08-14 00:00:00</value>
</records> 

然后在bundles上面的资源注册表返回的内容中,您将能够使用斜杠 ( 'my-product') 后面的捆绑包“前缀”部分来查找捆绑包的注册表记录代理,如下所示:

my_bundle = bundles['my-product']

该记录将提供对包的已定义接口的属性访问(有关详细信息,请参阅Products.CMFPlone.interfaces.resources.IBundleRegistry)。所以你应该能够检查它是否为编译的 js 或 css 设置了正确的值:

assert my_bundle.jscompilation == '++plone++static/my-compiled.js'
assert my_bundle.csscompilation == '++plone++static/my-compiled.css'

已注册资源的记录将以相同的方式工作,一个类似字典的对象,其键对应于registry.xml斜杠后面的资源注册的“前缀”部分。在这种情况下返回的记录将支持Products.CMFPlone.interfaces.resources.IResourceRegistry。但是您仍然可以使用属性访问来验证您期望的值是否已正确注册。

如果您有使用不推荐使用的portal_javascriptportal_css工具注册的资源(使用jsregistry.xmlcssregistry.xml通用设置导入步骤),找到它们的关键是 Plone 现在将自动将这些资源包含在一个名为plone-legacy. 由于包具有resources提供该包中包含的资源列表的属性,因此您应该能够执行以下操作:

bundles = getUtility(IRegistry).collectionOfInterface(
    IBundleRegistry, prefix="plone.bundles"
)
legacy_bundle = bundles['plone-legacy']
assert "my-oldskool.js" in legacy_bundle.resources

这方面的示例也可以在 Products.CMFPlone 中的资源测试中找到。特别是在TestResourceNodeImporter测试用例中。

于 2016-04-09T01:05:02.830 回答
0

由于没有简单的方法来完成这项任务,并且建议的解决方案添加了超过 10 行代码,我想说这个测试必须在 Plone 5 中跳过:

IS_PLONE_5 = api.env.plone_version().startswith('5')

@unittest.skipIf(IS_PLONE_5, 'No easy way to test this under Plone 5')
def test_cssregistry(self):
    resource_ids = self.portal.portal_css.getResourceIds()
    self.assertIn(CSS, resource_ids)
于 2016-05-02T16:07:29.523 回答