How to use value method in Molotov

Best Python code snippet using molotov_python

univ.py

Source:univ.py Github

copy

Full Screen

1# ASN.1 "universal" data types2import operator, sys3from pyasn1.type import base, tag, constraint, namedtype, namedval, tagmap4from pyasn1.codec.ber import eoo5from pyasn1.compat import octets6from pyasn1 import error7# "Simple" ASN.1 types (yet incomplete)8class Integer(base.AbstractSimpleAsn1Item):9 tagSet = baseTagSet = tag.initTagSet(10 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02)11 )12 namedValues = namedval.NamedValues()13 def __init__(self, value=None, tagSet=None, subtypeSpec=None,14 namedValues=None):15 if namedValues is None:16 self.__namedValues = self.namedValues17 else:18 self.__namedValues = namedValues19 base.AbstractSimpleAsn1Item.__init__(20 self, value, tagSet, subtypeSpec21 )22 def __and__(self, value): return self.clone(self._value & value)23 def __rand__(self, value): return self.clone(value & self._value)24 def __or__(self, value): return self.clone(self._value | value)25 def __ror__(self, value): return self.clone(value | self._value)26 def __xor__(self, value): return self.clone(self._value ^ value)27 def __rxor__(self, value): return self.clone(value ^ self._value)28 def __lshift__(self, value): return self.clone(self._value << value)29 def __rshift__(self, value): return self.clone(self._value >> value)30 def __add__(self, value): return self.clone(self._value + value)31 def __radd__(self, value): return self.clone(value + self._value)32 def __sub__(self, value): return self.clone(self._value - value)33 def __rsub__(self, value): return self.clone(value - self._value)34 def __mul__(self, value): return self.clone(self._value * value)35 def __rmul__(self, value): return self.clone(value * self._value)36 def __mod__(self, value): return self.clone(self._value % value)37 def __rmod__(self, value): return self.clone(value % self._value)38 def __pow__(self, value, modulo=None): return self.clone(pow(self._value, value, modulo))39 def __rpow__(self, value): return self.clone(pow(value, self._value))40 if sys.version_info[0] <= 2:41 def __div__(self, value): return self.clone(self._value // value)42 def __rdiv__(self, value): return self.clone(value // self._value)43 else:44 def __truediv__(self, value): return self.clone(self._value / value)45 def __rtruediv__(self, value): return self.clone(value / self._value)46 def __divmod__(self, value): return self.clone(self._value // value)47 def __rdivmod__(self, value): return self.clone(value // self._value)48 __hash__ = base.AbstractSimpleAsn1Item.__hash__49 def __int__(self): return int(self._value)50 if sys.version_info[0] <= 2:51 def __long__(self): return long(self._value)52 def __float__(self): return float(self._value) 53 def __abs__(self): return abs(self._value)54 def __index__(self): return int(self._value)55 def __lt__(self, value): return self._value < value56 def __le__(self, value): return self._value <= value57 def __eq__(self, value): return self._value == value58 def __ne__(self, value): return self._value != value59 def __gt__(self, value): return self._value > value60 def __ge__(self, value): return self._value >= value61 def prettyIn(self, value):62 if not isinstance(value, str):63 try:64 return int(value)65 except:66 raise error.PyAsn1Error(67 'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1])68 )69 r = self.__namedValues.getValue(value)70 if r is not None:71 return r72 try:73 return int(value)74 except:75 raise error.PyAsn1Error(76 'Can\'t coerce %s into integer: %s' % (value, sys.exc_info()[1])77 )78 def prettyOut(self, value):79 r = self.__namedValues.getName(value)80 return r is None and str(value) or repr(r)81 def getNamedValues(self): return self.__namedValues82 def clone(self, value=None, tagSet=None, subtypeSpec=None,83 namedValues=None):84 if value is None and tagSet is None and subtypeSpec is None \85 and namedValues is None:86 return self87 if value is None:88 value = self._value89 if tagSet is None:90 tagSet = self._tagSet91 if subtypeSpec is None:92 subtypeSpec = self._subtypeSpec93 if namedValues is None:94 namedValues = self.__namedValues95 return self.__class__(value, tagSet, subtypeSpec, namedValues)96 def subtype(self, value=None, implicitTag=None, explicitTag=None,97 subtypeSpec=None, namedValues=None):98 if value is None:99 value = self._value100 if implicitTag is not None:101 tagSet = self._tagSet.tagImplicitly(implicitTag)102 elif explicitTag is not None:103 tagSet = self._tagSet.tagExplicitly(explicitTag)104 else:105 tagSet = self._tagSet106 if subtypeSpec is None:107 subtypeSpec = self._subtypeSpec108 else:109 subtypeSpec = subtypeSpec + self._subtypeSpec110 if namedValues is None:111 namedValues = self.__namedValues112 else:113 namedValues = namedValues + self.__namedValues114 return self.__class__(value, tagSet, subtypeSpec, namedValues)115class Boolean(Integer):116 tagSet = baseTagSet = tag.initTagSet(117 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01),118 )119 subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(0,1)120 namedValues = Integer.namedValues.clone(('False', 0), ('True', 1))121class BitString(base.AbstractSimpleAsn1Item):122 tagSet = baseTagSet = tag.initTagSet(123 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03)124 )125 namedValues = namedval.NamedValues()126 def __init__(self, value=None, tagSet=None, subtypeSpec=None,127 namedValues=None):128 if namedValues is None:129 self.__namedValues = self.namedValues130 else:131 self.__namedValues = namedValues132 base.AbstractSimpleAsn1Item.__init__(133 self, value, tagSet, subtypeSpec134 )135 def clone(self, value=None, tagSet=None, subtypeSpec=None,136 namedValues=None):137 if value is None and tagSet is None and subtypeSpec is None \138 and namedValues is None:139 return self140 if value is None:141 value = self._value142 if tagSet is None:143 tagSet = self._tagSet144 if subtypeSpec is None:145 subtypeSpec = self._subtypeSpec146 if namedValues is None:147 namedValues = self.__namedValues148 return self.__class__(value, tagSet, subtypeSpec, namedValues)149 def subtype(self, value=None, implicitTag=None, explicitTag=None,150 subtypeSpec=None, namedValues=None):151 if value is None:152 value = self._value153 if implicitTag is not None:154 tagSet = self._tagSet.tagImplicitly(implicitTag)155 elif explicitTag is not None:156 tagSet = self._tagSet.tagExplicitly(explicitTag)157 else:158 tagSet = self._tagSet159 if subtypeSpec is None:160 subtypeSpec = self._subtypeSpec161 else:162 subtypeSpec = subtypeSpec + self._subtypeSpec163 if namedValues is None:164 namedValues = self.__namedValues165 else:166 namedValues = namedValues + self.__namedValues167 return self.__class__(value, tagSet, subtypeSpec, namedValues)168 def __str__(self): return str(tuple(self))169 # Immutable sequence object protocol170 def __len__(self):171 if self._len is None:172 self._len = len(self._value)173 return self._len174 def __getitem__(self, i):175 if isinstance(i, slice):176 return self.clone(operator.getitem(self._value, i))177 else:178 return self._value[i]179 def __add__(self, value): return self.clone(self._value + value)180 def __radd__(self, value): return self.clone(value + self._value)181 def __mul__(self, value): return self.clone(self._value * value)182 def __rmul__(self, value): return self * value183 def prettyIn(self, value):184 r = []185 if not value:186 return ()187 elif isinstance(value, str):188 if value[0] == '\'':189 if value[-2:] == '\'B':190 for v in value[1:-2]:191 if v == '0':192 r.append(0)193 elif v == '1':194 r.append(1)195 else:196 raise error.PyAsn1Error(197 'Non-binary BIT STRING initializer %s' % (v,)198 )199 return tuple(r)200 elif value[-2:] == '\'H':201 for v in value[1:-2]:202 i = 4203 v = int(v, 16)204 while i:205 i = i - 1206 r.append((v>>i)&0x01)207 return tuple(r)208 else:209 raise error.PyAsn1Error(210 'Bad BIT STRING value notation %s' % (value,)211 ) 212 else:213 for i in value.split(','):214 j = self.__namedValues.getValue(i)215 if j is None:216 raise error.PyAsn1Error(217 'Unknown bit identifier \'%s\'' % (i,)218 )219 if j >= len(r):220 r.extend([0]*(j-len(r)+1))221 r[j] = 1222 return tuple(r)223 elif isinstance(value, (tuple, list)):224 r = tuple(value)225 for b in r:226 if b and b != 1:227 raise error.PyAsn1Error(228 'Non-binary BitString initializer \'%s\'' % (r,)229 )230 return r231 elif isinstance(value, BitString):232 return tuple(value)233 else:234 raise error.PyAsn1Error(235 'Bad BitString initializer type \'%s\'' % (value,)236 )237 def prettyOut(self, value):238 return '\"\'%s\'B\"' % ''.join([str(x) for x in value])239class OctetString(base.AbstractSimpleAsn1Item):240 tagSet = baseTagSet = tag.initTagSet(241 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04)242 )243 defaultBinValue = defaultHexValue = base.noValue244 encoding = 'us-ascii'245 def __init__(self, value=None, tagSet=None, subtypeSpec=None,246 encoding=None, binValue=None, hexValue=None):247 if encoding is None:248 self._encoding = self.encoding249 else:250 self._encoding = encoding251 if binValue is not None:252 value = self.fromBinaryString(binValue)253 if hexValue is not None:254 value = self.fromHexString(hexValue)255 if value is None or value is base.noValue:256 value = self.defaultHexValue257 if value is None or value is base.noValue:258 value = self.defaultBinValue259 self.__intValue = None260 base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec)261 def clone(self, value=None, tagSet=None, subtypeSpec=None,262 encoding=None, binValue=None, hexValue=None):263 if value is None and tagSet is None and subtypeSpec is None and \264 encoding is None and binValue is None and hexValue is None:265 return self266 if value is None and binValue is None and hexValue is None:267 value = self._value268 if tagSet is None:269 tagSet = self._tagSet270 if subtypeSpec is None:271 subtypeSpec = self._subtypeSpec272 if encoding is None:273 encoding = self._encoding274 return self.__class__(275 value, tagSet, subtypeSpec, encoding, binValue, hexValue276 )277 278 if sys.version_info[0] <= 2:279 def prettyIn(self, value):280 if isinstance(value, str):281 return value282 elif isinstance(value, (tuple, list)):283 try:284 return ''.join([ chr(x) for x in value ])285 except ValueError:286 raise error.PyAsn1Error(287 'Bad OctetString initializer \'%s\'' % (value,)288 ) 289 else:290 return str(value)291 else:292 def prettyIn(self, value):293 if isinstance(value, bytes):294 return value295 elif isinstance(value, OctetString):296 return value.asOctets()297 elif isinstance(value, (tuple, list, map)):298 try:299 return bytes(value)300 except ValueError:301 raise error.PyAsn1Error(302 'Bad OctetString initializer \'%s\'' % (value,)303 )304 else:305 try:306 return str(value).encode(self._encoding)307 except UnicodeEncodeError:308 raise error.PyAsn1Error(309 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding)310 )311 312 def fromBinaryString(self, value):313 bitNo = 8; byte = 0; r = ()314 for v in value:315 if bitNo:316 bitNo = bitNo - 1317 else:318 bitNo = 7319 r = r + (byte,)320 byte = 0321 if v == '0':322 v = 0323 elif v == '1':324 v = 1325 else:326 raise error.PyAsn1Error(327 'Non-binary OCTET STRING initializer %s' % (v,)328 )329 byte = byte | (v << bitNo)330 return octets.ints2octs(r + (byte,))331 332 def fromHexString(self, value): 333 r = p = ()334 for v in value:335 if p:336 r = r + (int(p+v, 16),)337 p = ()338 else:339 p = v340 if p:341 r = r + (int(p+'0', 16),)342 return octets.ints2octs(r)343 def prettyOut(self, value):344 if sys.version_info[0] <= 2:345 numbers = tuple([ ord(x) for x in value ])346 else:347 numbers = tuple(value)348 if [ x for x in numbers if x < 32 or x > 126 ]:349 return '0x' + ''.join([ '%.2x' % x for x in numbers ])350 else:351 return str(value)352 def __repr__(self):353 if self._value is base.noValue:354 return self.__class__.__name__ + '()'355 if [ x for x in self.asNumbers() if x < 32 or x > 126 ]:356 return self.__class__.__name__ + '(hexValue=\'' + ''.join([ '%.2x' % x for x in self.asNumbers() ])+'\')'357 else:358 return self.__class__.__name__ + '(\'' + self.prettyOut(self._value) + '\')'359 360 if sys.version_info[0] <= 2:361 def __str__(self): return str(self._value)362 def __unicode__(self):363 return self._value.decode(self._encoding, 'ignore')364 def asOctets(self): return self._value365 def asNumbers(self):366 if self.__intValue is None:367 self.__intValue = tuple([ ord(x) for x in self._value ])368 return self.__intValue369 else:370 def __str__(self): return self._value.decode(self._encoding, 'ignore')371 def __bytes__(self): return self._value372 def asOctets(self): return self._value373 def asNumbers(self):374 if self.__intValue is None:375 self.__intValue = tuple(self._value)376 return self.__intValue377 378 # Immutable sequence object protocol379 380 def __len__(self):381 if self._len is None:382 self._len = len(self._value)383 return self._len384 def __getitem__(self, i):385 if isinstance(i, slice):386 return self.clone(operator.getitem(self._value, i))387 else:388 return self._value[i]389 def __add__(self, value): return self.clone(self._value + self.prettyIn(value))390 def __radd__(self, value): return self.clone(self.prettyIn(value) + self._value)391 def __mul__(self, value): return self.clone(self._value * value)392 def __rmul__(self, value): return self * value393class Null(OctetString):394 defaultValue = ''.encode() # This is tightly constrained395 tagSet = baseTagSet = tag.initTagSet(396 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05)397 )398 subtypeSpec = OctetString.subtypeSpec+constraint.SingleValueConstraint(''.encode())399 400if sys.version_info[0] <= 2:401 intTypes = (int, long)402else:403 intTypes = int404class ObjectIdentifier(base.AbstractSimpleAsn1Item):405 tagSet = baseTagSet = tag.initTagSet(406 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06)407 )408 def __add__(self, other): return self.clone(self._value + other)409 def __radd__(self, other): return self.clone(other + self._value)410 def asTuple(self): return self._value411 412 # Sequence object protocol413 414 def __len__(self):415 if self._len is None:416 self._len = len(self._value)417 return self._len418 def __getitem__(self, i):419 if isinstance(i, slice):420 return self.clone(421 operator.getitem(self._value, i)422 )423 else:424 return self._value[i]425 def __str__(self): return self.prettyPrint()426 427 def index(self, suboid): return self._value.index(suboid)428 def isPrefixOf(self, value):429 """Returns true if argument OID resides deeper in the OID tree"""430 l = len(self)431 if l <= len(value):432 if self._value[:l] == value[:l]:433 return 1434 return 0435 def prettyIn(self, value):436 """Dotted -> tuple of numerics OID converter"""437 if isinstance(value, tuple):438 pass439 elif isinstance(value, ObjectIdentifier):440 return tuple(value) 441 elif isinstance(value, str):442 r = []443 for element in [ x for x in value.split('.') if x != '' ]:444 try:445 r.append(int(element, 0))446 except ValueError:447 raise error.PyAsn1Error(448 'Malformed Object ID %s at %s: %s' %449 (str(value), self.__class__.__name__, sys.exc_info()[1])450 )451 value = tuple(r)452 else:453 try:454 value = tuple(value)455 except TypeError:456 raise error.PyAsn1Error(457 'Malformed Object ID %s at %s: %s' %458 (str(value), self.__class__.__name__,sys.exc_info()[1])459 )460 for x in value:461 if not isinstance(x, intTypes) or x < 0:462 raise error.PyAsn1Error(463 'Invalid sub-ID in %s at %s' % (value, self.__class__.__name__)464 )465 466 return value467 def prettyOut(self, value): return '.'.join([ str(x) for x in value ])468 469class Real(base.AbstractSimpleAsn1Item):470 try:471 _plusInf = float('inf')472 _minusInf = float('-inf')473 _inf = (_plusInf, _minusInf)474 except ValueError:475 # Infinity support is platform and Python dependent476 _plusInf = _minusInf = None477 _inf = ()478 tagSet = baseTagSet = tag.initTagSet(479 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09)480 )481 def __normalizeBase10(self, value):482 m, b, e = value483 while m and m % 10 == 0:484 m = m / 10485 e = e + 1486 return m, b, e487 def prettyIn(self, value):488 if isinstance(value, tuple) and len(value) == 3:489 for d in value:490 if not isinstance(d, intTypes):491 raise error.PyAsn1Error(492 'Lame Real value syntax: %s' % (value,)493 )494 if value[1] not in (2, 10):495 raise error.PyAsn1Error(496 'Prohibited base for Real value: %s' % (value[1],)497 )498 if value[1] == 10:499 value = self.__normalizeBase10(value)500 return value501 elif isinstance(value, intTypes):502 return self.__normalizeBase10((value, 10, 0))503 elif isinstance(value, float):504 if self._inf and value in self._inf:505 return value506 else:507 e = 0508 while int(value) != value:509 value = value * 10510 e = e - 1511 return self.__normalizeBase10((int(value), 10, e))512 elif isinstance(value, Real):513 return tuple(value)514 elif isinstance(value, str): # handle infinite literal515 try:516 return float(value)517 except ValueError:518 pass519 raise error.PyAsn1Error(520 'Bad real value syntax: %s' % (value,)521 )522 523 def prettyOut(self, value):524 if value in self._inf:525 return '\'%s\'' % value526 else:527 return str(value)528 def isPlusInfinity(self): return self._value == self._plusInf529 def isMinusInfinity(self): return self._value == self._minusInf530 def isInfinity(self): return self._value in self._inf531 532 def __str__(self): return str(float(self))533 534 def __add__(self, value): return self.clone(float(self) + value)535 def __radd__(self, value): return self + value536 def __mul__(self, value): return self.clone(float(self) * value)537 def __rmul__(self, value): return self * value538 def __sub__(self, value): return self.clone(float(self) - value)539 def __rsub__(self, value): return self.clone(value - float(self))540 def __mod__(self, value): return self.clone(float(self) % value)541 def __rmod__(self, value): return self.clone(value % float(self))542 def __pow__(self, value, modulo=None): return self.clone(pow(float(self), value, modulo))543 def __rpow__(self, value): return self.clone(pow(value, float(self)))544 if sys.version_info[0] <= 2:545 def __div__(self, value): return self.clone(float(self) / value)546 def __rdiv__(self, value): return self.clone(value / float(self))547 else:548 def __truediv__(self, value): return self.clone(float(self) / value)549 def __rtruediv__(self, value): return self.clone(value / float(self))550 def __divmod__(self, value): return self.clone(float(self) // value)551 def __rdivmod__(self, value): return self.clone(value // float(self))552 def __int__(self): return int(float(self))553 if sys.version_info[0] <= 2:554 def __long__(self): return long(float(self))555 def __float__(self):556 if self._value in self._inf:557 return self._value558 else:559 return float(560 self._value[0] * pow(self._value[1], self._value[2])561 )562 def __abs__(self): return abs(float(self))563 def __lt__(self, value): return float(self) < value564 def __le__(self, value): return float(self) <= value565 def __eq__(self, value): return float(self) == value566 def __ne__(self, value): return float(self) != value567 def __gt__(self, value): return float(self) > value568 def __ge__(self, value): return float(self) >= value569 if sys.version_info[0] <= 2:570 def __nonzero__(self): return bool(float(self))571 else:572 def __bool__(self): return bool(float(self))573 __hash__ = base.AbstractSimpleAsn1Item.__hash__574 def __getitem__(self, idx):575 if self._value in self._inf:576 raise error.PyAsn1Error('Invalid infinite value operation')577 else:578 return self._value[idx]579 580class Enumerated(Integer):581 tagSet = baseTagSet = tag.initTagSet(582 tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A)583 )584# "Structured" ASN.1 types585class SetOf(base.AbstractConstructedAsn1Item):586 componentType = None587 tagSet = baseTagSet = tag.initTagSet(588 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)589 )590 typeId = 1591 def _cloneComponentValues(self, myClone, cloneValueFlag):592 idx = 0; l = len(self._componentValues)593 while idx < l:594 c = self._componentValues[idx]595 if c is not None:596 if isinstance(c, base.AbstractConstructedAsn1Item):597 myClone.setComponentByPosition(598 idx, c.clone(cloneValueFlag=cloneValueFlag)599 )600 else:601 myClone.setComponentByPosition(idx, c.clone())602 idx = idx + 1603 604 def _verifyComponent(self, idx, value):605 if self._componentType is not None and \606 not self._componentType.isSuperTypeOf(value):607 raise error.PyAsn1Error('Component type error %s' % (value,))608 def getComponentByPosition(self, idx): return self._componentValues[idx]609 def setComponentByPosition(self, idx, value=None, verifyConstraints=True):610 l = len(self._componentValues)611 if idx >= l:612 self._componentValues = self._componentValues + (idx-l+1)*[None]613 if value is None:614 if self._componentValues[idx] is None:615 if self._componentType is None:616 raise error.PyAsn1Error('Component type not defined')617 self._componentValues[idx] = self._componentType.clone()618 self._componentValuesSet = self._componentValuesSet + 1619 return self620 elif not isinstance(value, base.Asn1Item):621 if self._componentType is None:622 raise error.PyAsn1Error('Component type not defined')623 if isinstance(self._componentType, base.AbstractSimpleAsn1Item):624 value = self._componentType.clone(value=value)625 else:626 raise error.PyAsn1Error('Instance value required')627 if verifyConstraints:628 if self._componentType is not None:629 self._verifyComponent(idx, value)630 self._verifySubtypeSpec(value, idx) 631 if self._componentValues[idx] is None:632 self._componentValuesSet = self._componentValuesSet + 1633 self._componentValues[idx] = value634 return self635 def getComponentTagMap(self):636 if self._componentType is not None:637 return self._componentType.getTagMap()638 def prettyPrint(self, scope=0):639 scope = scope + 1640 r = self.__class__.__name__ + ':\n' 641 for idx in range(len(self._componentValues)):642 r = r + ' '*scope643 if self._componentValues[idx] is None:644 r = r + '<empty>'645 else:646 r = r + self._componentValues[idx].prettyPrint(scope)647 return r648class SequenceOf(SetOf):649 tagSet = baseTagSet = tag.initTagSet(650 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)651 )652 typeId = 2653class SequenceAndSetBase(base.AbstractConstructedAsn1Item):654 componentType = namedtype.NamedTypes()655 def __init__(self, componentType=None, tagSet=None,656 subtypeSpec=None, sizeSpec=None):657 base.AbstractConstructedAsn1Item.__init__(658 self, componentType, tagSet, subtypeSpec, sizeSpec659 )660 if self._componentType is None:661 self._componentTypeLen = 0662 else:663 self._componentTypeLen = len(self._componentType)664 def __getitem__(self, idx):665 if isinstance(idx, str):666 return self.getComponentByName(idx)667 else:668 return base.AbstractConstructedAsn1Item.__getitem__(self, idx)669 def __setitem__(self, idx, value):670 if isinstance(idx, str):671 self.setComponentByName(idx, value)672 else:673 base.AbstractConstructedAsn1Item.__setitem__(self, idx, value)674 675 def _cloneComponentValues(self, myClone, cloneValueFlag):676 idx = 0; l = len(self._componentValues)677 while idx < l:678 c = self._componentValues[idx]679 if c is not None:680 if isinstance(c, base.AbstractConstructedAsn1Item):681 myClone.setComponentByPosition(682 idx, c.clone(cloneValueFlag=cloneValueFlag)683 )684 else:685 myClone.setComponentByPosition(idx, c.clone())686 idx = idx + 1687 def _verifyComponent(self, idx, value):688 if idx >= self._componentTypeLen:689 raise error.PyAsn1Error(690 'Component type error out of range'691 )692 t = self._componentType[idx].getType()693 if not t.isSuperTypeOf(value):694 raise error.PyAsn1Error('Component type error %r vs %r' % (t, value))695 def getComponentByName(self, name):696 return self.getComponentByPosition(697 self._componentType.getPositionByName(name)698 )699 def setComponentByName(self, name, value=None, verifyConstraints=True):700 return self.setComponentByPosition(701 self._componentType.getPositionByName(name), value,702 verifyConstraints703 )704 def getComponentByPosition(self, idx):705 try:706 return self._componentValues[idx]707 except IndexError:708 if idx < self._componentTypeLen:709 return710 raise711 def setComponentByPosition(self, idx, value=None, verifyConstraints=True):712 l = len(self._componentValues)713 if idx >= l:714 self._componentValues = self._componentValues + (idx-l+1)*[None]715 if value is None:716 if self._componentValues[idx] is None:717 self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone()718 self._componentValuesSet = self._componentValuesSet + 1719 return self720 elif not isinstance(value, base.Asn1Item):721 t = self._componentType.getTypeByPosition(idx)722 if isinstance(t, base.AbstractSimpleAsn1Item):723 value = t.clone(value=value)724 else:725 raise error.PyAsn1Error('Instance value required')726 if verifyConstraints:727 if self._componentTypeLen:728 self._verifyComponent(idx, value)729 self._verifySubtypeSpec(value, idx) 730 if self._componentValues[idx] is None:731 self._componentValuesSet = self._componentValuesSet + 1732 self._componentValues[idx] = value733 return self734 def getNameByPosition(self, idx):735 if self._componentTypeLen:736 return self._componentType.getNameByPosition(idx)737 def getDefaultComponentByPosition(self, idx):738 if self._componentTypeLen and self._componentType[idx].isDefaulted:739 return self._componentType[idx].getType()740 def getComponentType(self):741 if self._componentTypeLen:742 return self._componentType743 744 def setDefaultComponents(self):745 if self._componentTypeLen == self._componentValuesSet:746 return747 idx = self._componentTypeLen748 while idx:749 idx = idx - 1750 if self._componentType[idx].isDefaulted:751 if self.getComponentByPosition(idx) is None:752 self.setComponentByPosition(idx)753 elif not self._componentType[idx].isOptional:754 if self.getComponentByPosition(idx) is None:755 raise error.PyAsn1Error(756 'Uninitialized component #%s at %r' % (idx, self)757 )758 def prettyPrint(self, scope=0):759 scope = scope + 1760 r = self.__class__.__name__ + ':\n'761 for idx in range(len(self._componentValues)):762 if self._componentValues[idx] is not None:763 r = r + ' '*scope764 componentType = self.getComponentType()765 if componentType is None:766 r = r + '<no-name>'767 else:768 r = r + componentType.getNameByPosition(idx)769 r = '%s=%s\n' % (770 r, self._componentValues[idx].prettyPrint(scope)771 )772 return r773class Sequence(SequenceAndSetBase):774 tagSet = baseTagSet = tag.initTagSet(775 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)776 )777 typeId = 3778 def getComponentTagMapNearPosition(self, idx):779 if self._componentType:780 return self._componentType.getTagMapNearPosition(idx)781 782 def getComponentPositionNearType(self, tagSet, idx):783 if self._componentType:784 return self._componentType.getPositionNearType(tagSet, idx)785 else:786 return idx787 788class Set(SequenceAndSetBase):789 tagSet = baseTagSet = tag.initTagSet(790 tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)791 )792 typeId = 4793 def getComponent(self, innerFlag=0): return self794 795 def getComponentByType(self, tagSet, innerFlag=0):796 c = self.getComponentByPosition(797 self._componentType.getPositionByType(tagSet)798 )799 if innerFlag and isinstance(c, Set):800 # get inner component by inner tagSet801 return c.getComponent(1)802 else:803 # get outer component by inner tagSet804 return c805 806 def setComponentByType(self, tagSet, value=None, innerFlag=0,807 verifyConstraints=True):808 idx = self._componentType.getPositionByType(tagSet)809 t = self._componentType.getTypeByPosition(idx)810 if innerFlag: # set inner component by inner tagSet811 if t.getTagSet():812 return self.setComponentByPosition(813 idx, value, verifyConstraints814 )815 else:816 t = self.setComponentByPosition(idx).getComponentByPosition(idx)817 return t.setComponentByType(818 tagSet, value, innerFlag, verifyConstraints819 )820 else: # set outer component by inner tagSet821 return self.setComponentByPosition(822 idx, value, verifyConstraints823 )824 825 def getComponentTagMap(self):826 if self._componentType:827 return self._componentType.getTagMap(True)828 def getComponentPositionByType(self, tagSet):829 if self._componentType:830 return self._componentType.getPositionByType(tagSet)831class Choice(Set):832 tagSet = baseTagSet = tag.TagSet() # untagged833 sizeSpec = constraint.ConstraintsIntersection(834 constraint.ValueSizeConstraint(1, 1)835 )836 typeId = 5837 _currentIdx = None838 def __eq__(self, other):839 if self._componentValues:840 return self._componentValues[self._currentIdx] == other841 return NotImplemented842 def __ne__(self, other):843 if self._componentValues:844 return self._componentValues[self._currentIdx] != other845 return NotImplemented846 def __lt__(self, other):847 if self._componentValues:848 return self._componentValues[self._currentIdx] < other849 return NotImplemented850 def __le__(self, other):851 if self._componentValues:852 return self._componentValues[self._currentIdx] <= other853 return NotImplemented854 def __gt__(self, other):855 if self._componentValues:856 return self._componentValues[self._currentIdx] > other857 return NotImplemented858 def __ge__(self, other):859 if self._componentValues:860 return self._componentValues[self._currentIdx] >= other861 return NotImplemented862 if sys.version_info[0] <= 2:863 def __nonzero__(self): return bool(self._componentValues)864 else:865 def __bool__(self): return bool(self._componentValues)866 def __len__(self): return self._currentIdx is not None and 1 or 0867 868 def verifySizeSpec(self):869 if self._currentIdx is None:870 raise error.PyAsn1Error('Component not chosen')871 else:872 self._sizeSpec(' ')873 def _cloneComponentValues(self, myClone, cloneValueFlag):874 try:875 c = self.getComponent()876 except error.PyAsn1Error:877 pass878 else:879 if isinstance(c, Choice):880 tagSet = c.getEffectiveTagSet()881 else:882 tagSet = c.getTagSet()883 if isinstance(c, base.AbstractConstructedAsn1Item):884 myClone.setComponentByType(885 tagSet, c.clone(cloneValueFlag=cloneValueFlag)886 )887 else:888 myClone.setComponentByType(tagSet, c.clone())889 def setComponentByPosition(self, idx, value=None, verifyConstraints=True):890 l = len(self._componentValues)891 if idx >= l:892 self._componentValues = self._componentValues + (idx-l+1)*[None]893 if self._currentIdx is not None:894 self._componentValues[self._currentIdx] = None895 if value is None:896 if self._componentValues[idx] is None:897 self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone()898 self._componentValuesSet = 1899 self._currentIdx = idx900 return self901 elif not isinstance(value, base.Asn1Item):902 value = self._componentType.getTypeByPosition(idx).clone(903 value=value904 )905 if verifyConstraints:906 if self._componentTypeLen:907 self._verifyComponent(idx, value)908 self._verifySubtypeSpec(value, idx) 909 self._componentValues[idx] = value910 self._currentIdx = idx911 self._componentValuesSet = 1912 return self913 def getMinTagSet(self):914 if self._tagSet:915 return self._tagSet916 else:917 return self._componentType.genMinTagSet()918 def getEffectiveTagSet(self):919 if self._tagSet:920 return self._tagSet921 else:922 c = self.getComponent()923 if isinstance(c, Choice):924 return c.getEffectiveTagSet()925 else:926 return c.getTagSet()927 def getTagMap(self):928 if self._tagSet:929 return Set.getTagMap(self)930 else:931 return Set.getComponentTagMap(self)932 def getComponent(self, innerFlag=0):933 if self._currentIdx is None:934 raise error.PyAsn1Error('Component not chosen')935 else:936 c = self._componentValues[self._currentIdx]937 if innerFlag and isinstance(c, Choice):938 return c.getComponent(innerFlag)939 else:940 return c941 def getName(self, innerFlag=0):942 if self._currentIdx is None:943 raise error.PyAsn1Error('Component not chosen')944 else:945 if innerFlag:946 c = self._componentValues[self._currentIdx]947 if isinstance(c, Choice):948 return c.getName(innerFlag)949 return self._componentType.getNameByPosition(self._currentIdx)950 def setDefaultComponents(self): pass951class Any(OctetString):952 tagSet = baseTagSet = tag.TagSet() # untagged953 typeId = 6954 def getTagMap(self):955 return tagmap.TagMap(956 { self.getTagSet(): self },957 { eoo.endOfOctets.getTagSet(): eoo.endOfOctets },958 self959 )960# XXX...

Full Screen

Full Screen

test_selectdatewidget.py

Source:test_selectdatewidget.py Github

copy

Full Screen

...442 self.assertEqual(443 w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date'),444 '13-08-1899',445 )446 def test_format_value(self):447 valid_formats = [448 '2000-1-1', '2000-10-15', '2000-01-01',449 '2000-01-0', '2000-0-01', '2000-0-0',450 '0-01-01', '0-01-0', '0-0-01', '0-0-0',451 ]452 for value in valid_formats:453 year, month, day = (int(x) for x in value.split('-'))454 with self.subTest(value=value):455 self.assertEqual(self.widget.format_value(value), {'day': day, 'month': month, 'year': year})456 invalid_formats = [457 '2000-01-001', '2000-001-01', '2-01-01', '20-01-01', '200-01-01',458 '20000-01-01',459 ]460 for value in invalid_formats:461 with self.subTest(value=value):462 self.assertEqual(self.widget.format_value(value), {'day': None, 'month': None, 'year': None})463 def test_value_omitted_from_data(self):464 self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), True)465 self.assertIs(self.widget.value_omitted_from_data({'field_month': '12'}, {}, 'field'), False)466 self.assertIs(self.widget.value_omitted_from_data({'field_year': '2000'}, {}, 'field'), False)467 self.assertIs(self.widget.value_omitted_from_data({'field_day': '1'}, {}, 'field'), False)468 data = {'field_day': '1', 'field_month': '12', 'field_year': '2000'}469 self.assertIs(self.widget.value_omitted_from_data(data, {}, 'field'), False)470 @override_settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True)471 def test_years_rendered_without_separator(self):472 widget = SelectDateWidget(years=(2007,))473 self.check_html(widget, 'mydate', '', html=(474 """475 <select name="mydate_month" id="id_mydate_month">476 <option value="0">---</option>...

Full Screen

Full Screen

module_xml_grabber.py

Source:module_xml_grabber.py Github

copy

Full Screen

...24 if clean_files[value]['Division'] == 'IPM':25 clean_files[value]['Division'] = 'Industrial IPM'26 if clean_files[value]['Division'] == 'MOS_MOD':27 clean_files[value]['Division'] = 'MOSFET Modules'28 # clean_files = rename_value(clean_files,value,'Division','Old')29 clean_files = rename_section(clean_files, value, 'Vcc', 'vcc_value')30 clean_files = rename_section(clean_files, value, 'ThermalContactResistance', 'Module RTH DC')31 clean_files = rename_section(clean_files, value, 'RatedVoltage', 'Nameplate Voltage')32 clean_files = rename_section(clean_files, value, 'RatedCurrent', 'Nameplate Current')33 clean_files = rename_section(clean_files, value, 'BaseData', 'base_data_unknown')34 clean_files = rename_section(clean_files, value, 'Deprecation', 'deprecation_unknown')35 clean_files = rename_section(clean_files, value, 'ElementNumber', 'number_of_switches')36 clean_files = rename_section(clean_files, value, 'InterpolationDegree', 'interp_degree')37 clean_files = rename_section(clean_files, value, 'Lower', 'lower_unknown')38 clean_files = rename_section(clean_files, value, 'ModDate', 'mod_date')39 clean_files = rename_section(clean_files, value, 'ModUser', 'mod_user')40 clean_files = rename_section(clean_files, value, 'PathEn', 'path_en')41 clean_files = rename_section(clean_files, value, 'PathJa', 'path_ja')42 # clean_files = rename_section(clean_files, value, 'Priority', 'priority_unknown')...

Full Screen

Full Screen

fields.py

Source:fields.py Github

copy

Full Screen

1# Copyright 2013 Red Hat, Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License"); you may4# not use this file except in compliance with the License. You may obtain5# a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12# License for the specific language governing permissions and limitations13# under the License.14import abc15import datetime16import iso860117import netaddr18import six19from nova.i18n import _20from nova.network import model as network_model21from nova.openstack.common import timeutils22class KeyTypeError(TypeError):23 def __init__(self, expected, value):24 super(KeyTypeError, self).__init__(25 _('Key %(key)s must be of type %(expected)s not %(actual)s'26 ) % {'key': repr(value),27 'expected': expected.__name__,28 'actual': value.__class__.__name__,29 })30class ElementTypeError(TypeError):31 def __init__(self, expected, key, value):32 super(ElementTypeError, self).__init__(33 _('Element %(key)s:%(val)s must be of type %(expected)s'34 ' not %(actual)s'35 ) % {'key': key,36 'val': repr(value),37 'expected': expected,38 'actual': value.__class__.__name__,39 })40class AbstractFieldType(six.with_metaclass(abc.ABCMeta, object)):41 @abc.abstractmethod42 def coerce(self, obj, attr, value):43 """This is called to coerce (if possible) a value on assignment.44 This method should convert the value given into the designated type,45 or throw an exception if this is not possible.46 :param:obj: The NovaObject on which an attribute is being set47 :param:attr: The name of the attribute being set48 :param:value: The value being set49 :returns: A properly-typed value50 """51 pass52 @abc.abstractmethod53 def from_primitive(self, obj, attr, value):54 """This is called to deserialize a value.55 This method should deserialize a value from the form given by56 to_primitive() to the designated type.57 :param:obj: The NovaObject on which the value is to be set58 :param:attr: The name of the attribute which will hold the value59 :param:value: The serialized form of the value60 :returns: The natural form of the value61 """62 pass63 @abc.abstractmethod64 def to_primitive(self, obj, attr, value):65 """This is called to serialize a value.66 This method should serialize a value to the form expected by67 from_primitive().68 :param:obj: The NovaObject on which the value is set69 :param:attr: The name of the attribute holding the value70 :param:value: The natural form of the value71 :returns: The serialized form of the value72 """73 pass74 @abc.abstractmethod75 def describe(self):76 """Returns a string describing the type of the field."""77 pass78 @abc.abstractmethod79 def stringify(self, value):80 """Returns a short stringified version of a value."""81 pass82class FieldType(AbstractFieldType):83 @staticmethod84 def coerce(obj, attr, value):85 return value86 @staticmethod87 def from_primitive(obj, attr, value):88 return value89 @staticmethod90 def to_primitive(obj, attr, value):91 return value92 def describe(self):93 return self.__class__.__name__94 def stringify(self, value):95 return str(value)96class UnspecifiedDefault(object):97 pass98class Field(object):99 def __init__(self, field_type, nullable=False,100 default=UnspecifiedDefault, read_only=False):101 self._type = field_type102 self._nullable = nullable103 self._default = default104 self._read_only = read_only105 def __repr__(self):106 args = {107 'nullable': self._nullable,108 'default': self._default,109 }110 return '%s(%s)' % (self._type.__class__.__name__,111 ','.join(['%s=%s' % (k, v)112 for k, v in args.items()]))113 @property114 def nullable(self):115 return self._nullable116 @property117 def default(self):118 return self._default119 @property120 def read_only(self):121 return self._read_only122 def _null(self, obj, attr):123 if self.nullable:124 return None125 elif self._default != UnspecifiedDefault:126 # NOTE(danms): We coerce the default value each time the field127 # is set to None as our contract states that we'll let the type128 # examine the object and attribute name at that time.129 return self._type.coerce(obj, attr, self._default)130 else:131 raise ValueError(_("Field `%s' cannot be None") % attr)132 def coerce(self, obj, attr, value):133 """Coerce a value to a suitable type.134 This is called any time you set a value on an object, like:135 foo.myint = 1136 and is responsible for making sure that the value (1 here) is of137 the proper type, or can be sanely converted.138 This also handles the potentially nullable or defaultable139 nature of the field and calls the coerce() method on a140 FieldType to actually do the coercion.141 :param:obj: The object being acted upon142 :param:attr: The name of the attribute/field being set143 :param:value: The value being set144 :returns: The properly-typed value145 """146 if value is None:147 return self._null(obj, attr)148 else:149 return self._type.coerce(obj, attr, value)150 def from_primitive(self, obj, attr, value):151 """Deserialize a value from primitive form.152 This is responsible for deserializing a value from primitive153 into regular form. It calls the from_primitive() method on a154 FieldType to do the actual deserialization.155 :param:obj: The object being acted upon156 :param:attr: The name of the attribute/field being deserialized157 :param:value: The value to be deserialized158 :returns: The deserialized value159 """160 if value is None:161 return None162 else:163 return self._type.from_primitive(obj, attr, value)164 def to_primitive(self, obj, attr, value):165 """Serialize a value to primitive form.166 This is responsible for serializing a value to primitive167 form. It calls to_primitive() on a FieldType to do the actual168 serialization.169 :param:obj: The object being acted upon170 :param:attr: The name of the attribute/field being serialized171 :param:value: The value to be serialized172 :returns: The serialized value173 """174 if value is None:175 return None176 else:177 return self._type.to_primitive(obj, attr, value)178 def describe(self):179 """Return a short string describing the type of this field."""180 name = self._type.describe()181 prefix = self.nullable and 'Nullable' or ''182 return prefix + name183 def stringify(self, value):184 if value is None:185 return 'None'186 else:187 return self._type.stringify(value)188class String(FieldType):189 @staticmethod190 def coerce(obj, attr, value):191 # FIXME(danms): We should really try to avoid the need to do this192 if isinstance(value, (six.string_types, int, long, float,193 datetime.datetime)):194 return unicode(value)195 else:196 raise ValueError(_('A string is required here, not %s') %197 value.__class__.__name__)198 @staticmethod199 def stringify(value):200 return '\'%s\'' % value201class UUID(FieldType):202 @staticmethod203 def coerce(obj, attr, value):204 # FIXME(danms): We should actually verify the UUIDness here205 return str(value)206class Integer(FieldType):207 @staticmethod208 def coerce(obj, attr, value):209 return int(value)210class Float(FieldType):211 def coerce(self, obj, attr, value):212 return float(value)213class Boolean(FieldType):214 @staticmethod215 def coerce(obj, attr, value):216 return bool(value)217class DateTime(FieldType):218 @staticmethod219 def coerce(obj, attr, value):220 if isinstance(value, six.string_types):221 # NOTE(danms): Being tolerant of isotime strings here will help us222 # during our objects transition223 value = timeutils.parse_isotime(value)224 elif not isinstance(value, datetime.datetime):225 raise ValueError(_('A datetime.datetime is required here'))226 if value.utcoffset() is None:227 # NOTE(danms): Legacy objects from sqlalchemy are stored in UTC,228 # but are returned without a timezone attached.229 # As a transitional aid, assume a tz-naive object is in UTC.230 value = value.replace(tzinfo=iso8601.iso8601.Utc())231 return value232 def from_primitive(self, obj, attr, value):233 return self.coerce(obj, attr, timeutils.parse_isotime(value))234 @staticmethod235 def to_primitive(obj, attr, value):236 return timeutils.isotime(value)237 @staticmethod238 def stringify(value):239 return timeutils.isotime(value)240class IPAddress(FieldType):241 @staticmethod242 def coerce(obj, attr, value):243 try:244 return netaddr.IPAddress(value)245 except netaddr.AddrFormatError as e:246 raise ValueError(six.text_type(e))247 def from_primitive(self, obj, attr, value):248 return self.coerce(obj, attr, value)249 @staticmethod250 def to_primitive(obj, attr, value):251 return str(value)252class IPV4Address(IPAddress):253 @staticmethod254 def coerce(obj, attr, value):255 result = IPAddress.coerce(obj, attr, value)256 if result.version != 4:257 raise ValueError(_('Network "%s" is not valid') % value)258 return result259class IPV6Address(IPAddress):260 @staticmethod261 def coerce(obj, attr, value):262 result = IPAddress.coerce(obj, attr, value)263 if result.version != 6:264 raise ValueError(_('Network "%s" is not valid') % value)265 return result266class IPV4AndV6Address(IPAddress):267 @staticmethod268 def coerce(obj, attr, value):269 result = IPAddress.coerce(obj, attr, value)270 if result.version != 4 and result.version != 6:271 raise ValueError(_('Network "%s" is not valid') % value)272 return result273class IPNetwork(IPAddress):274 @staticmethod275 def coerce(obj, attr, value):276 try:277 return netaddr.IPNetwork(value)278 except netaddr.AddrFormatError as e:279 raise ValueError(six.text_type(e))280class IPV4Network(IPNetwork):281 @staticmethod282 def coerce(obj, attr, value):283 try:284 return netaddr.IPNetwork(value, version=4)285 except netaddr.AddrFormatError as e:286 raise ValueError(six.text_type(e))287class IPV6Network(IPNetwork):288 @staticmethod289 def coerce(obj, attr, value):290 try:291 return netaddr.IPNetwork(value, version=6)292 except netaddr.AddrFormatError as e:293 raise ValueError(six.text_type(e))294class CompoundFieldType(FieldType):295 def __init__(self, element_type, **field_args):296 self._element_type = Field(element_type, **field_args)297class List(CompoundFieldType):298 def coerce(self, obj, attr, value):299 if not isinstance(value, list):300 raise ValueError(_('A list is required here'))301 for index, element in enumerate(list(value)):302 value[index] = self._element_type.coerce(303 obj, '%s[%i]' % (attr, index), element)304 return value305 def to_primitive(self, obj, attr, value):306 return [self._element_type.to_primitive(obj, attr, x) for x in value]307 def from_primitive(self, obj, attr, value):308 return [self._element_type.from_primitive(obj, attr, x) for x in value]309 def stringify(self, value):310 return '[%s]' % (311 ','.join([self._element_type.stringify(x) for x in value]))312class Dict(CompoundFieldType):313 def coerce(self, obj, attr, value):314 if not isinstance(value, dict):315 raise ValueError(_('A dict is required here'))316 for key, element in value.items():317 if not isinstance(key, six.string_types):318 # NOTE(guohliu) In order to keep compatibility with python3319 # we need to use six.string_types rather than basestring here,320 # since six.string_types is a tuple, so we need to pass the321 # real type in.322 raise KeyTypeError(six.string_types[0], key)323 value[key] = self._element_type.coerce(324 obj, '%s["%s"]' % (attr, key), element)325 return value326 def to_primitive(self, obj, attr, value):327 primitive = {}328 for key, element in value.items():329 primitive[key] = self._element_type.to_primitive(330 obj, '%s["%s"]' % (attr, key), element)331 return primitive332 def from_primitive(self, obj, attr, value):333 concrete = {}334 for key, element in value.items():335 concrete[key] = self._element_type.from_primitive(336 obj, '%s["%s"]' % (attr, key), element)337 return concrete338 def stringify(self, value):339 return '{%s}' % (340 ','.join(['%s=%s' % (key, self._element_type.stringify(val))341 for key, val in sorted(value.items())]))342class Set(CompoundFieldType):343 def coerce(self, obj, attr, value):344 if not isinstance(value, set):345 raise ValueError(_('A set is required here'))346 coerced = set()347 for element in value:348 coerced.add(self._element_type.coerce(349 obj, '%s["%s"]' % (attr, element), element))350 return coerced351 def to_primitive(self, obj, attr, value):352 return tuple(353 self._element_type.to_primitive(obj, attr, x) for x in value)354 def from_primitive(self, obj, attr, value):355 return set([self._element_type.from_primitive(obj, attr, x)356 for x in value])357 def stringify(self, value):358 return 'set([%s])' % (359 ','.join([self._element_type.stringify(x) for x in value]))360class Object(FieldType):361 def __init__(self, obj_name, **kwargs):362 self._obj_name = obj_name363 super(Object, self).__init__(**kwargs)364 def coerce(self, obj, attr, value):365 try:366 obj_name = value.obj_name()367 except AttributeError:368 obj_name = ""369 if obj_name != self._obj_name:370 raise ValueError(_('An object of type %s is required here') %371 self._obj_name)372 return value373 @staticmethod374 def to_primitive(obj, attr, value):375 return value.obj_to_primitive()376 @staticmethod377 def from_primitive(obj, attr, value):378 # FIXME(danms): Avoid circular import from base.py379 from nova.objects import base as obj_base380 # NOTE (ndipanov): If they already got hydrated by the serializer, just381 # pass them back unchanged382 if isinstance(value, obj_base.NovaObject):383 return value384 return obj_base.NovaObject.obj_from_primitive(value, obj._context)385 def describe(self):386 return "Object<%s>" % self._obj_name387 def stringify(self, value):388 if 'uuid' in value.fields:389 ident = '(%s)' % (value.obj_attr_is_set('uuid') and value.uuid or390 'UNKNOWN')391 elif 'id' in value.fields:392 ident = '(%s)' % (value.obj_attr_is_set('id') and value.id or393 'UNKNOWN')394 else:395 ident = ''396 return '%s%s' % (self._obj_name, ident)397class NetworkModel(FieldType):398 @staticmethod399 def coerce(obj, attr, value):400 if isinstance(value, network_model.NetworkInfo):401 return value402 elif isinstance(value, six.string_types):403 # Hmm, do we need this?404 return network_model.NetworkInfo.hydrate(value)405 else:406 raise ValueError(_('A NetworkModel is required here'))407 @staticmethod408 def to_primitive(obj, attr, value):409 return value.json()410 @staticmethod411 def from_primitive(obj, attr, value):412 return network_model.NetworkInfo.hydrate(value)413 def stringify(self, value):414 return 'NetworkModel(%s)' % (415 ','.join([str(vif['id']) for vif in value]))416class AutoTypedField(Field):417 AUTO_TYPE = None418 def __init__(self, **kwargs):419 super(AutoTypedField, self).__init__(self.AUTO_TYPE, **kwargs)420class StringField(AutoTypedField):421 AUTO_TYPE = String()422class UUIDField(AutoTypedField):423 AUTO_TYPE = UUID()424class IntegerField(AutoTypedField):425 AUTO_TYPE = Integer()426class FloatField(AutoTypedField):427 AUTO_TYPE = Float()428class BooleanField(AutoTypedField):429 AUTO_TYPE = Boolean()430class DateTimeField(AutoTypedField):431 AUTO_TYPE = DateTime()432class IPAddressField(AutoTypedField):433 AUTO_TYPE = IPAddress()434class IPV4AddressField(AutoTypedField):435 AUTO_TYPE = IPV4Address()436class IPV6AddressField(AutoTypedField):437 AUTO_TYPE = IPV6Address()438class IPV4AndV6AddressField(AutoTypedField):439 AUTO_TYPE = IPV4AndV6Address()440class IPNetworkField(AutoTypedField):441 AUTO_TYPE = IPNetwork()442class IPV4NetworkField(AutoTypedField):443 AUTO_TYPE = IPV4Network()444class IPV6NetworkField(AutoTypedField):445 AUTO_TYPE = IPV6Network()446class DictOfStringsField(AutoTypedField):447 AUTO_TYPE = Dict(String())448class DictOfNullableStringsField(AutoTypedField):449 AUTO_TYPE = Dict(String(), nullable=True)450class ListOfStringsField(AutoTypedField):451 AUTO_TYPE = List(String())452class SetOfIntegersField(AutoTypedField):453 AUTO_TYPE = Set(Integer())454class ListOfDictOfNullableStringsField(AutoTypedField):455 AUTO_TYPE = List(Dict(String(), nullable=True))456class ObjectField(AutoTypedField):457 def __init__(self, objtype, **kwargs):458 self.AUTO_TYPE = Object(objtype)459 super(ObjectField, self).__init__(**kwargs)460class ListOfObjectsField(AutoTypedField):461 def __init__(self, objtype, **kwargs):462 self.AUTO_TYPE = List(Object(objtype))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Molotov automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful