[Zope3-checkins]
SVN: Zope3/branches/jim-uniqueid-restructure/src/zope/app/
Finished restructuring.
Jim Fulton
jim at zope.com
Mon Nov 29 19:21:14 EST 2004
Log message for revision 28537:
Finished restructuring.
Changed:
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/README.txt
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/catalog.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/configure.zcml
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/tests.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/configure.zcml
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/__init__.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/__init__.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/configure.zcml
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/tracking.txt
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/configure.zcml
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/ftests.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/interfaces.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/tests.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/__init__.py
D Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/browser/
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/configure.zcml
D Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/ftests.py
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/interfaces.py
A Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.py
A Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.txt
U Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/tests.py
D Zope3/branches/jim-uniqueid-restructure/src/zope/app/uniqueid/
-=-
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/README.txt
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/README.txt 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/README.txt 2004-11-30 00:21:14 UTC (rev 28537)
@@ -14,7 +14,7 @@
to spcify a names filter adapter.
Catalogs use a unique-id tool to assign short (integer) ids to
-objects. Before creating a catalog, you must create a uniqueid tool:
+objects. Before creating a catalog, you must create a intid tool:
>>> print http(r"""
... POST /++etc++site/default/AddUtility/action.html HTTP/1.1
@@ -23,17 +23,17 @@
... Content-Type: application/x-www-form-urlencoded
... Referer: http://localhost:8081/++etc++site/default/AddUtility
...
- ... type_name=BrowserAdd__zope.app.uniqueid.UniqueIdUtility&id=&add=+Add+""")
+ ... type_name=BrowserAdd__zope.app.intid.IntIds&id=&add=+Add+""")
HTTP/1.1 303 ...
And register it:
>>> print http(r"""
- ... POST /++etc++site/default/UniqueIdUtility/addRegistration.html HTTP/1.1
+ ... POST /++etc++site/default/IntIds/addRegistration.html HTTP/1.1
... Authorization: Basic bWdyOm1ncnB3
... Content-Length: 864
... Content-Type: multipart/form-data; boundary=---------------------------68417209514430962931254091825
- ... Referer: http://localhost:8081/++etc++site/default/UniqueIdUtility/addRegistration.html
+ ... Referer: http://localhost:8081/++etc++site/default/IntIds/addRegistration.html
...
... -----------------------------68417209514430962931254091825
... Content-Disposition: form-data; name="field.name"
@@ -42,7 +42,7 @@
... -----------------------------68417209514430962931254091825
... Content-Disposition: form-data; name="field.interface"
...
- ... zope.app.uniqueid.interfaces.IUniqueIdUtility
+ ... zope.app.intid.interfaces.IIntIds
... -----------------------------68417209514430962931254091825
... Content-Disposition: form-data; name="field.interface-empty-marker"
...
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/catalog.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/catalog.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/catalog.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -25,7 +25,7 @@
from zope.app.annotation.interfaces import IAttributeAnnotatable
from zope.app.container.interfaces import IContainer
from zope.app.catalog.interfaces import ICatalog
-from zope.app.uniqueid.interfaces import IUniqueIdUtility
+from zope.app.intid.interfaces import IIntIds
from zope.index.interfaces import ISimpleQuery
@@ -64,13 +64,13 @@
index.unindex_doc(docid)
def updateIndex(self, index):
- uidutil = zapi.getUtility(IUniqueIdUtility)
+ uidutil = zapi.getUtility(IIntIds)
for uid, ref in uidutil.items():
obj = ref()
index.index_doc(uid, obj)
def updateIndexes(self):
- uidutil = zapi.getUtility(IUniqueIdUtility)
+ uidutil = zapi.getUtility(IIntIds)
for uid, ref in uidutil.items():
obj = ref()
for index in self.values():
@@ -96,7 +96,7 @@
if not pendingResults:
break # nothing left, short-circuit
# Next we turn the IISet of docids into a generator of objects
- uidutil = zapi.getUtility(IUniqueIdUtility)
+ uidutil = zapi.getUtility(IIntIds)
results = ResultSet(pendingResults, uidutil)
return results
@@ -122,10 +122,10 @@
index.__parent__.updateIndex(index)
def indexDocSubscriber(event):
- """A subscriber to UniqueIdAddedEvent"""
+ """A subscriber to IntIdAddedEvent"""
for cat in zapi.getAllUtilitiesRegisteredFor(ICatalog):
ob = event.object
- id = zapi.getUtility(IUniqueIdUtility, context=cat).getId(ob)
+ id = zapi.getUtility(IIntIds, context=cat).getId(ob)
cat.index_doc(id, ob)
@@ -133,15 +133,15 @@
"""A subscriber to ObjectModifiedEvent"""
for cat in zapi.getAllUtilitiesRegisteredFor(ICatalog):
ob = event.object
- id = zapi.getUtility(IUniqueIdUtility, context=cat).queryId(ob)
+ id = zapi.getUtility(IIntIds, context=cat).queryId(ob)
if id is not None:
cat.index_doc(id, ob)
def unindexDocSubscriber(event):
- """A subscriber to UniqueIdRemovedEvent"""
+ """A subscriber to IntIdRemovedEvent"""
for cat in zapi.getAllUtilitiesRegisteredFor(ICatalog):
ob = event.object
- id = zapi.getUtility(IUniqueIdUtility, context=cat).queryId(ob)
+ id = zapi.getUtility(IIntIds, context=cat).queryId(ob)
if id is not None:
cat.unindex_doc(id)
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/configure.zcml
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/configure.zcml 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/configure.zcml 2004-11-30 00:21:14 UTC (rev 28537)
@@ -35,7 +35,7 @@
<subscriber
factory=".catalog.indexDocSubscriber"
- for="zope.app.uniqueid.interfaces.IUniqueIdAddedEvent"
+ for="zope.app.intid.interfaces.IIntIdAddedEvent"
/>
<subscriber
@@ -45,7 +45,7 @@
<subscriber
factory=".catalog.unindexDocSubscriber"
- for="zope.app.uniqueid.interfaces.IUniqueIdRemovedEvent"
+ for="zope.app.intid.interfaces.IIntIdRemovedEvent"
/>
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/tests.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/tests.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/catalog/tests.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -26,7 +26,7 @@
from zope.app.tests import ztapi, setup
from zope.app.tests.placelesssetup import PlacelessSetup
from BTrees.IIBTree import IISet
-from zope.app.uniqueid.interfaces import IUniqueIdUtility
+from zope.app.intid.interfaces import IIntIds
from zope.index.interfaces import IInjection, ISimpleQuery
from zope.app.catalog.interfaces import ICatalog
@@ -45,9 +45,9 @@
return self.obj
-class UniqueIdUtilityStub:
- """A stub for UniqueIdUtility."""
- implements(IUniqueIdUtility)
+class IntIdsStub:
+ """A stub for IntIds."""
+ implements(IIntIds)
def __init__(self):
self.ids = {}
@@ -132,9 +132,9 @@
del catalog['author']
self.assertEqual(list(catalog.keys()), ['title'])
- def _frob_uniqueidutil(self, ints=True, apes=True):
- uidutil = UniqueIdUtilityStub()
- ztapi.provideUtility(IUniqueIdUtility, uidutil)
+ def _frob_intidutil(self, ints=True, apes=True):
+ uidutil = IntIdsStub()
+ ztapi.provideUtility(IIntIds, uidutil)
# whack some objects in our little objecthub
if ints:
for i in range(10):
@@ -151,7 +151,7 @@
def test_updateindexes(self):
"""Test a full refresh."""
- self._frob_uniqueidutil()
+ self._frob_intidutil()
catalog = Catalog()
catalog['author'] = StubIndex('author', None)
catalog['title'] = StubIndex('author', None)
@@ -162,7 +162,7 @@
def test_updateindex(self):
"""Test a full refresh."""
- self._frob_uniqueidutil()
+ self._frob_intidutil()
catalog = Catalog()
catalog['author'] = StubIndex('author', None)
catalog['title'] = StubIndex('author', None)
@@ -174,7 +174,7 @@
def test_basicsearch(self):
"""Test the simple search results interface."""
- self._frob_uniqueidutil(ints=0)
+ self._frob_intidutil(ints=0)
catalog = Catalog()
catalog['simiantype'] = StubIndex('simiantype', None)
catalog['name'] = StubIndex('name', None)
@@ -230,7 +230,7 @@
sm = zapi.getServices(self.root)
setup.addService(sm, Utilities, LocalUtilityService())
self.utility = setup.addUtility(
- sm, '', IUniqueIdUtility, UniqueIdUtilityStub())
+ sm, '', IIntIds, IntIdsStub())
self.cat = setup.addUtility(sm, '', ICatalog, CatalogStub())
def tearDown(self):
@@ -239,13 +239,13 @@
def test_indexDocSubscriber(self):
from zope.app.catalog.catalog import indexDocSubscriber
from zope.app.container.contained import ObjectAddedEvent
- from zope.app.uniqueid.interfaces import UniqueIdAddedEvent
+ from zope.app.intid.interfaces import IntIdAddedEvent
ob = Stub()
ob2 = Stub()
id = self.utility.register(ob)
- indexDocSubscriber(UniqueIdAddedEvent(ob, ObjectAddedEvent(ob2)))
+ indexDocSubscriber(IntIdAddedEvent(ob, ObjectAddedEvent(ob2)))
self.assertEqual(self.cat.regs, [(id, ob)])
self.assertEqual(self.cat.unregs, [])
@@ -271,7 +271,7 @@
def test_unindexDocSubscriber(self):
from zope.app.catalog.catalog import unindexDocSubscriber
from zope.app.container.contained import ObjectRemovedEvent
- from zope.app.uniqueid.interfaces import UniqueIdRemovedEvent
+ from zope.app.intid.interfaces import IntIdRemovedEvent
ob = Stub()
ob2 = Stub()
@@ -279,12 +279,12 @@
id = self.utility.register(ob)
unindexDocSubscriber(
- UniqueIdRemovedEvent(ob2, ObjectRemovedEvent(ob3)))
+ IntIdRemovedEvent(ob2, ObjectRemovedEvent(ob3)))
self.assertEqual(self.cat.unregs, [])
self.assertEqual(self.cat.regs, [])
unindexDocSubscriber(
- UniqueIdRemovedEvent(ob, ObjectRemovedEvent(ob3)))
+ IntIdRemovedEvent(ob, ObjectRemovedEvent(ob3)))
self.assertEqual(self.cat.unregs, [id])
self.assertEqual(self.cat.regs, [])
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/configure.zcml
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/configure.zcml 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/configure.zcml 2004-11-30 00:21:14 UTC (rev 28537)
@@ -57,7 +57,8 @@
<!-- Utilities -->
<include package="zope.app.schema" />
- <include package="zope.app.uniqueid" />
+ <include package="zope.app.intid" />
+ <include package="zope.app.keyreference" />
<!-- Misc. Service Manager objects -->
<include package="zope.app.module" />
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/__init__.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/__init__.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/__init__.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -29,22 +29,23 @@
from zope.interface import implements
from zope.security.proxy import removeSecurityProxy
-from zope.app.container.contained import Contained
-from zope.app.uniqueid.interfaces import IUniqueIdUtility, IReference
-from zope.app.uniqueid.interfaces import UniqueIdRemovedEvent
-from zope.app.uniqueid.interfaces import UniqueIdAddedEvent
from zope.app import zapi
+
+from zope.app.container.contained import Contained
+from zope.app.keyreference.interfaces import IKeyReference
from zope.app.location.interfaces import ILocation
+from zope.app.intid.interfaces import IIntIds
+from zope.app.intid.interfaces import IntIdRemovedEvent
+from zope.app.intid.interfaces import IntIdAddedEvent
-
-class UniqueIdUtility(Persistent, Contained):
+class IntIds(Persistent, Contained):
"""This utility provides a two way mapping between objects and
integer ids.
- IReferences to objects are stored in the indexes.
+ IKeyReferences to objects are stored in the indexes.
"""
- implements(IUniqueIdUtility)
+ implements(IIntIds)
_v_nextid = None
@@ -68,11 +69,11 @@
return default
def getId(self, ob):
- ref = IReference(ob)
+ ref = IKeyReference(ob)
return self.ids[ref]
def queryId(self, ob, default=None):
- ref = IReference(ob)
+ ref = IKeyReference(ob)
return self.ids.get(ref, default)
def _generateId(self):
@@ -94,7 +95,7 @@
def register(self, ob):
# Note that we'll still need to keep this proxy removal.
ob = removeSecurityProxy(ob)
- ref = IReference(ob)
+ ref = IKeyReference(ob)
if ref in self.ids:
return self.ids[ref]
uid = self._generateId()
@@ -103,54 +104,12 @@
return uid
def unregister(self, ob):
- ref = IReference(ob)
+ ref = IKeyReference(ob)
uid = self.ids[ref]
del self.refs[uid]
del self.ids[ref]
-
-class ReferenceToPersistent(object):
- """An IReference for persistent object which is comparable.
-
- These references compare by _p_oids of the objects they reference.
- """
- implements(IReference)
-
- def __init__(self, object):
- if not getattr(object, '_p_oid', None):
- IConnection(object).add(object)
- self.object = object
-
- def __call__(self):
- return self.object
-
- def __hash__(self):
- return hash(self.object._p_oid)
-
- def __cmp__(self, other):
- if not isinstance(other, ReferenceToPersistent):
- raise TypeError("Cannot compare ReferenceToPersistent with %r" %
- (other,))
- return cmp(self.object._p_oid, other.object._p_oid)
-
-
-def connectionOfPersistent(ob):
- """An adapter which gets a ZODB connection of a persistent object.
-
- We are assuming the object has a parent if it has been created in
- this transaction.
-
- Raises ValueError if it is impossible to get a connection.
- """
- cur = ob
- while not getattr(cur, '_p_jar', None):
- cur = getattr(cur, '__parent__', None)
- if cur is None:
- raise ValueError('Can not get connection of %r' % (ob,))
- return cur._p_jar
-
-
-def removeUniqueIdSubscriber(ob, event):
+def removeIntIdSubscriber(ob, event):
"""A subscriber to ObjectRemovedEvent
Removes the unique ids registered for the object in all the unique
@@ -158,21 +117,29 @@
"""
# Notify the catalogs that this object is about to be removed.
- notify(UniqueIdRemovedEvent(ob, event))
+ notify(IntIdRemovedEvent(ob, event))
- for utility in zapi.getAllUtilitiesRegisteredFor(IUniqueIdUtility):
+ for utility in zapi.getAllUtilitiesRegisteredFor(IIntIds):
try:
utility.unregister(ob)
except KeyError:
pass
-def addUniqueIdSubscriber(ob, event):
+def addIntIdSubscriber(ob, event):
"""A subscriber to ObjectAddedEvent
Registers the object added in all unique id utilities and fires
an event for the catalogs.
"""
- for utility in zapi.getAllUtilitiesRegisteredFor(IUniqueIdUtility):
+ for utility in zapi.getAllUtilitiesRegisteredFor(IIntIds):
utility.register(ob)
- notify(UniqueIdAddedEvent(ob, event))
+ notify(IntIdAddedEvent(ob, event))
+
+# BBB
+UniqueIdUtility = IntIds
+import zope.app.keyreference
+ReferenceToPersistent = zope.app.keyreference.KeyReferenceToPersistent
+import sys
+sys.modules['zope.app.uniqueid'] = sys.modules['zope.app.intid']
+del sys
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/__init__.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/__init__.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/__init__.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -19,7 +19,7 @@
from zope.app import zapi
-class UniqueIdUtilityView(object):
+class IntIdsView(object):
def len(self):
return len(removeSecurityProxy(self.context).refs)
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/configure.zcml
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/configure.zcml 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/configure.zcml 2004-11-30 00:21:14 UTC (rev 28537)
@@ -3,7 +3,7 @@
xmlns="http://namespaces.zope.org/browser">
<tool
- interface="zope.app.uniqueid.interfaces.IUniqueIdUtility"
+ interface="zope.app.intid.interfaces.IIntIds"
title="Unique Id Tool"
description="Unique Ids Tools are used to provide system-wide unique ids
for documents."
@@ -12,24 +12,24 @@
<addMenuItem
title="Unique Id Utility"
description="A utility that provides unique ids to objects"
- class="zope.app.uniqueid.UniqueIdUtility"
+ class="zope.app.intid.IntIds"
permission="zope.ManageServices"
/>
<page
name="index.html"
menu="zmi_views" title="Registered Objects"
- for="zope.app.uniqueid.interfaces.IUniqueIdUtility"
+ for="zope.app.intid.interfaces.IIntIds"
permission="zope.ManageServices"
- class=".UniqueIdUtilityView"
+ class=".IntIdsView"
template="registrations.pt"
/>
<page
name="populate"
- for="zope.app.uniqueid.interfaces.IUniqueIdUtility"
+ for="zope.app.intid.interfaces.IIntIds"
permission="zope.ManageServices"
- class=".UniqueIdUtilityView"
+ class=".IntIdsView"
attribute="populate"
/>
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/tracking.txt
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/tracking.txt 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/browser/tracking.txt 2004-11-30 00:21:14 UTC (rev 28537)
@@ -9,24 +9,24 @@
created. We really need to rethink how we manage TTW utilities.)
>>> print http(r"""
- ... GET /++etc++site/AddIUniqueIdUtilityTool HTTP/1.1
+ ... GET /++etc++site/AddIIntIdsTool HTTP/1.1
... Authorization: Basic mgr:mgrpw
- ... Referer: http://localhost:8081/++etc++site/@@manageIUniqueIdUtilityTool.html
+ ... Referer: http://localhost:8081/++etc++site/@@manageIIntIdsTool.html
... """)
HTTP/1.1 200 Ok
...
>>> print http(r"""
- ... POST /++etc++site/AddIUniqueIdUtilityTool/action.html HTTP/1.1
+ ... POST /++etc++site/AddIIntIdsTool/action.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Content-Length: 69
... Content-Type: application/x-www-form-urlencoded
- ... Referer: http://localhost:8081/++etc++site/AddIUniqueIdUtilityTool
+ ... Referer: http://localhost:8081/++etc++site/AddIIntIdsTool
...
- ... type_name=BrowserAdd__zope.app.uniqueid.UniqueIdUtility&id=&add=+Add+""")
+ ... type_name=BrowserAdd__zope.app.intid.IntIds&id=&add=+Add+""")
HTTP/1.1 303 See Other
...
- Location: ../@@manageIUniqueIdUtilityTool.html
+ Location: ../@@manageIIntIdsTool.html
...
Now, we'll add a few folders:
@@ -75,7 +75,7 @@
the objects we added:
>>> print http(r"""
- ... GET /++etc++site/tools/UniqueIdUtility/@@index.html HTTP/1.1
+ ... GET /++etc++site/tools/IntIds/@@index.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Referer: http://localhost:8081/++etc++site/tools/@@contents.html
... """)
@@ -102,7 +102,7 @@
We'll see that reflected in the utility:
>>> print http(r"""
- ... GET /++etc++site/tools/UniqueIdUtility/@@index.html HTTP/1.1
+ ... GET /++etc++site/tools/IntIds/@@index.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Referer: http://localhost:8081/++etc++site/tools/@@contents.html
... """)
@@ -129,7 +129,7 @@
all of the objects will go away:
>>> print http(r"""
- ... GET /++etc++site/tools/UniqueIdUtility/@@index.html HTTP/1.1
+ ... GET /++etc++site/tools/IntIds/@@index.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Referer: http://localhost:8081/++etc++site/tools/@@contents.html
... """)
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/configure.zcml
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/configure.zcml 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/configure.zcml 2004-11-30 00:21:14 UTC (rev 28537)
@@ -1,25 +1,8 @@
<configure xmlns="http://namespaces.zope.org/zope">
- <adapter
- for="persistent.interfaces.IPersistent"
- provides=".interfaces.IReference"
- factory=".ReferenceToPersistent"
- trusted="y"
- />
-
- <class class=".ReferenceToPersistent">
- <require permission="zope.Public" interface=".interfaces.IReference" />
- </class>
-
- <adapter
- for="persistent.interfaces.IPersistent"
- provides="ZODB.interfaces.IConnection"
- factory="zope.app.uniqueid.connectionOfPersistent"
- />
-
- <localUtility class=".UniqueIdUtility">
+ <localUtility class=".IntIds">
<factory
- id="zope.app.uniqueid.UniqueIdUtility"
+ id="zope.app.intid.IntIds"
/>
<implements
@@ -28,28 +11,28 @@
<require
permission="zope.Public"
- interface=".interfaces.IUniqueIdUtilityQuery"
+ interface=".interfaces.IIntIdsQuery"
/>
<require
permission="zope.ManageContent"
- interface=".interfaces.IUniqueIdUtilitySet"
+ interface=".interfaces.IIntIdsSet"
/>
<require
permission="zope.Public"
- interface=".interfaces.IUniqueIdUtilityManage"
+ interface=".interfaces.IIntIdsManage"
/>
</localUtility>
<subscriber
- factory=".removeUniqueIdSubscriber"
+ factory=".removeIntIdSubscriber"
for="zope.app.location.interfaces.ILocation
zope.app.container.interfaces.IObjectRemovedEvent"
/>
<subscriber
- factory=".addUniqueIdSubscriber"
+ factory=".addIntIdSubscriber"
for="zope.app.location.interfaces.ILocation
zope.app.container.interfaces.IObjectAddedEvent"
/>
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/ftests.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/ftests.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/ftests.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -26,11 +26,11 @@
from zope.app.tests.functional import BrowserTestCase
-class TestUniqueIdUtility(BrowserTestCase):
+class TestIntIds(BrowserTestCase):
def setUp(self):
- from zope.app.uniqueid import UniqueIdUtility
- from zope.app.uniqueid.interfaces import IUniqueIdUtility
+ from zope.app.intid import IntIds
+ from zope.app.intid.interfaces import IIntIds
BrowserTestCase.setUp(self)
@@ -38,10 +38,10 @@
root = self.getRootFolder()
sm = zapi.traverse(root, '/++etc++site')
- addUtility(sm, 'uniqueid', IUniqueIdUtility, UniqueIdUtility())
+ addUtility(sm, 'intid', IIntIds, IntIds())
commit()
- type_name = 'BrowserAdd__zope.app.uniqueid.UniqueIdUtility'
+ type_name = 'BrowserAdd__zope.app.intid.IntIds'
response = self.publish(
self.basepath + '/contents.html',
@@ -53,12 +53,12 @@
# default = zapi.traverse(root, '/++etc++site/default')
# rm = default.getRegistrationManager()
# registration = UtilityRegistration(
-# 'cwm', IUniqueIdUtility, self.basepath+'/uniqueid')
+# 'cwm', IIntIds, self.basepath+'/intid')
# pd_id = rm.addRegistration(registration)
# zapi.traverse(rm, pd_id).status = ActiveStatus
def test(self):
- response = self.publish(self.basepath + '/uniqueid/@@index.html',
+ response = self.publish(self.basepath + '/intid/@@index.html',
basic='mgr:mgrpw')
self.assertEquals(response.getStatus(), 200)
# The utility registers in itself when it is being added
@@ -66,11 +66,11 @@
self.assert_('<a href="/++etc++site">/++etc++site</a>'
not in response.getBody())
- response = self.publish(self.basepath + '/uniqueid/@@populate',
+ response = self.publish(self.basepath + '/intid/@@populate',
basic='mgr:mgrpw')
self.assertEquals(response.getStatus(), 302)
- response = self.publish(self.basepath + '/uniqueid/@@index.html',
+ response = self.publish(self.basepath + '/intid/@@index.html',
basic='mgr:mgrpw')
self.assertEquals(response.getStatus(), 200)
body = response.getBody()
@@ -81,7 +81,7 @@
def test_suite():
suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TestUniqueIdUtility))
+ suite.addTest(unittest.makeSuite(TestIntIds))
return suite
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/interfaces.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/interfaces.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/interfaces.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -6,21 +6,8 @@
from zope.interface import Interface, Attribute, implements
-class IReference(Interface):
- """A reference to an object (similar to a weak reference).
+class IIntIdsQuery(Interface):
- The references are compared by their hashes.
- """
-
- def __call__():
- """Get the object this reference is linking to."""
-
- def __hash__():
- """Get a unique identifier of the referenced object."""
-
-
-class IUniqueIdUtilityQuery(Interface):
-
def getObject(uid):
"""Return an object by its unique id"""
@@ -40,7 +27,7 @@
Return the default if the object isn't registered
"""
-class IUniqueIdUtilitySet(Interface):
+class IIntIdsSet(Interface):
def register(ob):
"""Register an object and returns a unique id generated for it.
@@ -54,7 +41,7 @@
ValueError is raised if ob is not registered previously.
"""
-class IUniqueIdUtilityManage(Interface):
+class IIntIdsManage(Interface):
"""Some methods used by the view."""
def __len__():
@@ -64,15 +51,14 @@
"""Return a list of (id, object) pairs."""
-class IUniqueIdUtility(IUniqueIdUtilitySet, IUniqueIdUtilityQuery,
- IUniqueIdUtilityManage):
+class IIntIds(IIntIdsSet, IIntIdsQuery, IIntIdsManage):
"""A utility that assigns unique ids to objects.
Allows to query object by id and id by object.
"""
-class IUniqueIdRemovedEvent(Interface):
+class IIntIdRemovedEvent(Interface):
"""A unique id will be removed
The event is published before the unique id is removed
@@ -84,19 +70,19 @@
original_event = Attribute("The IObjectRemoveEvent related to this event")
-class UniqueIdRemovedEvent:
+class IntIdRemovedEvent:
"""The event which is published before the unique id is removed
from the utility so that the catalogs can unindex the object.
"""
- implements(IUniqueIdRemovedEvent)
+ implements(IIntIdRemovedEvent)
def __init__(self, object, event):
self.object = object
self.original_event = event
-class IUniqueIdAddedEvent(Interface):
+class IIntIdAddedEvent(Interface):
"""A unique id has been added
The event gets sent when an object is registered in a
@@ -108,12 +94,12 @@
original_event = Attribute("The ObjectAddedEvent related to this event")
-class UniqueIdAddedEvent:
+class IntIdAddedEvent:
"""The event which gets sent when an object is registered in a
unique id utility.
"""
- implements(IUniqueIdAddedEvent)
+ implements(IIntIdAddedEvent)
def __init__(self, object, event):
self.object = object
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/tests.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/tests.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/intid/tests.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -44,29 +44,30 @@
class ReferenceSetupMixin(object):
"""Registers adapters ILocation->IConnection and IPersistent->IReference"""
def setUp(self):
- from zope.app.uniqueid import connectionOfPersistent
- from zope.app.uniqueid import ReferenceToPersistent
- from zope.app.uniqueid.interfaces import IReference
+ from zope.app.keyreference.persistent import connectionOfPersistent
+ from zope.app.keyreference.persistent import KeyReferenceToPersistent
+ from zope.app.keyreference.interfaces import IKeyReference
self.root = setup.placefulSetUp(site=True)
ztapi.provideAdapter(ILocation, IConnection, connectionOfPersistent)
- ztapi.provideAdapter(IPersistent, IReference, ReferenceToPersistent)
+ ztapi.provideAdapter(IPersistent, IKeyReference,
+ KeyReferenceToPersistent)
def tearDown(self):
setup.placefulTearDown()
-class TestUniqueIdUtility(ReferenceSetupMixin, unittest.TestCase):
+class TestIntIds(ReferenceSetupMixin, unittest.TestCase):
def test_interface(self):
- from zope.app.uniqueid.interfaces import IUniqueIdUtility
- from zope.app.uniqueid import UniqueIdUtility
+ from zope.app.intid.interfaces import IIntIds
+ from zope.app.intid import IntIds
- verifyObject(IUniqueIdUtility, UniqueIdUtility())
+ verifyObject(IIntIds, IntIds())
def test(self):
- from zope.app.uniqueid import UniqueIdUtility
+ from zope.app.intid import IntIds
- u = UniqueIdUtility()
+ u = IntIds()
obj = P()
obj._p_jar = ConnectionStub()
@@ -89,9 +90,9 @@
self.assertRaises(KeyError, u.getId, obj)
def test_len_items(self):
- from zope.app.uniqueid import UniqueIdUtility
- from zope.app.uniqueid import ReferenceToPersistent
- u = UniqueIdUtility()
+ from zope.app.intid import IntIds
+ from zope.app.keyreference.persistent import KeyReferenceToPersistent
+ u = IntIds()
obj = P()
obj._p_jar = ConnectionStub()
@@ -99,7 +100,7 @@
self.assertEquals(u.items(), [])
uid = u.register(obj)
- ref = ReferenceToPersistent(obj)
+ ref = KeyReferenceToPersistent(obj)
self.assertEquals(len(u), 1)
self.assertEquals(u.items(), [(uid, ref)])
@@ -107,7 +108,7 @@
obj2.__parent__ = obj
uid2 = u.register(obj2)
- ref2 = ReferenceToPersistent(obj2)
+ ref2 = KeyReferenceToPersistent(obj2)
self.assertEquals(len(u), 2)
result = u.items()
expected = [(uid, ref), (uid2, ref2)]
@@ -121,9 +122,9 @@
self.assertEquals(u.items(), [])
def test_getenrateId(self):
- from zope.app.uniqueid import UniqueIdUtility
+ from zope.app.intid import IntIds
- u = UniqueIdUtility()
+ u = IntIds()
self.assertEquals(u._v_nextid, None)
id1 = u._generateId()
self.assert_(u._v_nextid is not None)
@@ -136,73 +137,11 @@
self.assertNotEqual(id3, id1)
-class TestReferenceToPersistent(ReferenceSetupMixin, unittest.TestCase):
-
- def test(self):
- from zope.app.uniqueid.interfaces import IReference
- from zope.app.uniqueid import ReferenceToPersistent
-
- ob = P()
- ob._p_oid = 'x' * 20
- ref = ReferenceToPersistent(ob)
- verifyObject(IReference, ref)
- self.assert_(ref() is ob)
-
- parent = P()
- conn = ConnectionStub()
- parent._p_jar = conn
- ob2 = P()
- ob2.__parent__ = parent
- ref = ReferenceToPersistent(ob2)
- ob = ref()
- self.assert_(ob is ob2)
- self.assertEquals(ob._p_jar, conn)
-
- def test_compare(self):
- from zope.app.uniqueid import ReferenceToPersistent
-
- ob1 = Persistent()
- ob2 = Persistent()
- ob3 = Persistent()
- ob1._p_oid = 'x' * 20
- ob2._p_oid = ob3._p_oid = 'y' * 20
- ref1 = ReferenceToPersistent(ob1)
- ref2 = ReferenceToPersistent(ob2)
- ref3 = ReferenceToPersistent(ob3)
- self.assert_(ref1 < ref2)
- self.assert_(ref2 == ref3)
- self.assertRaises(TypeError, ref1.__cmp__, object())
-
-
-class TestConnectionOfPersistent(unittest.TestCase):
-
- def test(self):
- from zope.app.uniqueid import connectionOfPersistent
-
- conn = object()
-
- ob1 = P()
- ob1._p_jar = conn
-
- ob2 = P()
- ob2.__parent__ = ob1
-
- ob3 = P()
-
- self.assertEquals(connectionOfPersistent(ob1), conn)
- self.assertEquals(connectionOfPersistent(ob2), conn)
- self.assertRaises(ValueError, connectionOfPersistent, ob3)
-
- ob3.__parent__ = object()
- self.assertRaises(ValueError, connectionOfPersistent, ob3)
- self.assertRaises(ValueError, connectionOfPersistent, object())
-
-
class TestSubscribers(ReferenceSetupMixin, unittest.TestCase):
def setUp(self):
- from zope.app.uniqueid.interfaces import IUniqueIdUtility
- from zope.app.uniqueid import UniqueIdUtility
+ from zope.app.intid.interfaces import IIntIds
+ from zope.app.intid import IntIds
from zope.app.folder import Folder, rootFolder
ReferenceSetupMixin.setUp(self)
@@ -210,7 +149,7 @@
sm = zapi.getServices(self.root)
setup.addService(sm, Utilities, LocalUtilityService())
self.utility = setup.addUtility(sm, '1',
- IUniqueIdUtility, UniqueIdUtility())
+ IIntIds, IntIds())
self.root['folder1'] = Folder()
self.root._p_jar = ConnectionStub()
@@ -219,13 +158,13 @@
sm1_1 = setup.createServiceManager(self.folder1_1)
setup.addService(sm1_1, Utilities, LocalUtilityService())
- self.utility1 = setup.addUtility(sm1_1, '2', IUniqueIdUtility,
- UniqueIdUtility())
+ self.utility1 = setup.addUtility(sm1_1, '2', IIntIds,
+ IntIds())
- def test_removeUniqueIdSubscriber(self):
- from zope.app.uniqueid import removeUniqueIdSubscriber
+ def test_removeIntIdSubscriber(self):
+ from zope.app.intid import removeIntIdSubscriber
from zope.app.container.contained import ObjectRemovedEvent
- from zope.app.uniqueid.interfaces import IUniqueIdRemovedEvent
+ from zope.app.intid.interfaces import IIntIdRemovedEvent
parent_folder = self.root['folder1']['folder1_1']
folder = self.root['folder1']['folder1_1']['folder1_1_1']
id = self.utility.register(folder)
@@ -235,11 +174,11 @@
setSite(self.folder1_1)
events = []
- ztapi.handle([IUniqueIdRemovedEvent], events.append)
+ ztapi.handle([IIntIdRemovedEvent], events.append)
# This should unregister the object in all utilities, not just the
# nearest one.
- removeUniqueIdSubscriber(folder, ObjectRemovedEvent(parent_folder))
+ removeIntIdSubscriber(folder, ObjectRemovedEvent(parent_folder))
self.assertRaises(KeyError, self.utility.getObject, id)
self.assertRaises(KeyError, self.utility1.getObject, id1)
@@ -248,20 +187,20 @@
self.assertEquals(events[0].object, folder)
self.assertEquals(events[0].original_event.object, parent_folder)
- def test_addUniqueIdSubscriber(self):
- from zope.app.uniqueid import addUniqueIdSubscriber
+ def test_addIntIdSubscriber(self):
+ from zope.app.intid import addIntIdSubscriber
from zope.app.container.contained import ObjectAddedEvent
- from zope.app.uniqueid.interfaces import IUniqueIdAddedEvent
+ from zope.app.intid.interfaces import IIntIdAddedEvent
parent_folder = self.root['folder1']['folder1_1']
folder = self.root['folder1']['folder1_1']['folder1_1_1']
setSite(self.folder1_1)
events = []
- ztapi.handle([IUniqueIdAddedEvent], events.append)
+ ztapi.handle([IIntIdAddedEvent], events.append)
# This should unregister the object in all utilities, not just the
# nearest one.
- addUniqueIdSubscriber(folder, ObjectAddedEvent(parent_folder))
+ addIntIdSubscriber(folder, ObjectAddedEvent(parent_folder))
# Check that the folder got registered
id = self.utility.getId(folder)
@@ -274,9 +213,7 @@
def test_suite():
suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TestUniqueIdUtility))
- suite.addTest(unittest.makeSuite(TestReferenceToPersistent))
- suite.addTest(unittest.makeSuite(TestConnectionOfPersistent))
+ suite.addTest(unittest.makeSuite(TestIntIds))
suite.addTest(unittest.makeSuite(TestSubscribers))
return suite
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/__init__.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/__init__.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/__init__.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -11,168 +11,8 @@
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
-"""Unique id utility.
+"""Key references
-This utility assigns unique integer ids to objects and allows lookups
-by object and by id.
-
-This functionality can be used in cataloging.
-
$Id$
"""
-import random
-from BTrees import IOBTree, OIBTree
-from ZODB.interfaces import IConnection
-from persistent import Persistent
-from zope.event import notify
-from zope.interface import implements
-from zope.security.proxy import removeSecurityProxy
-
-from zope.app.container.contained import Contained
-from zope.app.uniqueid.interfaces import IUniqueIdUtility, IReference
-from zope.app.uniqueid.interfaces import UniqueIdRemovedEvent
-from zope.app.uniqueid.interfaces import UniqueIdAddedEvent
-from zope.app import zapi
-from zope.app.location.interfaces import ILocation
-
-
-
-class UniqueIdUtility(Persistent, Contained):
- """This utility provides a two way mapping between objects and
- integer ids.
-
- IReferences to objects are stored in the indexes.
- """
- implements(IUniqueIdUtility)
-
- _v_nextid = None
-
- def __init__(self):
- self.ids = OIBTree.OIBTree()
- self.refs = IOBTree.IOBTree()
-
- def __len__(self):
- return len(self.ids)
-
- def items(self):
- return list(self.refs.items())
-
- def getObject(self, id):
- return self.refs[id]()
-
- def queryObject(self, id, default=None):
- r = self.refs.get(id)
- if r is not None:
- return r()
- return default
-
- def getId(self, ob):
- ref = IReference(ob)
- return self.ids[ref]
-
- def queryId(self, ob, default=None):
- ref = IReference(ob)
- return self.ids.get(ref, default)
-
- def _generateId(self):
- """Generate an id which is not yet taken.
-
- This tries to allocate sequential ids so they fall into the
- same BTree bucket, and randomizes if it stumbles upon a
- used one.
- """
- while True:
- if self._v_nextid is None:
- self._v_nextid = random.randint(0, 2**31)
- uid = self._v_nextid
- self._v_nextid += 1
- if uid not in self.refs:
- return uid
- self._v_nextid = None
-
- def register(self, ob):
- # Note that we'll still need to keep this proxy removal.
- ob = removeSecurityProxy(ob)
- ref = IReference(ob)
- if ref in self.ids:
- return self.ids[ref]
- uid = self._generateId()
- self.refs[uid] = ref
- self.ids[ref] = uid
- return uid
-
- def unregister(self, ob):
- ref = IReference(ob)
- uid = self.ids[ref]
- del self.refs[uid]
- del self.ids[ref]
-
-
-class ReferenceToPersistent(object):
- """An IReference for persistent object which is comparable.
-
- These references compare by _p_oids of the objects they reference.
- """
- implements(IReference)
-
- def __init__(self, object):
- if not getattr(object, '_p_oid', None):
- IConnection(object).add(object)
- self.object = object
-
- def __call__(self):
- return self.object
-
- def __hash__(self):
- return hash(self.object._p_oid)
-
- def __cmp__(self, other):
- if not isinstance(other, ReferenceToPersistent):
- raise TypeError("Cannot compare ReferenceToPersistent with %r" %
- (other,))
- return cmp(self.object._p_oid, other.object._p_oid)
-
-
-def connectionOfPersistent(ob):
- """An adapter which gets a ZODB connection of a persistent object.
-
- We are assuming the object has a parent if it has been created in
- this transaction.
-
- Raises ValueError if it is impossible to get a connection.
- """
- cur = ob
- while not getattr(cur, '_p_jar', None):
- cur = getattr(cur, '__parent__', None)
- if cur is None:
- raise ValueError('Can not get connection of %r' % (ob,))
- return cur._p_jar
-
-
-def removeUniqueIdSubscriber(ob, event):
- """A subscriber to ObjectRemovedEvent
-
- Removes the unique ids registered for the object in all the unique
- id utilities.
- """
-
- # Notify the catalogs that this object is about to be removed.
- notify(UniqueIdRemovedEvent(ob, event))
-
- for utility in zapi.getAllUtilitiesRegisteredFor(IUniqueIdUtility):
- try:
- utility.unregister(ob)
- except KeyError:
- pass
-
-def addUniqueIdSubscriber(ob, event):
- """A subscriber to ObjectAddedEvent
-
- Registers the object added in all unique id utilities and fires
- an event for the catalogs.
- """
- for utility in zapi.getAllUtilitiesRegisteredFor(IUniqueIdUtility):
- utility.register(ob)
-
- notify(UniqueIdAddedEvent(ob, event))
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/configure.zcml
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/configure.zcml 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/configure.zcml 2004-11-30 00:21:14 UTC (rev 28537)
@@ -2,59 +2,19 @@
<adapter
for="persistent.interfaces.IPersistent"
- provides=".interfaces.IReference"
- factory=".ReferenceToPersistent"
+ provides=".interfaces.IKeyReference"
+ factory=".persistent.KeyReferenceToPersistent"
trusted="y"
/>
- <class class=".ReferenceToPersistent">
- <require permission="zope.Public" interface=".interfaces.IReference" />
+ <class class=".persistent.KeyReferenceToPersistent">
+ <require permission="zope.Public" interface=".interfaces.IKeyReference" />
</class>
<adapter
for="persistent.interfaces.IPersistent"
provides="ZODB.interfaces.IConnection"
- factory="zope.app.uniqueid.connectionOfPersistent"
+ factory=".persistent.connectionOfPersistent"
/>
- <localUtility class=".UniqueIdUtility">
- <factory
- id="zope.app.uniqueid.UniqueIdUtility"
- />
-
- <implements
- interface="zope.app.annotation.interfaces.IAttributeAnnotatable"
- />
-
- <require
- permission="zope.Public"
- interface=".interfaces.IUniqueIdUtilityQuery"
- />
-
- <require
- permission="zope.ManageContent"
- interface=".interfaces.IUniqueIdUtilitySet"
- />
- <require
- permission="zope.Public"
- interface=".interfaces.IUniqueIdUtilityManage"
- />
-
- </localUtility>
-
- <subscriber
- factory=".removeUniqueIdSubscriber"
- for="zope.app.location.interfaces.ILocation
- zope.app.container.interfaces.IObjectRemovedEvent"
- />
-
- <subscriber
- factory=".addUniqueIdSubscriber"
- for="zope.app.location.interfaces.ILocation
- zope.app.container.interfaces.IObjectAddedEvent"
- />
-
- <!-- Views -->
- <include package=".browser" />
-
</configure>
Deleted: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/ftests.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/ftests.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/ftests.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -1,89 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Functional tests for the unique id utility.
-
-$Id$
-"""
-
-import unittest
-import re
-from transaction import commit
-
-from zope.app import zapi
-from zope.app.tests import ztapi
-from zope.app.tests.setup import addUtility
-from zope.app.tests.functional import BrowserTestCase
-
-
-class TestUniqueIdUtility(BrowserTestCase):
-
- def setUp(self):
- from zope.app.uniqueid import UniqueIdUtility
- from zope.app.uniqueid.interfaces import IUniqueIdUtility
-
- BrowserTestCase.setUp(self)
-
- self.basepath = '/++etc++site/default'
- root = self.getRootFolder()
-
- sm = zapi.traverse(root, '/++etc++site')
- addUtility(sm, 'uniqueid', IUniqueIdUtility, UniqueIdUtility())
- commit()
-
- type_name = 'BrowserAdd__zope.app.uniqueid.UniqueIdUtility'
-
- response = self.publish(
- self.basepath + '/contents.html',
- basic='mgr:mgrpw',
- form={'type_name': type_name,
- 'new_value': 'mgr' })
-
-# root = self.getRootFolder()
-# default = zapi.traverse(root, '/++etc++site/default')
-# rm = default.getRegistrationManager()
-# registration = UtilityRegistration(
-# 'cwm', IUniqueIdUtility, self.basepath+'/uniqueid')
-# pd_id = rm.addRegistration(registration)
-# zapi.traverse(rm, pd_id).status = ActiveStatus
-
- def test(self):
- response = self.publish(self.basepath + '/uniqueid/@@index.html',
- basic='mgr:mgrpw')
- self.assertEquals(response.getStatus(), 200)
- # The utility registers in itself when it is being added
- self.assert_(response.getBody().find('1 objects') > 0)
- self.assert_('<a href="/++etc++site">/++etc++site</a>'
- not in response.getBody())
-
- response = self.publish(self.basepath + '/uniqueid/@@populate',
- basic='mgr:mgrpw')
- self.assertEquals(response.getStatus(), 302)
-
- response = self.publish(self.basepath + '/uniqueid/@@index.html',
- basic='mgr:mgrpw')
- self.assertEquals(response.getStatus(), 200)
- body = response.getBody()
- self.assert_('3 objects' in body)
- self.assert_('<a href="/++etc++site">/++etc++site</a>' in body)
- self.checkForBrokenLinks(body, response.getPath(), basic='mgr:mgrpw')
-
-
-def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TestUniqueIdUtility))
- return suite
-
-
-if __name__ == '__main__':
- unittest.main()
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/interfaces.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/interfaces.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/interfaces.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -1,120 +1,36 @@
-"""
-Interfaces for the unique id utility.
+##############################################################################
+#
+# Copyright (c) 2004 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Key-reference interfaces
$Id$
"""
-from zope.interface import Interface, Attribute, implements
+import zope.interface
-
-class IReference(Interface):
+class IKeyReference(zope.interface.Interface):
"""A reference to an object (similar to a weak reference).
The references are compared by their hashes.
"""
def __call__():
- """Get the object this reference is linking to."""
+ """Get the object this reference is linking to.
+ """
def __hash__():
- """Get a unique identifier of the referenced object."""
-
-
-class IUniqueIdUtilityQuery(Interface):
-
- def getObject(uid):
- """Return an object by its unique id"""
-
- def getId(ob):
- """Get a unique id of an object.
+ """Get a unique identifier of the referenced object.
"""
- def queryObject(uid, default=None):
- """Return an object by its unique id
-
- Return the default if the uid isn't registered
+ def __cmp__(ref):
+ """Compare the reference to another reference.
"""
-
- def queryId(ob, default=None):
- """Get a unique id of an object.
-
- Return the default if the object isn't registered
- """
-
-class IUniqueIdUtilitySet(Interface):
-
- def register(ob):
- """Register an object and returns a unique id generated for it.
-
- If the object is already registered, its id is returned anyway.
- """
-
- def unregister(ob):
- """Remove the object from the indexes.
-
- ValueError is raised if ob is not registered previously.
- """
-
-class IUniqueIdUtilityManage(Interface):
- """Some methods used by the view."""
-
- def __len__():
- """Return the number of objects indexed."""
-
- def items():
- """Return a list of (id, object) pairs."""
-
-
-class IUniqueIdUtility(IUniqueIdUtilitySet, IUniqueIdUtilityQuery,
- IUniqueIdUtilityManage):
- """A utility that assigns unique ids to objects.
-
- Allows to query object by id and id by object.
- """
-
-
-class IUniqueIdRemovedEvent(Interface):
- """A unique id will be removed
-
- The event is published before the unique id is removed
- from the utility so that the indexing objects can unindex the object.
- """
-
- object = Attribute("The object being removed")
-
- original_event = Attribute("The IObjectRemoveEvent related to this event")
-
-
-class UniqueIdRemovedEvent:
- """The event which is published before the unique id is removed
- from the utility so that the catalogs can unindex the object.
- """
-
- implements(IUniqueIdRemovedEvent)
-
- def __init__(self, object, event):
- self.object = object
- self.original_event = event
-
-
-class IUniqueIdAddedEvent(Interface):
- """A unique id has been added
-
- The event gets sent when an object is registered in a
- unique id utility.
- """
-
- object = Attribute("The object being added")
-
- original_event = Attribute("The ObjectAddedEvent related to this event")
-
-
-class UniqueIdAddedEvent:
- """The event which gets sent when an object is registered in a
- unique id utility.
- """
-
- implements(IUniqueIdAddedEvent)
-
- def __init__(self, object, event):
- self.object = object
- self.original_event = event
Copied: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.py (from rev 28536, Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/__init__.py)
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/__init__.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -0,0 +1,67 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Unique id utility.
+
+This utility assigns unique integer ids to objects and allows lookups
+by object and by id.
+
+This functionality can be used in cataloging.
+
+$Id$
+"""
+from ZODB.interfaces import IConnection
+import zope.interface
+
+import zope.app.keyreference.interfaces
+
+class KeyReferenceToPersistent(object):
+ """An IReference for persistent object which is comparable.
+
+ These references compare by _p_oids of the objects they reference.
+ """
+ zope.interface.implements(zope.app.keyreference.interfaces.IKeyReference)
+
+ def __init__(self, object):
+ if not getattr(object, '_p_oid', None):
+ IConnection(object).add(object)
+ self.object = object
+
+ def __call__(self):
+ return self.object
+
+ def __hash__(self):
+ return hash(self.object._p_oid)
+
+ def __cmp__(self, other):
+ if not isinstance(other, KeyReferenceToPersistent):
+ raise TypeError("Cannot compare ReferenceToPersistent with %r" %
+ (other,))
+ return cmp(self.object._p_oid, other.object._p_oid)
+
+
+def connectionOfPersistent(ob):
+ """An adapter which gets a ZODB connection of a persistent object.
+
+ We are assuming the object has a parent if it has been created in
+ this transaction.
+
+ Raises ValueError if it is impossible to get a connection.
+ """
+ cur = ob
+ while not getattr(cur, '_p_jar', None):
+ cur = getattr(cur, '__parent__', None)
+ if cur is None:
+ raise ValueError('Can not get connection of %r' % (ob,))
+ return cur._p_jar
+
Added: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.txt
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.txt 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.txt 2004-11-30 00:21:14 UTC (rev 28537)
@@ -0,0 +1,123 @@
+Key References for Persistent Objects
+=====================================
+
+`zope.keyreference.persistent.KeyReferenceToPersistent` provides an
+`zope.app.keyreference.interfaces.IReference` reference for persistent
+objects.
+
+Let's look at an example. First, we'll create some persistent objects
+in a database:
+
+ >>> from ZODB.tests.util import DB
+ >>> import transaction
+ >>> from persistent.dict import PersistentDict
+
+ >>> db = DB()
+ >>> conn = db.open()
+ >>> root = conn.root()
+
+ >>> root['ob1'] = PersistentDict()
+ >>> root['ob2'] = PersistentDict()
+
+ >>> transaction.commit()
+
+Then we'll create some key references:
+
+ >>> from zope.app.keyreference.persistent import KeyReferenceToPersistent
+
+ >>> key1 = KeyReferenceToPersistent(root['ob1'])
+ >>> key2 = KeyReferenceToPersistent(root['ob2'])
+
+We can call the keys to get the objects:
+
+ >>> key1() is root['ob1'], key1() is root['ob1']
+ (True, True)
+
+New keys to the same objects are equal to the old:
+
+ >>> KeyReferenceToPersistent(root['ob1']) == key1
+ True
+
+and have the same hashes:
+
+ >>> hash(KeyReferenceToPersistent(root['ob1'])) == hash(key1)
+ True
+
+We'll store the key references in the database:
+
+ >>> root['key1'] = key1
+ >>> root['key2'] = key2
+
+and use the keys to store the objects again:
+
+ >>> root[key1] = root['ob1']
+ >>> root[key2] = root['ob2']
+
+ >>> transaction.commit()
+
+Now we'll open another connection:
+
+ >>> conn2 = db.open()
+
+And verify that we can use the keys to look up the objects:
+
+ >>> root2 = conn2.root()
+ >>> key1 = root2['key1']
+ >>> root2[key1] is root2['ob1']
+ True
+ >>> key2 = root2['key2']
+ >>> root2[key2] is root2['ob2']
+ True
+
+and that we can also call the keys to get the objects:
+
+ >>> key1() is root2['ob1']
+ True
+ >>> key2() is root2['ob2']
+ True
+
+We can't get the key reference for an object that hasn't been saved
+yet:
+
+ >>> KeyReferenceToPersistent(PersistentDict())
+ ... # doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ TypeError: ('Could not adapt', ...
+
+We can get references to unsaved objects if they have an adapter to
+`ZODB.interfaces.IConnection`. The `add` method on the connection
+will be used to give the object an object id, which is enough
+information to compute the reference. To see this, we'll create an
+object that conforms to `IConnection` in a silly way:
+
+ >>> import persistent
+ >>> from ZODB.interfaces import IConnection
+ >>> class C(persistent.Persistent):
+ ... def __conform__(self, iface):
+ ... if iface is IConnection:
+ ... return conn2
+
+ >>> ob3 = C()
+ >>> key3 = KeyReferenceToPersistent(ob3)
+ >>> transaction.abort()
+
+
+Location-based connection adapter
+---------------------------------
+
+The function `zope.app.keyreference.connectionOfPersistent` adapts
+objects to connections using a simple location-based heuristic. It
+checked to see if the object has a `__parent__` that has a connection:
+
+ >>> from zope.app.keyreference.persistent import connectionOfPersistent
+ >>> ob3 = PersistentDict()
+ >>> connectionOfPersistent(ob3)
+ ... # doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ ValueError: Can not get connection of ...
+
+ >>> ob3.__parent__ = root2['ob1']
+ >>> connectionOfPersistent(ob3) is conn2
+ True
Property changes on: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/persistent.txt
___________________________________________________________________
Name: svn:eol-style
+ native
Modified: Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/tests.py
===================================================================
--- Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/tests.py 2004-11-29 22:38:41 UTC (rev 28536)
+++ Zope3/branches/jim-uniqueid-restructure/src/zope/app/keyreference/tests.py 2004-11-30 00:21:14 UTC (rev 28537)
@@ -16,269 +16,13 @@
$Id$
"""
import unittest
-from zope.interface.verify import verifyObject
-from persistent import Persistent
-from persistent.interfaces import IPersistent
-from zope.app.tests import setup, ztapi
-from zope.app import zapi
-from zope.interface import implements
-from ZODB.interfaces import IConnection
-from zope.app.location.interfaces import ILocation
-from zope.app.component.hooks import setSite
-from zope.app.utility import LocalUtilityService
-from zope.app.servicenames import Utilities
-
-class P(Persistent):
- implements(ILocation)
-
-
-class ConnectionStub(object):
- next = 1
- def add(self, ob):
- ob._p_jar = self
- ob._p_oid = self.next
- self.next += 1
-
-
-class ReferenceSetupMixin(object):
- """Registers adapters ILocation->IConnection and IPersistent->IReference"""
- def setUp(self):
- from zope.app.uniqueid import connectionOfPersistent
- from zope.app.uniqueid import ReferenceToPersistent
- from zope.app.uniqueid.interfaces import IReference
- self.root = setup.placefulSetUp(site=True)
- ztapi.provideAdapter(ILocation, IConnection, connectionOfPersistent)
- ztapi.provideAdapter(IPersistent, IReference, ReferenceToPersistent)
-
- def tearDown(self):
- setup.placefulTearDown()
-
-
-class TestUniqueIdUtility(ReferenceSetupMixin, unittest.TestCase):
-
- def test_interface(self):
- from zope.app.uniqueid.interfaces import IUniqueIdUtility
- from zope.app.uniqueid import UniqueIdUtility
-
- verifyObject(IUniqueIdUtility, UniqueIdUtility())
-
- def test(self):
- from zope.app.uniqueid import UniqueIdUtility
-
- u = UniqueIdUtility()
- obj = P()
- obj._p_jar = ConnectionStub()
-
- self.assert_(u.queryId(obj) is None)
- self.assert_(u.queryId(obj, 42) is 42)
- self.assert_(u.queryObject(42) is None)
- self.assert_(u.queryObject(42, obj) is obj)
-
- uid = u.register(obj)
- self.assert_(u.getObject(uid) is obj)
- self.assert_(u.queryObject(uid) is obj)
- self.assertEquals(u.getId(obj), uid)
- self.assertEquals(u.queryId(obj), uid)
-
- uid2 = u.register(obj)
- self.assertEquals(uid, uid2)
-
- u.unregister(obj)
- self.assertRaises(KeyError, u.getObject, uid)
- self.assertRaises(KeyError, u.getId, obj)
-
- def test_len_items(self):
- from zope.app.uniqueid import UniqueIdUtility
- from zope.app.uniqueid import ReferenceToPersistent
- u = UniqueIdUtility()
- obj = P()
- obj._p_jar = ConnectionStub()
-
- self.assertEquals(len(u), 0)
- self.assertEquals(u.items(), [])
-
- uid = u.register(obj)
- ref = ReferenceToPersistent(obj)
- self.assertEquals(len(u), 1)
- self.assertEquals(u.items(), [(uid, ref)])
-
- obj2 = P()
- obj2.__parent__ = obj
-
- uid2 = u.register(obj2)
- ref2 = ReferenceToPersistent(obj2)
- self.assertEquals(len(u), 2)
- result = u.items()
- expected = [(uid, ref), (uid2, ref2)]
- result.sort()
- expected.sort()
- self.assertEquals(result, expected)
-
- u.unregister(obj)
- u.unregister(obj2)
- self.assertEquals(len(u), 0)
- self.assertEquals(u.items(), [])
-
- def test_getenrateId(self):
- from zope.app.uniqueid import UniqueIdUtility
-
- u = UniqueIdUtility()
- self.assertEquals(u._v_nextid, None)
- id1 = u._generateId()
- self.assert_(u._v_nextid is not None)
- id2 = u._generateId()
- self.assert_(id1 + 1, id2)
- u.refs[id2 + 1] = "Taken"
- id3 = u._generateId()
- self.assertNotEqual(id3, id2 + 1)
- self.assertNotEqual(id3, id2)
- self.assertNotEqual(id3, id1)
-
-
-class TestReferenceToPersistent(ReferenceSetupMixin, unittest.TestCase):
-
- def test(self):
- from zope.app.uniqueid.interfaces import IReference
- from zope.app.uniqueid import ReferenceToPersistent
-
- ob = P()
- ob._p_oid = 'x' * 20
- ref = ReferenceToPersistent(ob)
- verifyObject(IReference, ref)
- self.assert_(ref() is ob)
-
- parent = P()
- conn = ConnectionStub()
- parent._p_jar = conn
- ob2 = P()
- ob2.__parent__ = parent
- ref = ReferenceToPersistent(ob2)
- ob = ref()
- self.assert_(ob is ob2)
- self.assertEquals(ob._p_jar, conn)
-
- def test_compare(self):
- from zope.app.uniqueid import ReferenceToPersistent
-
- ob1 = Persistent()
- ob2 = Persistent()
- ob3 = Persistent()
- ob1._p_oid = 'x' * 20
- ob2._p_oid = ob3._p_oid = 'y' * 20
- ref1 = ReferenceToPersistent(ob1)
- ref2 = ReferenceToPersistent(ob2)
- ref3 = ReferenceToPersistent(ob3)
- self.assert_(ref1 < ref2)
- self.assert_(ref2 == ref3)
- self.assertRaises(TypeError, ref1.__cmp__, object())
-
-
-class TestConnectionOfPersistent(unittest.TestCase):
-
- def test(self):
- from zope.app.uniqueid import connectionOfPersistent
-
- conn = object()
-
- ob1 = P()
- ob1._p_jar = conn
-
- ob2 = P()
- ob2.__parent__ = ob1
-
- ob3 = P()
-
- self.assertEquals(connectionOfPersistent(ob1), conn)
- self.assertEquals(connectionOfPersistent(ob2), conn)
- self.assertRaises(ValueError, connectionOfPersistent, ob3)
-
- ob3.__parent__ = object()
- self.assertRaises(ValueError, connectionOfPersistent, ob3)
- self.assertRaises(ValueError, connectionOfPersistent, object())
-
-
-class TestSubscribers(ReferenceSetupMixin, unittest.TestCase):
-
- def setUp(self):
- from zope.app.uniqueid.interfaces import IUniqueIdUtility
- from zope.app.uniqueid import UniqueIdUtility
- from zope.app.folder import Folder, rootFolder
-
- ReferenceSetupMixin.setUp(self)
-
- sm = zapi.getServices(self.root)
- setup.addService(sm, Utilities, LocalUtilityService())
- self.utility = setup.addUtility(sm, '1',
- IUniqueIdUtility, UniqueIdUtility())
-
- self.root['folder1'] = Folder()
- self.root._p_jar = ConnectionStub()
- self.root['folder1']['folder1_1'] = self.folder1_1 = Folder()
- self.root['folder1']['folder1_1']['folder1_1_1'] = Folder()
-
- sm1_1 = setup.createServiceManager(self.folder1_1)
- setup.addService(sm1_1, Utilities, LocalUtilityService())
- self.utility1 = setup.addUtility(sm1_1, '2', IUniqueIdUtility,
- UniqueIdUtility())
-
- def test_removeUniqueIdSubscriber(self):
- from zope.app.uniqueid import removeUniqueIdSubscriber
- from zope.app.container.contained import ObjectRemovedEvent
- from zope.app.uniqueid.interfaces import IUniqueIdRemovedEvent
- parent_folder = self.root['folder1']['folder1_1']
- folder = self.root['folder1']['folder1_1']['folder1_1_1']
- id = self.utility.register(folder)
- id1 = self.utility1.register(folder)
- self.assertEquals(self.utility.getObject(id), folder)
- self.assertEquals(self.utility1.getObject(id1), folder)
- setSite(self.folder1_1)
-
- events = []
- ztapi.handle([IUniqueIdRemovedEvent], events.append)
-
- # This should unregister the object in all utilities, not just the
- # nearest one.
- removeUniqueIdSubscriber(folder, ObjectRemovedEvent(parent_folder))
-
- self.assertRaises(KeyError, self.utility.getObject, id)
- self.assertRaises(KeyError, self.utility1.getObject, id1)
-
- self.assertEquals(len(events), 1)
- self.assertEquals(events[0].object, folder)
- self.assertEquals(events[0].original_event.object, parent_folder)
-
- def test_addUniqueIdSubscriber(self):
- from zope.app.uniqueid import addUniqueIdSubscriber
- from zope.app.container.contained import ObjectAddedEvent
- from zope.app.uniqueid.interfaces import IUniqueIdAddedEvent
- parent_folder = self.root['folder1']['folder1_1']
- folder = self.root['folder1']['folder1_1']['folder1_1_1']
- setSite(self.folder1_1)
-
- events = []
- ztapi.handle([IUniqueIdAddedEvent], events.append)
-
- # This should unregister the object in all utilities, not just the
- # nearest one.
- addUniqueIdSubscriber(folder, ObjectAddedEvent(parent_folder))
-
- # Check that the folder got registered
- id = self.utility.getId(folder)
- id1 = self.utility1.getId(folder)
-
- self.assertEquals(len(events), 1)
- self.assertEquals(events[0].original_event.object, parent_folder)
- self.assertEquals(events[0].object, folder)
-
-
def test_suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TestUniqueIdUtility))
- suite.addTest(unittest.makeSuite(TestReferenceToPersistent))
- suite.addTest(unittest.makeSuite(TestConnectionOfPersistent))
- suite.addTest(unittest.makeSuite(TestSubscribers))
- return suite
+ from zope.testing import doctest
+ return unittest.TestSuite((
+ doctest.DocFileSuite('persistent.txt'),
+ ))
if __name__ == '__main__':
- unittest.main()
+ unittest.main(defaultTest='test_suite')
+
More information about the Zope3-Checkins
mailing list