def setUp(test): setup.placefulSetUp(True) setUpDublinCore() component.provideAdapter(storage.Storage) component.provideAdapter(AttributeAnnotations) hooks.setHooks() setup.setUpTraversal() setup.setUpSiteManagerLookup() setup.setUpTestAsModule(test, 'zojax.content.model.README') # generate extension ExtensionClass = ExtensionType( "content.model", IViewModelExtension, ViewModelExtension, "View Model", "View model extension.", layer=interface.Interface) # register adater component.provideAdapter( Wrapper(ExtensionClass), (interface.Interface, interface.Interface, ExtensionMarker), IViewModelExtension) # register vocabulary getVocabularyRegistry().register( 'zojax.content.model-list', Models()) component.provideAdapter( Renderer, (IViewModelSupport, interface.Interface), interface.Interface, name='index.html')
def setUp(test): site = setup.placefulSetUp(True) component.provideAdapter(storage.Storage) component.provideAdapter(AttributeAnnotations) component.provideUtility(expressions.path_translator, name='path') ext = extensiontype.ExtensionType( 'portlets', interfaces.IPortletsExtension, extension.PortletsExtension, 'Portlets', u'') component.provideAdapter(ext, (IExtensible,), interfaces.IPortletsExtension) setup.setUpTestAsModule(test, name='zojax.portlet.TESTS') getVocabularyRegistry().register('zojax portlets', vocabulary.Portlets())
def setUpRegistration(test): setUp(test) zope.component.provideAdapter( quotationtool.biblatex.bibtex.EntryBibtexRepresentation) zope.component.provideAdapter( quotationtool.biblatex.bibtex.BibliographyBibtexRepresentation) zope.component.provideUtility( quotationtool.biblatex.entrytypes.EntryTypesConfiguration(), quotationtool.biblatex.interfaces.IEntryTypesConfiguration, '') # register vocabularies vocabulary.setVocabularyRegistry(vocabulary.VocabularyRegistry()) vr = vocabulary.getVocabularyRegistry() from quotationtool.biblatex.entrytypes import EntryTypeVocabulary vr.register('quotationtool.biblatex.EntryTypes', EntryTypeVocabulary) from quotationtool.biblatex import vocabulary as vocabularies vr.register('quotationtool.biblatex.Pagination', vocabularies.PaginationVocabulary) vr.register('quotationtool.biblatex.EditorRoles', vocabularies.EditorRoleVocabulary) vr.register('quotationtool.biblatex.Pubstate', vocabularies.PubstateVocabulary) vr.register('quotationtool.biblatex.Type', vocabularies.TypeVocabulary) vr.register('quotationtool.biblatex.Gender', vocabularies.GenderVocabulary) vr.register('quotationtool.biblatex.AuthorTypes', vocabularies.AuthorTypeVocabulary) vr.register('quotationtool.biblatex.Language', vocabularies.LanguageVocabulary) vr.register('quotationtool.biblatex.Hyphenation', vocabularies.HyphenationVocabulary)
def vocabulary(self): # TODO: check if there are vocabularies that need to be protected name = self.request.form.get('name', None) vocab = () try: # TODO: getUtility(IVocabularyFactory???) vr = getVocabularyRegistry() vocab = vr.get(self.context, name) except: # eat all exceptions pass if not vocab: # try IContextSourceBinder vocab = queryUtility(IContextSourceBinder, name=name) if vocab is None: return [] vocab = vocab(self.context) result = [] for term in vocab: data = {'token': term.token, 'title': term.title} if hasattr(term, 'data'): data.update(term.data) result.append(data) return result
def __call__(self): # Get the corresponding vocabulary vr = getVocabularyRegistry() vocabular = vr.get(None, self.field.vocabularyName) # Get the data to construct the store fields = ['value', 'title'] data = list() for term in vocabular: entry = dict() entry['value'] = term.token entry['title'] = term.title data.append(entry) # Attributes for the combobox self.name = self.field.getName() self.fieldLabel = translate(self.field.title, context=self.recipe.request) self.emptyText = self.field.default self.allowBlank = not self.field.required self.valueField = 'value' self.displayField = 'title' self.queryMode = 'local' self.store = "Ext.create('Ext.data.Store', {fields: %s, data: %s})" % (json.dumps(fields, indent=' ' * 4), json.dumps(data, indent=' ' * 4)) # Render the template tmpl = loader.load('combobox.json.tpl', cls=NewTextTemplate) stream = tmpl.generate(view=self) return stream.render()
def setUp(self): super(TestAvailableListingViewsVocabulary, self).setUp() self.testcase_mocker = Mocker() provideUtility(tile.availableListingViewsVocabulary, name= u"Available Listing Views") # mock the registry, so that we have a static # configuration in our tests. we test functionality, # not configuration.. proxy = self.testcase_mocker.mock() proxy.listing_views self.testcase_mocker.result({ 'listing': 'List contents', 'summary': 'Summarize contents'}) self.testcase_mocker.count(0, None) registry = self.testcase_mocker.mock() provideUtility(provides=IRegistry, component=registry) registry.forInterface(IContentListingTileSettings) self.testcase_mocker.result(proxy) self.testcase_mocker.count(0, None) # we need to register the vocabulary utility in the # vocabulary registry manually at this point: vocabulary_registry = getVocabularyRegistry() try: vocabulary_registry.get(None, u"Available Listing Views") except VocabularyRegistryError: factory = getUtility(IVocabularyFactory, name=u"Available Listing Views") vocabulary_registry.register(u"Available Listing Views", factory) self.testcase_mocker.replay()
def setUp(self): self.root = setup.placefulSetUp(site=True) conn_stub = ConnectionStub() def register(arg): """i just do not know what is this method doing :(""" conn_stub.register = register self.root._p_jar = conn_stub provideAdapter(connectionOfPersistent, adapts=[IPersistent], provides=IConnection, ) provideAdapter(KeyReferenceToPersistent, adapts=[IPersistent], provides=IKeyReference) provideHandler(setQreatureSiteManager) provideHandler(setQuizUtilities) provideHandler(addQreatureIntIdSubscriber) provideAdapter(SiteManagerAdapter) provideAdapter(ResultInterval) quiz = Quiz(u'init title',u'init body') self.root.__setitem__('quiz', quiz) #the site is quiz! not the root hooks.siteinfo.site = quiz provideAdapter(ResultInterval,adapts=[interfaces.IQuizResult], provides=IResultInterval) provideAdapter(QuizAsXML,adapts=[interfaces.IQuiz], provides=interfaces.IQuizAsXML) provideAdapter(AttributeAnnotations, adapts=[interfaces.IQuizContainer], provides=IAnnotations) provideAdapter(QuizContainerNameChooser, adapts=[interfaces.IQuizContainer], provides=INameChooser) vocabulary.setVocabularyRegistry(vocabulary.VocabularyRegistry()) vr = vocabulary.getVocabularyRegistry() vr.register('Quiz Results',depends_voc) vr.register('Percentage', percentage) vr.register('Quiz Leads', leads_voc) provideUtility(flatten, interfaces.IQreatureUtility, "Flatten")
def map_with_vocab(self, behavior, fieldname, value): """Look in the schema for a vocab and return the mapped value """ if type(value) == int: return str(value) portal = self.layer['portal'] fields = getFieldsInOrder(behavior) for name, field in fields: if name == fieldname: # We have different types of fields, so we have to check, # that we become the vocabulary value_type = field if IList.providedBy(field) or ITuple.providedBy(field): value_type = field.value_type if IChoice.providedBy(value_type): if value_type.vocabulary: vocab = value_type.vocabulary(portal) else: vocab = getVocabularyRegistry().get( portal, value_type.vocabularyName) value = vocab.getTerm(value).title return value
def print_filing_prefixes(self): """Reutrns all filing prefixes and their translations""" voca = getVocabularyRegistry().get( self.context, 'opengever.dossier.type_prefixes') for term in voca: self.log('%s: %s' % (term.value, term.title))
def locked(self): cur = self.getCurrentEditorialStatus() if cur is None: return False vocReg = getVocabularyRegistry() voc = vocReg.get(cur, 'quotationtool.editorial.Status') return voc.getTermByToken(cur.status).locked
def js(self): value_type = self.field.value_type vocab = None if IChoice.providedBy(self.field.value_type): if value_type.vocabulary: vocab = value_type.vocabulary if value_type.vocabularyName: vocab = getVocabularyRegistry().get( self.context, self.field.value_type.vocabularyName) values = [(term.token, term.value) for term in vocab] old_values = self._get_old_values(vocab) else: values = enumerate(self.context.portal_catalog.uniqueValuesFor('Subject')) old_values = enumerate(self.context.Subject()) tags = "" old_tags = "" index = 0 for index, value in values: tags += "{id: '%s', name: '%s'}" % (value.replace("'", "\\'"), value.replace("'", "\\'")) if values.index((index, value)) < len(values) - 1: tags += ", " old_index = 0 # XXX: this is not used #prepopulate for index, value in old_values: old_tags += u"{id: '%s', name: '%s'}" % (value.replace("'", "\\'"), value.replace("'", "\\'")) if old_values.index((index, value)) < len(old_values) - 1: old_tags += ", " result = self.js_template % dict(id=self.id, klass=self.klass, newtags=unicode(tags, errors='ignore'), oldtags=old_tags) return result
def setUp(self): super(TestArchiver, self).setUp() grok('opengever.dossier.archive') grok('opengever.dossier.behaviors.filing') file_path = os.path.join( os.path.dirname(opengever.dossier.__file__), 'vdexvocabs', 'type_prefixes.vdex') vocabulary_registry = getVocabularyRegistry() try: vocabulary_registry.get(None, 'opengever.dossier.type_prefixes') except VocabularyRegistryError: vocabulary_registry.register( 'opengever.dossier.type_prefixes', VdexVocabulary(file_path)) proxy = self.mocker.mock() proxy.client_id self.mocker.result('SKA ARCH') self.mocker.count(0, None) registry = self.mocker.mock() provideUtility(provides=IRegistry, component=registry) registry.forInterface(IBaseClientID) self.mocker.result(proxy) self.mocker.count(0, None)
def constraint(self, value): """See `IField`.""" if zope_isinstance(value, DBItem) and value.enum == GitGranteeType: return value != GitGranteeType.PERSON else: return value in getVocabularyRegistry().get( None, "ValidPersonOrTeam")
def setUp(self): from zope.schema.vocabulary import _clear from zope.schema.vocabulary import getVocabularyRegistry from zope.schema.tests.states import StateVocabulary _clear() vr = getVocabularyRegistry() vr.register("states", StateVocabulary)
def setUp(self): super(TestArchiver, self).setUp() grok('opengever.dossier.archive') grok('opengever.dossier.behaviors.filing') file_path = os.path.join(os.path.dirname(opengever.dossier.__file__), 'vdexvocabs', 'type_prefixes.vdex') vocabulary_registry = getVocabularyRegistry() try: vocabulary_registry.get(None, 'opengever.dossier.type_prefixes') except VocabularyRegistryError: vocabulary_registry.register('opengever.dossier.type_prefixes', VdexVocabulary(file_path)) proxy = self.mocker.mock() proxy.client_id self.mocker.result('SKA ARCH') self.mocker.count(0, None) registry = self.mocker.mock() provideUtility(provides=IRegistry, component=registry) registry.forInterface(IBaseClientID) self.mocker.result(proxy) self.mocker.count(0, None)
def test_site_layouts_vocabulary_and_manifest(self): from zope.schema.vocabulary import getVocabularyRegistry portal = self.layer['portal'] vocab = getVocabularyRegistry().get(portal, 'plone.availableSiteLayouts') vocab = list(vocab) vocab.sort(key=lambda t: t.token) self.assertEqual(len(vocab), 3) def _get_layout_vocab(token): for term in vocab: if term.token == token: return term term = _get_layout_vocab('testlayout1/site.html') self.assertEqual(term.title, 'Testlayout1') self.assertEqual(term.value, u'/++sitelayout++testlayout1/site.html') term = _get_layout_vocab('testlayout2/mylayout.html') self.assertEqual(term.title, 'My site layout') self.assertEqual(term.value, u'/++sitelayout++testlayout2/mylayout.html') term = _get_layout_vocab('testlayout2/mylayout2.html') self.assertEqual(term.title, 'My site layout 2') self.assertEqual(term.value, u'/++sitelayout++testlayout2/mylayout2.html')
def setUp(self): super(TestVocabularyPickerWidget, self).setUp() self.context = self.factory.makeTeam() self.vocabulary_registry = getVocabularyRegistry() self.vocabulary = self.vocabulary_registry.get(self.context, 'ValidTeamOwner') self.request = LaunchpadTestRequest()
def getDefaultLaTeXLayout(self): voc = getVocabularyRegistry().get(self, 'ftw.book.layoutsVocabulary') if len(voc) > 0: return voc.by_value.keys()[0] else: return None
def test_items_for_field_vocabulary(self): widget = self._getWidget(attribute_type="reference") vocab = getVocabularyRegistry().get(None, 'BuildableDistroSeries') value_fn = lambda item: canonical_url(item.value, force_local_path=True) expected_items = self._makeExpectedItems(vocab, value_fn=value_fn) self.assertEqual(simplejson.dumps(expected_items), widget.json_items)
def test_items_for_field_vocabulary(self): widget = self._getWidget(attribute_type="reference") vocab = getVocabularyRegistry().get(None, 'BuildableDistroSeries') value_fn = lambda item: canonical_url( item.value, force_local_path=True) expected_items = self._makeExpectedItems(vocab, value_fn=value_fn) self.assertEqual(simplejson.dumps(expected_items), widget.json_items)
def prettyprint_country(self, country): context = aq_inner(self.context) vr = getVocabularyRegistry() countries_vocabulary = vr.get(context, 'chromsystems.userdata.CountryList') term = countries_vocabulary.getTerm(country) return term.title
def set(self, value): vr = getVocabularyRegistry() vocabular = vr.get(None, self.field.vocabularyName) term = vocabular.getTermByToken(value) if term.value is None: self.field.set(self.model, None) else: self.field.set(self.model, term.value)
def _vocabTermValues(self): """Return the token values for the vocab.""" # XXX Abel Deuring 2010-05-21, bug 583502: We cannot simply iterate # over the items of AllUserTeamsPariticipationVocabulary, so # so iterate over all Persons and check membership. vocabulary_registry = getVocabularyRegistry() vocab = vocabulary_registry.get(None, 'AllUserTeamsParticipation') return [p for p in IStore(Person).find(Person) if p in vocab]
def course_types(self): context = aq_inner(self.context) vr = getVocabularyRegistry() vocab = vr.get(context, 'hph.lectures.CourseType') course_types = dict() for term in vocab: course_types[term.value] = term.title return course_types
def prettify_status(self, status): context = aq_inner(self.context) registry = getVocabularyRegistry() vocabulary = registry.get(context, 'wigo.statusapp.ComponentStatus') term = vocabulary.getTerm(status) info = {} info['title'] = term.title info['value'] = term.value return info
def _is_risk(component): """Does this channel component identify a risk?""" vocabulary = getVocabularyRegistry().get(None, "SnapStoreChannel") try: vocabulary.getTermByToken(component) except LookupError: return False else: return True
def getVocabulary(field): if field.vocabulary is not None: return field.vocabulary vr = getVocabularyRegistry() try: return vr.get(None, field.vocabularyName) except VocabularyRegistryError: return None
def _getDistributionOrProductOrProjectGroup(self, name): """Return the matching distribution, product or project, or None.""" vocabulary_registry = getVocabularyRegistry() vocab = vocabulary_registry.get( None, 'DistributionOrProductOrProjectGroup') try: return vocab.getTermByToken(name).value except LookupError: return None
def _getDistributionOrProductOrProjectGroup(self, name): """Return the matching distribution, product or project, or None.""" vocabulary_registry = getVocabularyRegistry() vocab = vocabulary_registry.get(None, 'DistributionOrProductOrProjectGroup') try: return vocab.getTermByToken(name).value except LookupError: return None
def _clear(): """Re-initialize the vocabulary registry.""" # This should normally only be needed by the testing framework, # but is also used for module initialization. global vocabularyRegistry vocabulary._clear() vocabularyRegistry = vocabulary.getVocabularyRegistry() vocabulary._clear() vocabulary.setVocabularyRegistry(ZopeVocabularyRegistry())
def getVocabulary(field): if field.vocabulary is not None: return field.vocabulary vr=getVocabularyRegistry() try: return vr.get(None, field.vocabularyName) except VocabularyRegistryError: return None
def __call__(self, context): if isinstance(self.vocab, basestring): original_vocab = getVocabularyRegistry().get(context, self.vocab) else: original_vocab = self.vocab if callable(self.visible_terms): self.visible_terms = self.visible_terms(context, original_vocab) if self.plone_registry is not None and \ self.visible_terms_from_registry is not None: record = self.plone_registry.get(self.visible_terms_from_registry, None) if record and type(record) == list: if type(self.visible_terms) == list: for term in record: if not term in self.visible_terms: self.visible_terms.append(term) else: self.visible_terms = record if getattr(original_vocab, 'visible_terms', False) and \ isinstance(original_vocab.visible_terms, list): if self.visible_terms is None: self.visible_terms = original_vocab.visible_terms else: self.visible_terms += original_vocab.visible_terms if callable(self.hidden_terms): self.hidden_terms = self.hidden_terms(context, original_vocab) if self.plone_registry is not None and \ self.hidden_terms_from_registry is not None: record = self.plone_registry.get(self.hidden_terms_from_registry, None) if record and type(record) == list: if type(self.hidden_terms) == list: for term in record: if not term in self.hidden_terms: self.hidden_terms.append(term) else: self.hidden_terms = record if getattr(original_vocab, 'hidden_terms', False) and \ isinstance(original_vocab.hidden_terms, list): if self.hidden_terms is None: self.hidden_terms = original_vocab.hidden_terms else: self.hidden_terms += original_vocab.hidden_terms return self.wrapper_class( original_vocab, visible_terms=self.visible_terms, hidden_terms=self.hidden_terms, )
def pretty_category(self, category): context = aq_inner(self.context) vr = getVocabularyRegistry() records = vr.get(context, 'jobtool.jobcontent.jobCategory') try: vocabterm = records.getTerm(category) prettyname = vocabterm.title except KeyError: prettyname = category return prettyname
def pretty_distributor(self, distributor): context = aq_inner(self.context) vr = getVocabularyRegistry() records = vr.get(context, 'jobtool.jobcontent.externalDistributors') try: vocabterm = records.getTerm(distributor) prettyname = vocabterm.title except KeyError: prettyname = distributor return prettyname
def setUpFive(self): """Initialize Five without loading the site.zcml file to avoid loading all Products.* . This basically pushes a special vocabulary registry that supports global and local utilities. """ self._oldVocabularyRegistry = getVocabularyRegistry() setVocabularyRegistry(Zope2VocabularyRegistry())
def prettify_degree(self, value): context = aq_inner(self.context) vr = getVocabularyRegistry() vocab = vr.get(context, 'hph.lectures.CourseDegree') title = _(u"undefined") if value is not None: for term in vocab: if term.value == value: title = term.title return title
def vocabulary(self, field): vocabulary = field.vocabulary if vocabulary is None: reg = getVocabularyRegistry() try: vocabulary = reg.get(self.context, field.vocabularyName) except VocabularyRegistryError: raise ValueError("Can't get values from vocabulary %s" % field.vocabularyName) return [(t.value, t.token) for t in vocabulary._terms]
def task_type_category(self): for category in [ 'unidirectional_by_reference', 'unidirectional_by_value', 'bidirectional_by_reference', 'bidirectional_by_value' ]: voc = getVocabularyRegistry().get(self, 'opengever.task.' + category) if self.task_type in voc: return category return None
def task_type_category(self): for category in ['unidirectional_by_reference', 'unidirectional_by_value', 'bidirectional_by_reference', 'bidirectional_by_value']: voc = getVocabularyRegistry().get( self, 'opengever.task.' + category) if self.task_type in voc: return category return None
def pretty_term(self, token): context = aq_inner(self.context) vr = getVocabularyRegistry() records = vr.get(context, 'chromsystems.shopcontent.ShopCategories') try: vocabterm = records.getTerm(token) prettyname = vocabterm.title except KeyError: prettyname = token return prettyname
def status(self): curr = IEditorialHistory(self.context).getCurrentEditorialStatus() vocReg = getVocabularyRegistry() voc = vocReg.get(self.context, 'quotationtool.editorial.Status') if curr: status = curr.status else: status = 'needs_revision' return _('editorial-statusflag-title', u"Editorial Status: $STATUS", mapping={'STATUS': translate(voc.getTermByToken(status).title, context=self.request)})
def _getVocabValue(self, vocabName=None, token=None): vocabReg = vocabulary.getVocabularyRegistry() if vocabReg is not None: vocab = vocabReg.get(self.request, vocabName) if vocab is not None: try: vocabTerm = vocab.getTerm(token) if vocabTerm: return vocabTerm.title except LookupError: return None
def status_vocabulary(self): context = aq_inner(self.context) registry = getVocabularyRegistry() vocabulary = registry.get(context, 'wigo.statusapp.ComponentStatus') data = [] for term in vocabulary: info = {} info['title'] = term.title info['value'] = term.value data.append(info) return data
def translate_participation_role(role): site = getSite() vr = getVocabularyRegistry() vocab = vr.get(site, 'opengever.dossier.participation_roles') try: term = vocab.getTerm(role) except LookupError: return role else: return term.title
def __call__(self, context): """See `IContextSourceBinder`.""" user = getUtility(ILaunchBag).user if user is not None and user.languages: translations_user = ITranslationsPerson(user) terms = [ SimpleTerm(language, language.code, language.displayname) for language in translations_user.translatable_languages] if terms: return SimpleVocabulary(terms) return getVocabularyRegistry().get(None, "TranslatableLanguage")
def get_label(self): vocabulary_registry = getVocabularyRegistry() vocab = vocabulary_registry.get( api.portal.get(), 'opengever.dossier.participation_roles') try: term = vocab.getTerm(self.role) except LookupError: return self.role else: return term.title
def setUp(test): setup.placelessSetUp() from z3c.form import testing testing.setupFormDefaults() vr = getVocabularyRegistry() from schooltool.basicperson.vocabularies import groupVocabularyFactory from schooltool.basicperson.vocabularies import advisorVocabularyFactory vr.register('schooltool.basicperson.group_vocabulary', groupVocabularyFactory()) vr.register('schooltool.basicperson.advisor_vocabulary', advisorVocabularyFactory()) setUpRelationships() setUpAnnotations()
def vocabValue(self, vocabName=None, token=None): if vocabName is None: return None if token is None: return None vocabReg = vocabulary.getVocabularyRegistry() if vocabReg is not None: vocab = vocabReg.get(self.request, vocabName) if vocab is not None: vocabTerm = vocab.getTerm(token) if vocabTerm: return vocabTerm.title return None
def bind(self, object): """See zope.schema._bootstrapinterfaces.IField.""" clone = super(Choice, self).bind(object) # get registered vocabulary if needed: if IContextSourceBinder.providedBy(self.vocabulary): clone.vocabulary = self.vocabulary(object) assert ISource.providedBy(clone.vocabulary) elif clone.vocabulary is None and self.vocabularyName is not None: vr = getVocabularyRegistry() clone.vocabulary = vr.get(object, self.vocabularyName) assert ISource.providedBy(clone.vocabulary) return clone