def test_create_source(self): """Create a source using the transformer. """ version = self.root.document.get_editable() sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0) # We now save the source, this going to create it. saved_text = self.transform( """ <h1> Document Example </h1> <div class="external-source" data-silva-name="cs_citation" data-silva-settings="field_citation=Super%20citation&field_author=moi"> </div> """, ISaveEditorFilter, version, ) # One source have been created. sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1) instance_key = list(sources.all())[0] parameters, source = sources.get_parameters(instance=instance_key) self.assertTrue(verifyObject(IExternalSourceInstance, parameters)) self.assertEqual(parameters.get_source_identifier(), "cs_citation") self.assertEqual(parameters.get_parameter_identifier(), instance_key) self.assertEqual(source.id, "cs_citation") self.assertEqual(parameters.citation, u"Super citation") self.assertEqual(parameters.author, u"moi") self.assertEqual(parameters.source, u"") tests.assertXMLEqual( saved_text, """ <div class="external-source" data-source-instance="%s"> </div> """ % instance_key, ) # You can render this source for the editor editor_text = self.transform(saved_text, IInputEditorFilter, version) tests.assertXMLEqual( editor_text, """ <h1> Document Example </h1> <div class="external-source" data-silva-instance="%s"> </div> """ % instance_key, ) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def test_create_source(self): """Create a source using the transformer. """ version = self.root.document.get_editable() sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0) # We now save the source, this going to create it. saved_text = self.transform( """ <h1> Document Example </h1> <div class="external-source" data-silva-name="cs_citation" data-silva-settings="field_citation=Super%20citation&field_author=moi"> </div> """, ISaveEditorFilter, version) # One source have been created. sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1) instance_key = list(sources.all())[0] parameters, source = sources.get_parameters(instance=instance_key) self.assertTrue(verifyObject(IExternalSourceInstance, parameters)) self.assertEqual(parameters.get_source_identifier(), 'cs_citation') self.assertEqual(parameters.get_parameter_identifier(), instance_key) self.assertEqual(source.id, 'cs_citation') self.assertEqual(parameters.citation, u'Super citation') self.assertEqual(parameters.author, u'moi') self.assertEqual(parameters.source, u'') tests.assertXMLEqual( saved_text, """ <div class="external-source" data-source-instance="%s"> </div> """ % instance_key) # You can render this source for the editor editor_text = self.transform(saved_text, IInputEditorFilter, version) tests.assertXMLEqual( editor_text, """ <h1> Document Example </h1> <div class="external-source" data-silva-instance="%s"> </div> """ % instance_key) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def test_display_source_with_default_alignement(self): """If you render without any layer, you will see the code source rendered. """ version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory( "body", version.body, """ <div class="external-source default" data-source-instance="%s"> </div> """ % self.instance_key, IDisplayFilter, ) tests.assertXMLEqual( unicode(transformer), """ <div class="citation"> Don't trust citations on the Internet <div class="author"> Charlemagne </div> <div class="source"> The Internet </div> </div> """, ) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def get(self, block_id): block = self.manager.get_block(block_id) if block is not None: return block, component.getWrapper( (block, self.context, self.request), IBlockController) return None, None
def getDeserializers(self): form = self.form deserializers = {} for field in form.fields: deserializers[field.identifier] = component.getWrapper( (field, form), IXMLFieldDeserializer) return deserializers
def test_create(self): """Create a source by hand. """ request = TestRequest(form={ 'field_citation': 'je bent een hero', 'field_author': 'u', 'field_source': 'google', }) version = self.root.example.get_editable() sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0) controller = sources(request, name='cs_citation') # You cannot save or remove the source, it does not exist yet. with self.assertRaises(AssertionError): controller.save() with self.assertRaises(AssertionError): controller.remove() self.assertEqual(controller.getId(), None) # But you can create it, and it will created after. controller.create() self.assertNotEqual(controller.getId(), None) self.assertEqual(len(sources.all()), 1) instance_key = list(sources.all())[0] parameters, source = sources.get_parameters(instance=instance_key) self.assertTrue(verifyObject(IExternalSourceInstance, parameters)) self.assertEqual(controller.getId(), instance_key) self.assertEqual(parameters.get_parameter_identifier(), instance_key) self.assertEqual(parameters.get_source_identifier(), 'cs_citation') self.assertEqual(source.id, 'cs_citation') self.assertEqual(parameters.citation, u'je bent een hero') self.assertEqual(parameters.author, u'u') self.assertEqual(parameters.source, u'google')
def test_create_transform(self): """Create a new source instance, of an existing code source. """ request = TestRequest() version = self.root.example.get_editable() version.body.save(version, request, HTML_WORKING_SOURCE) # This gives access to all the sources sources = getWrapper(version, IExternalSourceManager) self.assertTrue(verifyObject(IExternalSourceManager, sources)) self.assertEqual(len(sources.all()), 1) instance_key = list(sources.all())[0] parameters, source = sources.get_parameters(instance=instance_key) self.assertTrue(verifyObject(IExternalSourceInstance, parameters)) # A parameters store data self.assertEqual(parameters.get_source_identifier(), 'cs_citation') self.assertEqual(parameters.get_parameter_identifier(), instance_key) self.assertEqual(source.id, 'cs_citation') self.assertEqual(parameters.citation, u'je bent een klootzak') self.assertEqual(parameters.author, u'jou') self.assertEqual(parameters.source, u'wikipedia') # You can bind parameters to a content and a request controller = sources(request, instance=instance_key) self.assertTrue(verifyObject(IExternalSourceController, controller))
def setUp(self): super(EditCustomSourceTransformerTestCase, self).setUp() factory = self.root.manage_addProduct["SilvaExternalSources"] factory.manage_addCodeSource("cs_source", "Test Source", "script") factory = self.root.cs_source.manage_addProduct["PythonScripts"] factory.manage_addPythonScript("script") script = self.root.cs_source._getOb("script") script.write( """ ##parameters=model,version,REQUEST return '<a href="http://silvacms.org">SilvaCMS</a><b>Silva is cool</b>' """ ) version = self.root.document.get_editable() sources = getWrapper(version, IExternalSourceManager) controller = sources(TestRequest(form={}), name="cs_source") controller.create() self.instance_key = controller.getId() self.saved_text = ( """ <h1>This is a title</h1> <div class="external-source" data-source-instance="%s"> </div> <p>Well good bye!</p> """ % self.instance_key )
def setUp(self): self.root = self.layer.get_application() self.layer.login('manager') # Create a test document. factory = self.root.manage_addProduct['silva.app.document'] factory.manage_addDocument('example', 'Example') # Create a test code source. factory = self.root.manage_addProduct['SilvaExternalSources'] factory.manage_addCodeSource('codesource', 'Test Source', 'script') source = self.root._getOb('codesource', None) # Add the rendering script factory = source.manage_addProduct['PythonScripts'] factory.manage_addPythonScript('script') script = source._getOb('script') script.write(""" ##parameters=model,version,REQUEST return "Render source" """) # Create an instance of the code source version = self.root.example.get_editable() sources = getWrapper(version, IExternalSourceManager) controller = sources(TestRequest(), name='codesource') controller.create() self._instance = controller.getId()
def test_export_design_and_reference_block(self): with Transaction(): factory = self.root.export.manage_addProduct['Silva'] with self.layer.open_fixture('image.png') as image_file: factory.manage_addImage('image', 'Image', image_file) block = ReferenceBlock() controller = getWrapper( (block, self.page, TestRequest()), interfaces.IBlockController) controller.content = self.root.export.image manager = interfaces.IBlockManager(self.page) manager.add('one', block) exporter = self.assertExportEqual( self.root.export, 'test_export_ref_block.silvaxml') self.assertEqual( exporter.getZexpPaths(), []) self.assertEqual( exporter.getAssetPaths(), [(('', 'root', 'export', 'image'), '1')]) self.assertEqual( exporter.getProblems(), [])
def test_export_page_model(self): with Transaction(): factory = self.root.export.manage_addProduct['silva.core.contentlayout'] factory.manage_addPageModel('model', 'A Page Model') version = self.root.export.model.get_editable() version.set_design(self.design) text_block = TextBlock(identifier='text block 1') controller = getWrapper( (text_block, self.page, TestRequest()), interfaces.IBlockController) controller.text = "<div>text</div>" manager = interfaces.IBlockManager(version) manager.add('two', text_block) manager.add('two', BlockSlot( identifier='slot-two', css_class="large")) manager.add('one', BlockSlot( identifier='slot-one', restrictions=[ restrictions.CodeSourceName( allowed=set(['allow1', 'allow2']), disallowed=set(['dis1', 'dis2'])), restrictions.Content(schema=IImage), restrictions.BlockAll()])) exporter = self.assertExportEqual( self.root.export, 'test_export_page_model.silvaxml') self.assertEqual(exporter.getZexpPaths(), []) self.assertEqual(exporter.getAssetPaths(), []) self.assertEqual(exporter.getProblems(), [])
def test_display_source_with_default_alignement(self): """If you render without any layer, you will see the code source rendered. """ version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory( 'body', version.body, """ <div class="external-source default" data-source-instance="%s"> </div> """ % self.instance_key, IDisplayFilter) tests.assertXMLEqual( unicode(transformer), """ <div class="citation"> Don't trust citations on the Internet <div class="author"> Charlemagne </div> <div class="source"> The Internet </div> </div> """) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def createSource(self, identifier, context): importer = self.getExtra() factory = getWrapper(context, IExternalSourceManager) try: self.source = factory(importer.request, name=identifier) except SourceError, error: importer.reportProblem( u"Broken source in import: {0}".format(error), context) return None
def setUp(self): self.root = self.layer.get_application() self.layer.login('manager') factory = self.root.manage_addProduct['silva.app.document'] factory.manage_addDocument('example', 'Example') version = self.root.example.get_editable() version.body.save(version, TestRequest(), HTML_WORKING_SOURCE) self.sources = getWrapper(version, IExternalSourceManager) self.identifier = list(self.sources.all())[0]
def publishTraverse(self, request, name): factory = getWrapper(self.context, IExternalSourceManager) try: self.source = factory(request, name=urllib.unquote(name)) except SourceError: parent = super(SourceAssetAddForm, self) return parent.publishTraverse(request, name) self.fields = self.titleFields self.__name__ = '/'.join((self.__name__, name)) return self
def publishTraverse(self, request, name): factory = getWrapper(self.context, IExternalSourceManager) try: self.source = factory(request, name=urllib.parse.unquote(name)) except SourceError: parent = super(SourceAssetAddForm, self) return parent.publishTraverse(request, name) self.fields = self.titleFields self.__name__ = '/'.join((self.__name__, name)) return self
def test_controller_anchor(self): """Verify text block controller with a piece of text that contains some anchors. """ context = self.root.page.get_editable() view = MockView(context) block = TextBlock() # Test controller controller = getWrapper( (block, view.context, view.request), IBlockController, default=None) self.assertTrue(verifyObject(IBlockController, controller)) self.assertEqual(controller.editable(), True) # Change the text with a reference. TEXT_ANCHOR = """ <p> <a class="anchor" name="simple" title="Simple Anchor">Simple Anchor</a> The ultimate store of the anchors. <a class="anchor" name="advanced" title="Advanced Anchor">Advanced Anchor</a> </p> """ TEXT_ANCHOR_STORED = """ <p> <a class="anchor" name="simple" title="Simple Anchor">Simple Anchor</a> The ultimate store of the anchors. <a class="anchor" name="advanced" title="Advanced Anchor">Advanced Anchor</a> </p> """ controller.text = TEXT_ANCHOR self.assertXMLEqual( controller.text, TEXT_ANCHOR_STORED) self.assertXMLEqual( controller.render(view), TEXT_ANCHOR) indexes = controller.indexes() self.assertEqual(len(indexes), 2) # Remove the text. This should clean the reference. controller.remove() self.assertXMLEqual( controller.text, u'') self.assertEqual( controller.indexes(), [])
def test_delete_source(self): """If you save again without provided the html for the source, it is removed. """ version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory("body", version.body, "", ISaveEditorFilter) tests.assertXMLEqual(unicode(transformer), "") sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0)
def test_create_transform_broken_failover(self): """Create a source that doesn't exists with failover. No source is created, but no error is yielded. """ request = TestRequest() version = self.root.example.get_editable() version.body.save(version, request, HTML_BROKEN_SOURCE) # This gives access to all the sources sources = getWrapper(version, IExternalSourceManager) self.assertTrue(verifyObject(IExternalSourceManager, sources)) self.assertEqual(len(sources.all()), 0)
def test_delete_source(self): """If you save again without provided the html for the source, it is removed. """ version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory('body', version.body, "", ISaveEditorFilter) tests.assertXMLEqual(unicode(transformer), "") sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0)
def sax_source_parameters(self, source_manager): """`source_manager` should be a IExternalSourceManager bounded to an instance. """ self.startElementNS(NS_SOURCE_URI, 'fields') for serializer in getWrapper(source_manager, IXMLFormSerialization).getSerializers(): self.startElementNS(NS_SOURCE_URI, 'field', {(None, 'id'): serializer.identifier}) serializer(self) self.endElementNS(NS_SOURCE_URI, 'field') self.endElementNS(NS_SOURCE_URI, 'fields')
def test_controller(self): """Verify reference block controller. """ service = getUtility(IReferenceService) context = self.root.page.get_editable() view = MockView(context) block = ReferenceBlock() # By default the page has no reference self.assertEqual( list(service.get_references_from(context)), []) # Test controller controller = getWrapper( (block, view.context, view.request), IBlockController, default=None) self.assertTrue(verifyObject(IBlockController, controller)) self.assertEqual(controller.editable(), True) self.assertEqual(controller.content, None) self.assertMultiLineEqual( controller.render(view), 'Content reference is broken or missing.') self.assertEqual( controller.indexes(), []) self.assertEqual( controller.fulltext(), []) # Change the reference. controller.content = self.root.test self.assertEqual(controller.content, self.root.test) self.assertMultiLineEqual( controller.render(view), 'Content is not viewable.') self.assertEqual( controller.indexes(), []) self.assertEqual( controller.fulltext(), []) self.assertEqual( len(list(service.get_references_from(context))), 1) # Remove the reference. controller.remove() self.assertEqual(controller.content, None) self.assertEqual( list(service.get_references_from(context)), [])
def test_broken_render_source_asset(self): """Test a source that renders a source with a broken render script. """ factory = self.root.manage_addProduct['SilvaExternalSources'] factory.manage_addSourceAsset('asset', 'Test Asset') asset = self.root._getOb('asset', None) version = asset.get_editable() # Create a test code source factory = self.root.manage_addProduct['SilvaExternalSources'] factory.manage_addCodeSource('brokensource', 'Broken Source', 'script') source = self.root._getOb('brokensource', None) # Add the rendering script factory = source.manage_addProduct['PythonScripts'] factory.manage_addPythonScript('script') script = source._getOb('script') script.write(""" ##parameters=model,version,REQUEST I am broken return "Render source" """) # Create a source with the new test source sources = getWrapper(version, IExternalSourceManager) controller = sources(TestRequest(), name='brokensource') controller.create() version.set_parameters_identifier(controller.getId()) # You can preview it, but it will fail with a nice message with self.layer.get_browser(public_settings) as browser: browser.login('editor') self.assertEqual(browser.open('/root/++preview++/asset'), 200) self.assertEqual(browser.inspect.title, []) self.assertEqual( browser.inspect.content, ['Error while rendering Broken Source\n ' 'A programmation error happened while rendering the source.']) IPublicationWorkflow(asset).publish() # We published the asset we still a nice error message instead # of a failure message. with self.layer.get_browser(public_settings) as browser: browser.options.handle_errors = False self.assertEqual(browser.open('/root/asset'), 200) self.assertEqual(browser.inspect.title, []) self.assertEqual( browser.inspect.content, ['Sorry, this Silva Source Asset is not viewable.'])
def sax_source_parameters(self, source_manager): """`source_manager` should be a IExternalSourceManager bounded to an instance. """ self.startElementNS(NS_SOURCE_URI, 'fields') for serializer in getWrapper( source_manager, IXMLFormSerialization).getSerializers(): self.startElementNS( NS_SOURCE_URI, 'field', {(None, 'id'): serializer.identifier}) serializer(self) self.endElementNS(NS_SOURCE_URI, 'field') self.endElementNS(NS_SOURCE_URI, 'fields')
def test_export_text_block(self): with Transaction(): block = TextBlock(identifier='text block 1') controller = getWrapper( (block, self.page, TestRequest()), interfaces.IBlockController) controller.text = "<div>text</div>" manager = interfaces.IBlockManager(self.page) manager.add('two', block) exporter = self.assertExportEqual( self.root.export, 'test_export_text_block.silvaxml') self.assertEqual(exporter.getZexpPaths(), []) self.assertEqual(exporter.getAssetPaths(), []) self.assertEqual(exporter.getProblems(), [])
def setUp(self): super(EditSourceTransformerTestCase, self).setUp() version = self.root.document.get_editable() sources = getWrapper(version, IExternalSourceManager) controller = sources(TestRequest( form={ 'field_citation': "Don't trust citations on the Internet", 'field_author': "Charlemagne", 'field_source': "The Internet" }), name='cs_citation') controller.create() self.instance_key = controller.getId() self.saved_text = """ <div class="external-source" data-source-instance="%s"> </div> """ % self.instance_key
def test_controller_text(self): """Verify text controller with a simple piece of text. """ context = self.root.page.get_editable() view = MockView(context) block = TextBlock() service = getUtility(IReferenceService) # By default the page has no reference self.assertEqual(list(service.get_references_from(context)), []) # Test controller controller = getWrapper( (block, view.context, view.request), IBlockController, default=None) self.assertTrue(verifyObject(IBlockController, controller)) self.assertEqual(controller.editable(), True) # Change the text. TEXT = """ <p> This is some rich text. </p>""" controller.text = TEXT self.assertXMLEqual(controller.text, TEXT) self.assertXMLEqual( controller.render(view), TEXT) self.assertEqual( controller.indexes(), []) self.assertEqual( controller.fulltext(), ['This is some rich text.']) self.assertEqual( list(service.get_references_from(context)), []) # Remove the block. controller.remove() self.assertXMLEqual( controller.text, u'') self.assertEqual( list(service.get_references_from(context)), [])
def render(self, view): for block_id, block in self.manager.get_slot(view.slot_id): if block is not None: controller = component.getWrapper( (block, self.context, self.request), IBlockController) try: yield {"block_id": block_id, "block_editable": bool(controller.editable()), "block_data": controller.render(view)} except: logger.error( u'Error rendering block %s in page %s.', block_id, '/'.join(self.context.getPhysicalPath())) else: logger.error( u'Missing block %s in page %s.', block_id, '/'.join(self.context.getPhysicalPath()))
def test_display_source_with_multi_tags(self): """Display and render a source that have multiple top level tags. """ version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory('body', version.body, self.saved_text, IDisplayFilter) tests.assertXMLEqual( unicode(transformer), """ <h1>This is a title</h1> <a href="http://silvacms.org">SilvaCMS</a> <b>Silva is cool</b> <p>Well good bye!</p> """) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def test_export_source_block(self): with Transaction(): source_manager = getWrapper(self.page, IExternalSourceManager) parameters = dict(field_citation="A joke is a very serious thing.", field_author="Winston Churchill") request = TestRequest(form=parameters) controller = source_manager(request, name='cs_citation') marker = controller.create() self.assertIs(marker, silvaforms.SUCCESS) manager = interfaces.IBlockManager(self.page) manager.add('one', SourceBlock(controller.getId())) exporter = self.assertExportEqual( self.root.export, 'test_export_source_block.silvaxml') self.assertEqual(exporter.getZexpPaths(), []) self.assertEqual(exporter.getAssetPaths(), []) self.assertEqual(exporter.getProblems(), [])
def test_display_broken_source_public(self): """If you delete the code source object, and render without a preview layer, you have no message. """ self.root.manage_delObjects(['cs_citation']) version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory('body', version.body, self.saved_text, IDisplayFilter) tests.assertXMLEqual(unicode(transformer), """ <div class="external-source"> </div> """) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def test_display_source_with_multi_tags(self): """Display and render a source that have multiple top level tags. """ version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory("body", version.body, self.saved_text, IDisplayFilter) tests.assertXMLEqual( unicode(transformer), """ <h1>This is a title</h1> <a href="http://silvacms.org">SilvaCMS</a> <b>Silva is cool</b> <p>Well good bye!</p> """, ) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def save(self): data, errors = self.extractData() source_data, source_errors = self.source.extractData() if errors or source_errors: return silvaforms.FAILURE try: content = self._add(self.context, data) except ValueError as error: self.send_message(error.args[0], type="error") return silvaforms.FAILURE editable = content.get_editable() factory = getWrapper(editable, IExternalSourceManager) source = factory(self.request, name=self.source.getSourceId()) source.create() editable.set_parameters_identifier(source.getId()) notify(ObjectModifiedEvent(content)) self.send_message(_("Source Asset added."), type="feedback") raise RedirectToPage(content=content)
def test_display_broken_source_public(self): """If you delete the code source object, and render without a preview layer, you have no message. """ self.root.manage_delObjects(["cs_citation"]) version = self.root.document.get_editable() factory = getMultiAdapter((version, TestRequest()), ITransformerFactory) transformer = factory("body", version.body, self.saved_text, IDisplayFilter) tests.assertXMLEqual( unicode(transformer), """ <div class="external-source"> </div> """, ) sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 1)
def setUp(self): self.root = self.layer.get_application() self.layer.login('manager') factory = self.root.manage_addProduct['silva.app.document'] factory.manage_addDocument('example', 'Example') # Create cs_data as a copy of cs_citation token = self.root.manage_copyObjects(['cs_citation']) self.root.manage_pasteObjects(token) self.root.manage_renameObject('copy_of_cs_citation', 'cs_data') # Create source. version = self.root.example.get_editable() version.body.save(version, TestRequest(), HTML_BROKEN_SOURCE) self.sources = getWrapper(version, IExternalSourceManager) self.identifier = list(self.sources.all())[0] # Remove source, that will break the instance. self.root.manage_delObjects(['cs_data'])
def test_controller(self): """Test block slot controller. """ view = MockView(self.root.page.get_editable()) block = BlockSlot() controller = getWrapper( (block, view.context, view.request), IBlockController, default=None) self.assertTrue(verifyObject(IBlockController, controller)) self.assertEqual(controller.get_tag(), 'section') self.assertEqual(controller.get_css_class(), '') controller.set_identifier('modified-identifier') self.assertEqual(controller.get_identifier(), 'modified-identifier') # Check cs_blacklist and cs_whitelist self.assertEqual(controller.get_cs_blacklist(), set()) self.assertEqual(controller.get_cs_whitelist(), set()) # Check content_restriction self.assertIs(controller.get_content_restriction(), None) self.assertIs(controller.get_content_restriction_name(), None) controller.set_content_restriction(IImage) self.assertIs(controller.get_content_restriction(), IImage) self.assertEqual( controller.get_content_restriction_name(), 'Silva Image') controller.set_content_restriction(None) self.assertIs(controller.get_content_restriction(), None) self.assertIs(controller.get_content_restriction_name(), None) # Check block_all self.assertFalse(controller.get_block_all()) controller.set_block_all(True) self.assertTrue(controller.get_block_all()) controller.set_block_all(False) self.assertFalse(controller.get_block_all())
def test_working_source_asset(self): """Test a working source asset. """ factory = self.root.manage_addProduct['SilvaExternalSources'] factory.manage_addSourceAsset('asset', 'Test Asset') asset = self.root._getOb('asset', None) version = asset.get_editable() # Create a source with cs_citation sources = getWrapper(version, IExternalSourceManager) controller = sources(TestRequest(), name='cs_citation') controller.create() controller.getContent().citation = 'Silva is a great CMS.' version.set_parameters_identifier(controller.getId()) # The content is not yet published. self.assertEqual(asset.get_parameters_form(), None) self.assertEqual(asset.get_icon(), None) self.assertEqual(asset.get_description(), 'Broken or missing source.') self.assertEqual(asset.is_usable(), False) self.assertEqual(asset.is_previewable(), False) self.assertEqual(asset.is_cacheable(), False) # You can preview it. with self.layer.get_browser(public_settings) as browser: browser.login('editor') self.assertEqual(browser.open('/root/++preview++/asset'), 200) self.assertEqual(browser.inspect.title, []) self.assertEqual(browser.inspect.content, ['Silva is a great CMS.']) # We publish it original = self.root.cs_citation IPublicationWorkflow(asset).publish() self.assertEqual(asset.get_parameters_form(), None) self.assertEqual(asset.get_icon(), original.get_icon()) self.assertEqual(asset.get_description(), original.get_description()) self.assertEqual(asset.is_usable(), True) self.assertEqual(asset.is_previewable(), True) self.assertEqual(asset.is_cacheable(), True) # Since it is published you can now see it. with self.layer.get_browser(public_settings) as browser: self.assertEqual(browser.open('/root/asset'), 200) self.assertEqual(browser.inspect.title, []) self.assertEqual(browser.inspect.content, ['Silva is a great CMS.'])
def __call__(self, tree): exported = self.handler.getExported() for node in tree.xpath( '//html:div[contains(@class, "external-source")]', namespaces={'html': 'http://www.w3.org/1999/xhtml'}): if 'data-source-instance' not in node.attrib: exported.reportProblem( u'Broken source in document while exporting: ' u'Source parameters are missing.', self.context) continue identifier = node.attrib['data-source-instance'] del node.attrib['data-source-instance'] try: source = self.sources(exported.request, instance=identifier) except SourceError as error: exported.reportProblem( u'Broken source in document while exporting:' u'{0}'.format(error), self.context) continue if source.source is None: exported.reportProblem( u'Broken source in document while exporting: ' u'source is no longer installed in the Silva site.', self.context) continue node.attrib['source-identifier'] = source.getSourceId() # Fix this. producer = FieldProducer(self.context, self.handler, root=node) producer.startPrefixMapping(None, NS_SOURCE_URI) producer.startElement('fields') for serializer in getWrapper( source, IXMLFormSerialization).getSerializers(): producer.startElement( 'field', {(None, 'id'): serializer.identifier}) serializer(producer) producer.endElement('field') producer.endElement('fields') producer.endPrefixMapping(None)
def __call__(self, form): data, errors = form.extractData() if errors: return silvaforms.FAILURE api = form.__parent__.__parent__ container = form.context.get_container() factory = container.manage_addProduct['SilvaExternalSources'] factory.manage_addSourceAsset(data['id'], data['title']) asset = container._getOb(data['id']) editable = asset.get_editable() factory = getWrapper(editable, IExternalSourceManager) target = factory(form.request, name=api.block_controller.getSourceId()) target.create() api.block_controller.copy(target) editable.set_parameters_identifier(target.getId()) self.block_id = api.manager.replace(api.block_id, ReferenceBlock()) self.block, self.block_controller = api.manager.get(self.block_id) self.block_controller.content = asset notify(ObjectModifiedEvent(editable)) notify(ObjectModifiedEvent(form.context)) return silvaforms.SUCCESS
def save_asset(self, target=None): with Transaction(): # Helper to save the parameters in the test source asset. version = self.root.folder.asset.get_editable() if target is not None: target = getUtility(IIntIds).register(target) else: target = '0' request = TestRequest( form={'field_paths': str(target), 'field_toc_types': "Silva Folder", 'field_depth': "0", 'field_sort_on': "silva", 'field_order': "normal"}) factory = getWrapper(version, IExternalSourceManager) source = factory(request, name='cs_toc') marker = source.create() version.set_parameters_identifier(source.getId()) self.assertIs(marker, silvaforms.SUCCESS) return version
def __call__(self, tree): importer = self.handler.getExtra() request = importer.request for node in tree.xpath( '//html:div[contains(@class, "external-source")]', namespaces={'html': 'http://www.w3.org/1999/xhtml'}): name = node.attrib.get('source-identifier') if name is None: importer.reportProblem(u"Broken source in import.", self.context) continue try: source = self.sources(request, name=name) except SourceError as error: importer.reportProblem( u"Broken source in import: {0}".format(error), self.context) continue identifier = source.new() deserializers = getWrapper( source, IXMLFormSerialization).getDeserializers() for field_node in node.xpath('./cs:fields/cs:field', namespaces={'cs': NS_SOURCE_URI}): field_id = field_node.attrib['id'] if field_id.startswith('field-'): # XXX Backward compatiblity 3.0b1 field_id = field_id[6:].replace('-', '_') deserializer = deserializers.get(field_id) if deserializer is None: # This field have been removed. Ignore it. logger.warn(u"Unknown source parameter %s in %s" % (field_id, name)) continue # Deserialize the value deserializer(field_node, self.handler) del node[:] del node.attrib['source-identifier'] node.attrib['data-source-instance'] = identifier
def __call__(self, tree): exported = self.handler.getExported() for node in tree.xpath( '//html:div[contains(@class, "external-source")]', namespaces={'html': 'http://www.w3.org/1999/xhtml'}): if 'data-source-instance' not in node.attrib: exported.reportProblem( u'Broken source in document while exporting: ' u'Source parameters are missing.', self.context) continue identifier = node.attrib['data-source-instance'] del node.attrib['data-source-instance'] try: source = self.sources(exported.request, instance=identifier) except SourceError as error: exported.reportProblem( u'Broken source in document while exporting:' u'{0}'.format(error), self.context) continue if source.source is None: exported.reportProblem( u'Broken source in document while exporting: ' u'source is no longer installed in the Silva site.', self.context) continue node.attrib['source-identifier'] = source.getSourceId() # Fix this. producer = FieldProducer(self.context, self.handler, root=node) producer.startPrefixMapping(None, NS_SOURCE_URI) producer.startElement('fields') for serializer in getWrapper( source, IXMLFormSerialization).getSerializers(): producer.startElement('field', {(None, 'id'): serializer.identifier}) serializer(producer) producer.endElement('field') producer.endElement('fields') producer.endPrefixMapping(None)
def test_create_broken(self): """Create a broken source: you can't access the create method. """ request = TestRequest() version = self.root.example.get_editable() # This gives access to all the sources sources = getWrapper(version, IExternalSourceManager) self.assertTrue(verifyObject(IExternalSourceManager, sources)) self.assertEqual(len(sources.all()), 0) with self.assertRaises(errors.SourceMissingError): sources.get_parameters() with self.assertRaises(errors.SourceMissingError): sources.get_parameters(name='cs_nonexisting') with self.assertRaises(errors.SourceMissingError): sources(request, name='cs_nonexisting') with self.assertRaises(errors.ParametersMissingError): sources.get_parameters(instance='nonexisting') with self.assertRaises(errors.ParametersMissingError): sources(request, instance='nonexisting')
def test_document_with_missing_source(self): """Import a document that uses a source that is missing on the system. The document is imported, but not the source. """ importer = self.assertImportFile( 'test_import_source_missing.silvaxml', ['/root/example']) document = self.root.example self.assertTrue(verifyObject(IDocument, document)) self.assertEqual(document.get_viewable(), None) self.assertNotEqual(document.get_editable(), None) version = document.get_editable() sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0) self.assertEqual( importer.getProblems(), [('Broken source in import: ' 'External Source cs_ultimate is not available.', version)])
def test_document_with_source(self): """Import a document that uses a source. """ importer = self.assertImportFile( 'test_import_source.silvaxml', ['/root/example']) self.assertEqual(importer.getProblems(), []) document = self.root.example self.assertTrue(verifyObject(IDocument, document)) self.assertEqual(document.get_viewable(), None) self.assertNotEqual(document.get_editable(), None) version = document.get_editable() sources = getWrapper(version, IExternalSourceManager) keys = list(sources.all()) self.assertEqual(len(keys), 1) parameters, source = sources.get_parameters(instance=keys[0]) self.assertEqual(parameters.get_source_identifier(), 'cs_citation') self.assertEqual(source.id, 'cs_citation') self.assertEqual(parameters.citation, "héhé l'aime le quéqué") self.assertEqual(parameters.author, 'ouam') self.assertEqual(parameters.source, 'wikipedia')
def setUp(self): super(EditCustomSourceTransformerTestCase, self).setUp() factory = self.root.manage_addProduct['SilvaExternalSources'] factory.manage_addCodeSource('cs_source', 'Test Source', 'script') factory = self.root.cs_source.manage_addProduct['PythonScripts'] factory.manage_addPythonScript('script') script = self.root.cs_source._getOb('script') script.write(""" ##parameters=model,version,REQUEST return '<a href="http://silvacms.org">SilvaCMS</a><b>Silva is cool</b>' """) version = self.root.document.get_editable() sources = getWrapper(version, IExternalSourceManager) controller = sources(TestRequest(form={}), name='cs_source') controller.create() self.instance_key = controller.getId() self.saved_text = """ <h1>This is a title</h1> <div class="external-source" data-source-instance="%s"> </div> <p>Well good bye!</p> """ % self.instance_key
def test_create(self): """Create a source by hand. """ request = TestRequest( form={ 'field_citation': 'je bent een hero', 'field_author': 'u', 'field_source': 'google', }) version = self.root.example.get_editable() sources = getWrapper(version, IExternalSourceManager) self.assertEqual(len(sources.all()), 0) controller = sources(request, name='cs_citation') # You cannot save or remove the source, it does not exist yet. with self.assertRaises(AssertionError): controller.save() with self.assertRaises(AssertionError): controller.remove() self.assertEqual(controller.getId(), None) # But you can create it, and it will created after. controller.create() self.assertNotEqual(controller.getId(), None) self.assertEqual(len(sources.all()), 1) instance_key = list(sources.all())[0] parameters, source = sources.get_parameters(instance=instance_key) self.assertTrue(verifyObject(IExternalSourceInstance, parameters)) self.assertEqual(controller.getId(), instance_key) self.assertEqual(parameters.get_parameter_identifier(), instance_key) self.assertEqual(parameters.get_source_identifier(), 'cs_citation') self.assertEqual(source.id, 'cs_citation') self.assertEqual(parameters.citation, u'je bent een hero') self.assertEqual(parameters.author, u'u') self.assertEqual(parameters.source, u'google')
def get_controller(self, request): manager = getWrapper(self, IExternalSourceManager) return manager(request, instance=self._parameter_identifier)
def get_source(self): if not hasattr(aq_base(self), '_v_original_source'): manager = getWrapper(self, IExternalSourceManager) _, source = manager.get_parameters(self._parameter_identifier) self._v_original_source = source return self._v_original_source
def get_parameters(self): manager = getWrapper(self, IExternalSourceManager) parameters, _ = manager.get_parameters(self._parameter_identifier) return parameters
def get_controller(self, layers=[]): version = self.root.example.get_editable() sources = getWrapper(version, IExternalSourceManager) return sources(TestRequest(layers=layers), instance=self._instance)
def prepare(self, name, text): self.sources = getWrapper(self.context, IExternalSourceManager)