def test_encode_decode(): class Foo(object): def __init__(self, foo): self.foo = foo custombson.register(Foo) class Bar: def __init__(self, bar): self.bar = bar custombson.register(Bar) data = {'foo': Foo(Foo('foo')), 'bar': Bar(Bar('bar'))} son = bson.BSON.encode(data) decoded = son.decode() assert isinstance(decoded['foo'], Foo) assert isinstance(decoded['foo'].foo, Foo) assert decoded['foo'].foo.foo == 'foo' assert isinstance(decoded['bar'], Bar) assert isinstance(decoded['bar'].bar, Bar) assert decoded['bar'].bar.bar == 'bar'
yield cond def hasSubQuery(self): for cond in self._iterconds(): if isinstance(cond, Query): return True return False def hasFulltext(self): for cond in self._iterconds(): if isinstance(cond, Fulltext): return True return False custombson.register(ConditionGroup) class Query(SubQuery): """ Represents a query tree to be sent to the IFC. A query tree is intended to be applied to all instances of a a single TOC. """ def __init__(self, toc, _attrList=(), **conds): """ Initialise the object. Arguments: tocName - the name of the objective TOC _attrList - attributes to fetch from the db conds - initial conds to add Returns: None
# Copyright 2019 Open End AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pytransact.exceptions import BlmError, ClientError from pytransact.custombson import register ERROR_CODES = ['out of stock'] class JSONError(BlmError): pass register(JSONError) def cJSONError(*args, **kw): return ClientError(JSONError(*args, **kw))
if '_st' not in builtins.__dict__: builtins.__dict__['_st'] = lambda x: x class ClientError(Exception): """ Used to wrap another exception so that it is sent to the client in unmodified form. All other exceptions should be replaced with a general exception, and the 'real' exception should be printed on the console. """ # spickle.stateExtension(ClientError) # not spicklable since it's for # internal use custombson.register(ClientError) class LocalisedError(Exception): """ Base error class for all errors that are possible to translate into a localised, human-readable form. """ message = '' # defaults to 'Exceptions.<exception name>' t = {} # Translatable parameters nt = {} # Non-translatable parameters def xlat(self, tfunc, raiseError=False): """ Perform string/value translation.
def validateValueList(self, values): """ Validate that a given list of values conforms to the restriction. Arguments: values - the list of values to validate. Returns: List of failures: [[type, specific, index],] If no errors: [] """ if len(values) < self.min: raise QuantityMinError(len(values), self.min) if self.max is not None and len(values) > self.max: raise QuantityMaxError(len(values), self.max) custombson.register(Quantity) def QuantityMax(max): return Quantity(0, max) def QuantityMin(min): return Quantity(min, None) class Distinct(Restriction): """ This class implements the distinct values restriction for a TOI value. For Mapping type attributes, this restriction applies to keys, not values. """
elif gridfiles == 2: return self.value._id == other.value._id return False def __ne__(self, other): return not self == other def __hash__(self): try: return hash(self.md5) except AttributeError: self.md5 = hashlib.md5(self.getvalue()).hexdigest() return hash(self.md5) custombson.register(BlobVal) class Blob(Attribute): """ This class implements a blob type attribute. """ _validModifiers = (ReorderOnly, ReadOnly, Quantity, Size, Unchangeable) _validQueryOps = (Empty, NotEmpty, Readable) @classmethod def coerceValue(cls, val): """ Coerce a value to the type of the attribute, raise exception on fail.
Returns: A dictionary containing the state-relevant variables. """ rval = {} for v in vars: rval[v] = getattr(self, v) return rval class Parent(Property): """ This class implements the parent type property for a TOI value. """ custombson.register(Parent) class MessageID(Property): """ This class implements the message ID type property for a TOI value. """ custombson.register(MessageID) class Presentation(Property): """ This class implements the presentation type property for a TOI value. """
self.orgAttrs = {} for attrName in toc._attributes: newValue = newAttr.get(attrName) oldValue = oldAttr.get(attrName) if newValue is not None: if oldValue != newValue: self.diffAttrs[attrName] = newValue if oldValue is None: oldValue = getattr(toc, attrName).empty self.orgAttrs[attrName] = oldValue def setAttrDiff(self, toc, toid, oldAttr, newAttr): self.setDiff(toc, toid, oldAttr, {}, newAttr, {}) def setToi(self, toi): new = dict((attr, getattr(toi, attr).value) for attr in toi._modified) self.setAttrDiff(toi.__class__, toi.id[0], toi._orgAttrData, new) def diffsOld(self, oldToi): diffs = {} for name, val in self.orgAttrs.items(): old = getattr(oldToi, name) if val != old: diffs[name] = (old, val) return diffs spickle.stateExtension(DiffTOI) custombson.register(DiffTOI)