r13570 - in Products.ATVocabularyManager/trunk/Products/ATVocabularyManager: . skins/ATVocabularyManager tests tools types/alias types/simple types/tree types/vdex utils
"Wouter Vanden Hove" <[email protected]> Tue, 05 Apr 2011 18:30:18 +0000
| Newsgroups | gmane.comp.web.zope.plone.archetypes.cvs |
|---|---|
| Message-ID | <[email protected]> |
Author: WouterVH
Date: Tue Apr 5 18:30:17 2011
New Revision: 13570
Modified:
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/Makefile
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/backports.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/config.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/event.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/importexport.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/namedvocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/setuphandlers.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/skins/ATVocabularyManager/vocabulary_delete.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/common.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testATVocabularyManager.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSimpleVocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSkeletonPloneTest.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testTreeVocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_functional.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_searchTreeVocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/utils.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tools/vocabularylib.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/alias/vocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/sortedvocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/term.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/vocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/term.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/vocabulary.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/vdex/vocabularyxml.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/text.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/vocabs.py
Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/xml.py
Log:
pyflakes, pep8 cleanup
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/Makefile
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/Makefile (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/Makefile Tue Apr 5 18:30:17 2011
@@ -11,4 +11,4 @@
## removes compiled python and backup files
clean:
@find . -name "*.pyc" -exec rm {} \;
- @find . -name "*~" -exec rm {} \;
\ No newline at end of file
+ @find . -name "*~" -exec rm {} \;
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/backports.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/backports.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/backports.py Tue Apr 5 18:30:17 2011
@@ -4,6 +4,7 @@
#
from zope.interface import Interface
+
class IVocabularyTerm(Interface):
"""A VocabularyTerm has a value (which is used to
display the term) and a key that is used to identify
@@ -27,4 +28,4 @@
list containing the Keys of A, B, and C forming
a path.
eg: [keyA, keyB, keyC]
- """
\ No newline at end of file
+ """
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/config.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/config.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/config.py Tue Apr 5 18:30:17 2011
@@ -7,35 +7,35 @@
# package configuration
-PROJECTNAME = "ATVocabularyManager"
+PROJECTNAME = 'ATVocabularyManager'
SKINS_DIR = 'skins'
-DEPENDENCIES = ['Archetypes',]
+DEPENDENCIES = ['Archetypes', ]
-TOOL_NAME ="portal_vocabularies"
-TOOL_TITLE="Vocabulary Library"
-TOOL_META ="VocabularyLibrary"
+TOOL_NAME = 'portal_vocabularies'
+TOOL_TITLE = 'Vocabulary Library'
+TOOL_META = 'VocabularyLibrary'
-ADD_CONTENT_PERMISSION = "Add ATVocabularyManager content"
+ADD_CONTENT_PERMISSION = 'Add ATVocabularyManager content'
-DEFAULT_VOCABULARY_CONTAINER='SimpleVocabulary'
-DEFAULT_VOCABULARY_ITEM ='SimpleVocabularyTerm'
+DEFAULT_VOCABULARY_CONTAINER = 'SimpleVocabulary'
+DEFAULT_VOCABULARY_ITEM = 'SimpleVocabularyTerm'
-VDEX_EXPORT_NEWL = '\n'
-VDEX_EXPORT_INDENT= '\t'
+VDEX_EXPORT_NEWL = '\n'
+VDEX_EXPORT_INDENT = '\t'
# encoding of files in flat-file csv import
IMPORT_ENCODING = 'latin-1'
-SORT_METHOD_FOLDER_ORDER = "getObjPositionInParent"
+SORT_METHOD_FOLDER_ORDER = "getObjPositionInParent"
SORT_METHOD_LEXICO_VALUES = "lexicographic_values"
-SORT_METHOD_LEXICO_KEYS = "lexicographic_keys"
+SORT_METHOD_LEXICO_KEYS = "lexicographic_keys"
VOCABULARY_SORT_ORDERS = DisplayList((
- ('getObjPositionInParent', "Vocabulary Folder Order", 'sort_method_folder_order'),
- ('lexicographic_values', "Lexicographic sort by values", 'sort_method_lexi_value'),
- ('lexicographic_keys', "Lexicographic sort by keys", 'sort_method_lexi_keys'),
+ ('getObjPositionInParent', 'Vocabulary Folder Order', 'sort_method_folder_order'),
+ ('lexicographic_values', 'Lexicographic sort by values', 'sort_method_lexi_value'),
+ ('lexicographic_keys', 'Lexicographic sort by keys', 'sort_method_lexi_keys'),
))
# LinguaPlone addon?
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/event.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/event.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/event.py Tue Apr 5 18:30:17 2011
@@ -2,7 +2,8 @@
from zope import interface
from Products.ATVocabularyManager import interfaces
from Products.ATVocabularyManager.tools import vocabularylib
-from Products.CMFCore import utils as cmfutils
+#from Products.CMFCore import utils as cmfutils
+
class TermRenamedEvent(object):
interface.implements(interfaces.ITermRenamedEvent)
@@ -13,6 +14,7 @@
self.term = term
self.vocabulary = vocabulary
+
class TermDeletedEvent(object):
interface.implements(interfaces.ITermDeletedEvent)
@@ -21,6 +23,7 @@
self.term = term
self.vocabulary = vocabulary
+
def find_toplevel_vocab(obj):
result = obj
while hasattr(result, 'aq_parent'):
@@ -31,6 +34,7 @@
return None
+
def term_removed_handler(obj, evt):
vocab = find_toplevel_vocab(obj)
event.notify(TermDeletedEvent(obj.Title(), obj, vocab))
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/importexport.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/importexport.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/importexport.py Tue Apr 5 18:30:17 2011
@@ -2,7 +2,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
import os
from imsvdex.vdex import VDEXManager
@@ -17,9 +17,10 @@
from Products.CMFPlone.utils import normalizeString
from interfaces import IATVocabularyLibrary
+
class ATVMXMLAdapter(XMLAdapterBase):
adapts(IATVocabularyLibrary, ISetupEnviron)
-
+
name = 'vocabularies'
def _importNode(self, node):
@@ -28,12 +29,12 @@
if self.environ.shouldPurge():
self._purgeVocabs()
self._initVocabs(node)
- self._logger.info('ATVocabularyManager library imported.')
-
+ self._logger.info('ATVocabularyManager library imported.')
+
def _purgeVocabs(self):
ids = self.context.contentIds()
self.context.manage_delObjects(ids)
-
+
def _initVocabs(self, node):
for objnode in node.getElementsByTagName('object'):
filename = objnode.getAttribute('name')
@@ -48,45 +49,46 @@
raise
vocabid = vdex.getVocabIdentifier()
if not vocabid:
- vocabid = filename[:filename.rfind('.')]
- vocabname = vocabid
+ vocabid = filename[:filename.rfind('.')]
+ vocabname = vocabid
if vocabname in self.context.objectIds():
self.context.manage_delObjects([vocabname])
try:
self._logger.info(
'Import VDEX file %s with identifier %s' % \
- (filename, vocabname))
+ (filename, vocabname))
self.context.invokeFactory('VdexFileVocabulary', vocabname)
except BadRequest, e:
self._logger.warning(
'Import VDEX file %s with identifier %s renamed as %s' % \
- (filename, vocabid, vocabname))
+ (filename, vocabid, vocabname))
vocabname = normalizeString(vocabid, context=self.context)
if vocabname in self.context.objectIds():
self.context.manage_delObjects([vocabname])
self.context.invokeFactory('VdexFileVocabulary', vocabname)
- self.context[vocabname].importXMLBinding(data)
+ self.context[vocabname].importXMLBinding(data)
elif filename.endswith('.csv') or filename.endswith('.txt'):
# CSV file
- self._logger.info('CSV import not yet implemented.')
+ self._logger.info('CSV import not yet implemented.')
else:
- self._logger.info('Unknown File Format.')
-
+ self._logger.info('Unknown File Format.')
+
def importVocabularies(context):
"""Import vocabularies from an XML file.
"""
site = context.getSite()
- tool = getToolByName(site, 'portal_vocabularies')
+ tool = getToolByName(site, 'portal_vocabularies')
importObjects(tool, '', context)
+
def exportVocabularies(context):
"""Export vocabularies as an XML file.
"""
site = context.getSite()
- tool = getToolByName(site, 'portal_vocabularies')
+ tool = getToolByName(site, 'portal_vocabularies')
if tool is None:
logger = context.getLogger('atvm')
logger.info('Nothing to export.')
return
- exportObjects(tool, '', context)
\ No newline at end of file
+ exportObjects(tool, '', context)
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/namedvocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/namedvocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/namedvocabulary.py Tue Apr 5 18:30:17 2011
@@ -8,7 +8,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
import Missing
@@ -19,6 +19,7 @@
from Products.ATVocabularyManager.types.tree.vocabulary import TreeVocabulary
from config import TOOL_NAME
+
class NamedVocabulary(object):
implements(IVocabulary)
@@ -82,8 +83,8 @@
vt = getToolByName(instance, TOOL_NAME)
vocab = vt.getVocabularyByName(self.vocab_name)
if vocab is None:
- raise KeyError('Vocabulary id not found in '+\
- 'portal_vocabularies : %s' % self.vocab_name)
+ raise KeyError('Vocabulary id not found in '+ \
+ 'portal_vocabularies : %s' % self.vocab_name)
assert(IVocabulary.providedBy(vocab))
return vocab
@@ -109,7 +110,7 @@
# we can get a list, or just a value
if not isinstance(terms, (tuple, list)):
- terms=[terms,]
+ terms=[terms, ]
uc = getToolByName(instance, 'uid_catalog')
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/setuphandlers.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/setuphandlers.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/setuphandlers.py Tue Apr 5 18:30:17 2011
@@ -1,12 +1,15 @@
from Products.CMFCore.utils import getToolByName
from Products.ATVocabularyManager.config import TOOL_TITLE
+
def importVarious(self):
+
if self.readDataFile('atvocabularymanager.txt') is None:
return
+
site = self.getSite()
catalog = getToolByName(site, 'uid_catalog')
-
+
idxName = 'getTermKeyPath'
if idxName not in catalog.schema():
@@ -18,4 +21,4 @@
vtool = getToolByName(site, 'portal_vocabularies')
vtool.title = TOOL_TITLE
# remove from portal_catalog
- vtool.unindexObject()
\ No newline at end of file
+ vtool.unindexObject()
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/skins/ATVocabularyManager/vocabulary_delete.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/skins/ATVocabularyManager/vocabulary_delete.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/skins/ATVocabularyManager/vocabulary_delete.py Tue Apr 5 18:30:17 2011
@@ -9,24 +9,24 @@
##
from Products.CMFPlone import transaction_note
-ids=context.REQUEST.get('ids', [])
-titles=[]
-titles_and_ids=[]
+ids = context.REQUEST.get('ids', [])
+titles = []
+titles_and_ids = []
-status='failure'
-message='No vocabulary to delete.'
+status = 'failure'
+message = 'No vocabulary to delete.'
for id in ids:
- obj=context.restrictedTraverse(id)
+ obj = context.restrictedTraverse(id)
titles.append(obj.title_or_id())
titles_and_ids.append('%s (%s)' % (obj.title_or_id(), obj.getId()))
if ids:
- status='success'
- message=', '.join(titles)+' has been deleted.'
+ status = 'success'
+ message = ', '.join(titles)+' has been deleted.'
transaction_note('Deleted %s from %s' % (', '.join(titles_and_ids), context.absolute_url()))
context.manage_delObjects(ids)
qs = context.create_query_string(portal_status_message=message)
-return context.REQUEST.RESPONSE.redirect('%s/view?%s' % (context.absolute_url(),qs))
+return context.REQUEST.RESPONSE.redirect('%s/view?%s' % (context.absolute_url(), qs))
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/common.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/common.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/common.py Tue Apr 5 18:30:17 2011
@@ -8,10 +8,11 @@
from Products.Five import zcml
from Products.Five import fiveconfigure
-from Products.PloneTestCase import PloneTestCase as ptc
+#from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import onsetup
from Products.CMFCore.utils import getToolByName
+
@onsetup
def installProducts():
fiveconfigure.debug_mode = True
@@ -28,9 +29,11 @@
ZopeTestCase.installProduct('LinguaPlone')
ZopeTestCase.installProduct(PROJECTNAME)
+
def installWithinPortal(portal):
qi = getToolByName(portal, 'portal_quickinstaller')
qi.installProduct(PROJECTNAME)
+
def getATVM(portal):
return portal[TOOL_NAME]
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testATVocabularyManager.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testATVocabularyManager.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testATVocabularyManager.py Tue Apr 5 18:30:17 2011
@@ -4,9 +4,9 @@
import unittest
from time import sleep
-from Testing import ZopeTestCase
+#from Testing import ZopeTestCase
from Products.PloneTestCase import PloneTestCase
-from Products.Five import zcml
+#from Products.Five import zcml
import Products.ATVocabularyManager
from Products.ATVocabularyManager.config import *
@@ -20,28 +20,25 @@
class TestATVocabularyManager(PloneTestCase.PloneTestCase):
def afterSetUp(self):
- self.qi = getToolByName(self.portal, 'portal_quickinstaller')
+ self.qi = getToolByName(self.portal, 'portal_quickinstaller')
- def test_install(self):
+ def test_install(self):
# atvm is not installed
self.failIf(self.qi.isProductInstalled(PROJECTNAME))
-
+
# installing atvm
self.qi.installProduct(PROJECTNAME)
self.failUnless(self.qi.isProductInstalled(PROJECTNAME))
-
-
+
def test_uninstall(self):
# installing atvm
self.qi.installProduct(PROJECTNAME)
- self.failUnless(self.qi.isProductInstalled(PROJECTNAME))
-
+ self.failUnless(self.qi.isProductInstalled(PROJECTNAME))
+
#now uninstall it
- self.qi.uninstallProducts([PROJECTNAME,])
+ self.qi.uninstallProducts([PROJECTNAME, ])
self.failIf(self.qi.isProductInstalled(PROJECTNAME))
-
-
-
+
def test_reinstall(self):
# installing atvm
self.qi.installProduct(PROJECTNAME)
@@ -49,80 +46,78 @@
sleep(1) # Else the ids are too similar and reinstall will fail. Oh well
#reinstallProducts
- self.qi.reinstallProducts([PROJECTNAME,])
+ self.qi.reinstallProducts([PROJECTNAME, ])
self.failUnless(self.qi.isProductInstalled(PROJECTNAME))
-
def test_vocabulariesDeletedAtUninstall(self):
"""the tool and all the vocabularies get deleted
at product uninstall.
"""
-
+
self.loginAsPortalOwner()
-
+
#install the product
self.qi.installProduct(PROJECTNAME)
-
+
#create some vocabulary
atvm = getToolByName(self.portal, 'portal_vocabularies')
- atvm.invokeFactory('SimpleVocabulary','foo')
+ atvm.invokeFactory('SimpleVocabulary', 'foo')
vocab = atvm.getVocabularyByName('foo')
vocab.invokeFactory('SimpleVocabularyTerm', 'bar', title='Some test')
-
+
#uninstall the product
- self.qi.uninstallProducts([PROJECTNAME,])
+ self.qi.uninstallProducts([PROJECTNAME, ])
self.failIf(self.qi.isProductInstalled(PROJECTNAME))
-
+
#see if tool hidden
# XXX CMFQuickInstallerTool 3.0.3 does not delete the portal items any
# any longer if Folderish. Asked eleddy and jens what they think about
# the implications here(feature/bug) [do3cc]
#self.assertRaises(AttributeError, getToolByName, self.portal, 'portal_vocabularies')
-
-
+
+
#install the product again
sleep(1)
self.qi.installProduct(PROJECTNAME)
self.failUnless(self.qi.isProductInstalled(PROJECTNAME))
-
+
#all vocabs are gone!
atvm = getToolByName(self.portal, 'portal_vocabularies')
foo = atvm.getVocabularyByName('foo')
# see the XXX about CMFQuickInstallerTool above
#self.failUnless(foo is None)
-
+
def test_zexpOfVocabulariesAtUninstall(self):
"""vocabulariees get deleted together with the tool at product uninstallation.
-
+
as a kind of safetybelt a zexp of all vocabularies gets created
when atvm gets uninstalled (in case this was done by accident)
"""
#XXX add a test for this here and patch Extensions/Install.py
-
def test_vocabulariesPreservedAtReinstall(self):
"""the tool and all the vocabularies are preserved when
reinstalling the product.
"""
-
+
self.loginAsPortalOwner()
#install the product
self.qi.installProduct(PROJECTNAME)
-
+
#create some vocabulary
atvm = getToolByName(self.portal, 'portal_vocabularies')
- atvm.invokeFactory('SimpleVocabulary','foo')
+ atvm.invokeFactory('SimpleVocabulary', 'foo')
vocab = atvm.getVocabularyByName('foo')
vocab.invokeFactory('SimpleVocabularyTerm', 'bar', title='Some test')
-
+
#reinstall the product
sleep(1)
- self.qi.reinstallProducts([PROJECTNAME,])
+ self.qi.reinstallProducts([PROJECTNAME, ])
+
-
#the tool and the vocabularies are still there
atvm = getToolByName(self.portal, 'portal_vocabularies')
@@ -130,7 +125,7 @@
self.failIf(foo is None)
self.failIf(foo.bar is None)
self.assertEqual(foo.bar.Title(), 'Some test')
-
+
def test_suite():
from unittest import TestSuite, makeSuite
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSimpleVocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSimpleVocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSimpleVocabulary.py Tue Apr 5 18:30:17 2011
@@ -12,7 +12,6 @@
import common
-
class TestSimpleVocabulary(PloneTestCase.PloneTestCase):
def afterSetUp(self):
@@ -21,25 +20,23 @@
def setupSimpleVocabularyContainer(self):
self.setRoles(['Manager'])
- self.atvm.invokeFactory('SimpleVocabulary','svtest')
+ self.atvm.invokeFactory('SimpleVocabulary', 'svtest')
self.atvm.svtest.setTitle('Test Vocabulary')
-
def setupSimpleVocabulary(self):
self.setupSimpleVocabularyContainer()
self.atvm.svtest.invokeFactory('SimpleVocabularyTerm', 'key1')
self.atvm.svtest.key1.setTitle('Value 1')
self.logout()
-
def testAddTerm(self):
self.setupSimpleVocabularyContainer()
svtest = self.atvm.svtest
- svtest.addTerm('foo','bar')
+ svtest.addTerm('foo', 'bar')
self.assertEqual(svtest.foo.getVocabularyValue(), 'bar')
# Test adding a term with a key that matches an attribute that
# already exists via acquisition
- svtest.addTerm('author','Author')
+ svtest.addTerm('author', 'Author')
self.assertEqual(svtest.author.getVocabularyValue(), 'Author')
def testImportCSVwoTitlerow(self):
@@ -51,18 +48,17 @@
"""
svtest = self.atvm.svtest
svtest.importCSV(csvdata)
- vocab=svtest.getVocabularyDict()
+ vocab = svtest.getVocabularyDict()
# first both lines used?
- self.assertEqual(vocab['key1'],'value1')
- self.assertEqual(vocab['key2'],'value2')
+ self.assertEqual(vocab['key1'], 'value1')
+ self.assertEqual(vocab['key2'], 'value2')
# there must be an Value value3 with a uuid as key
for key in vocab.keys():
if vocab[key] == 'value3':
self.failUnless(key!="")
-
def testImportCSVMultilingual(self):
qi = getToolByName(self.portal, 'portal_quickinstaller')
@@ -107,7 +103,6 @@
frTerm = svtest[key].getTermValue(lang='fr')
self.assertEqual(frTerm, 'value3fr')
-
def testImportCSVMultilingualNoTitleRow(self):
self.setupSimpleVocabularyContainer()
@@ -142,7 +137,6 @@
enTerm = svtest[key].getTermValue()
self.assertEqual(enTerm, 'value3en')
-
def _createTestVocabulary(self):
"""creates a simplevocabulary for testing purposes
using the utlity methods provided by atvocabularymanager
@@ -159,7 +153,6 @@
createSimpleVocabs(self.atvm, testvocabs)
-
def testTranslations(self):
"""Test if SimpleVocabulary works with Linguaplone
"""
@@ -196,7 +189,7 @@
# if ``instance`` is None, the vocabulary uses the
# current language of the languagetool
- langtool = getToolByName(self.portal,'portal_languages')
+ langtool = getToolByName(self.portal, 'portal_languages')
# set available portal languages
langtool.supported_langs=['en', 'de']
# per default english is the preferred language
@@ -212,7 +205,6 @@
# dictionary has to return another title now
self.assertEqual('Oesterreich', deDict[enKey], "Vocab Title is not translated")
-
def testGetTermKeyPath(self):
"""A SimpleVocabularyTerm simply returns a list containing it's key
"""
@@ -222,7 +214,6 @@
self.assertEqual(['aut'], vocab.aut.getTermKeyPath())
-
def test_suite():
from unittest import TestSuite, makeSuite
optionflags = doctest.REPORT_ONLY_FIRST_FAILURE | doctest.ELLIPSIS
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSkeletonPloneTest.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSkeletonPloneTest.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testSkeletonPloneTest.py Tue Apr 5 18:30:17 2011
@@ -5,7 +5,7 @@
import unittest
-from Testing import ZopeTestCase
+#from Testing import ZopeTestCase
from Products.PloneTestCase import PloneTestCase
import common
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testTreeVocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testTreeVocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/testTreeVocabulary.py Tue Apr 5 18:30:17 2011
@@ -4,7 +4,7 @@
import unittest
-from Testing import ZopeTestCase
+#from Testing import ZopeTestCase
from Products.PloneTestCase import PloneTestCase
from Products.ATVocabularyManager.utils.vocabs import createHierarchicalVocabs
@@ -22,9 +22,8 @@
self.atvm = common.getATVM(self.portal)
self.loginAsPortalOwner()
-
def setupExampleTreeVocabulary(self):
- hierarchicalVocabs={}
+ hierarchicalVocabs = {}
hierarchicalVocabs[('regions', 'Some regions in europe')] = {
('aut', 'Austria'): {
@@ -33,15 +32,12 @@
}
},
('ger', 'Germany'): {
- ('bav', 'Bavaria'):{}
+ ('bav', 'Bavaria'): {}
},
}
createHierarchicalVocabs(self.atvm, hierarchicalVocabs)
-
-
-
def test_getTermKeyPath(self):
"""Test for the method term.getTermKeyPath.
@@ -65,7 +61,6 @@
"""tests if treevocabulary works fine with linguaplone
"""
self.setupExampleTreeVocabulary()
-
self._translateVocabulary()
# a term and it's translation have to provide the same keys
@@ -75,19 +70,16 @@
self.assertEqual(aut.getTermKey(), autDe.getTermKey())
-
# check if displaylist are translated correctly
-
- langtool = getToolByName(self.portal,'portal_languages')
+ langtool = getToolByName(self.portal, 'portal_languages')
# set available portal languages
langtool.supported_langs=['en', 'de']
- # per default englisch is the preferred language
+ # per default english is the preferred language
self.assertEqual('en', langtool.getPreferredLanguage())
enDict = vocab.getVocabularyDict()
-
autUID=vocab.aut.UID()
# title for austria in english
self.assertEqual('Austria', enDict[autUID][0])
@@ -103,20 +95,14 @@
germanyUID = vocab.ger.UID()
self.assertEqual('Germany', deDict[germanyUID][0], "Canonical's is not used for unstranslated vocabularies")
-
-
-
def _translateVocabulary(self):
"""translates the vocabulary 'regions'
created in ``setupExampleTreeVocabulary``
"""
-
-
# we need to install 'Linguaplone' to translate
# vocabularies
qi = getToolByName(self.portal, 'portal_quickinstaller')
-
lpAvailable = qi.isProductAvailable('LinguaPlone')
self.failUnless(lpAvailable, "Product LinguaPlone has to be available in INSTANCE_HOME")
@@ -134,8 +120,6 @@
# titles are correctly used as fallbacks
-
-
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
@@ -145,4 +129,3 @@
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
-
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_functional.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_functional.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_functional.py Tue Apr 5 18:30:17 2011
@@ -6,13 +6,12 @@
"""
-import os, sys
+import glob
+import os
+import sys
import unittest
-
-import glob
from zope.testing import doctest
-import unittest
from Testing.ZopeTestCase import FunctionalDocFileSuite as Suite
from Products.PloneTestCase import PloneTestCase
from Products.ATVocabularyManager.tests import PACKAGE_HOME
@@ -29,7 +28,7 @@
#PloneTestCase.installProduct('ATVocabularyManager')
#PloneTestCase.setupPloneSite(products=['ATVocabularyManager'])
-# Using module common to install products and create plone site
+# Using module common to install products and create plone site
import common
@@ -50,10 +49,12 @@
return [filename for filename in
glob.glob(os.path.sep.join([PACKAGE_HOME, '*.txt']))]
+
def list_nontestbrowser_tests():
return [filename for filename in list_doctests()
if os.path.basename(filename) not in REQUIRE_TESTBROWSER]
+
def test_suite():
# BBB: We can obviously remove this when testbrowser is Plone
# mainstream, read: with Five 1.4.
@@ -85,4 +86,3 @@
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
-
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_searchTreeVocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_searchTreeVocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/test_searchTreeVocabulary.py Tue Apr 5 18:30:17 2011
@@ -10,14 +10,13 @@
from Testing import ZopeTestCase
from Products.PloneTestCase import PloneTestCase
-from Products.CMFCore.utils import getToolByName
+#from Products.CMFCore.utils import getToolByName
import common
-
-
from Products.ATVocabularyManager import doc
+
class TestSearchTreeVocabulary(PloneTestCase.PloneTestCase):
"""
"""
@@ -30,27 +29,24 @@
self.loginAsPortalOwner()
-
def test_suite():
from unittest import TestSuite
from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite
-
-
optionflags = doctest.REPORT_ONLY_FIRST_FAILURE | doctest.ELLIPSIS
suites = []
-
+
scriptTests = ['search_treevocabulary.txt',
]
for test in scriptTests:
- suites.append( ZopeDocFileSuite(test,
+ suites.append(ZopeDocFileSuite(test,
optionflags=optionflags,
package='Products.ATVocabularyManager.doc',
test_class=TestSearchTreeVocabulary,
))
- return TestSuite( suites )
+ return TestSuite(suites)
##code-section module-footer #fill in your manual code here
@@ -58,4 +54,3 @@
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
-
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/utils.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/utils.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tests/utils.py Tue Apr 5 18:30:17 2011
@@ -1,20 +1,17 @@
import sys
import code
-
+
def interact(locals=None):
- """Emulate the interactive Python interpreter.
+ """Emulate the interactive Python interpreter.
+
+ locals -- passed to InteractiveInterpreter.__init__()
- locals -- passed to InteractiveInterpreter.__init__()
-
- thanks to Jens Klein aka jenzenz
- """
-
- savestdout = sys.stdout
- sys.stdout = sys.stderr
- console = code.InteractiveConsole(locals)
- console.interact("exit using Ctrl-D")
- sys.stdout = savestdout
-
+ thanks to Jens Klein aka jenzenz
+ """
-
\ No newline at end of file
+ savestdout = sys.stdout
+ sys.stdout = sys.stderr
+ console = code.InteractiveConsole(locals)
+ console.interact("exit using Ctrl-D")
+ sys.stdout = savestdout
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tools/vocabularylib.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tools/vocabularylib.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/tools/vocabularylib.py Tue Apr 5 18:30:17 2011
@@ -7,13 +7,13 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
from zope.interface import implements
from AccessControl import ClassSecurityInfo
-from Acquisition import aq_base
+#from Acquisition import aq_base
from OFS.Cache import Cacheable
from Products.PlacelessTranslationService.Negotiator import getLangPrefs
from Products.CMFCore.utils import getToolByName
@@ -21,7 +21,7 @@
from Products.CMFCore.permissions import ModifyPortalContent
from Products.CMFCore.permissions import View
from Products.Archetypes.atapi import *
-from Products.Archetypes.interfaces.vocabulary import IVocabulary
+#from Products.Archetypes.interfaces.vocabulary import IVocabulary
from Products.ATVocabularyManager.config import TOOL_NAME
from Products.ATVocabularyManager.config import DEFAULT_VOCABULARY_CONTAINER
from Products.ATVocabularyManager.config import PROJECTNAME
@@ -31,16 +31,19 @@
### note: use Archetypes registry infrastructure in future
_vocabterm_types = {}
+
def registerVocabularyTerm(klass, container_name=DEFAULT_VOCABULARY_CONTAINER):
"""register a IVocabularyTerm implementing class and map it to container """
if not container_name in _vocabterm_types.keys():
_vocabterm_types[container_name] = []
_vocabterm_types[container_name].append(klass)
+
def registerVocabularyContainer(klass):
""" (deprecated) register a IVocabulary implementing class """
pass
+
### note: derive somewhere in future from BaseTool
class VocabularyLibrary(UniqueObject, OrderedBaseFolder, Cacheable):
'''
@@ -60,7 +63,7 @@
manage_options = OrderedBaseFolder.manage_options + Cacheable.manage_options
- schema=OrderedBaseFolderSchema + Schema((
+ schema = OrderedBaseFolderSchema + Schema((
# a tool doesnt need an idwidget and title for edit
id_field,
title_field,
@@ -87,10 +90,7 @@
"""fetches vocabulary form cache if present, else return None."""
view_name = self.getId() + '-vocabdicts'
keywords = self._makeCacheKeywords(vocab)
- self.ZCacheable_set(vdict,
- view_name=view_name,
- keywords=keywords)
-
+ self.ZCacheable_set(vdict, view_name=view_name, keywords=keywords)
def _makeCacheKeywords(self, vocab):
"""returns a key for use in the cache."""
@@ -116,7 +116,7 @@
#Methods
def allowedContentTypesForContainer(self, containername):
""" return all allowed fti for a containertype """
- tt = getToolByName(self,'portal_types')
+ tt = getToolByName(self, 'portal_types')
if not containername in _vocabterm_types.keys():
return []
@@ -144,13 +144,13 @@
OrderedBaseFolder.PUT(self, ids, REQUEST)
security.declarePrivate('PUT_factory')
- def PUT_factory( self, name, typ, body ):
+ def PUT_factory(self, name, typ, body):
""" Dispatcher for PUT requests to non-existent IDs.
Should always use VDEX. Copied from CMFPhotoAlbum.
"""
import md5
- md5name=md5.md5(name).hexdigest()
- self.invokeFactory( 'VdexVocabulary', md5name )
+ md5name = md5.md5(name).hexdigest()
+ self.invokeFactory('VdexVocabulary', md5name)
return self[md5name]
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/alias/vocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/alias/vocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/alias/vocabulary.py Tue Apr 5 18:30:17 2011
@@ -9,11 +9,11 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
-import csv
-from StringIO import StringIO
+#import csv
+#from StringIO import StringIO
from zope.interface import implements
from Products.ATVocabularyManager.config import *
if HAS_LINGUA_PLONE:
@@ -28,6 +28,7 @@
from Products.ATVocabularyManager.config import TOOL_NAME as VOCABTOOL_NAME
from Products.ATVocabularyManager.config import PROJECTNAME
+
class AliasVocabulary(BaseContent):
implements(IVocabulary)
@@ -35,7 +36,7 @@
security = ClassSecurityInfo()
meta_type = 'AliasVocabulary'
- schema=BaseFolderSchema + Schema((
+ schema = BaseFolderSchema + Schema((
StringField('id',
required=1, ## Still actually required, but
## the widget will supply the missing value
@@ -82,7 +83,6 @@
)
))
-
def getPossibleTargets(self, instance):
""" fetch a list of vocabularie w/o AliasVocabulary """
vlib = getToolByName(instance, VOCABTOOL_NAME)
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/sortedvocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/sortedvocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/sortedvocabulary.py Tue Apr 5 18:30:17 2011
@@ -14,7 +14,7 @@
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
#
-__author__ = '''gotcha'''
+__author__ = '''gotcha'''
__docformat__ = 'plaintext'
@@ -36,25 +36,24 @@
class SortedSimpleVocabulary(SimpleVocabulary):
security = ClassSecurityInfo()
- __implements__ = getattr(OrderedBaseFolder,'__implements__',()) + (IVocabulary,)
+ __implements__ = getattr(OrderedBaseFolder, '__implements__', ()) + (IVocabulary, )
# This name appears in the 'add' box
- archetype_name = 'Sorted Simple Vocabulary'
-
- meta_type = 'SortedSimpleVocabulary'
- portal_type = 'SortedSimpleVocabulary'
- allowed_content_types = list(getattr(SimpleVocabulary, 'allowed_content_types', []))
- filter_content_types = 1
- global_allow = 0
- allow_discussion = 0
- #content_icon = 'SortedSimpleVocabulary.gif'
- immediate_view = 'base_view'
- default_view = 'base_view'
- suppl_views = ()
- typeDescription = "SortedSimpleVocabulary"
- typeDescMsgId = 'description_edit_sortedsimplevocabulary'
+ archetype_name = 'Sorted Simple Vocabulary'
+ meta_type = 'SortedSimpleVocabulary'
+ portal_type = 'SortedSimpleVocabulary'
+ allowed_content_types = list(getattr(SimpleVocabulary, 'allowed_content_types', []))
+ filter_content_types = 1
+ global_allow = 0
+ allow_discussion = 0
+ #content_icon = 'SortedSimpleVocabulary.gif'
+ immediate_view = 'base_view'
+ default_view = 'base_view'
+ suppl_views = ()
+ typeDescription = "SortedSimpleVocabulary"
+ typeDescMsgId = 'description_edit_sortedsimplevocabulary'
def getDisplayList(self, instance):
""" returns a object of class DisplayList as defined in
@@ -62,20 +61,19 @@
The instance of the content class is given as parameter.
"""
- vdict=self.getVocabularyDict(instance)
+ vdict = self.getVocabularyDict(instance)
key_values = []
for key in vdict.keys():
- key_values.append((key,vdict[key]))
+ key_values.append((key, vdict[key]))
+
def cmp_second_term(item1, item2):
return cmp(item1[1].upper(), item2[1].upper())
+
key_values.sort(cmp_second_term)
dl = DisplayList(key_values)
return dl
+
registerType(SortedSimpleVocabulary, PROJECTNAME)
registerVocabularyContainer(SortedSimpleVocabulary)
-
-
-
-
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/term.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/term.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/term.py Tue Apr 5 18:30:17 2011
@@ -8,7 +8,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
from zope import event
@@ -37,7 +37,7 @@
archetype_name = 'Simple Vocabulary Term'
_at_rename_after_creation = True
- __implements__ = getattr(BaseContent,'__implements__',()) + (IVocabularyTerm,)
+ __implements__ = getattr(BaseContent, '__implements__', ()) + (IVocabularyTerm, )
schema = BaseSchema + Schema((
StringField('id',
@@ -68,15 +68,14 @@
)
aliases = {
- '(Default)' : 'base_view',
- 'view' : 'base_view',
- 'edit' : 'base_edit',
+ '(Default)': 'base_view',
+ 'view': 'base_view',
+ 'edit': 'base_edit',
}
# Methods
# methods from Interface IVocabularTerm
-
def getTermKey(self):
"""
"""
@@ -98,8 +97,7 @@
def getTermKeyPath(self):
# terms of flat vocabularies can savely return their key
- return [self.getTermKey(),]
-
+ return [self.getTermKey(), ]
def getVocabularyKey(self):
''' returns the key of the field '''
@@ -139,21 +137,17 @@
edit = update
# uncomment lines below when you need
- factory_type_information={
- 'allowed_content_types':() ,
+ factory_type_information = {
+ 'allowed_content_types': (),
'allow_discussion': 0,
- 'immediate_view':'simplevocabulary_view',
- 'global_allow':0,
- 'filter_content_types':1,
+ 'immediate_view': 'simplevocabulary_view',
+ 'global_allow': 0,
+ 'filter_content_types': 1,
}
-
- actions= (
-
-
- )
+ actions = ()
registerType(SimpleVocabularyTerm, PROJECTNAME)
-registerVocabularyTerm(SimpleVocabularyTerm,'SimpleVocabulary')
+registerVocabularyTerm(SimpleVocabularyTerm, 'SimpleVocabulary')
registerVocabularyTerm(SimpleVocabularyTerm, 'SortedSimpleVocabulary')
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/vocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/vocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/simple/vocabulary.py Tue Apr 5 18:30:17 2011
@@ -9,7 +9,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
import csv
@@ -40,6 +40,7 @@
from Products.ATVocabularyManager.config import TOOL_NAME as VOCABTOOL_NAME
from Products.ATVocabularyManager.config import PROJECTNAME
+
class SimpleVocabulary(OrderedBaseFolder):
implements(IVocabulary)
@@ -47,16 +48,16 @@
security = ClassSecurityInfo()
meta_type = 'SimpleVocabulary'
- schema=BaseFolderSchema + Schema((
+ schema = BaseFolderSchema + Schema((
StringField('id',
- required=1, ## Still actually required, but
+ required = 1, ## Still actually required, but
## the widget will supply the missing value
## on non-submits
- mode="rw",
- accessor="getId",
- mutator="setId",
- default='',
- widget=StringWidget(
+ mode = "rw",
+ accessor = "getId",
+ mutator = "setId",
+ default = '',
+ widget = StringWidget(
label="Vocabulary Name",
label_msgid="label_vocab_name",
description="Should not contain spaces, underscores or mixed case.",
@@ -66,11 +67,11 @@
),
TextField('description',
- default='',
- required=0,
- searchable=0,
- accessor="Description",
- storage=MetadataStorage(),
+ default = '',
+ required = 0,
+ searchable = 0,
+ accessor = "Description",
+ storage = MetadataStorage(),
widget = TextAreaWidget(description = "Enter a brief description",
description_msgid = "help_description",
label = "Description",
@@ -81,10 +82,10 @@
),
StringField("sortMethod",
- default = SORT_METHOD_LEXICO_VALUES,
- required = 0, # smooth upgrades from 1.0.0-beta2
- searchable= 0,
- widget = SelectionWidget(
+ default = SORT_METHOD_LEXICO_VALUES,
+ required = 0, # smooth upgrades from 1.0.0-beta2
+ searchable = 0,
+ widget = SelectionWidget(
label = "Sort method",
label_msgid = "label_sort_method",
description = "Sort method used for displaying vocabulary terms",
@@ -98,27 +99,27 @@
# Methods for fti modification - better make a mixin class from it?
def allowedContentTypes(self):
- tt = getToolByName(self,'portal_types')
+ tt = getToolByName(self, 'portal_types')
cv=self.contentValues()
if len(cv):
- tt = getToolByName(self,'portal_types')
- allowed=[tt[cv[0].meta_type],]
+ tt = getToolByName(self, 'portal_types')
+ allowed=[tt[cv[0].meta_type], ]
else:
- vt = getToolByName(self,VOCABTOOL_NAME)
+ vt = getToolByName(self, VOCABTOOL_NAME)
allowed= vt.allowedContentTypesForContainer(self.meta_type)
return allowed
def updateRegisteredTypes(self):
""" updates own fti based on registered containers """
- tt = getToolByName(self,'portal_types')
+ tt = getToolByName(self, 'portal_types')
ti = tt[self.meta_type]
- vt = getToolByName(self,VOCABTOOL_NAME)
+ vt = getToolByName(self, VOCABTOOL_NAME)
allowedmetatypes = vt.allowedMetaTypesForContainer(self.meta_type)
ti.allowed_content_types=tuple(allowedmetatypes)
security.declareProtected(AddPortalContent, 'invokeFactory')
- def invokeFactory( self, type_name, id, RESPONSE=None, *args, **kw):
+ def invokeFactory(self, type_name, id, RESPONSE=None, *args, **kw):
""" Invokes the portal_types tool """
try:
return OrderedBaseFolder.invokeFactory(self, type_name, id, RESPONSE, *args, **kw)
@@ -127,14 +128,12 @@
self.updateRegisteredTypes()
return OrderedBaseFolder.invokeFactory(self, type_name, id, RESPONSE, *args, **kw)
- # check for linguaplone
def isLinguaPloneInstalled(self):
""" checks if LinguaPlone is installed """
return ILinguaPloneProductLayer in registered_layers() \
or self.portal_quickinstaller.isProductInstalled('LinguaPlone')
# Methods from Interface IVocabulary
-
def getDisplayList(self, instance):
"""Returns a object of class DisplayList as defined in Products.Archetypes.utils.
@@ -142,9 +141,9 @@
The list is sorted accordingly to the sortMethod chosen.
"""
dl = DisplayList()
- vdict=self.getVocabularyDict(instance)
+ vdict = self.getVocabularyDict(instance)
for key in self.getSortedKeys():
- dl.add(key,vdict[key])
+ dl.add(key, vdict[key])
return dl
def getVocabularyLines(self, instance=None):
@@ -155,7 +154,7 @@
vdict = self.getVocabularyDict(instance)
for key in self.getSortedKeys():
- termlist.append( (key, vdict[key]) )
+ termlist.append((key, vdict[key]))
return termlist
def getVocabularyDict(self, instance=None):
@@ -170,7 +169,7 @@
lang = instance.getLanguage()
except AttributeError:
# we retrieve the current language
- langtool = getToolByName(self,'portal_languages')
+ langtool = getToolByName(self, 'portal_languages')
lang = langtool.getPreferredLanguage()
return self._getTranslatedVocabularyDict(lang)
else:
@@ -180,7 +179,6 @@
vdict[obj.getTermKey()] = obj.getTermValue()
return vdict
-
def _getTranslatedVocabularyDict(self, lang):
vdict = OrderedDict()
for obj in self.contentValues():
@@ -205,7 +203,7 @@
selected sort method (may be unsorted if method = no sort)
"""
sortMethod = self.getSortMethod()
- keys = [term.getVocabularyKey() for term in self.contentValues()]
+ keys = [term.getVocabularyKey() for term in self.contentValues()]
if not hasattr(self, 'sortMethod'):
# smooth upgrade from previous releases
@@ -214,19 +212,19 @@
if sortMethod == SORT_METHOD_LEXICO_KEYS:
keys.sort()
return keys
+
if sortMethod == SORT_METHOD_LEXICO_VALUES:
# returns keys sorted by lexicogarphic order of VALUES
terms = self.contentValues()
- terms.sort(lambda x,y: cmp(x.getVocabularyValue(),y.getVocabularyValue()))
+ terms.sort(lambda x, y: cmp(x.getVocabularyValue(), y.getVocabularyValue()))
return [term.getVocabularyKey() for term in terms]
+
if sortMethod == SORT_METHOD_FOLDER_ORDER:
return keys
# fallback
return keys
-
-
security.declareProtected(AddPortalContent, 'addTerm')
def addTerm(self, key, value, language=None, termtype=DEFAULT_VOCABULARY_ITEM,
silentignore=False, **kwargs):
@@ -254,11 +252,10 @@
raise ValueError, 'type %s is not allowed as vocabularyterm in this context' % termtype
- self.invokeFactory(termtype,key)
+ self.invokeFactory(termtype, key)
self[key].setTitle(value)
return True
-
security.declareProtected(AddPortalContent, 'importCSV')
def importCSV(self, csvdata,
termtype=DEFAULT_VOCABULARY_ITEM,
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/term.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/term.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/term.py Tue Apr 5 18:30:17 2011
@@ -6,7 +6,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
from Products.ATVocabularyManager.config import *
@@ -21,9 +21,9 @@
except ImportError:
from Products.ATVocabularyManager.backports import IVocabularyTerm
-from zope.interface import noLongerProvides
+#from zope.interface import noLongerProvides
from Products.Archetypes.debug import deprecated
-from Products.Archetypes.interfaces.vocabulary import IVocabulary
+#from Products.Archetypes.interfaces.vocabulary import IVocabulary
from Products.ATVocabularyManager.tools import registerVocabularyContainer
from Products.ATVocabularyManager.tools import registerVocabularyTerm
from Products.ATVocabularyManager.types.simple import SimpleVocabularyTerm
@@ -35,38 +35,39 @@
""" Term inside of a TreeVocabulary or as an subterm
"""
- __implements__ = getattr(TreeVocabulary,'__implements__',()) + (IVocabularyTerm,)
+ __implements__ = getattr(TreeVocabulary, '__implements__', ()) + (IVocabularyTerm, )
security = ClassSecurityInfo()
meta_type = 'TreeVocabularyTerm'
schema = BaseSchema + Schema((
StringField('id',
- required=0, ## Still actually required, but
+ required = 0, ## Still actually required, but
## the widget will supply the missing value
## on non-submits
- mode="rw",
- accessor="getId",
- mutator="setId",
- default='',
- widget=IdWidget(
- label="Key",
- label_msgid="label_key",
- description="Should not contain spaces, underscores or mixed "
+ mode = "rw",
+ accessor = "getId",
+ mutator = "setId",
+ default = '',
+ widget = IdWidget(
+ label = "Key",
+ label_msgid = "label_key",
+ description = "Should not contain spaces, underscores or mixed "
"case. This key is for export purposes only. Plone uses "
"as internal key the object's UID.",
- description_msgid="help_key",
- i18n_domain="atvocabularymanager"),
+ description_msgid = "help_key",
+ i18n_domain = "atvocabularymanager"),
),
+
StringField('title',
- required=1,
- searchable=0,
- default='',
- accessor='Title',
- widget=StringWidget(
- label="Value",
- label_msgid="label_value",
- i18n_domain="atvocabularymanager"),
+ required = 1,
+ searchable = 0,
+ default = '',
+ accessor = 'Title',
+ widget = StringWidget(
+ label = "Value",
+ label_msgid = "label_value",
+ i18n_domain = "atvocabularymanager"),
)),
)
@@ -74,7 +75,6 @@
# Methods
# methods from Interface IVocabularyTerm
-
def getTermKey(self):
"""
"""
@@ -83,7 +83,6 @@
else:
return self.getCanonical().UID()
-
def getTermValue(self, lang=None):
"""
"""
@@ -94,7 +93,7 @@
return trans and trans.Title() or self.Title()
def getTermKeyPath(self):
- path = [self.getTermKey(),]
+ path = [self.getTermKey(), ]
actTerm = self
while actTerm.aq_parent.portal_type != 'TreeVocabulary' \
and hasattr(actTerm.aq_parent, 'getTermKey'):
@@ -122,6 +121,6 @@
registerType(TreeVocabularyTerm, PROJECTNAME)
registerVocabularyContainer(TreeVocabularyTerm)
-registerVocabularyTerm(TreeVocabularyTerm,'TreeVocabulary')
-registerVocabularyTerm(TreeVocabularyTerm,'TreeVocabularyTerm')
+registerVocabularyTerm(TreeVocabularyTerm, 'TreeVocabulary')
+registerVocabularyTerm(TreeVocabularyTerm, 'TreeVocabularyTerm')
# end of class TreeVocabularyTerm
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/vocabulary.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/vocabulary.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/tree/vocabulary.py Tue Apr 5 18:30:17 2011
@@ -6,7 +6,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = 'Jens Klein <[email protected]>'
+__author__ = 'Jens Klein <[email protected]>'
__docformat__ = 'plaintext'
from Products.ATVocabularyManager.config import *
@@ -16,7 +16,7 @@
from Products.Archetypes.atapi import *
from AccessControl import ClassSecurityInfo
-from Products.CMFCore.permissions import AddPortalContent
+#from Products.CMFCore.permissions import AddPortalContent
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import base_hasattr
from Products.Archetypes.utils import OrderedDict
@@ -32,16 +32,16 @@
schema = SimpleVocabulary.schema + Schema((
BooleanField('ShowLeavesOnly',
- widget=BooleanWidget(
- label="Show leaves only",
- label_msgid="label_show_leaves_only",
- description="Check to show only leaves in this vocabulary.",
- description_msgid="help_show_leaves_only",
- i18n_domain="atvocabularymanager",
+ widget = BooleanWidget(
+ label = "Show leaves only",
+ label_msgid = "label_show_leaves_only",
+ description = "Check to show only leaves in this vocabulary.",
+ description_msgid = "help_show_leaves_only",
+ i18n_domain = "atvocabularymanager",
),
),
-)
-)
+))
+
class TreeVocabulary(SimpleVocabulary):
security = ClassSecurityInfo()
@@ -66,25 +66,29 @@
""" append subtree to flat display list
"""
for key in vdict.keys():
- if type(vdict[key]) == type((1,2)):
- value = vdict[key][0]
- subdict= vdict[key][1] or None
+ if type(vdict[key]) == type((1, 2)):
+ value = vdict[key][0]
+ subdict = vdict[key][1] or None
else:
- value = vdict[key]
- subdict= None
+ value = vdict[key]
+ subdict = None
if valueparent and display_parents == 'tree':
value = '%s - %s' % (valueparent, value)
if valueparent and display_parents == 'marker':
# Extract any leading -'s from the parent
markers = 0
for char in valueparent:
- if char == '-': markers += 1
- else: break
+ if char == '-':
+ markers += 1
+ else:
+ break
value = '%s-- %s' % ('-'*markers, value)
+
if (not self.showLeafsOnly()) or (not subdict):
- displaylist.add(key,value)
+ displaylist.add(key, value)
+
if subdict:
- self._appendToDisplayList(displaylist,subdict,value,
+ self._appendToDisplayList(displaylist, subdict, value,
display_parents=display_parents)
def getVocabularyDict(self, instance=None):
@@ -100,7 +104,7 @@
lang = instance.getLanguage()
except AttributeError:
# we try to retrieve the current language
- langtool = getToolByName(self,'portal_languages')
+ langtool = getToolByName(self, 'portal_languages')
lang = langtool.getPreferredLanguage()
return self._getTranslatedVocabularyDict(lang)
@@ -109,8 +113,6 @@
# return all contentObjects
return self._getUntranslatedVocabularyDict()
-
-
def _getTranslatedVocabularyDict(self, lang):
"""returns a vocabulary dict using the titles of the
translations for language ``lang``
@@ -127,27 +129,24 @@
key = obj.getTermKey()
# but use the title of the appropriate translation
# if it is available (getTermValue is LP aware)
- vsubdict=obj._getTranslatedVocabularyDict(lang)
+ vsubdict = obj._getTranslatedVocabularyDict(lang)
vdict[key] = (obj.getTermValue(lang=lang), vsubdict)
return vdict
-
def _getUntranslatedVocabularyDict(self):
"""returns a vocabulary dictionary as defined in the interface
"""
vdict = OrderedDict()
for obj in self.contentValues():
- vsubdict=obj._getUntranslatedVocabularyDict()
+ vsubdict = obj._getUntranslatedVocabularyDict()
vdict[obj.getVocabularyKey()] = ( \
- obj.getVocabularyValue(),
- vsubdict
- )
+ obj.getVocabularyValue(), vsubdict)
return vdict
def showLeafsOnly(self):
""" indicates if only leaves should be shown """
- if base_hasattr(self,'getShowLeavesOnly'):
+ if base_hasattr(self, 'getShowLeavesOnly'):
return self.getShowLeavesOnly()
return None
@@ -156,7 +155,6 @@
return 0
-
registerType(TreeVocabulary, PROJECTNAME)
registerVocabularyContainer(TreeVocabulary)
# end of class TreeVocabulary
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/vdex/vocabularyxml.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/vdex/vocabularyxml.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/types/vdex/vocabularyxml.py Tue Apr 5 18:30:17 2011
@@ -10,7 +10,7 @@
#
# BSD-like licence, see LICENCE.txt
#
-__author__ = '''Jens Klein <[email protected]>'''
+__author__ = '''Jens Klein <[email protected]>'''
__docformat__ = 'plaintext'
from zope.interface import implements
@@ -31,47 +31,49 @@
IMSVDEXVocabularySchema = Schema((
StringField(
- name='title',
- required=1,
- searchable=1,
- default='',
- accessor='Title',
- widget=StringWidget(
- label_msgid='label_title',
- visible={'view' : 'invisible', 'edit' : 'invisible'},
- i18n_domain='plone',
+ name = 'title',
+ required = 1,
+ searchable = 1,
+ default = '',
+ accessor = 'Title',
+ widget = StringWidget(
+ label_msgid = 'label_title',
+ visible = {'view': 'invisible', 'edit': 'invisible'},
+ i18n_domain = 'plone',
),
),
TextField(
'description',
- default='',
- searchable=1,
- accessor="Description",
- schemata='default',
- widget=TextAreaWidget(
- visible={'view' : 'visible', 'edit' : 'invisible'},
- label='Description',
- description="A short summary of the content",
- label_msgid="label_description",
- description_msgid="help_description",
- i18n_domain="plone"),
+ default = '',
+ searchable = 1,
+ accessor = "Description",
+ schemata = 'default',
+ widget = TextAreaWidget(
+ visible = {'view': 'visible', 'edit': 'invisible'},
+ label = 'Description',
+ description = "A short summary of the content",
+ label_msgid = "label_description",
+ description_msgid = "help_description",
+ i18n_domain = "plone"),
),
+
FileField(
- name='vdex',
- allowable_content_types=["text/xml"],
- widget=FileWidget(
- label="VDEX-XML-Data",
- label_msgid='IMSVDEXVocabulary_label_vdex',
- description="upload the IMS Vocabulary Definition Format "
+ name = 'vdex',
+ allowable_content_types = ["text/xml"],
+ widget = FileWidget(
+ label = "VDEX-XML-Data",
+ label_msgid = 'IMSVDEXVocabulary_label_vdex',
+ description = "upload the IMS Vocabulary Definition Format "
"compliant XML file into this text field.",
- description_msgid='IMSVDEXVocabulary_description_vdex',
- i18n_domain='ATVocabularyManager',
+ description_msgid = 'IMSVDEXVocabulary_description_vdex',
+ i18n_domain = 'ATVocabularyManager',
allow_file_upload = True,
),
- default_output_type="text/plain",
- default_content_type="text/xml"
+ default_output_type = "text/plain",
+ default_content_type = "text/xml"
),
-),)
+))
+
class IMSVDEXVocabulary(BaseContent):
"""Content type for handling of VDEX compliant vocabulary.
@@ -129,7 +131,7 @@
return vdict
manager = self._getManager()
if manager is None:
- return { self.getId(): 'no or corrupt vocabulary with name %s' % \
+ return {self.getId(): 'no or corrupt vocabulary with name %s' % \
self.getId()}
vdict = manager.getVocabularyDict(lang=self._getLanguage())
vtool.cacheVocabularyDict(self, vdict)
@@ -194,7 +196,7 @@
# try to get it from PTS
accepted = getLangPrefs(self.REQUEST)
if len(accepted) > 0:
- lang = accepted[0]
+ lang = accepted[0]
else:
# bummer, it cant determine a language
lang = 'neutral'
@@ -207,18 +209,18 @@
if not vdict:
return
for key in vdict.keys():
- if type(vdict[key]) == type((1,2)):
- value = vdict[key][0]
+ if type(vdict[key]) == type((1, 2)):
+ value = vdict[key][0]
subdict= vdict[key][1] or None
else:
- value = vdict[key]
+ value = vdict[key]
subdict= None
if valueparent:
value = '%s - %s' % (valueparent, value)
if not self.showLeafsOnly() or subdict:
- displaylist.add(key,value)
+ displaylist.add(key, value)
if subdict:
- self._appendToDisplayList(displaylist, subdict,value)
+ self._appendToDisplayList(displaylist, subdict, value)
def SearchableText(self):
"""dont find in live-search"""
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/text.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/text.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/text.py Tue Apr 5 18:30:17 2011
@@ -1,5 +1,6 @@
from types import UnicodeType
+
def convertStringToId(s, maxlen=None):
"""
Converts a string into a Zope-safe ID.
@@ -33,7 +34,7 @@
# remove ALL double-underscores
while s.find("__") > -1:
- s = s.replace('__','_')
+ s = s.replace('__', '_')
# trim to maxlength
if maxlen and len(s) > maxlen:
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/vocabs.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/vocabs.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/vocabs.py Tue Apr 5 18:30:17 2011
@@ -3,6 +3,7 @@
from Products.CMFCore.utils import getToolByName
from imsvdex.vdex import VDEXManager
+
def fetchValueByKeyFromVocabularyDict(searchedkey, vdict):
"""recursive find of a key in the vocabulary dictionary tree."""
for key in vdict.keys():
@@ -10,7 +11,7 @@
if vdict[key] in types.StringTypes:
return vdict[key]
else:
- return vdict[key][0]
+ return vdict[key][0]
for key in vdict.keys():
if vdict[key] not in types.StringTypes:
if not vdict[key][1]:
@@ -19,14 +20,14 @@
if res is not None:
return res
return None
-
+
def createSimpleVocabs(atvm, simpleVocabDictionary):
"""
creates simple ATVM vocabularies out of tuples stored in the dictionary
- simpleVocabDictionary.
+ simpleVocabDictionary.
code taken from http://plone.org/documentation/tutorial/archgenxml-getting-started/vocabulary-manager
-
+
example:
simpleVocabs['examplestates'] = (
('aut', u'Austria'),
@@ -35,7 +36,7 @@
('fin', u'Finland'),
)
"""
-
+
for vkey in simpleVocabDictionary.keys():
# create vocabulary if it doesn't exist:
vocabname = vkey
@@ -46,16 +47,16 @@
for (ikey, value) in simpleVocabDictionary[vkey]:
if not hasattr(vocab, ikey):
vocab.invokeFactory('SimpleVocabularyTerm', ikey)
- vocab[ikey].setTitle(value)
+ vocab[ikey].setTitle(value)
vocab[ikey].reindexObject()
vocab.reindexObject()
-
+
def createHierarchicalVocabs(atvm, hierarchicalVocabDictionary):
"""
creates TreeVocabularyTerms out of dictionaries of the following format:
-
- hierarchicalVocabs[('exampleregions', 'Regions used in ATVocabExample')] =
+
+ hierarchicalVocabs[('exampleregions', 'Regions used in ATVocabExample')] =
('aut', 'Austria'): {
('tyr', 'Tyrol'): {
('auss', 'Ausserfern'): {},
@@ -66,46 +67,47 @@
},
}
"""
-
+
def createVocabularyTerms(vocabulary, id, title, subDictionary):
"""
vocabulary the TreeVocabulary(Term) to operate on
id,title the new terms title and id
subDictionary a (maybe empty) dictionary containing (termId, termTitle) keys with dictionaries again.
-
+
creates a new term within vocabulary and recursively
checks whether there are subvocabularies to create
"""
if not hasattr(vocabulary, id):
vocabulary.invokeFactory('TreeVocabularyTerm', id, title=title)
-
+
newTerm = vocabulary[id]
-
-
+
+
for key, value in subDictionary.iteritems():
createVocabularyTerms(newTerm, key[0], key[1], value)
-
+
newTerm.reindexObject()
-
-
+
+
for vkey in hierarchicalVocabDictionary.keys():
# create vocabulary if it doesn't exist:
vocabname = vkey
- if not hasattr(atvm, vocabname[0]):
- # just to be sure, normally vocabulary is created in Install.py
+ if not hasattr(atvm, vocabname[0]):
+ # just to be sure, normally vocabulary is created in Install.py
atvm.invokeFactory('TreeVocabulary', vocabname[0], title=vocabname[1])
-
+
# new terms will be created, title changes in dictionary won't affect
# existing terms
vocab = atvm[vocabname[0]]
-
-
+
+
for (id, title), value in hierarchicalVocabDictionary[vkey].iteritems():
if not hasattr(vocab, id):
- createVocabularyTerms(vocab, id, title, value)
+ createVocabularyTerms(vocab, id, title, value)
vocab.reindexObject()
-
+
+
def loadVdexVocabs(site, directory, files, remove=True):
atvm = getToolByName(site, 'portal_vocabularies')
for filename in files:
@@ -122,11 +124,10 @@
vdex = VDEXManager(data)
vocabname = vdex.getVocabIdentifier()
if vocabname in atvm.contentIds():
- if remove:
- atvm.manage_delObjects([vocabname])
- else:
- # logging here?
- continue
+ if remove:
+ atvm.manage_delObjects([vocabname])
+ else:
+ # logging here?
+ continue
atvm.invokeFactory('VdexFileVocabulary', vocabname)
- atvm[vocabname].importXMLBinding(data)
-
+ atvm[vocabname].importXMLBinding(data)
Modified: Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/xml.py
==============================================================================
--- Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/xml.py (original)
+++ Products.ATVocabularyManager/trunk/Products/ATVocabularyManager/utils/xml.py Tue Apr 5 18:30:17 2011
@@ -4,28 +4,33 @@
from types import StringTypes
-def setAttr(doc,node,key,value):
+
+def setAttr(doc, node, key, value):
""" little helper to abbrev. the process of setting an XML-Attribute """
if type(value) not in StringTypes:
- value=repr(value)
- attr=doc.createAttribute(key)
+ value = repr(value)
+
+ attr = doc.createAttribute(key)
node.setAttributeNode(attr)
node.setAttribute(key, value)
return attr
-def appendNode(doc,parent,key):
+
+def appendNode(doc, parent, key):
""" little helper to abbrev. the process of creating a simple node """
- node=doc.createElement(key)
+ node = doc.createElement(key)
parent.appendChild(node)
return node
-def appendText(doc,parent,key,content):
+
+def appendText(doc, parent, key, content):
""" little helper to abbrev. the process of creating a text-node """
- node=appendNode(doc,parent,key)
- textnode=doc.createTextNode(content)
+ node = appendNode(doc, parent, key)
+ textnode = doc.createTextNode(content)
node.appendChild(textnode)
return node
+
def getData(parent):
data = ""
for child in parent.childNodes:
@@ -43,7 +48,8 @@
# it can handle CDATA Nodes, but return it as a textnode
return getData(parent)
-def getChildrenByTagName(parent,name):
+
+def getChildrenByTagName(parent, name):
nodes = []
for child in parent.childNodes:
if child.nodeType == child.ELEMENT_NODE:
------------------------------------------------------------------------------
Xperia(TM) PLAY
It's a major breakthrough. An authentic gaming
smartphone on the nation's most reliable network.
And it wants your games.
http://p.sf.net/sfu/verizon-sfdev