def _getContext(): global _context if _context is None: _clearContext() from zope.testing.cleanup import addCleanUp addCleanUp(_clearContext) return _context
def _getContext(): global _context if _context is None: _clearContext() try: from zope.testing.cleanup import addCleanUp except ImportError: #pragma NO COVER pass else: #pragma NO COVER addCleanUp(_clearContext) del addCleanUp return _context
def doMonkies(): """Monkey patch various methods to provide container events. """ global hasContainerEvents hasContainerEvents = True patchMethod(ObjectManager, '_setObject', _setObject) patchMethod(ObjectManager, '_delObject', _delObject) patchMethod(ObjectManager, 'manage_afterAdd', manage_afterAdd) patchMethod(ObjectManager, 'manage_beforeDelete', manage_beforeDelete) patchMethod(ObjectManager, 'manage_afterClone', manage_afterClone) patchMethod(Item, 'manage_afterAdd', manage_afterAdd) patchMethod(Item, 'manage_beforeDelete', manage_beforeDelete) patchMethod(Item, 'manage_afterClone', manage_afterClone) patchMethod(BTreeFolder2Base, '_setObject', BT_setObject) patchMethod(BTreeFolder2Base, '_delObject', BT_delObject) patchMethod(CopyContainer, 'manage_renameObject', manage_renameObject) patchMethod(CopyContainer, 'manage_pasteObjects', manage_pasteObjects) patchMethod(CopyContainer, 'manage_clone', manage_clone) patchMethod(OrderSupport, 'moveObjectsByDelta', moveObjectsByDelta) patchMethod(OrderSupport, 'moveObjectToPosition', moveObjectToPosition) patchMethod(OrderSupport, 'manage_renameObject', OS_manage_renameObject) patchMethod(AppInitializer, 'install_errorlog', install_errorlog) patchMethod(AppInitializer, 'install_browser_id_manager', install_browser_id_manager) patchMethod(AppInitializer, 'install_session_data_manager', install_session_data_manager) patchMethod(CatalogAwareness.CatalogAware, 'manage_afterAdd', CA_manage_afterAdd) patchMethod(CatalogAwareness.CatalogAware, 'manage_beforeDelete', CA_manage_beforeDelete) patchMethod(CatalogAwareness.CatalogAware, 'manage_afterClone', CA_manage_afterClone) patchMethod(CatalogPathAwareness.CatalogAware, 'manage_afterAdd', CA_manage_afterAdd) patchMethod(CatalogPathAwareness.CatalogAware, 'manage_beforeDelete', CA_manage_beforeDelete) patchMethod(CatalogPathAwareness.CatalogAware, 'manage_afterClone', CA_manage_afterClone) zcml.load_config('event.zcml', Products.Five, execute=False) addCleanUp(undoMonkies)
warnings.warn( "The type %r has __ext_ignore_updateFromExternalObject__=True. " "Please remove updateFromExternalObject from the type." % (kind, ), FutureWarning) _usable_updateFromExternalObject_cache[kind] = usable_from return usable_from try: from zope.testing import cleanup # pylint:disable=ungrouped-imports except ImportError: # pragma: no cover pass else: cleanup.addCleanUp(_argspec_cache.clear) cleanup.addCleanUp(_usable_updateFromExternalObject_cache.clear) class DefaultInternalObjectFactoryFinder(object): def find_factory_for_named_value(self, name, value): # pylint:disable=unused-argument return find_factory_for(value) interface.classImplements(DefaultInternalObjectFactoryFinder, INamedExternalizedObjectFactoryFinder) _default_factory_finder = DefaultInternalObjectFactoryFinder() def update_from_external_object(containedObject,
__all__ = [ 'register_legacy_search_module', ] #: .. deprecated:: 1.0 #: This is legacy functionality, please do not access directly. #: The public interface is through :func:`register_legacy_search_module` LEGACY_FACTORY_SEARCH_MODULES = set() try: from zope.testing.cleanup import addCleanUp # pylint: disable=ungrouped-imports except ImportError: # pragma: no cover pass else: addCleanUp(LEGACY_FACTORY_SEARCH_MODULES.clear) def register_legacy_search_module(module_name): """ The legacy creation search routines will use the modules registered by this method. Note that there are no order guarantees about how the modules will be searched. Duplicate class names are thus undefined. :param module_name: Either the name of a module to look for at runtime in :data:`sys.modules`, or a module-like object having a ``__dict__``.
def removePatches(): """Remove all monkey patches. """ from App.FactoryDispatcher import FactoryDispatcher, ProductDispatcher from App import Extensions from Products.ExternalMethod import ExternalMethod if isMonkeyPatched(ProductDispatcher.__bobo_traverse__): ProductDispatcher.__bobo_traverse__ = _original__bobo_traverse__ if isMonkeyPatched(Extensions.getPath): Extensions.getPath = _originalGetPath ExternalMethod.getPath = _originalGetPath cleanup.addCleanUp(removePatches) # BEGIN MONKEY PATCHES # Most of these monkey patches were repurposed from the code I # wrote for Basket - Rocky def product_packages(): """Returns all product packages including the regularly defined zope2 packages and those without the Products namespace package. """ old_product_packages = {} for x in dir(Products): m = getattr(Products, x) if isinstance(m, types.ModuleType): old_product_packages[x] = m
server = start_server(app, url) WSGI_SERVERS[name] = {'url': url, 'server': server} return server def stopWSGIServer(name): """Stop WSGI server by given name reference""" global WSGI_SERVERS if WSGI_SERVERS is not None: server = WSGI_SERVERS[name]['server'] server.quit() server.join(1) del WSGI_SERVERS[name] def getWSGIApplication(name): """Returns the application refenced by name""" global WSGI_SERVERS if WSGI_SERVERS is not None: server = WSGI_SERVERS[name]['server'] return server.app def stopServers(): global WSGI_SERVERS if WSGI_SERVERS is not None: names = list(WSGI_SERVERS.keys()) for n in names: stopWSGIServer(n) cleanup.addCleanUp(stopServers)
setattr(class_, name, original) if attr is not None: try: delattr(class_, attr) except (AttributeError, KeyError): pass def unregisterClass(class_): delattr(class_, 'meta_type') try: delattr(class_, 'icon') except AttributeError: pass def cleanUp(): global _register_monkies for class_ in _register_monkies: unregisterClass(class_) _register_monkies = [] global _meta_type_regs Products.meta_types = tuple([ info for info in Products.meta_types if info['name'] not in _meta_type_regs ]) _meta_type_regs = [] from zope.testing.cleanup import addCleanUp addCleanUp(cleanUp) del addCleanUp
already = getattr(class_, '_localsite_marker', False) if site_class is not None and not already: class_._localsite_marker = True _context.action( discriminator = (class_,), callable = classSiteHook, args=(class_, site_class) ) if not IPossibleSite.implementedBy(class_): _context.action( discriminator = (class_, IPossibleSite), callable = classImplements, args=(class_, IPossibleSite) ) # clean up code def uninstallSiteHooks(): for class_ in _localsite_monkies: _localsite_monkies.remove(class_) delattr(class_, 'getSiteManager') delattr(class_, 'setSiteManager') classImplementsOnly(class_, implementedBy(class_)-IPossibleSite) if getattr(class_, '_localsite_marker', False): delattr(class_, '_localsite_marker') from zope.testing.cleanup import addCleanUp addCleanUp(uninstallSiteHooks) del addCleanUp
such as authenticated principals. If it is None, the current interaction is used. :return: A boolean value. ``checkPermission`` is guaranteed to return ``True`` if *permission* is :data:`zope.security.checker.CheckerPublic` or ``None``. :raise NoInteraction: If there is no current interaction and no interaction argument was given. """ if permission is CheckerPublic or permission is None: return True if interaction is None: try: interaction = thread_local.interaction except AttributeError: raise NoInteraction return interaction.checkPermission(permission, object) def _clear(): global _defaultPolicy _defaultPolicy = ParanoidSecurityPolicy try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(_clear) addCleanUp(endInteraction)
return self._stylesheet_info[source][name] except KeyError: return None def listStylesheetNames(self): names = [] for k, v in self._stylesheet_info.items(): for name in v.keys(): names.append("%s:%s" % (k, name)) return tuple(names) stylesheet_registry = StylesheetRegistry() # Test cleanup support from zope.testing.cleanup import addCleanUp addCleanUp(stylesheet_registry.clear) del addCleanUp class IStylesheetDirective(Interface): """ Register XSLT file with the global registry. """ source = TextLine( title=u"Source", description=u"The source of XML data.", required=True ) from_ = TextLine( title=u"From", description=u"Value which describes XML data before transformation.",
def _make_registry(self): return PersistentComponents() def _new_Subscription(self, **kwargs): return PersistentSubscription(**kwargs) # The name string must match the variable name to pickle correctly global_subscription_manager = GlobalWebhookSubscriptionManager( 'global_subscription_manager') def getGlobalSubscriptionManager(): return global_subscription_manager def resetGlobals(): global_subscription_manager.__dict__.clear() global_subscription_manager.__init__('global_subscription_manager') global_subscription_registry.__init__('global_subscription_registry') try: from zope.testing.cleanup import addCleanUp # pylint:disable=ungrouped-imports except ImportError: # pragma: no cover pass else: addCleanUp(resetGlobals) del addCleanUp
def getRequest(): try: i = zope.security.management.getInteraction() # raises NoInteraction except zope.security.interfaces.NoInteraction: return for p in i.participations: if IRequest.providedBy(p): return p def need(library_name): request = getRequest() # only take note of needed libraries if there is a request, and it is # capable of handling resource librarys if request is not None and hasattr(request, 'resource_libraries'): if not library_name in request.resource_libraries: request.resource_libraries.append(library_name) def getRequired(name): return library_info[name].required def getIncluded(name): return library_info[name].included try: from zope.testing import cleanup except ImportError: # pragma: no cover pass else: cleanup.addCleanUp(library_info.clear)
self.delCell(role_id, principal_id) def getPrincipalsForRole(self, role_id): ''' See the interface IPrincipalRoleMap ''' return self.getRow(role_id) def getRolesForPrincipal(self, principal_id): ''' See the interface IPrincipalRoleMap ''' return self.getCol(principal_id) def getSetting(self, role_id, principal_id, default=Unset): ''' See the interface IPrincipalRoleMap ''' return self.queryCell(role_id, principal_id, default) def getPrincipalsAndRoles(self): ''' See the interface IPrincipalRoleMap ''' return self.getAllCells() # Roles are our rows, and principals are our columns principalRoleManager = PrincipalRoleManager() # Register our cleanup with Testing.CleanUp to make writing unit tests # simpler. try: from zope.testing.cleanup import addCleanUp except ImportError: pass else: addCleanUp(principalRoleManager._clear) del addCleanUp
def unpatch_zc_resourcelibrary(): global _hooks if _hooks is not None: zc.resourcelibrary.getRequired = _hooks['getRequired'] zc.resourcelibrary.getIncluded = _hooks['getIncluded'] _hooks = None try: from zope.testing.cleanup import addCleanUp except ImportError: pass else: addCleanUp(unpatch_zc_resourcelibrary) del addCleanUp class ResourceLibrary(object): adapts(IBrowserRequest) implements(IResourceLibrary) __name__ = None def __init__(self, request): self.request = request @classmethod def configure(cls): pass
for c in class_.__mro__: if '__call__' in c.__dict__: return True return False def expressiontype(_context, name, handler): _context.action(discriminator=("tales:expressiontype", name), callable=registerType, args=(name, handler)) def registerType(name, handler): Engine.registerType(name, handler) TrustedEngine.registerType(name, handler) def clear(): Engine.__init__() _Engine(Engine) TrustedEngine.__init__() _TrustedEngine(TrustedEngine) try: from zope.testing.cleanup import addCleanUp except ImportError: pass else: addCleanUp(clear)
self.adapters = GlobalAdapterRegistry(self, "adapters") self.utilities = GlobalAdapterRegistry(self, "utilities") def __reduce__(self): # Global site managers are pickled as global objects return self.__name__ base = BaseGlobalComponents("base") try: from zope.testing.cleanup import addCleanUp except ImportError: pass else: addCleanUp(lambda: base.__init__("base")) del addCleanUp globalSiteManager = base def getGlobalSiteManager(): return globalSiteManager # The following APIs provide global registration support for Python code. # We eventually want to deprecate these in favor of using the global # component registry directly. def provideUtility(component, provides=None, name=u""):
def clearThreadSiteSubscriber(event): """A subscriber to EndRequestEvent Cleans up the site thread global after the request is processed. """ clearSite() # Clear the site thread global clearSite = zope.component.hooks.setSite try: from zope.testing.cleanup import addCleanUp except ImportError: pass else: addCleanUp(clearSite) @zope.component.adapter(zope.interface.Interface) @zope.interface.implementer(zope.component.interfaces.IComponentLookup) def SiteManagerAdapter(ob): """An adapter from ILocation to IComponentLookup. The ILocation is interpreted flexibly, we just check for ``__parent__``. """ current = ob while True: if zope.component.interfaces.ISite.providedBy(current): return current.getSiteManager() current = getattr(current, '__parent__', None)
import logging logger = logging.getLogger("zope.server") severity = { 'info': logging.INFO, 'warning': logging.WARN, 'error': logging.ERROR, } def log_info(self, message, type='info'): logger.log(severity.get(type, logging.INFO), message) _orig_log_info = asyncore.dispatcher.log_info def setUp(): asyncore.dispatcher.log_info = log_info setUp() try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(setUp)
self.tasks = [] self.running_tasks = False try: for task in old: task.cancel() finally: self.set_async() def defer(self): pass try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: # Tests are very bad about actually closing # all the channels that they create. This leads to # an ever growing active_channels map. def _clean_active_channels(): for c in list(ServerChannelBase.active_channels.values()): try: c.close() except BaseException: # pragma: no cover pass ServerChannelBase.active_channels.clear() addCleanUp(_clean_active_channels)
as the prefix in actual TALES expressions.""", required=True ) handler = GlobalObject( title=u"Handler", description=u"""Handler is class that implements zope.tales.interfaces.ITALESExpression.""", required=True ) def expressiontype(_context, name, handler): _context.action( discriminator = ("tales:expressiontype", name), callable = registerType, args = (name, handler) ) def registerType(name, handler): Engine.registerType(name, handler) TrustedEngine.registerType(name, handler) def clear(): Engine.__init__() _Engine(Engine) TrustedEngine.__init__() _TrustedEngine(TrustedEngine) addCleanUp(clear)
redirected to the logging module. """ import asyncore import logging logger = logging.getLogger("zope.server") severity = { 'info': logging.INFO, 'warning': logging.WARN, 'error': logging.ERROR, } def log_info(self, message, type='info'): logger.log(severity.get(type, logging.INFO), message) _orig_log_info = asyncore.dispatcher.log_info def setUp(): asyncore.dispatcher.log_info = log_info setUp() try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(setUp)
def _init_registries(self): self.adapters = GlobalAdapterRegistry(self, 'adapters') self.utilities = GlobalAdapterRegistry(self, 'utilities') def __reduce__(self): # Global site managers are pickled as global objects return self.__name__ base = BaseGlobalComponents('base') try: from zope.testing.cleanup import addCleanUp except ImportError: #pragma NO COVER pass else: addCleanUp(lambda: base.__init__('base')) del addCleanUp globalSiteManager = base def getGlobalSiteManager(): return globalSiteManager # The following APIs provide global registration support for Python code. # We eventually want to deprecate these in favor of using the global # component registry directly. def provideUtility(component, provides=None, name=u''): base.registerUtility(component, provides, name, event=False) def provideAdapter(factory, adapts=None, provides=None, name=u''): base.registerAdapter(factory, adapts, provides, name, event=False)
""" if interfaces.ISite.providedBy(event.object): setSite(event.object) def clearThreadSiteSubscriber(event): """A subscriber to EndRequestEvent Cleans up the site thread global after the request is processed. """ clearSite() # Clear the site thread global clearSite = setSite from zope.testing.cleanup import addCleanUp addCleanUp(clearSite) def SiteManagerAdapter(ob): """An adapter from ILocation to ISiteManager. The ILocation is interpreted flexibly, we just check for ``__parent__``. """ current = ob while True: if interfaces.ISite.providedBy(current): return current.getSiteManager() current = getattr(current, '__parent__', None) if current is None: # It is not a location or has no parent, so we return the global
def getSnapshot(): global _snapshot if _snapshot is None: _snapshot = ModulesSnapshot() return _snapshot def restoreModules(): global _snapshot if _snapshot is not None: _snapshot.restore() _snapshot = None cleanup.addCleanUp(restoreModules) def module(module_name): """A decorator to put method or class to the given module.""" snapshot = getSnapshot() if type(module_name) == type(sys): module_name = module_name.__name__ def mock_something(something): name = getattr(something, '__name__', None) snapshot.mock_attr(module_name, name, fake=something) return something return mock_something
""" class IHtmlBodyContentFooterViewletManager(IViewletManager): """ A viewlet that operates within a footer in the main content of the body (after the main content). """ class IHtmlBodyFooterViewletManager(IViewletManager): """ A viewlet that operates after the main body content, near the very end of the html <body> tag. """ def _cleanUp(): PAGEKINDS.clear() PAGEKINDS.update(_build(IPageKind, {}, tx=frozenset)) COMMENTSYSTEMS.clear() COMMENTSYSTEMS.update(_build(ICommentKindAllowed, {}, '__comment_system__')) _cleanUp() try: from zope.testing import cleanup except ImportError: # pragma: no cover pass else: cleanup.addCleanUp(_cleanUp)
from zope.testing import cleanup events = [] def getEvents(event_type=None, filter=None): r = [] for event in events: if event_type is not None and not event_type.providedBy(event): continue if filter is not None and not filter(event): continue r.append(event) return r def clearEvents(): del events[:] cleanup.addCleanUp(clearEvents) class PlacelessSetup: def setUp(self): provideHandler(objectEventNotify) provideHandler(dispatchUtilityRegistrationEvent) provideHandler(dispatchAdapterRegistrationEvent) provideHandler(dispatchSubscriptionAdapterRegistrationEvent) provideHandler(dispatchHandlerRegistrationEvent) provideHandler(events.append, (None,)) def setUp(test=None): PlacelessSetup().setUp()
def register_directory(module_info): return file_template_registry.register_directory(module_info) def _clear(): """Remove the registries (for use by tests).""" inline_template_registry.clear() file_template_registry.clear() try: from zope.testing.cleanup import addCleanUp except ImportError: # don't have that part of Zope pass else: addCleanUp(_clear) del addCleanUp def lookup(module_info, template_name, mark_as_associated=False): try: return file_template_registry.lookup( module_info, template_name, mark_as_associated) except TemplateLookupError as e: try: return inline_template_registry.lookup( module_info, template_name, mark_as_associated) except TemplateLookupError: # re-raise first error again raise e
def _clear(self): self.__init__() self.__defaultid = None self.__defaultObject = None principalRegistry = PrincipalRegistry() # Register our cleanup with Testing.CleanUp to make writing unit tests # simpler. try: from zope.testing.cleanup import addCleanUp except ImportError: pass else: addCleanUp(principalRegistry._clear) del addCleanUp class PrincipalBase(object): __name__ = __parent__ = None def __init__(self, id, title, description): self.id = id self.title = title self.description = description self.groups = [] class Group(PrincipalBase): def getLogin(self):
_upgrade_registry.clear() def cleanUpImportSteps(): global _import_step_regs for name in _import_step_regs: try: _import_step_registry.unregisterStep(name) except KeyError: pass _import_step_regs = [] def cleanUpExportSteps(): global _export_step_regs for name in _export_step_regs: try: _export_step_registry.unregisterStep(name) except KeyError: pass _export_step_regs = [] from zope.testing.cleanup import addCleanUp addCleanUp(cleanUpProfiles) addCleanUp(cleanUpImportSteps) addCleanUp(cleanUpExportSteps) del addCleanUp
self._hook_register_transaction_event() def tpc_abort(self, txn): if self._store._tpc: try: self._store.rollback() finally: self._hook_register_transaction_event() def sortKey(self): # Stores in TPC mode should be the last to be committed, this makes # it possible to have TPC behavior when there's only a single store # not in TPC mode. if self._store._tpc: prefix = "zz" else: prefix = "aa" return "%s_store_%d" % (prefix, id(self)) global_zstorm = ZStorm() try: from zope.testing.cleanup import addCleanUp except ImportError: # We don't have zope.testing installed. pass else: addCleanUp(global_zstorm._reset) del addCleanUp
pass events = [] def getEvents(event_type=None, filter=None): r = [] for event in events: if event_type is not None and not event_type.providedBy(event): continue if filter is not None and not filter(event): continue r.append(event) return r def clearEvents(): del events[:] addCleanUp(clearEvents) class PlacelessSetup: def setUp(self): provideHandler(objectEventNotify) provideHandler(dispatchUtilityRegistrationEvent) provideHandler(dispatchAdapterRegistrationEvent) provideHandler(dispatchSubscriptionAdapterRegistrationEvent) provideHandler(dispatchHandlerRegistrationEvent) provideHandler(events.append, (None,)) def setUp(test=None): PlacelessSetup().setUp()
return siteinfo.adapter_hook(interface, object, name, default) except ComponentLookupError: return default def setHooks(): from zope.component import _api _api.adapter_hook.sethook(adapter_hook) _api.getSiteManager.sethook(getSiteManager) def resetHooks(): # Reset hookable functions to original implementation. from zope.component import _api _api.adapter_hook.reset() _api.getSiteManager.reset() # be sure the old adapter hook isn't cached, since # it is derived from the SiteManager try: del siteinfo.adapter_hook except AttributeError: pass # Clear the site thread global clearSite = setSite try: from zope.testing.cleanup import addCleanUp except ImportError: #pragma NO COVER pass else: addCleanUp(resetHooks)
top_level=False) result.append(value) result = ILocatedExternalSequence(result) return result _usable_externalObject_cache = WeakKeyDictionary() _usable_externalObject_cache_get = _usable_externalObject_cache.get try: # pylint:disable=ungrouped-imports from zope.testing import cleanup except ImportError: # pragma: no cover pass else: cleanup.addCleanUp(_usable_externalObject_cache.clear) def _obj_has_usable_externalObject(obj): # This is for legacy code support, to allow existing methods to # move to adapters and call us without infinite recursion. # We use __class__ instead of type() to allow for proxies; # The proxy itself cannot implement toExternalObject kind = obj.__class__ answer = _usable_externalObject_cache_get(kind) if answer is None: answer = False has_ext_obj = hasattr(kind, 'toExternalObject') if has_ext_obj: ext_ignored = getattr(kind, '__ext_ignore_toExternalObject__', None) answer = not ext_ignored
The duration is provided in millisecond. """ rval = [] for key, report in Reports.get(self.cid).items(): last = report.last info = { 'query': key, 'counter': report.hits, 'duration': report.duration * 1000, 'last': { 'duration': last.duration * 1000, 'details': [ dict(id=d.name, duration=d.duration * 1000, length=d.num) for d in last.details ], }, } rval.append(info) return rval # Make sure we provide test isolation from zope.testing.cleanup import addCleanUp addCleanUp(PriorityMap.clear) addCleanUp(Reports.clear) addCleanUp(ValueIndexes.clear) del addCleanUp
self.adapters = GlobalAdapterRegistry(self, 'adapters') self.utilities = GlobalAdapterRegistry(self, 'utilities') def __reduce__(self): # Global site managers are pickled as global objects return self.__name__ base = BaseGlobalComponents('base') try: from zope.testing.cleanup import addCleanUp except ImportError: #pragma NO COVER pass else: addCleanUp(lambda: base.__init__('base')) del addCleanUp globalSiteManager = base @inherits_arch_docs def getGlobalSiteManager(): return globalSiteManager # The following APIs provide global registration support for Python code. # We eventually want to deprecate these in favor of using the global # component registry directly.
if unwrapped is not proxy: proxy = unwrapped break else: # We didn't break. Nothing unwrapped. go_again = False return unwrapped def registerProxyUnwrapper(func): """ Register a function that can unwrap a single proxy from a proxied object. If there is nothing to unwrap, the function should return the given object. .. versionadded:: 1.0 This is a provisional way to extend the unwrapping functionality (where speed is critical). It may not be supported in the future. """ _unwrappers.append(func) try: from zope.testing import cleanup except ImportError: # pragma: no cover pass else: cleanup.addCleanUp(_init_unwrappers) _init_unwrappers()
wait_time = 2.5 while not self.stopping: try: return self.producer.getConnection(url) except socket.error, e: wait_time = int(min(wait_time * 2, 21)) if wait_time > 20: # we waited a full minute, we assume a permanent failure logger.debug("Error %s connecting to %s - reconnect " "failed.", e, url) self.stopping = True break logger.debug("Error %s connecting to %s - will " "retry in %d second(s)", e, url, wait_time) for i in xrange(wait_time): if self.stopping: break time.sleep(1) return None # must be stopping! DEFAULT_PURGER = DefaultPurger() def stopThreads(): purger = DEFAULT_PURGER purger.stopThreads() from zope.testing.cleanup import addCleanUp addCleanUp(stopThreads) del addCleanUp
def reset(self): Reports.clear_entry(self.cid) def report(self): """Returns a statistic report of catalog queries as list of dicts. The duration is provided in millisecond. """ rval = [] for key, report in Reports.get(self.cid).items(): last = report.last info = { 'query': key, 'counter': report.hits, 'duration': report.duration * 1000, 'last': {'duration': last.duration * 1000, 'details': [dict(id=d.name, duration=d.duration * 1000) for d in last.details], }, } rval.append(info) return rval # Make sure we provide test isolation from zope.testing.cleanup import addCleanUp addCleanUp(PriorityMap.clear) addCleanUp(Reports.clear) del addCleanUp
def __init__(self, parent=None, name=None): self.__parent__ = parent self.__name__ = name super(GlobalAdapterRegistry, self).__init__() def __reduce__(self): return GAR, (self.__parent__, self.__name__) # Global Site Manager Instance globalSiteManager = GlobalSiteManager('globalSiteManager') # Register our cleanup with zope.testing.cleanup to make writing unit tests # simpler. from zope.testing.cleanup import addCleanUp addCleanUp(lambda : globalSiteManager.__init__(globalSiteManager.__name__)) del addCleanUp class AdapterRegistration(object): """Registration for a simple adapter.""" def __init__(self, required, provided, name, value, doc=''): (self.required, self.provided, self.name, self.value, self.doc ) = required, provided, name, value, doc def __repr__(self): return '%s(%r, %r, %r, %r, %r)' % ( self.__class__.__name__, tuple([getattr(r, '__name__', None) for r in self.required]),
>>> stub_utcnow(faketime().next) >>> utcnow() datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>) >>> utcnow() datetime.datetime(1970, 1, 1, 0, 1, tzinfo=<UTC>) >>> utcnow() datetime.datetime(1970, 1, 1, 0, 2, tzinfo=<UTC>) When we set the stubbed value to None, utcnow starts returning real time: >>> stub_utcnow(None) >>> tick = utc.localize(datetime.utcnow()) >>> tack = utcnow() >>> tock = utc.localize(datetime.utcnow()) >>> tick <= tack <= tock True """ global _utcnow_hook if value is None: _utcnow_hook = None elif callable(value): _utcnow_hook = value else: _utcnow_hook = lambda: value addCleanUp(stub_utcnow, (None, ))
r = [] for event in events: if event_type is not None and not event_type.providedBy(event): continue if filter is not None and not filter(event): continue r.append(event) return r def clearEvents(): #pragma NO COVER going aaway del events[:] addCleanUp(clearEvents) class PlacelessSetup: #pragma NO COVER going aaway def setUp(self): provideHandler(objectEventNotify) provideHandler(dispatchUtilityRegistrationEvent) provideHandler(dispatchAdapterRegistrationEvent) provideHandler(dispatchSubscriptionAdapterRegistrationEvent) provideHandler(dispatchHandlerRegistrationEvent) provideHandler(events.append, (None, )) def setUp(test=None): #pragma NO COVER going aaway PlacelessSetup().setUp()
# This is not a possible site, we need to monkey-patch it so that # it is. site_class = FiveSite else: if not IPossibleSite.implementedBy(site_class): raise ConfigurationError('Site class does not implement ' 'IPossibleClass: %s' % site_class) if site_class is not None: _context.action(discriminator=(class_, ), callable=classSiteHook, args=(class_, site_class)) _context.action(discriminator=(class_, IPossibleSite), callable=classImplements, args=(class_, IPossibleSite)) # clean up code def uninstallSiteHooks(): for class_ in _localsite_monkies: delattr(class_, 'getSiteManager') delattr(class_, 'setSiteManager') classImplementsOnly(class_, implementedBy(class_) - IPossibleSite) _localsite_monkies.remove(class_) from zope.testing.cleanup import addCleanUp addCleanUp(uninstallSiteHooks) del addCleanUp
except socket.error, e: wait_time = int(min(wait_time * 2, 21)) if wait_time > 20: # we waited a full minute, we assume a permanent failure logger.debug( "Error %s connecting to %s - reconnect " "failed.", e, url) self.stopping = True break logger.debug( "Error %s connecting to %s - will " "retry in %d second(s)", e, url, wait_time) for i in xrange(wait_time): if self.stopping: break time.sleep(1) return None # must be stopping! DEFAULT_PURGER = DefaultPurger() def stopThreads(): purger = DEFAULT_PURGER purger.stopThreads() from zope.testing.cleanup import addCleanUp addCleanUp(stopThreads) del addCleanUp
if not ZODB.interfaces.IDatabase.providedBy(db): zope.interface.directlyProvides(db, ZODB.interfaces.IDatabase) zope.component.provideUtility(db, ZODB.interfaces.IDatabase, name) db.setActivityMonitor(ZODB.ActivityMonitor.ActivityMonitor()) result.append(db) return result, databases __config_context = None def getConfigContext(): return __config_context __config_source = None def getConfigSource(): return __config_source def reset(): global _configured _configured = False global __config_source __config_source = None global __config_context __config_context = None from zope.testing.cleanup import addCleanUp addCleanUp(reset) del addCleanUp
return component.getGlobalSiteManager() def setHooks(): component.adapter_hook.sethook(adapter_hook) component.getSiteManager.sethook(getSiteManager) def resetHooks(): component.adapter_hook.reset() component.getSiteManager.reset() # make sure hooks get cleaned up after tests are run addCleanUp(resetHooks) def engine_subscriber(engine): print('got: {0!s} '.format(engine)) def test_suite(): optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS globs = { 'DummySite': DummySite, 'setSite': setSite, 'getSite': getSite, 'TEST_DSN': TEST_DSN, 'TEST_DSN1': TEST_DSN1, 'TEST_DSN2': TEST_DSN2,
def _clear(): global _defaultPolicy _defaultPolicy = ParanoidSecurityPolicy # XXX This code is used to support automated testing. However, it shouldn't be # here and needs to be refactored. The empty addCleanUp-method is a temporary # workaround to fix packages that depend on zope.security but don't have a # need for zope.testing. try: from zope.testing.cleanup import addCleanUp except ImportError: def addCleanUp(arg): pass addCleanUp(_clear) # # ISecurityManagement implementation # def getSecurityPolicy(): """Get the system default security policy.""" return _defaultPolicy def setSecurityPolicy(aSecurityPolicy): """Set the system default security policy, and return the previous value. This method should only be called by system startup code. It should never, for example, be called during a web request.
): try: func = getattr(itertools, func) except AttributeError: assert func in missing, "Expected %s but not found" % (func,) continue # pragma: no cover This is hit on Python 2, but it doesn't always show result = func(*args) if func == itertools.tee: result = result[0] tresult = type(result) if tresult not in _default_checkers: _default_checkers[tresult] = _iteratorChecker _fixup_itertools() del _fixup_itertools def _clear(): _checkers.clear() _checkers.update(_default_checkers) _checkers.update(BasicTypes) _clear() try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(_clear)
Reports.clear_entry(self.cid) def report(self): """Returns a statistic report of catalog queries as list of dicts. The duration is provided in millisecond. """ rval = [] for key, report in Reports.get(self.cid).items(): last = report.last info = { 'query': key, 'counter': report.hits, 'duration': report.duration * 1000, 'last': {'duration': last.duration * 1000, 'details': [dict(id=d.name, duration=d.duration * 1000) for d in last.details], }, } rval.append(info) return rval # Make sure we provide test isolation from zope.testing.cleanup import addCleanUp addCleanUp(PriorityMap.clear) addCleanUp(Reports.clear) addCleanUp(ValueIndexes.clear) del addCleanUp
# remove it del sitemanager['default'] site.setSiteManager(sitemanager) # add a cleanup hook so that grok will bootstrap itself again whenever # the Component Architecture is torn down. def resetBootstrap(): global _bootstrapped # we need to make sure that the grokker registry is clean again the_module_grokker.clear() _bootstrapped = False from zope.testing.cleanup import addCleanUp addCleanUp(resetBootstrap) def do_grok(dotted_name): global _bootstrapped if not _bootstrapped: bootstrap() _bootstrapped = True martian.grok_dotted_name(dotted_name, the_module_grokker) def grok_component(name, component, context=None, module_info=None, templates=None):
def lookup(self, method, mimetype, environment): """Lookup a factory for a given method+mimetype and a environment.""" for m,mt in ((method, mimetype), (method, '*'), ('*', '*')): factory_lst = self.getFactoriesFor(m, mt) if factory_lst: break else: raise ConfigurationError('No registered publisher found ' 'for (%s/%s)' % (method, mimetype)) # now iterate over all factory candidates and let them introspect # the request environment to figure out if they can handle the # request for d in factory_lst: factory = d['factory'] if factory.canHandle(environment): return factory # Actually we should never get here unless of improper # configuration (no default handler for method=* and mimetype=*) return None factoryRegistry = RequestPublicationRegistry() from zope.testing import cleanup cleanup.addCleanUp(lambda : factoryRegistry.__init__())
exclude = Tokens( title=u"Exclude", description=u"Names (which might contain unix shell-style wildcards) " u"to be excluded in the grokking process.", required=False, value_type=TextLine()) # add a cleanup hook so that grok will bootstrap itself again whenever # the Component Architecture is torn down. def resetBootstrap(): # we need to make sure that the grokker registry is clean again the_module_grokker.clear() from zope.testing.cleanup import addCleanUp addCleanUp(resetBootstrap) the_multi_grokker = martian.MetaMultiGrokker() the_module_grokker = martian.ModuleGrokker(the_multi_grokker) def skip_tests(name): return name in ['tests', 'ftests', 'testing'] def grokDirective(_context, package, exclude=None): if not exclude: exclude = None do_grok(package.__name__, _context, extra_exclude=exclude)
$Id$ """ from Products.Five.event import doMonkies from OFS.subscribers import deprecatedManageAddDeleteClasses def setDeprecatedManageAddDelete(class_): """Instances of the class will still see their old methods called.""" deprecatedManageAddDeleteClasses.append(class_) def cleanUp(): deprecatedManageAddDeleteClasses[:] = [] def containerEvents(_context): _context.action( discriminator=None, callable=doMonkies, args=(), ) def deprecatedManageAddDelete(_context, class_): _context.action( discriminator=('five:deprecatedManageAddDelete', class_), callable=setDeprecatedManageAddDelete, args=(class_,), ) from zope.testing.cleanup import addCleanUp addCleanUp(cleanUp) del addCleanUp
class BookModule(OnlineHelp): """Represent a book compiled from various `README.txt` and other `*.txt` documentation files. """ implements(IBookModule) # See zope.app.apidoc.interfaces.IDocumentationModule title = _('Book') # See zope.app.apidoc.interfaces.IDocumentationModule description = _(""" This is a developer's book compiled from all existing documentation files. It is not meant to be a complete or cohesive work, but each chapter in itself is a little story. Think about it like a collection of fairy tales. """) # Global Book Instance path = os.path.join(os.path.dirname(zope.app.apidoc.bookmodule.__file__), 'intro.txt') book = BookModule(_('Book'), path) def _clear(): global book book.__init__(book.title, book.path) from zope.testing import cleanup cleanup.addCleanUp(_clear)
"""Returns a statistic report of catalog queries as list of dicts. The duration is provided in millisecond. """ rval = [] for key, report in Reports.get(self.cid).items(): last = report.last info = { 'query': key, 'counter': report.hits, 'duration': report.duration * 1000, 'last': { 'duration': last.duration * 1000, 'details': [ dict(id=d.name, duration=d.duration * 1000) for d in last.details ], }, } rval.append(info) return rval # Make sure we provide test isolation from zope.testing.cleanup import addCleanUp addCleanUp(PriorityMap.clear) addCleanUp(Reports.clear) del addCleanUp
id=name, title=title, description=description, configuration=configuration, ) def getConfiguration(self, id): return self._config_info[id].copy() def listConfigurationIds(self): return tuple(self._config_ids) configuration_registry = ConfigurationRegistry() addCleanUp(configuration_registry.clear) del addCleanUp @implementer(ITransmogrifier) class Transmogrifier(DictMixin): adapts(IFolderish) def __init__(self, context): self.context = context def __call__(self, configuration_id, overrides={}): self.configuration_id = configuration_id raw = get_transmogrifier_configuration() self._raw = merge({}, raw, overrides)