class StaticContent(record('staticPaths processors')): """ Parent resource for all static content provided by all installed offerings. This resource has a child by the name of each offering which declares a static content path which serves that path. @ivar staticPaths: A C{dict} mapping offering names to L{FilePath} instances for each offering which should be able to publish static content. @ivar processors: A C{dict} mapping extensions (with leading ".") to two-argument callables. These processors will be attached to the L{nevow.static.File} returned by C{locateChild}. """ implements(IResource) def locateChild(self, context, segments): """ Find the offering with the name matching the first segment and return a L{File} for its I{staticContentPath}. """ name = segments[0] try: staticContent = self.staticPaths[name] except KeyError: return NotFound else: resource = File(staticContent.path) resource.processors = self.processors return resource, segments[1:] return NotFound
class ProviderOf(record("interface")): """ L{ProviderOf} is a retriever which will retrieve the facet which provides its C{interface}, if any exists at the terminus of the path. @ivar interface: The interface which defines the type of values returned by the C{retrieve} method. @type interface: L{zope.interface.interfaces.IInterface} """ implements(IRetriever) def retrieve(self, path): """ Retrieve the target of the path, as it provides the interface specified by this L{ProviderOf}. @return: the target of the path, adapted to this retriever's interface, as defined by L{Path.targetAs}. @rtype: L{ProviderOf.interface} """ return path.targetAs(self.interface) def objectionsTo(self, path, result): """ Implement L{IRetriever.objectionsTo} to yield no objections. """ return [] def shouldKeepGoing(self, path): """ Implement L{IRetriever.shouldKeepGoing} to always return C{True}. """ return True
def test_typeStringRepresentation(self): """ 'Record' types should have a name which provides information about the slots they contain. """ R = record('xyz abc def') self.assertEquals(R.__name__, "Record<xyz abc def>")
class ObtainResult(record("idea retriever")): """ The result of L{Idea.obtain}, this provides an iterable of results. @ivar reasonsWhyNot: If this iterator has already been exhausted, this will be a C{set} of L{IWhyNot} objects explaining possible reasons why there were no results. For example, if the room where the player attempted to obtain targets is dark, this may contain an L{IWhyNot} provider. However, until this iterator has been exhausted, it will be C{None}. @type reasonsWhyNot: C{set} of L{IWhyNot}, or C{NoneType} @ivar idea: the L{Idea} that L{Idea.obtain} was invoked on. @type idea: L{Idea} @ivar retriever: The L{IRetriever} that L{Idea.obtain} was invoked with. @type retriever: L{IRetriever} """ reasonsWhyNot = None def __iter__(self): """ A generator which yields each result of the query, then sets C{reasonsWhyNot}. """ reasonsWhyNot = set() for result in self.idea._doObtain(self.retriever, None, reasonsWhyNot): yield result self.reasonsWhyNot = reasonsWhyNot
class _PyLuceneHitsWrapper(record('index hits')): """ Container for a C{Hits} instance and the L{_PyLuceneIndex} from which it came. This gives the C{Hits} instance a sequence-like interface and when a _PyLuceneHitsWrapper is garbage collected, it closes the L{_PyLuceneIndex} it has a reference to. """ def __init__(self, *a, **kw): super(_PyLuceneHitsWrapper, self).__init__(*a, **kw) def close(ref, index=self.index): log.msg("Hits wrapper expiring, closing index.") index.close() _hitsWrapperWeakrefs[self] = weakref.ref(self, close) def __len__(self): return len(self.hits) def __getitem__(self, index): """ Retrieve the storeID field of the requested hit, converting it to an integer before returning it. This handles integer indexes as well as slices. """ if isinstance(index, slice): return SlicedView(self, index) if index >= len(self.hits): raise IndexError(index) return _PyLuceneHitWrapper(self.hits[index])
class ChoiceParameter( record('name choices label description multiple ' 'viewFactory', label=None, description="", multiple=False, viewFactory=IParameterView), _SelectiveCoercer): """ A choice parameter, represented by a <select> element in HTML. @ivar choices: A sequence of L{Option} instances (deprecated: a sequence of three-tuples giving the attributes of L{Option} instances). @ivar multiple: C{True} if multiple choice selections are allowed @ivar viewFactory: A two-argument callable which returns an L{IParameterView} provider which will be used as the view for this parameter, if one can be provided. It will be invoked with the parameter as the first argument and a default value as the second argument. The default should be returned if no view can be provided for the given parameter. """ def __init__(self, *a, **kw): ChoiceParameter.__bases__[0].__init__(self, *a, **kw) if self.choices and isinstance(self.choices[0], tuple): warnings.warn( "Pass a list of Option instances to ChoiceParameter, " "not a list of tuples.", category=DeprecationWarning, stacklevel=2) self.choices = [Option(*o) for o in self.choices] def type(self): if self.multiple: return MULTI_CHOICE_INPUT return CHOICE_INPUT type = property(type) def coercer(self, value): if self.multiple: return tuple(self.choices[int(v)].value for v in value) return self.choices[int(value)].value def compact(self): """ Don't do anything. """ def clone(self, choices): """ Make a copy of this parameter, supply different choices. @param choices: A sequence of L{Option} instances. @type choices: C{list} @rtype: L{ChoiceParameter} """ return self.__class__(self.name, choices, self.label, self.description, self.multiple, self.viewFactory)
class remembered(record('creationFunction')): """ This descriptor decorator is applied to a function to create an attribute which will be created on-demand, but remembered for the lifetime of the instance to which it is attached. Subsequent accesses of the attribute will return the remembered value. @ivar creationFunction: the decorated function, to be called to create the value. This should be a 1-argument callable, that takes only a 'self' parameter, like a method. """ value = None def __get__(self, oself, type): """ Retrieve the value if already cached, otherwise, call the C{creationFunction} to create it. """ remembername = "_remembered_" + self.creationFunction.func_name rememberedval = oself.__dict__.get(remembername, None) if rememberedval is not None: return rememberedval rememberme = self.creationFunction(oself) oself.__dict__[remembername] = rememberme return rememberme
class _DarkLocationProxy(structlike.record('thing')): """ An L{IVisible} implementation for darkened locations. """ implements(iimaginary.IVisible) def visualizeWithContents(self, paths): """ Return a L{language.Description} that tells the player they can't see. """ return language.Description( title=u"Blackness", exits=None, description=u"You cannot see anything because it is very dark.", components=None ) def isViewOf(self, thing): """ Implement L{IVisible.isViewOf} to delegate to this L{_DarkLocationProxy}'s L{Thing}'s L{IVisible.isViewOf}. In other words, this L{_DarkLocationProxy} C{isViewOf} its C{thing}. """ return self.thing.isViewOf(thing)
class ContainmentRelationship(structlike.record("containedBy contained")): """ Implementation of L{iimaginary.IContainmentRelationship}. The interface specifies no methods or attributes. See its documentation for more information. """ implements(iimaginary.IContainmentRelationship)
class _PageComponents( record( 'navigation searchAggregator staticShellContent settings themes')): """ I encapsulate various plugin objects that have some say in determining the available functionality on a given page """ pass
def testUnknownArgs(self): """ Test that passing in unknown keyword and / or positional arguments to a record's initializer causes TypeError to be raised. """ R = record('x') self.assertRaises(TypeError, R, x=5, y=6) self.assertRaises(TypeError, R, 5, 6)
class _AMPOneTimePad(record('padValue')): """ L{IOneTimePad} implementation used by L{OTPLogin}. @ivar padValue: The value of the one-time pad. @type padValue: C{str} """ implements(IOneTimePad)
class StandardIOService(record('protocol'), Service): """ Service for connecting a protocol to stdio. """ def startService(self): """ Connect C{self.protocol} to standard io. """ StandardIO(self.protocol)
class StubExit(structlike.record("name")): def shouldEvenAttemptTraversalFrom(self, where, thing): """ Yes. """ return True def traverse(self, thing): """
class _ContainerExit(structlike.record('container')): """ A L{_ContainerExit} is the exit from a container, or specifically, a L{Containment}; an exit by which actors may move to the container's container. @ivar container: the container that this L{_ContainerExit} points out from. @type container: L{Containment} """ implements(iimaginary.IExit, iimaginary.INameable) @property def name(self): """ Implement L{iimaginary.IExit.name} to return a descriptive name for the outward exit of this specific container. """ return 'out of ', language.Noun(self.container.thing).definiteNounPhrase() def traverse(self, thing): """ Implement L{iimaginary.IExit.traverse} to move the thing in transit to the container specified. """ thing.moveTo(self.container.thing.location) def knownTo(self, observer, name): """ This L{_ContainerExit} is known to observers inside it as 'out' (i.e. 'go out', 'look out'), but otherwise it has no known description. """ return (observer.location == self.container.thing) and (name == 'out') def shouldEvenAttemptTraversalFrom(self, where, observer): """ Container exits (currently) never appear as though they're an obvious route for traversal to any observer. (In the future, this should probably be based on the location of the observer; observers in an open container should generally be able to exit it.) """ return False @property def fromLocation(self): """ Container exits are exits from the container itself, so this property reflects the container's L{IThing}. """ return self.container.thing
class Vector(record('distance direction')): """ A L{Vector} is a link annotation which remembers a distance and a direction; for example, a link through a 'north' exit between rooms will have a direction of 'north' and a distance specified by that L{imaginary.objects.Exit} (defaulting to 1 meter). """ implements(IDistance)
class _ContainerEntrance(structlike.record('container')): """ A L{_ContainerEntrance} is the implicit entrance to a container from its location. If a container is open, and big enough, it can be entered. @ivar container: the container that this L{_ContainerEntrance} points to. @type container: L{Containment} """ implements(iimaginary.IExit, iimaginary.INameable) @property def name(self): """ Implement L{iimaginary.IExit.name} to return a descriptive name for the inward exit of this specific container. """ return 'into ', language.Noun(self.container.thing).definiteNounPhrase() def traverse(self, thing): """ Implement L{iimaginary.IExit.traverse} to move the thing in transit to the container specified. """ thing.moveTo(self.container) def knownTo(self, observer, name): """ Delegate L{iimaginary.INameable.knownTo} to this L{_ContainerEntrance}'s container's thing. """ return self.container.thing.knownTo(observer, name) def shouldEvenAttemptTraversalFrom(self, where, observer): """ Container entrances (currently) never appear as though they're an obvious route for traversal to any observer. (In the future, this should probably be based on the capacity of the container, whether it's open or closed, and the location of the observer.) """ return False @property def fromLocation(self): """ Container entrances are exits from the container's location into the container, so this property returns the container. """ return self.container.thing.location
class MockSource(record('channel')): """ Mock source object that counts function calls. """ def __init__(self, *a, **kw): super(MockSource, self).__init__(*a, **kw) self.calls = {} def notice(self, msg): self.calls['notice'] = self.calls.setdefault('notice', 0) + 1
class Generator(AtomElement, record('name uri version', uri=None, version=None)): """ Identifies the software used to generate the feed. @type name: C{str} or C{unicode} @type uri: C{str} or C{unicode} @type version: C{str} or C{unicode} """ def serialize(self): return E('generator', uri=self.uri, version=self.version)[self.name]
class Offering( record( 'name description siteRequirements appPowerups installablePowerups ' 'loginInterfaces themes staticContentPath version', staticContentPath=None, version=None)): """ A set of functionality which can be added to a Mantissa server. @see L{ixmantissa.IOffering} """ implements(plugin.IPlugin, ixmantissa.IOffering)
class FakeTheme(record('themeName loaders')): """ A placeholder for theme lookup. @ivar loaders: A dict of strings to loader objects. @ivar themeName: A name that describes this theme. """ def getDocFactory(self, name, default=None): """ @param name: A loader name. """ return self.loaders.get(name, default)
class VirtualHostWrapper(record('siteStore webViewer wrapped')): """ Resource wrapper which implements per-user virtual subdomains. This should be wrapped around any resource which sits at the root of the hierarchy. It will examine requests for their hostname and, when appropriate, redirect handling of the query to the appropriate sharing resource. @type siteStore: L{Store} @ivar siteStore: The site store which will be queried to determine which hostnames are associated with this server. @type webViewer: L{IWebViewer} @ivar webViewer: The web viewer representing the user. @type wrapped: L{IResource} provider @ivar wrapped: A resource to which traversal will be delegated if the request is not for a user subdomain. """ implements(IResource) def subdomain(self, hostname): """ Determine of which known domain the given hostname is a subdomain. @return: A two-tuple giving the subdomain part and the domain part or C{None} if the domain is not a subdomain of any known domain. """ hostname = hostname.split(":")[0] for domain in getDomainNames(self.siteStore): if hostname.endswith("." + domain): username = hostname[:-len(domain) - 1] if username != "www": return username, domain return None def locateChild(self, context, segments): """ Delegate dispatch to a sharing resource if the request is for a user subdomain, otherwise fall back to the wrapped resource's C{locateChild} implementation. """ request = IRequest(context) hostname = request.getHeader('host') info = self.subdomain(hostname) if info is not None: username, domain = info index = UserIndexPage(IRealm(self.siteStore), self.webViewer) resource = index.locateChild(None, [username])[0] return resource, segments return self.wrapped.locateChild(context, segments)
class Person(AtomElement, record('elemName name uri email', uri=None, email=None)): """ Represents a person. @ivar elemName: Element name to generate @type name: C{str} or C{unicode} @type uri: C{str} or C{unicode} or C{None} @type email: C{str} or C{unicode} or C{None} """ def serialize(self): return E(self.elemName)[E('name')[self.name], E('uri')[self.uri], E('email')[self.email]]
class FormParameter( record('name form label description default viewFactory', label=None, description=None, default=None, viewFactory=IParameterView), _SelectiveCoercer): """ A parameter which is a collection of other parameters, as composed by a L{LiveForm}. @type name: C{unicode} @ivar name: A name uniquely identifying this parameter within a particular form. @type form: L{LiveForm} @ivar form: The form which defines the grouped parameters. @type description: C{unicode} or C{NoneType} @ivar description: An explanation of the meaning or purpose of this parameter which will be presented in the view, or C{None} if the user is intended to guess. @type default: C{unicode} or C{NoneType} @ivar default: A value which will be initially presented in the view as the value for this parameter, or C{None} if no such value is to be presented. @ivar viewFactory: A two-argument callable which returns an L{IParameterView} provider which will be used as the view for this parameter, if one can be provided. It will be invoked with the parameter as the first argument and a default value as the second argument. The default should be returned if no view can be provided for the given parameter. """ implements(IParameter) type = FORM_INPUT def compact(self): """ Compact the wrapped form. """ self.form.compact() def coercer(self, value): """ Invoke the wrapped form with the given value and return its result. """ return self.form.invoke(value)
class Sigma(record('left right')): """ A simple record type which composes two attributes. """ def getLeft(self): """ Return the left attribute. """ return self.left def getRight(self): """ Return the right attribute. """ return self.right
class EditObject(record('object values')): """ Represent changes to be made to an object as the result of the submission of a L{ListChangeParameter}. @ivar object: The object which is to be edited. This is one of the elements of the C{modelObjects} sequence passed to L{ListChangeParameter.__init__} or it is one of the objects subsequently added to the L{ListChangeParameter} by a call to L{CreateObject.setter}. @ivar values: The new values for this object from the submission. """ def __cmp__(self, other): return cmp((self.object, self.values), (other.object, other.values))
class OneTimePadChecker(record('pads')): """ Checker which validates one-time pads. @ivar pads: Mapping between valid one-time pads and avatar IDs. @type pads: C{dict} """ implements(ICredentialsChecker) credentialInterfaces = (IOneTimePad, ) # ICredentialsChecker def requestAvatarId(self, credentials): if credentials.padValue in self.pads: return self.pads.pop(credentials.padValue) raise UnauthorizedLogin('Unknown one-time pad')
class Identifier(record('shareID localpart domain')): """ A fully-qualified identifier for an entity that can participate in a message either as a sender or a receiver. """ @classmethod def fromSharedItem(cls, sharedItem): """ Return an instance of C{cls} derived from the given L{Item} that has been shared. Note that this API does not provide any guarantees of which result it will choose. If there are are multiple possible return values, it will select and return only one. Items may be shared under multiple L{shareID}s. A user may have multiple valid account names. It is sometimes impossible to tell from context which one is appropriate, so if your application has another way to select a specific shareID you should use that instead. @param sharedItem: an L{Item} that should be shared. @return: an L{Identifier} describing the C{sharedItem} parameter. @raise L{NoSuchShare}: if the given item is not shared or its store does not contain any L{LoginMethod} items which would identify a user. """ localpart = None for (localpart, domain) in userbase.getAccountNames(sharedItem.store): break if localpart is None: raise NoSuchShare() for share in sharedItem.store.query(Share, Share.sharedItem == sharedItem): break else: raise NoSuchShare() return cls(shareID=share.shareID, localpart=localpart, domain=domain) def __cmp__(self, other): """ Compare this L{Identifier} to another object. """ # Note - might be useful to have this usable by arbitrary L{record} # objects. It can't be the default, but perhaps a mixin? if not isinstance(other, Identifier): return NotImplemented return cmp(_entuple(self), _entuple(other))
class AlsoKnownAs(record('name')): """ L{AlsoKnownAs} is an annotation that indicates that the link it annotates is known as a particular name. @ivar name: The name that this L{AlsoKnownAs}'s link's target is also known as. @type name: C{unicode} """ implements(INameable) def knownTo(self, observer, name): """ An L{AlsoKnownAs} is known to all observers as its C{name} attribute. """ return (self.name == name)
class NonManipulator(record("thing")): """ A L{NonManipulator} is the ephemeral actor, implementing the responses that normal users will see when they attempt to perform administrative actions. """ implements(IManipulator) def setIllumination(self, candelas): """ Don't actually set the illumination of the manipulator. """ raise ActionFailure( ThatDoesntWork( actor=self.thing, actorMessage= "You are insufficiently brilliant to do that directly."))
def testWithPositional(self): self._testme(record('x y z', x=1, y=2, z=3))
""" A basic script which connects a dumb client to a dumb server. """ import sys from epsilon.structlike import record from twisted.internet import reactor from twisted.python import log from game.ui import UI NetworkClientBase = record('log reactor uiFactory', log=log, reactor=reactor, uiFactory=UI) class NetworkClient(NetworkClientBase): """ An object which starts the Game client and connects it to a remote Game server. See L{run}. @ivar log: An object like L{twisted.python.log} @ivar reactor: An object like L{twisted.internet.reactor} @ivar uiFactory: An object like L{game.ui.UI} """ def run(self, host, port): """
import random from twisted.application.service import Service from game.vector import Vector from game.player import Player from game.environment import SimulationTime from game.terrain import Terrain from epsilon.structlike import record TCP_SERVICE_NAME = 'tcp-service-name' GAM3_SERVICE_NAME = 'gam3-service-name' point = record('x y') class World(SimulationTime): """ All-encompassing model object for the state of a Gam3 game (until we get some distribution up ins). @ivar random: An object like L{random.Random}, used for entropic things. @ivar playerCreationRectangle: A two-tuple of points giving the southwestern (lower bounds on x and y axis) and northeastern (upper bounds on x and y axis) corners of a rectangle within which new players will be created. @ivar observers: A C{list} of objects notified about state changes of this object.
def testCreateWithNoValuesAndNoDefaults(self): R = record('x') self.assertRaises(TypeError, R)
def testUndeclared(self): R = record('a') r = R(1) r.foo = 2 self.assertEquals(r.foo, 2)
from nevow.inevow import IQ from nevow import url from nevow.stan import NodeNotFound from xmantissa.ixmantissa import ITab from xmantissa.fragmentutils import dictFillSlots class TabMisconfiguration(Exception): def __init__(self, info, tab): Exception.__init__( self, "Inconsistent tab item factory information", info, tab) TabInfo = record('priority storeID children linkURL authoritative', authoritative=None) class Tab(object): """ Represent part or all of the layout of a single navigation tab. @ivar name: This tab's name. @type storeID: C{int} @ivar storeID: The Axiom store identifier of the Item to which the user should be directed when this tab is activated. @ivar priority: A float between 0 and 1 indicating the relative ordering of this tab amongst its peers. Higher priorities sort sooner. @ivar children: A tuple of tabs beneath this one.
def testWithoutPositional(self): self._testme(record(x=1, y=2, z=3))