class AnchorCollector(TransformationFilter): """Collect text anchors to save indexes on a text object's annotation. """ grok.implements(ISaveEditorFilter) grok.provides(ISaveEditorFilter) grok.order(50) def prepare(self, name, text): self.entries = ITextIndexEntries(text) self.entries.clear() truncate = prepare def __call__(self, tree): for anchor in tree.xpath('//a[@class="anchor"]'): if 'name' in anchor.attrib and 'title' in anchor.attrib: name = anchor.attrib['name'].strip() title = anchor.attrib['title'].strip() if name and title: # Only collect entries with a name and a title self.entries.add(name, title) # Save back stripped values anchor.attrib['name'] = name anchor.attrib['title'] = title if 'href' in anchor.attrib: # Those should not have any href, so clean them del anchor.attrib['href']
def test_import_anchor(self): """Test importing a document that contains anchor, and check they are reported to the indexes. """ importer = self.assertImportFile( 'test_import_anchor.silvaxml', ['/root/folder', '/root/folder/anchor', '/root/folder/indexer']) self.assertEqual(importer.getProblems(), []) self.assertEqual( self.root.folder.objectIds(), ['anchor', 'indexer']) document = self.root.folder.anchor self.assertTrue(verifyObject(IDocument, document)) self.assertNotEqual(document.get_viewable(), None) self.assertEqual(document.get_editable(), None) version = document.get_viewable() self.assertTrue(verifyObject(IDocumentVersion, version)) index = ITextIndexEntries(version.body) self.assertTrue(verifyObject(ITextIndexEntries, index)) self.assertEqual(len(index.entries), 2) self.assertEqual( map(lambda e: (e.anchor, e.title), index.entries), [('rock', 'Rock that anchor'), ('pop', 'That will pop your mind')]) index = IIndexEntries(document) self.assertTrue(verifyObject(IIndexEntries, index)) self.assertEqual(index.get_title(), 'Anchor\'s document') self.assertEqual(len(index.get_entries()), 2) self.assertEqual( index.get_entries(), [('rock', 'Rock that anchor'), ('pop', 'That will pop your mind')]) # Verify that the entries are available in the indexer indexer = self.root.folder.indexer self.assertTrue(verifyObject(IIndexer, indexer)) self.assertEqual( indexer.get_index_names(), ['Rock that anchor', 'That will pop your mind']) self.assertEqual( len(indexer.get_index_entry('Rock that anchor')), 1) self.assertEqual( len(indexer.get_index_entry('That will pop your mind')), 1)
def prepare(self, name, text): self.entries = ITextIndexEntries(text) self.entries.clear()