def test_tubeDiverting_ReEntrantResumeReceive(self): """ Diverting a tube that is receiving data from a fount which synchronously produces some data to C{receive} will ... uh .. work. """ @tube class Switcher(object): def received(self, data): if data == "switch": diverter.divert(series(Switchee(), fakeDrain)) return None else: return [data] @tube class Switchee(object): def received(self, data): yield "switched " + data fakeDrain = self.fd destinationTube = PassthruTube() # `reassemble` should not be called, so don't implement it directlyProvides(destinationTube, IDivertable) diverter = Diverter(destinationTube) firstDrain = series(Switcher(), diverter) ff = FakeFountWithBuffer() ff.bufferUp("before") ff.bufferUp("switch") ff.bufferUp("after") nf = ff.flowTo(firstDrain) nf.flowTo(fakeDrain) self.assertEquals(self.fd.received, ["before", "switched after"])
def __init__(self, value): """Create a term from the single value This class prevents the use of the silly bugged SimpleTerm. """ self.value = value self.token = value self.title = value directlyProvides(self, ITitledTokenizedTerm)
def __init__(self, name, label): """Create a term from the single value. This class prevents the use of the silly bugged SimpleTerm. """ self.value = name self.token = name self.title = label directlyProvides(self, ITitledTokenizedTerm)
def __init__(self, name, docstring): """Create a term from the single value This class prevents the use of the silly bugged SimpleTerm. """ self.value = name self.token = name self.title = _(name, default=docstring) directlyProvides(self, ITitledTokenizedTerm)
def __init__(self, value): """Create a term from the single value This class prevents the use of the silly bugged SimpleTerm. """ self.value = value self.token = value self.title = value directlyProvides(self, ITitledTokenizedTerm)
def setUp(self): app = self.layer['app'] self.portal = self.layer['portal'] self.request = self.layer['request'] directlyProvides(self.request, IBrowserLayer) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.browser = Browser(app) self.setup_content() transaction.commit()
def __new__(metacls, name, bases, dct): abstract = False if "_abstract" in dct: del dct["_abstract"] abstract = True new_class = type.__new__(metacls, name, bases, dct) if not abstract: classImplements(new_class, ISection) directlyProvides(new_class, ISectionBlueprint) return new_class
def __new__(metacls, name, bases, dct): abstract = False if "_abstract" in dct: del dct["_abstract"] abstract = True new_class = type.__new__(metacls, name, bases, dct) if not abstract: classImplements(new_class, ISection) directlyProvides(new_class, ISectionBlueprint) return new_class
def __init__(self, value, token=None, title=None): """Create a term for value and token. If token is omitted, str(value) is used for the token. If title is provided, term implements ITitledTokenizedTerm. """ self.value = value if token is None: token = value self.token = str(token) self.title = title if title is not None: directlyProvides(self, ITitledTokenizedTerm)
def setUp(self): app = self.layer['app'] self.portal = self.layer['portal'] self.wt = self.portal['portal_workflow'] self.request = self.layer['request'] directlyProvides(self.request, IBrowserLayer) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.browser = Browser(app) self.wt.setChainForPortalTypes(['Document', 'Event', 'Folder', 'News Item'], ['simple_publication_workflow'],) self.setup_content() transaction.commit()
def __init__(self, value, token=None, title=None): """Create a term for value and token. If token is omitted, str(value) is used for the token. If title is provided, term implements ITitledTokenizedTerm. """ self.value = value if token is None: token = value self.token = str(token) self.title = title if title is not None: directlyProvides(self, ITitledTokenizedTerm)
def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] setRoles(self.portal, TEST_USER_ID, ['Manager']) directlyProvides(self.request, IBrowserLayer) self.portal.portal_workflow.setChainForPortalTypes( ['Document', 'Folder', 'sc.microsite', ], ['one_state_workflow'], ) self.microsite = self.setup_microsite() self.acessibilidade = self.setup_acessibilidade() self.browser = Browser(self.layer['app']) transaction.commit()
def setUp(self): super(IntegrationTestCase, self).setUp() self.portal = self.layer['portal'] self.request = self.layer setRoles(self.portal, TEST_USER_ID, ['Manager']) self.view = self.portal.restrictedTraverse('@@mass-edit') self.portal.invokeFactory('Document', 'page1') self.portal.invokeFactory('Document', 'page2') self.page1 = self.portal['page1'] self.page2 = self.portal['page2'] directlyProvides(self.page1, IMassEditTest) directlyProvides(self.page2, IMassEditTest) self.page1.reindexObject() self.page2.reindexObject() processQueue()
def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] setRoles(self.portal, TEST_USER_ID, ['Manager']) self.setup_left_column_portlet() directlyProvides(self.request, IBrowserLayer) self.portal.portal_workflow.setChainForPortalTypes( [ 'Document', 'sc.microsite', ], ['one_state_workflow'], ) self.microsite = self.setup_microsite() self.page = self.setup_page(self.microsite) self.browser = Browser(self.layer['app']) transaction.commit()
def __init__(self, terms, *interfaces): """Initialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ self.by_value = {} self.by_token = {} self._terms = terms for term in self._terms: self.by_value[term.value] = term self.by_token[term.token] = term if not (len(self.by_value) == len(self.by_token) == len(terms)): raise ValueError( 'Supplied vocabulary values resulted in duplicate term tokens') if interfaces: directlyProvides(self, *interfaces)
def __init__(self, terms, *interfaces): """Initialize the vocabulary given a recursive dict (i.e a tree) with ITokenizedTerm objects for keys and self-similar dicts representing the branches for values. Refer to the method fromDict for more details. Concerning the ITokenizedTerm keys, the 'value' and 'token' attributes of each key (including nested ones) must be unique. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ self._terms = self.terms_factory() self._terms.update(terms) self.path_by_value = {} self.term_by_value = {} self.term_by_token = {} self._populateIndexes(terms) if interfaces: directlyProvides(self, *interfaces)
def __init__(self, terms, *interfaces): """Initialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ self.by_value = {} self.by_token = {} self._terms = terms for term in self._terms: if term.value in self.by_value: raise ValueError( 'term values must be unique: %s' % repr(term.value)) if term.token in self.by_token: raise ValueError( 'term tokens must be unique: %s' % repr(term.token)) self.by_value[term.value] = term self.by_token[term.token] = term if interfaces: directlyProvides(self, *interfaces)
def __init__(self, terms, *interfaces): """Initialize the vocabulary given a list of terms. The vocabulary keeps a reference to the list of terms passed in; it should never be modified while the vocabulary is used. One or more interfaces may also be provided so that alternate widgets may be bound without subclassing. """ self.by_value = {} self.by_token = {} self._terms = terms for term in self._terms: if term.value in self.by_value: raise ValueError( 'term values must be unique: %s' % repr(term.value)) if term.token in self.by_token: raise ValueError( 'term tokens must be unique: %s' % repr(term.token)) self.by_value[term.value] = term self.by_token[term.token] = term if interfaces: directlyProvides(self, *interfaces)
def test_tubeDivertingControlsWhereOutputGoes(self): """ If a siphon A with a tube Ap is flowing to a siphon B with a divertable tube Bp, Ap.received may switch B to a drain C, and C will receive any outputs produced by that received call; B (and Bp) will not. """ @tube class Switcher(object): def received(self, data): if data == "switch": yield "diverting" diverter.divert(series(Switchee(), fakeDrain)) yield "switched" else: yield data @tube class Switchee(object): def received(self, data): yield "switched({0})".format(data) fakeDrain = self.fd destinationTube = PassthruTube() # `reassemble` should not be called, so don't implement it directlyProvides(destinationTube, IDivertable) diverter = Diverter(PassthruTube()) firstDrain = series(Switcher(), diverter) self.ff.flowTo(firstDrain).flowTo(fakeDrain) self.ff.drain.receive("before") self.ff.drain.receive("switch") self.ff.drain.receive("after") self.assertEqual(self.fd.received, ["before", "diverting", "switched(switched)", "switched(after)"])
def setUp(self): super(IntegrationTestCase, self).setUp() directlyProvides(self.portal.REQUEST, IUploadLayer) directlyProvides(self.request, IUploadLayer)
def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] self.qi = self.portal['portal_quickinstaller'] directlyProvides(self.request, IBrowserLayer) setRoles(self.portal, TEST_USER_ID, ['Manager'])
from twisted.internet import main, posixbase from twisted.internet.interfaces import IReactorFDSet, IReactorDaemonize from twisted.python import log, failure class _IKQueue(Interface): """ An interface for KQueue implementations. """ kqueue = Attribute("An implementation of kqueue(2).") kevent = Attribute("An implementation of kevent(2).") declarations.directlyProvides(select, _IKQueue) @implementer(IReactorFDSet, IReactorDaemonize) class KQueueReactor(posixbase.PosixReactorBase): """ A reactor that uses kqueue(2)/kevent(2) and relies on Python 2.6 or higher which has built in support for kqueue in the select module. @ivar _kq: A C{kqueue} which will be used to check for I/O readiness. @ivar _impl: The implementation of L{_IKQueue} to use. @ivar _selectables: A dictionary mapping integer file descriptors to instances of L{FileDescriptor} which have been registered with the reactor. All L{FileDescriptor}s which are currently receiving read or
from Products.CMFCore.utils import getToolByName from collective.lineage.interfaces import IChildSite from plone.memoize import ram from zope.interface.declarations import directlyProvides from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm from zope.schema.vocabulary import SimpleVocabulary import plone.api # cache until next zope restart # XXX: ideally invalidate when new subsites are created @ram.cache(lambda *args: ()) def childSiteVocabulary(context): """returns the available childsites of the portal """ cat = getToolByName(context, 'portal_catalog') portal = plone.api.portal.get() brains = cat( object_provides=IChildSite.__identifier__, path=portal.getPhysicalPath(), sort_on='sortable_title' ) terms = [ SimpleTerm(value=brain.UID, token=brain.UID, title=brain.Title) for brain in brains ] return SimpleVocabulary(terms) directlyProvides(childSiteVocabulary, IVocabularyFactory)
def get_tor(reactor, launch_tor=False, tor_control_port=None, timing=None, stderr=sys.stderr): """ If launch_tor=True, I will try to launch a new Tor process, ask it for its SOCKS and control ports, and use those for outbound connections (and inbound onion-service listeners, if necessary). Otherwise if tor_control_port is provided, I will attempt to connect to an existing Tor's control port at the endpoint it specifies. I'll ask that Tor for its SOCKS port. With no arguments, I will try to connect to an existing Tor's control port at the usual places: [unix:/var/run/tor/control, tcp:127.0.0.1:9051, tcp:127.0.0.1:9151]. If any are successful, I'll ask that Tor for its SOCKS port. If none are successful, I'll attempt to do SOCKS to the usual places: [tcp:127.0.0.1:9050, tcp:127.0.0.1:9150]. If I am unable to make a SOCKS connection, the initial connection to the Rendezvous Server will fail, and the program will terminate. Control-port connections can only succeed if I can authenticate (by reading a cookie file named by the Tor process), so the current user must have permission to read that file (either they started Tor, e.g. TorBrowser, or they are in a unix group that's been given access, e.g. debian-tor). """ # rationale: launching a new Tor takes a long time, so only do it if # the user specifically asks for it with --launch-tor. Using an # existing Tor should be much faster, but still requires general # permission via --tor. if not txtorcon: raise errors.NoTorError() if not isinstance(launch_tor, bool): # note: False is int raise TypeError("launch_tor= must be boolean") if not isinstance(tor_control_port, (type(""), type(None))): raise TypeError("tor_control_port= must be str or None") assert tor_control_port != "" if launch_tor and tor_control_port is not None: raise ValueError("cannot combine --launch-tor and --tor-control-port=") timing = timing or DebugTiming() # Connect to an existing Tor, or create a new one. If we need to # launch an onion service, then we need a working control port (and # authentication cookie). If we're only acting as a client, we don't # need the control port. if launch_tor: print(" launching a new Tor process, this may take a while..", file=stderr) with timing.add("launch tor"): tor = yield txtorcon.launch(reactor, #data_directory=, #tor_binary=, ) elif tor_control_port: with timing.add("find tor"): control_ep = clientFromString(reactor, tor_control_port) tor = yield txtorcon.connect(reactor, control_ep) # might raise print(" using Tor via control port at %s" % tor_control_port, file=stderr) else: # Let txtorcon look through a list of usual places. If that fails, # we'll arrange to attempt the default SOCKS port with timing.add("find tor"): try: tor = yield txtorcon.connect(reactor) print(" using Tor via default control port", file=stderr) except Exception: # TODO: make this more specific. I think connect() is # likely to throw a reactor.connectTCP -type error, like # ConnectionFailed or ConnectionRefused or something print(" unable to find default Tor control port, using SOCKS", file=stderr) tor = SocksOnlyTor(reactor) directlyProvides(tor, _interfaces.ITorManager) returnValue(tor)
from twisted.internet import main, posixbase from twisted.internet.interfaces import IReactorFDSet, IReactorDaemonize from twisted.python import log, failure from zope.interface import implementer, declarations, Interface, Attribute class _IKQueue(Interface): """ An interface for KQueue implementations. """ kqueue = Attribute("An implementation of kqueue(2).") kevent = Attribute("An implementation of kevent(2).") declarations.directlyProvides(select, _IKQueue) @implementer(IReactorFDSet, IReactorDaemonize) class KQueueReactor(posixbase.PosixReactorBase): """ A reactor that uses kqueue(2)/kevent(2) and relies on Python 2.6 or higher which has built in support for kqueue in the select module. @ivar _kq: A C{kqueue} which will be used to check for I/O readiness. @ivar _impl: The implementation of L{_IKQueue} to use. @ivar _selectables: A dictionary mapping integer file descriptors to instances of L{FileDescriptor} which have been registered with the reactor. All L{FileDescriptor}s which are currently receiving read or
def TemplatesVocabulary(context): adapters = getUtilitiesFor(ICollectiveContactMailactionTemplate) terms = [] for adTuple in adapters: terms.append( SimpleTerm(value=adTuple[0], token=adTuple[0].encode('utf-8'), title=adTuple[0])) return SimpleVocabulary(terms) directlyProvides(TemplatesVocabulary, IVocabularyFactory) def MailSenderVocabulary(context): items = {} # Portal/global E-Mail Address portal = api.portal.get() items[portal.email_from_address] = formataddr(( portal.email_from_name, portal.email_from_address, )) # The current authenticated Members E-Mail. member = api.user.get_current()
def get_tor(reactor, launch_tor=False, tor_control_port=None, timing=None, stderr=sys.stderr): """ If launch_tor=True, I will try to launch a new Tor process, ask it for its SOCKS and control ports, and use those for outbound connections (and inbound onion-service listeners, if necessary). Otherwise if tor_control_port is provided, I will attempt to connect to an existing Tor's control port at the endpoint it specifies. I'll ask that Tor for its SOCKS port. With no arguments, I will try to connect to an existing Tor's control port at the usual places: [unix:/var/run/tor/control, tcp:127.0.0.1:9051, tcp:127.0.0.1:9151]. If any are successful, I'll ask that Tor for its SOCKS port. If none are successful, I'll attempt to do SOCKS to the usual places: [tcp:127.0.0.1:9050, tcp:127.0.0.1:9150]. If I am unable to make a SOCKS connection, the initial connection to the Rendezvous Server will fail, and the program will terminate. Control-port connections can only succeed if I can authenticate (by reading a cookie file named by the Tor process), so the current user must have permission to read that file (either they started Tor, e.g. TorBrowser, or they are in a unix group that's been given access, e.g. debian-tor). """ # rationale: launching a new Tor takes a long time, so only do it if # the user specifically asks for it with --launch-tor. Using an # existing Tor should be much faster, but still requires general # permission via --tor. if not txtorcon: raise errors.NoTorError() if not isinstance(launch_tor, bool): # note: False is int raise TypeError("launch_tor= must be boolean") if not isinstance(tor_control_port, (type(""), type(None))): raise TypeError("tor_control_port= must be str or None") assert tor_control_port != "" if launch_tor and tor_control_port is not None: raise ValueError("cannot combine --launch-tor and --tor-control-port=") timing = timing or DebugTiming() # Connect to an existing Tor, or create a new one. If we need to # launch an onion service, then we need a working control port (and # authentication cookie). If we're only acting as a client, we don't # need the control port. if launch_tor: print(" launching a new Tor process, this may take a while..", file=stderr) with timing.add("launch tor"): tor = yield txtorcon.launch(reactor, #data_directory=, #tor_binary=, ) elif tor_control_port: with timing.add("find tor"): control_ep = clientFromString(reactor, tor_control_port) tor = yield txtorcon.connect(reactor, control_ep) # might raise print(" using Tor via control port at %s" % tor_control_port, file=stderr) else: # Let txtorcon look through a list of usual places. If that fails, # we'll arrange to attempt the default SOCKS port with timing.add("find tor"): try: tor = yield txtorcon.connect(reactor) print(" using Tor via default control port", file=stderr) except Exception: # TODO: make this more specific. I think connect() is # likely to throw a reactor.connectTCP -type error, like # ConnectionFailed or ConnectionRefused or something print(" unable to find default Tor control port, using SOCKS", file=stderr) tor = SocksOnlyTor(reactor) directlyProvides(tor, _interfaces.ITorManager) returnValue(tor)
def TemplatesVocabulary(context): adapters = getUtilitiesFor(ICollectiveContactMailactionTemplate) terms = [] for adTuple in adapters: terms.append(SimpleTerm( value=adTuple[0], token=adTuple[0].encode('utf-8'), title=adTuple[0] )) return SimpleVocabulary(terms) directlyProvides(TemplatesVocabulary, IVocabularyFactory) def MailSenderVocabulary(context): items = {} # Portal/global E-Mail Address portal = api.portal.get() items[portal.email_from_address] = formataddr(( portal.email_from_name, portal.email_from_address, )) # The current authenticated Members E-Mail. member = api.user.get_current()