• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#
2# This file is part of pyasn1 software.
3#
4# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
5# License: http://snmplabs.com/pyasn1/license.html
6#
7import math
8import pickle
9import sys
10
11try:
12    import unittest2 as unittest
13
14except ImportError:
15    import unittest
16
17from tests.base import BaseTestCase
18
19from pyasn1.type import univ
20from pyasn1.type import tag
21from pyasn1.type import constraint
22from pyasn1.type import namedtype
23from pyasn1.type import namedval
24from pyasn1.type import error
25from pyasn1.compat.octets import str2octs, ints2octs, octs2ints, octs2str
26from pyasn1.error import PyAsn1Error
27from pyasn1.error import PyAsn1UnicodeEncodeError, PyAsn1UnicodeDecodeError
28
29
30class NoValueTestCase(BaseTestCase):
31    def testSingleton(self):
32        assert univ.NoValue() is univ.NoValue(), 'NoValue is not a singleton'
33
34    def testRepr(self):
35        try:
36            repr(univ.noValue)
37
38        except PyAsn1Error:
39            assert False, 'repr() on NoValue object fails'
40
41    def testIsInstance(self):
42        try:
43            assert isinstance(univ.noValue, univ.NoValue), 'isinstance() on NoValue() object fails'
44
45        except PyAsn1Error:
46            assert False, 'isinstance() on NoValue object fails'
47
48    def testStr(self):
49        try:
50            str(univ.noValue)
51
52        except PyAsn1Error:
53            pass
54
55        else:
56            assert False, 'str() works for NoValue object'
57
58    def testLen(self):
59        try:
60            len(univ.noValue)
61
62        except PyAsn1Error:
63            pass
64
65        else:
66            assert False, 'len() works for NoValue object'
67
68    def testCmp(self):
69        try:
70            univ.noValue == 1
71
72        except PyAsn1Error:
73            pass
74
75        else:
76            assert False, 'comparison works for NoValue object'
77
78    def testSubs(self):
79        try:
80            univ.noValue[0]
81
82        except PyAsn1Error:
83            pass
84
85        else:
86            assert False, '__getitem__() works for NoValue object'
87
88    def testKey(self):
89        try:
90            univ.noValue['key']
91
92        except PyAsn1Error:
93            pass
94
95        else:
96            assert False, '__getitem__() works for NoValue object'
97
98    def testKeyAssignment(self):
99        try:
100            univ.noValue['key'] = 123
101
102        except PyAsn1Error:
103            pass
104
105        else:
106            assert False, '__setitem__() works for NoValue object'
107
108    def testInt(self):
109        try:
110            int(univ.noValue)
111
112        except PyAsn1Error:
113            pass
114
115        else:
116            assert False, 'integer conversion works for NoValue object'
117
118    def testAdd(self):
119        try:
120            univ.noValue + univ.noValue
121
122        except PyAsn1Error:
123            pass
124
125        else:
126            assert False, 'addition works for NoValue object'
127
128    def testBitShift(self):
129        try:
130            univ.noValue << 1
131
132        except PyAsn1Error:
133            pass
134
135        else:
136            assert False, 'bitshift works for NoValue object'
137
138    def testBooleanEvaluation(self):
139        try:
140            if univ.noValue:
141                pass
142
143        except PyAsn1Error:
144            pass
145
146        else:
147            assert False, 'boolean evaluation works for NoValue object'
148
149    def testSizeOf(self):
150        try:
151            if hasattr(sys, 'getsizeof'):
152                sys.getsizeof(univ.noValue)
153
154            # TODO: remove when Py2.5 support is gone
155            elif sys.version_info > (2, 6):
156                raise unittest.SkipTest("no sys.getsizeof() method")
157
158        except PyAsn1Error:
159            assert False, 'sizeof failed for NoValue object'
160
161        except TypeError:
162            # TODO: remove when Py2.5 support is gone
163            if sys.version_info > (2, 6):
164                raise unittest.SkipTest("sys.getsizeof() raises TypeError")
165
166
167class IntegerTestCase(BaseTestCase):
168    def testStr(self):
169        assert str(univ.Integer(1)) in ('1', '1L'), 'str() fails'
170
171    def testRepr(self):
172        assert '123' in repr(univ.Integer(123))
173
174    def testAnd(self):
175        assert univ.Integer(1) & 0 == 0, '__and__() fails'
176
177    def testOr(self):
178        assert univ.Integer(1) | 0 == 1, '__or__() fails'
179
180    def testXor(self):
181        assert univ.Integer(1) ^ 0 == 1, '__xor__() fails'
182
183    def testRand(self):
184        assert 0 & univ.Integer(1) == 0, '__rand__() fails'
185
186    def testRor(self):
187        assert 0 | univ.Integer(1) == 1, '__ror__() fails'
188
189    def testRxor(self):
190        assert 0 ^ univ.Integer(1) == 1, '__rxor__() fails'
191
192    def testAdd(self):
193        assert univ.Integer(-4) + 6 == 2, '__add__() fails'
194
195    def testRadd(self):
196        assert 4 + univ.Integer(5) == 9, '__radd__() fails'
197
198    def testSub(self):
199        assert univ.Integer(3) - 6 == -3, '__sub__() fails'
200
201    def testRsub(self):
202        assert 6 - univ.Integer(3) == 3, '__rsub__() fails'
203
204    def testMul(self):
205        assert univ.Integer(3) * -3 == -9, '__mul__() fails'
206
207    def testRmul(self):
208        assert 2 * univ.Integer(3) == 6, '__rmul__() fails'
209
210    def testDivInt(self):
211        assert univ.Integer(4) / 2 == 2, '__div__() fails'
212
213    if sys.version_info[0] > 2:
214        def testDivFloat(self):
215            assert univ.Integer(3) / 2 == 1.5, '__div__() fails'
216
217        def testRdivFloat(self):
218            assert 3 / univ.Integer(2) == 1.5, '__rdiv__() fails'
219    else:
220        def testDivFloat(self):
221            assert univ.Integer(3) / 2 == 1, '__div__() fails'
222
223        def testRdivFloat(self):
224            assert 3 / univ.Integer(2) == 1, '__rdiv__() fails'
225
226    def testRdivInt(self):
227        assert 6 / univ.Integer(3) == 2, '__rdiv__() fails'
228
229    if sys.version_info[0] > 2:
230        def testTrueDiv(self):
231            assert univ.Integer(3) / univ.Integer(2) == 1.5, '__truediv__() fails'
232
233    def testFloorDiv(self):
234        assert univ.Integer(3) // univ.Integer(2) == 1, '__floordiv__() fails'
235
236    def testMod(self):
237        assert univ.Integer(3) % 2 == 1, '__mod__() fails'
238
239    def testRmod(self):
240        assert 4 % univ.Integer(3) == 1, '__rmod__() fails'
241
242    def testPow(self):
243        assert univ.Integer(3) ** 2 == 9, '__pow__() fails'
244
245    def testRpow(self):
246        assert 2 ** univ.Integer(2) == 4, '__rpow__() fails'
247
248    def testLshift(self):
249        assert univ.Integer(1) << 1 == 2, '<< fails'
250
251    def testRshift(self):
252        assert univ.Integer(2) >> 1 == 1, '>> fails'
253
254    def testInt(self):
255        assert int(univ.Integer(3)) == 3, '__int__() fails'
256
257    def testLong(self):
258        assert int(univ.Integer(8)) == 8, '__long__() fails'
259
260    def testFloat(self):
261        assert float(univ.Integer(4)) == 4.0, '__float__() fails'
262
263    def testPos(self):
264        assert +univ.Integer(1) == 1, '__pos__() fails'
265
266    def testNeg(self):
267        assert -univ.Integer(1) == -1, '__neg__() fails'
268
269    def testInvert(self):
270        assert ~univ.Integer(1) == -2, '__invert__() fails'
271
272    def testRound(self):
273        assert round(univ.Integer(1), 3) == 1.0, '__round__() fails'
274
275    def testFloor(self):
276        assert math.floor(univ.Integer(1)) == 1, '__floor__() fails'
277
278    def testCeil(self):
279        assert math.ceil(univ.Integer(1)) == 1, '__ceil__() fails'
280
281    if sys.version_info[0:2] > (2, 5):
282        def testTrunc(self):
283            assert math.trunc(univ.Integer(1)) == 1, '__trunc__() fails'
284
285    def testPrettyIn(self):
286        assert univ.Integer('3') == 3, 'prettyIn() fails'
287
288    def testTag(self):
289        assert univ.Integer().tagSet == tag.TagSet(
290            (),
291            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02)
292        )
293
294    def testNamedVals(self):
295
296        class Integer(univ.Integer):
297            namedValues = univ.Integer.namedValues.clone(('asn1', 1))
298
299        assert Integer('asn1') == 1, 'named val fails'
300        assert int(Integer('asn1')) == 1, 'named val fails'
301        assert str(Integer('asn1')) == 'asn1', 'named val __str__() fails'
302
303    def testSubtype(self):
304        assert univ.Integer().subtype(
305            value=1,
306            implicitTag=tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 2),
307            subtypeSpec=constraint.SingleValueConstraint(1, 3)
308        ) == univ.Integer(
309            value=1,
310            tagSet=tag.TagSet(tag.Tag(tag.tagClassPrivate,
311                                      tag.tagFormatSimple, 2)),
312            subtypeSpec=constraint.ConstraintsIntersection(constraint.SingleValueConstraint(1, 3))
313        )
314
315
316class IntegerPicklingTestCase(unittest.TestCase):
317
318    def testSchemaPickling(self):
319        old_asn1 = univ.Integer()
320        serialised = pickle.dumps(old_asn1)
321        assert serialised
322        new_asn1 = pickle.loads(serialised)
323        assert type(new_asn1) == univ.Integer
324        assert old_asn1.isSameTypeWith(new_asn1)
325
326    def testValuePickling(self):
327        old_asn1 = univ.Integer(-123)
328        serialised = pickle.dumps(old_asn1)
329        assert serialised
330        new_asn1 = pickle.loads(serialised)
331        assert new_asn1 == -123
332
333
334class BooleanTestCase(BaseTestCase):
335    def testTruth(self):
336        assert univ.Boolean(True) and univ.Boolean(1), 'Truth initializer fails'
337
338    def testFalse(self):
339        assert not univ.Boolean(False) and not univ.Boolean(0), 'False initializer fails'
340
341    def testStr(self):
342        assert str(univ.Boolean(1)) == 'True', 'str() fails'
343
344    def testInt(self):
345        assert int(univ.Boolean(1)) == 1, 'int() fails'
346
347    def testRepr(self):
348        assert 'Boolean' in repr(univ.Boolean(1))
349
350    def testTag(self):
351        assert univ.Boolean().tagSet == tag.TagSet(
352            (),
353            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01)
354        )
355
356    def testConstraints(self):
357
358        class Boolean(univ.Boolean):
359            pass
360
361        try:
362            Boolean(2)
363        except error.ValueConstraintError:
364            pass
365        else:
366            assert 0, 'constraint fail'
367
368
369class BooleanPicklingTestCase(unittest.TestCase):
370
371    def testSchemaPickling(self):
372        old_asn1 = univ.Boolean()
373        serialised = pickle.dumps(old_asn1)
374        assert serialised
375        new_asn1 = pickle.loads(serialised)
376        assert type(new_asn1) == univ.Boolean
377        assert old_asn1.isSameTypeWith(new_asn1)
378
379    def testValuePickling(self):
380        old_asn1 = univ.Boolean(True)
381        serialised = pickle.dumps(old_asn1)
382        assert serialised
383        new_asn1 = pickle.loads(serialised)
384        assert new_asn1 == True
385
386
387class BitStringTestCase(BaseTestCase):
388    def setUp(self):
389        BaseTestCase.setUp(self)
390
391        self.b = univ.BitString(
392            namedValues=namedval.NamedValues(('Active', 0), ('Urgent', 1))
393        )
394
395    def testBinDefault(self):
396
397        class BinDefault(univ.BitString):
398            defaultBinValue = '1010100110001010'
399
400        assert BinDefault() == univ.BitString(binValue='1010100110001010')
401
402    def testHexDefault(self):
403
404        class HexDefault(univ.BitString):
405            defaultHexValue = 'A98A'
406
407        assert HexDefault() == univ.BitString(hexValue='A98A')
408
409    def testSet(self):
410        assert self.b.clone('Active') == (1,)
411        assert self.b.clone('Urgent') == (0, 1)
412        assert self.b.clone('Urgent, Active') == (1, 1)
413        assert self.b.clone("'1010100110001010'B") == (1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0)
414        assert self.b.clone("'A98A'H") == (1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0)
415        assert self.b.clone(binValue='1010100110001010') == (1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0)
416        assert self.b.clone(hexValue='A98A') == (1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0)
417        assert self.b.clone('1010100110001010') == (1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0)
418        assert self.b.clone((1, 0, 1)) == (1, 0, 1)
419
420    def testStr(self):
421        assert str(self.b.clone('Urgent')) == '01'
422
423    def testRepr(self):
424        assert 'BitString' in repr(self.b.clone('Urgent,Active'))
425
426    def testTag(self):
427        assert univ.BitString().tagSet == tag.TagSet(
428            (),
429            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03)
430        )
431
432    def testLen(self):
433        assert len(self.b.clone("'A98A'H")) == 16
434
435    def testGetItem(self):
436        assert self.b.clone("'A98A'H")[0] == 1
437        assert self.b.clone("'A98A'H")[1] == 0
438        assert self.b.clone("'A98A'H")[2] == 1
439
440    if sys.version_info[:2] > (2, 4):
441        def testReverse(self):
442            assert list(reversed(univ.BitString([0, 0, 1]))) == list(univ.BitString([1, 0, 0]))
443
444    def testAsOctets(self):
445        assert self.b.clone(hexValue='A98A').asOctets() == ints2octs((0xa9, 0x8a)), 'testAsOctets() fails'
446
447    def testAsInts(self):
448        assert self.b.clone(hexValue='A98A').asNumbers() == (0xa9, 0x8a), 'testAsNumbers() fails'
449
450    def testMultipleOfEightPadding(self):
451        assert self.b.clone((1, 0, 1)).asNumbers() == (5,)
452
453    def testAsInteger(self):
454        assert self.b.clone('11000000011001').asInteger() == 12313
455        assert self.b.clone('1100110011011111').asInteger() == 52447
456
457    def testStaticDef(self):
458
459        class BitString(univ.BitString):
460            pass
461
462        assert BitString('11000000011001').asInteger() == 12313
463
464
465class BitStringPicklingTestCase(unittest.TestCase):
466
467    def testSchemaPickling(self):
468        old_asn1 = univ.BitString()
469        serialised = pickle.dumps(old_asn1)
470        assert serialised
471        new_asn1 = pickle.loads(serialised)
472        assert type(new_asn1) == univ.BitString
473        assert old_asn1.isSameTypeWith(new_asn1)
474
475    def testValuePickling(self):
476        old_asn1 = univ.BitString((1, 0, 1, 0))
477        serialised = pickle.dumps(old_asn1)
478        assert serialised
479        new_asn1 = pickle.loads(serialised)
480        assert new_asn1 == (1, 0, 1, 0)
481
482
483class OctetStringWithUnicodeMixIn(object):
484
485    initializer = ()
486    encoding = 'us-ascii'
487
488    def setUp(self):
489        self.pythonString = ints2octs(self.initializer).decode(self.encoding)
490        self.encodedPythonString = self.pythonString.encode(self.encoding)
491        self.numbersString = tuple(octs2ints(self.encodedPythonString))
492
493    def testInit(self):
494        assert univ.OctetString(self.encodedPythonString) == self.encodedPythonString, '__init__() fails'
495
496    def testInitFromAsn1(self):
497            assert univ.OctetString(univ.OctetString(self.encodedPythonString)) == self.encodedPythonString
498            assert univ.OctetString(univ.Integer(123)) == univ.OctetString('123')
499
500    def testSerialised(self):
501        if sys.version_info[0] < 3:
502            assert str(univ.OctetString(self.encodedPythonString, encoding=self.encoding)) == self.encodedPythonString, '__str__() fails'
503        else:
504            assert bytes(univ.OctetString(self.encodedPythonString, encoding=self.encoding)) == self.encodedPythonString, '__str__() fails'
505
506    def testPrintable(self):
507        if sys.version_info[0] < 3:
508            assert str(univ.OctetString(self.encodedPythonString, encoding=self.encoding)) == self.encodedPythonString, '__str__() fails'
509            assert unicode(univ.OctetString(self.pythonString, encoding=self.encoding)) == self.pythonString, 'unicode init fails'
510        else:
511            assert str(univ.OctetString(self.pythonString, encoding=self.encoding)) == self.pythonString, 'unicode init fails'
512
513    def testSeq(self):
514        assert univ.OctetString(self.encodedPythonString)[0] == self.encodedPythonString[0], '__getitem__() fails'
515
516    def testRepr(self):
517        assert 'abc' in repr(univ.OctetString('abc'))
518
519    def testAsOctets(self):
520        assert univ.OctetString(self.encodedPythonString).asOctets() == self.encodedPythonString, 'testAsOctets() fails'
521
522    def testAsInts(self):
523        assert univ.OctetString(self.encodedPythonString).asNumbers() == self.numbersString, 'testAsNumbers() fails'
524
525    def testAdd(self):
526        assert univ.OctetString(self.encodedPythonString) + self.encodedPythonString == self.encodedPythonString + self.encodedPythonString, '__add__() fails'
527
528    def testRadd(self):
529        assert self.encodedPythonString + univ.OctetString(self.encodedPythonString) == self.encodedPythonString + self.encodedPythonString, '__radd__() fails'
530
531    def testMul(self):
532        assert univ.OctetString(self.encodedPythonString) * 2 == self.encodedPythonString * 2, '__mul__() fails'
533
534    def testRmul(self):
535        assert 2 * univ.OctetString(self.encodedPythonString) == 2 * self.encodedPythonString, '__rmul__() fails'
536
537    def testContains(self):
538        s = univ.OctetString(self.encodedPythonString)
539        assert self.encodedPythonString in s
540        assert self.encodedPythonString * 2 not in s
541
542    if sys.version_info[:2] > (2, 4):
543       def testReverse(self):
544           assert list(reversed(univ.OctetString(self.encodedPythonString))) == list(reversed(self.encodedPythonString))
545
546
547class OctetStringWithAsciiTestCase(OctetStringWithUnicodeMixIn, BaseTestCase):
548    initializer = (97, 102)
549    encoding = 'us-ascii'
550
551
552class OctetStringUnicodeErrorTestCase(BaseTestCase):
553    def testEncodeError(self):
554        text = octs2str(ints2octs((0xff, 0xfe)))
555
556        try:
557            univ.OctetString(text, encoding='us-ascii')
558
559        except PyAsn1UnicodeEncodeError:
560            pass
561
562        # TODO: remove when Py2.5 support is gone
563        else:
564            if sys.version_info > (2, 6):
565                assert False, 'Unicode encoding error not caught'
566
567    def testDecodeError(self):
568        serialized = ints2octs((0xff, 0xfe))
569
570        try:
571            str(univ.OctetString(serialized, encoding='us-ascii'))
572
573        except PyAsn1UnicodeDecodeError:
574            pass
575
576        # TODO: remove when Py2.5 support is gone
577        else:
578            if sys.version_info > (2, 6):
579                assert False, 'Unicode decoding error not caught'
580
581
582class OctetStringWithUtf8TestCase(OctetStringWithUnicodeMixIn, BaseTestCase):
583    initializer = (208, 176, 208, 177, 208, 178)
584    encoding = 'utf-8'
585
586
587class OctetStringWithUtf16TestCase(OctetStringWithUnicodeMixIn, BaseTestCase):
588    initializer = (4, 48, 4, 49, 4, 50)
589    encoding = 'utf-16-be'
590
591
592if sys.version_info[0] > 2:
593
594    # Somehow comparison of UTF-32 encoded strings does not work in Py2
595
596    class OctetStringWithUtf32TestCase(OctetStringWithUnicodeMixIn, BaseTestCase):
597        initializer = (0, 0, 4, 48, 0, 0, 4, 49, 0, 0, 4, 50)
598        encoding = 'utf-32-be'
599
600
601class OctetStringTestCase(BaseTestCase):
602
603    def testBinDefault(self):
604
605        class BinDefault(univ.OctetString):
606            defaultBinValue = '1000010111101110101111000000111011'
607
608        assert BinDefault() == univ.OctetString(binValue='1000010111101110101111000000111011')
609
610    def testHexDefault(self):
611
612        class HexDefault(univ.OctetString):
613            defaultHexValue = 'FA9823C43E43510DE3422'
614
615        assert HexDefault() == univ.OctetString(hexValue='FA9823C43E43510DE3422')
616
617    def testBinStr(self):
618        assert univ.OctetString(binValue="1000010111101110101111000000111011") == ints2octs((133, 238, 188, 14, 192)), 'bin init fails'
619
620    def testHexStr(self):
621        assert univ.OctetString(hexValue="FA9823C43E43510DE3422") == ints2octs((250, 152, 35, 196, 62, 67, 81, 13, 227, 66, 32)), 'hex init fails'
622
623    def testTuple(self):
624        assert univ.OctetString((1, 2, 3, 4, 5)) == ints2octs((1, 2, 3, 4, 5)), 'tuple init failed'
625
626    def testRepr(self):
627        assert 'abc' in repr(univ.OctetString('abc'))
628
629    def testEmpty(self):
630        try:
631            str(univ.OctetString())
632        except PyAsn1Error:
633            pass
634        else:
635            assert 0, 'empty OctetString() not reported'
636
637    def testTag(self):
638        assert univ.OctetString().tagSet == tag.TagSet(
639            (),
640            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04)
641        )
642
643    def testStaticDef(self):
644
645        class OctetString(univ.OctetString):
646            pass
647
648        assert OctetString(hexValue="FA9823C43E43510DE3422") == ints2octs((250, 152, 35, 196, 62, 67, 81, 13, 227, 66, 32))
649
650
651class OctetStringPicklingTestCase(unittest.TestCase):
652
653    def testSchemaPickling(self):
654        old_asn1 = univ.BitString()
655        serialised = pickle.dumps(old_asn1)
656        assert serialised
657        new_asn1 = pickle.loads(serialised)
658        assert type(new_asn1) == univ.BitString
659        assert old_asn1.isSameTypeWith(new_asn1)
660
661    def testValuePickling(self):
662        old_asn1 = univ.BitString((1, 0, 1, 0))
663        serialised = pickle.dumps(old_asn1)
664        assert serialised
665        new_asn1 = pickle.loads(serialised)
666        assert new_asn1 == (1, 0, 1, 0)
667
668
669class Null(BaseTestCase):
670
671    def testInit(self):
672        assert not univ.Null().isValue
673        assert univ.Null(0) == str2octs('')
674        assert univ.Null(False) == str2octs('')
675        assert univ.Null('') == str2octs('')
676        assert univ.Null(None) == str2octs('')
677
678        try:
679            assert univ.Null(True)
680
681        except PyAsn1Error:
682            pass
683
684        try:
685            assert univ.Null('xxx')
686
687        except PyAsn1Error:
688            pass
689
690    def testStr(self):
691        assert str(univ.Null('')) == '', 'str() fails'
692
693    def testRepr(self):
694        assert 'Null' in repr(univ.Null(''))
695
696    def testTag(self):
697        assert univ.Null().tagSet == tag.TagSet(
698            (),
699            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05)
700        )
701
702    def testConstraints(self):
703        try:
704            univ.Null(2)
705        except error.ValueConstraintError:
706            pass
707        else:
708            assert 0, 'constraint fail'
709
710    def testStaticDef(self):
711
712        class Null(univ.Null):
713            pass
714
715        assert not Null('')
716
717
718class NullPicklingTestCase(unittest.TestCase):
719
720    def testSchemaPickling(self):
721        old_asn1 = univ.Null()
722        serialised = pickle.dumps(old_asn1)
723        assert serialised
724        new_asn1 = pickle.loads(serialised)
725        assert type(new_asn1) == univ.Null
726        assert old_asn1.isSameTypeWith(new_asn1)
727
728    def testValuePickling(self):
729        old_asn1 = univ.Null('')
730        serialised = pickle.dumps(old_asn1)
731        assert serialised
732        new_asn1 = pickle.loads(serialised)
733        assert not new_asn1
734
735
736class RealTestCase(BaseTestCase):
737    def testFloat4BinEnc(self):
738        assert univ.Real((0.25, 2, 3)) == 2.0, 'float initializer for binary encoding fails'
739
740    def testStr(self):
741        assert str(univ.Real(1.0)) == '1.0', 'str() fails'
742
743    def testRepr(self):
744        assert 'Real' in repr(univ.Real(-4.1))
745        assert 'Real' in repr(univ.Real(-4.1))
746        assert 'inf' in repr(univ.Real('inf'))
747        assert '-inf' in repr(univ.Real('-inf'))
748
749    def testAdd(self):
750        assert univ.Real(-4.1) + 1.4 == -2.7, '__add__() fails'
751
752    def testRadd(self):
753        assert 4 + univ.Real(0.5) == 4.5, '__radd__() fails'
754
755    def testSub(self):
756        assert univ.Real(3.9) - 1.7 == 2.2, '__sub__() fails'
757
758    def testRsub(self):
759        assert 6.1 - univ.Real(0.1) == 6, '__rsub__() fails'
760
761    def testMul(self):
762        assert univ.Real(3.0) * -3 == -9, '__mul__() fails'
763
764    def testRmul(self):
765        assert 2 * univ.Real(3.0) == 6, '__rmul__() fails'
766
767    def testDiv(self):
768        assert univ.Real(3.0) / 2 == 1.5, '__div__() fails'
769
770    def testRdiv(self):
771        assert 6 / univ.Real(3.0) == 2, '__rdiv__() fails'
772
773    def testMod(self):
774        assert univ.Real(3.0) % 2 == 1, '__mod__() fails'
775
776    def testRmod(self):
777        assert 4 % univ.Real(3.0) == 1, '__rmod__() fails'
778
779    def testPow(self):
780        assert univ.Real(3.0) ** 2 == 9, '__pow__() fails'
781
782    def testRpow(self):
783        assert 2 ** univ.Real(2.0) == 4, '__rpow__() fails'
784
785    def testInt(self):
786        assert int(univ.Real(3.0)) == 3, '__int__() fails'
787
788    def testLong(self):
789        assert int(univ.Real(8.0)) == 8, '__long__() fails'
790
791    def testFloat(self):
792        assert float(univ.Real(4.0)) == 4.0, '__float__() fails'
793
794    def testPrettyIn(self):
795        assert univ.Real((3, 10, 0)) == 3, 'prettyIn() fails'
796
797    # infinite float values
798    def testStrInf(self):
799        assert str(univ.Real('inf')) == 'inf', 'str() fails'
800
801    def testAddInf(self):
802        assert univ.Real('inf') + 1 == float('inf'), '__add__() fails'
803
804    def testRaddInf(self):
805        assert 1 + univ.Real('inf') == float('inf'), '__radd__() fails'
806
807    def testIntInf(self):
808        try:
809            assert int(univ.Real('inf'))
810        except OverflowError:
811            pass
812        else:
813            assert 0, '__int__() fails'
814
815    def testLongInf(self):
816        try:
817            assert int(univ.Real('inf'))
818        except OverflowError:
819            pass
820        else:
821            assert 0, '__long__() fails'
822        assert int(univ.Real(8.0)) == 8, '__long__() fails'
823
824    def testFloatInf(self):
825        assert float(univ.Real('-inf')) == float('-inf'), '__float__() fails'
826
827    def testPrettyInInf(self):
828        assert univ.Real(float('inf')) == float('inf'), 'prettyIn() fails'
829
830    def testPlusInf(self):
831        assert univ.Real('inf').isPlusInf, 'isPlusInfinity failed'
832
833    def testMinusInf(self):
834        assert univ.Real('-inf').isMinusInf, 'isMinusInfinity failed'
835
836    def testPos(self):
837        assert +univ.Real(1.0) == 1.0, '__pos__() fails'
838
839    def testNeg(self):
840        assert -univ.Real(1.0) == -1.0, '__neg__() fails'
841
842    def testRound(self):
843        assert round(univ.Real(1.123), 2) == 1.12, '__round__() fails'
844
845    def testFloor(self):
846        assert math.floor(univ.Real(1.6)) == 1.0, '__floor__() fails'
847
848    def testCeil(self):
849        assert math.ceil(univ.Real(1.2)) == 2.0, '__ceil__() fails'
850
851    if sys.version_info[0:2] > (2, 5):
852        def testTrunc(self):
853            assert math.trunc(univ.Real(1.1)) == 1.0, '__trunc__() fails'
854
855    def testTag(self):
856        assert univ.Real().tagSet == tag.TagSet(
857            (),
858            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09)
859        )
860
861    def testStaticDef(self):
862
863        class Real(univ.Real):
864            pass
865
866        assert Real(1.0) == 1.0
867
868
869class RealPicklingTestCase(unittest.TestCase):
870
871    def testSchemaPickling(self):
872        old_asn1 = univ.Real()
873        serialised = pickle.dumps(old_asn1)
874        assert serialised
875        new_asn1 = pickle.loads(serialised)
876        assert type(new_asn1) == univ.Real
877        assert old_asn1.isSameTypeWith(new_asn1)
878
879    def testValuePickling(self):
880        old_asn1 = univ.Real((1, 10, 3))
881        serialised = pickle.dumps(old_asn1)
882        assert serialised
883        new_asn1 = pickle.loads(serialised)
884        assert new_asn1 == 1000
885
886
887class ObjectIdentifier(BaseTestCase):
888    def testStr(self):
889        assert str(univ.ObjectIdentifier((1, 3, 6))) == '1.3.6', 'str() fails'
890
891    def testRepr(self):
892        assert '1.3.6' in repr(univ.ObjectIdentifier('1.3.6'))
893
894    def testEq(self):
895        assert univ.ObjectIdentifier((1, 3, 6)) == (1, 3, 6), '__cmp__() fails'
896
897    def testAdd(self):
898        assert univ.ObjectIdentifier((1, 3)) + (6,) == (1, 3, 6), '__add__() fails'
899
900    def testRadd(self):
901        assert (1,) + univ.ObjectIdentifier((3, 6)) == (1, 3, 6), '__radd__() fails'
902
903    def testLen(self):
904        assert len(univ.ObjectIdentifier((1, 3))) == 2, '__len__() fails'
905
906    def testPrefix(self):
907        o = univ.ObjectIdentifier('1.3.6')
908        assert o.isPrefixOf((1, 3, 6)), 'isPrefixOf() fails'
909        assert o.isPrefixOf((1, 3, 6, 1)), 'isPrefixOf() fails'
910        assert not o.isPrefixOf((1, 3)), 'isPrefixOf() fails'
911
912    def testInput1(self):
913        assert univ.ObjectIdentifier('1.3.6') == (1, 3, 6), 'prettyIn() fails'
914
915    def testInput2(self):
916        assert univ.ObjectIdentifier((1, 3, 6)) == (1, 3, 6), 'prettyIn() fails'
917
918    def testInput3(self):
919        assert univ.ObjectIdentifier(univ.ObjectIdentifier('1.3') + (6,)) == (1, 3, 6), 'prettyIn() fails'
920
921    def testUnicode(self):
922        s = '1.3.6'
923        if sys.version_info[0] < 3:
924            s = s.decode()
925        assert univ.ObjectIdentifier(s) == (1, 3, 6), 'unicode init fails'
926
927    def testTag(self):
928        assert univ.ObjectIdentifier().tagSet == tag.TagSet(
929            (),
930            tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06)
931        )
932
933    def testContains(self):
934        s = univ.ObjectIdentifier('1.3.6.1234.99999')
935        assert 1234 in s
936        assert 4321 not in s
937
938    def testStaticDef(self):
939
940        class ObjectIdentifier(univ.ObjectIdentifier):
941            pass
942
943        assert str(ObjectIdentifier((1, 3, 6))) == '1.3.6'
944
945
946class ObjectIdentifierPicklingTestCase(unittest.TestCase):
947
948    def testSchemaPickling(self):
949        old_asn1 = univ.ObjectIdentifier()
950        serialised = pickle.dumps(old_asn1)
951        assert serialised
952        new_asn1 = pickle.loads(serialised)
953        assert type(new_asn1) == univ.ObjectIdentifier
954        assert old_asn1.isSameTypeWith(new_asn1)
955
956    def testValuePickling(self):
957        old_asn1 = univ.ObjectIdentifier('2.3.1.1.2')
958        serialised = pickle.dumps(old_asn1)
959        assert serialised
960        new_asn1 = pickle.loads(serialised)
961        assert new_asn1 == (2, 3, 1, 1, 2)
962
963
964class SequenceOf(BaseTestCase):
965    def setUp(self):
966        BaseTestCase.setUp(self)
967        self.s1 = univ.SequenceOf(
968            componentType=univ.OctetString('')
969        )
970        self.s2 = self.s1.clone()
971
972    def testRepr(self):
973        assert 'a' in repr(self.s1.clone().setComponents('a', 'b'))
974
975    def testTag(self):
976        assert self.s1.tagSet == tag.TagSet(
977            (),
978            tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)
979        ), 'wrong tagSet'
980
981    def testSeq(self):
982        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
983        assert self.s1[0] == str2octs('abc'), 'set by idx fails'
984        self.s1[0] = 'cba'
985        assert self.s1[0] == str2octs('cba'), 'set by idx fails'
986
987    def testCmp(self):
988        self.s1.clear()
989        self.s1.setComponentByPosition(0, 'abc')
990        self.s2.clear()
991        self.s2.setComponentByPosition(0, univ.OctetString('abc'))
992        assert self.s1 == self.s2, '__cmp__() fails'
993
994    def testSubtypeSpec(self):
995        s = self.s1.clone(
996            componentType=univ.OctetString().subtype(
997                subtypeSpec=constraint.SingleValueConstraint(str2octs('abc'))))
998        try:
999            s.setComponentByPosition(
1000                0, univ.OctetString().subtype(
1001                    'abc', subtypeSpec=constraint.SingleValueConstraint(str2octs('abc'))))
1002        except PyAsn1Error:
1003            assert 0, 'constraint fails'
1004        try:
1005            s.setComponentByPosition(1, univ.OctetString('Abc'))
1006        except PyAsn1Error:
1007            try:
1008                s.setComponentByPosition(1, univ.OctetString('Abc'),
1009                                         verifyConstraints=False)
1010            except PyAsn1Error:
1011                assert 0, 'constraint fails with verifyConstraints=False'
1012        else:
1013            assert 0, 'constraint fails'
1014
1015    def testComponentTagsMatching(self):
1016        s = self.s1.clone()
1017        s.strictConstraints = True  # This requires types equality
1018        o = univ.OctetString('abc').subtype(explicitTag=tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 12))
1019        try:
1020            s.setComponentByPosition(0, o)
1021        except PyAsn1Error:
1022            pass
1023        else:
1024            assert 0, 'inner supertype tag allowed'
1025
1026    def testComponentConstraintsMatching(self):
1027        s = self.s1.clone()
1028        o = univ.OctetString().subtype(
1029            subtypeSpec=constraint.ConstraintsUnion(constraint.SingleValueConstraint(str2octs('cba'))))
1030        s.strictConstraints = True  # This requires types equality
1031        try:
1032            s.setComponentByPosition(0, o.clone('cba'))
1033        except PyAsn1Error:
1034            pass
1035        else:
1036            assert 0, 'inner supertype constraint allowed'
1037        s.strictConstraints = False  # This requires subtype relationships
1038        try:
1039            s.setComponentByPosition(0, o.clone('cba'))
1040        except PyAsn1Error:
1041            assert 0, 'inner supertype constraint disallowed'
1042        else:
1043            pass
1044
1045    def testConsistency(self):
1046        s = self.s1.clone(subtypeSpec=constraint.ConstraintsUnion(
1047            constraint.ValueSizeConstraint(1, 1)
1048        ))
1049        s.setComponentByPosition(0, univ.OctetString('abc'))
1050        assert not s.isInconsistent, 'size spec fails'
1051        s.setComponentByPosition(1, univ.OctetString('abc'))
1052        assert s.isInconsistent, 'size spec fails'
1053
1054    def testGetComponentTagMap(self):
1055        assert self.s1.componentType.tagMap.presentTypes == {
1056            univ.OctetString.tagSet: univ.OctetString('')
1057        }
1058
1059    def testSubtype(self):
1060        subtype = self.s1.subtype(
1061            implicitTag=tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 2),
1062            subtypeSpec=constraint.ValueSizeConstraint(0, 1)
1063        )
1064        subtype.clear()
1065        clone = self.s1.clone(
1066            tagSet=tag.TagSet(tag.Tag(tag.tagClassPrivate,
1067                                      tag.tagFormatSimple, 2)),
1068            subtypeSpec=constraint.ValueSizeConstraint(0, 1)
1069        )
1070        clone.clear()
1071        assert clone == subtype
1072
1073    def testClone(self):
1074        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1075        s = self.s1.clone()
1076        s.clear()
1077        assert len(s) == 0
1078        s = self.s1.clone(cloneValueFlag=1)
1079        assert len(s) == 1
1080        assert s.getComponentByPosition(0) == self.s1.getComponentByPosition(0)
1081
1082    def testSetComponents(self):
1083        assert self.s1.clone().setComponents('abc', 'def') == \
1084               self.s1.setComponentByPosition(0, 'abc').setComponentByPosition(1, 'def')
1085
1086    def testGetItem(self):
1087        s = self.s1.clone()
1088        s.append('xxx')
1089        assert s[0]
1090
1091        # this is a deviation from standard sequence protocol
1092        assert not s[2]
1093
1094    def testGetItemSlice(self):
1095        s = self.s1.clone()
1096        s.extend(['xxx', 'yyy', 'zzz'])
1097        assert s[:1] == [str2octs('xxx')]
1098        assert s[-2:] == [str2octs('yyy'), str2octs('zzz')]
1099        assert s[1:2] == [str2octs('yyy')]
1100
1101    def testSetItem(self):
1102        s = self.s1.clone()
1103        s.append('xxx')
1104        s[2] = 'yyy'
1105        assert len(s) == 3
1106        assert s[1] == str2octs('')
1107
1108    def testSetItemSlice(self):
1109        s = self.s1.clone()
1110        s[:1] = ['xxx']
1111        assert s == [str2octs('xxx')]
1112        s[-2:] = ['yyy', 'zzz']
1113        assert s == [str2octs('yyy'), str2octs('zzz')]
1114        s[1:2] = ['yyy']
1115        assert s == [str2octs('yyy'), str2octs('yyy')]
1116        assert len(s) == 2
1117
1118    def testAppend(self):
1119        self.s1.clear()
1120        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1121        assert len(self.s1) == 1
1122        self.s1.append('def')
1123        assert len(self.s1) == 2
1124        assert list(self.s1) == [str2octs(x) for x in ['abc', 'def']]
1125
1126    def testExtend(self):
1127        self.s1.clear()
1128        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1129        assert len(self.s1) == 1
1130        self.s1.extend(['def', 'ghi'])
1131        assert len(self.s1) == 3
1132        assert list(self.s1) == [str2octs(x) for x in ['abc', 'def', 'ghi']]
1133
1134    def testCount(self):
1135        self.s1.clear()
1136        for x in ['abc', 'def', 'abc']:
1137            self.s1.append(x)
1138        assert self.s1.count(str2octs('abc')) == 2
1139        assert self.s1.count(str2octs('def')) == 1
1140        assert self.s1.count(str2octs('ghi')) == 0
1141
1142    def testIndex(self):
1143        self.s1.clear()
1144        for x in ['abc', 'def', 'abc']:
1145            self.s1.append(x)
1146        assert self.s1.index(str2octs('abc')) == 0
1147        assert self.s1.index(str2octs('def')) == 1
1148        assert self.s1.index(str2octs('abc'), 1) == 2
1149
1150    def testSort(self):
1151        self.s1.clear()
1152        self.s1[0] = 'b'
1153        self.s1[1] = 'a'
1154        assert list(self.s1) == [str2octs('b'), str2octs('a')]
1155        self.s1.sort()
1156        assert list(self.s1) == [str2octs('a'), str2octs('b')]
1157
1158    def testStaticDef(self):
1159
1160        class SequenceOf(univ.SequenceOf):
1161            componentType = univ.OctetString('')
1162
1163        s = SequenceOf()
1164        s[0] = 'abc'
1165        assert len(s) == 1
1166        assert s == [str2octs('abc')]
1167
1168    def testUntyped(self):
1169        n = univ.SequenceOf()
1170
1171        assert not n.isValue
1172
1173        n[0] = univ.OctetString('fox')
1174
1175        assert n.isValue
1176
1177    def testLegacyInitializer(self):
1178        n = univ.SequenceOf(
1179            componentType=univ.OctetString()
1180        )
1181        o = univ.SequenceOf(
1182            univ.OctetString()  # this is the old way
1183        )
1184
1185        assert n.isSameTypeWith(o) and o.isSameTypeWith(n)
1186
1187        n[0] = 'fox'
1188        o[0] = 'fox'
1189
1190        assert n == o
1191
1192    def testGetComponentWithDefault(self):
1193
1194        class SequenceOf(univ.SequenceOf):
1195            componentType = univ.OctetString()
1196
1197        s = SequenceOf()
1198        assert s.getComponentByPosition(0, default=None, instantiate=False) is None
1199        assert s.getComponentByPosition(0, default=None) is None
1200        s[0] = 'test'
1201        assert s.getComponentByPosition(0, default=None) is not None
1202        assert s.getComponentByPosition(0, default=None) == str2octs('test')
1203        s.clear()
1204        assert s.getComponentByPosition(0, default=None) is None
1205
1206    def testGetComponentNoInstantiation(self):
1207
1208        class SequenceOf(univ.SequenceOf):
1209            componentType = univ.OctetString()
1210
1211        s = SequenceOf()
1212        assert s.getComponentByPosition(0, instantiate=False) is univ.noValue
1213        s[0] = 'test'
1214        assert s.getComponentByPosition(0, instantiate=False) is not univ.noValue
1215        assert s.getComponentByPosition(0, instantiate=False) == str2octs('test')
1216        s.clear()
1217        assert s.getComponentByPosition(0, instantiate=False) is univ.noValue
1218
1219    def testClear(self):
1220
1221        class SequenceOf(univ.SequenceOf):
1222            componentType = univ.OctetString()
1223
1224        s = SequenceOf()
1225        s.setComponentByPosition(0, 'test')
1226
1227        assert s.getComponentByPosition(0) == str2octs('test')
1228        assert len(s) == 1
1229        assert s.isValue
1230
1231        s.clear()
1232
1233        assert len(s) == 0
1234        assert s == []
1235        assert s.isValue
1236
1237    def testReset(self):
1238
1239        class SequenceOf(univ.SequenceOf):
1240            componentType = univ.OctetString()
1241
1242        s = SequenceOf()
1243        s.setComponentByPosition(0, 'test')
1244
1245        assert s.getComponentByPosition(0) == str2octs('test')
1246        assert s.isValue
1247
1248        s.reset()
1249
1250        assert not s.isValue
1251
1252    def testIsInconsistentSizeConstraint(self):
1253
1254        class SequenceOf(univ.SequenceOf):
1255            componentType = univ.OctetString()
1256            subtypeSpec = constraint.ValueSizeConstraint(0, 1)
1257
1258        s = SequenceOf()
1259
1260        assert s.isInconsistent
1261
1262        s[0] = 'test'
1263
1264        assert not s.isInconsistent
1265
1266        s[0] = 'test'
1267        s[1] = 'test'
1268
1269        assert s.isInconsistent
1270
1271        s.clear()
1272
1273        assert not s.isInconsistent
1274
1275        s.reset()
1276
1277        assert s.isInconsistent
1278
1279        s[1] = 'test'
1280
1281        assert not s.isInconsistent
1282
1283
1284class SequenceOfPicklingTestCase(unittest.TestCase):
1285
1286    def testSchemaPickling(self):
1287        old_asn1 = univ.SequenceOf(componentType=univ.OctetString())
1288        serialised = pickle.dumps(old_asn1)
1289        assert serialised
1290        new_asn1 = pickle.loads(serialised)
1291        assert type(new_asn1) == univ.SequenceOf
1292        assert old_asn1.isSameTypeWith(new_asn1)
1293
1294    def testValuePickling(self):
1295        old_asn1 = univ.SequenceOf(componentType=univ.OctetString())
1296        old_asn1[0] = 'test'
1297        serialised = pickle.dumps(old_asn1)
1298        assert serialised
1299        new_asn1 = pickle.loads(serialised)
1300        assert new_asn1
1301        assert new_asn1 == [str2octs('test')]
1302
1303
1304class Sequence(BaseTestCase):
1305    def setUp(self):
1306        BaseTestCase.setUp(self)
1307        self.s1 = univ.Sequence(
1308            componentType=namedtype.NamedTypes(
1309                namedtype.NamedType('name', univ.OctetString('')),
1310                namedtype.OptionalNamedType('nick', univ.OctetString('')),
1311                namedtype.DefaultedNamedType('age', univ.Integer(34))
1312            )
1313        )
1314
1315    def testRepr(self):
1316        assert 'name' in repr(self.s1.clone().setComponents('a', 'b'))
1317
1318    def testTag(self):
1319        assert self.s1.tagSet == tag.TagSet(
1320            (),
1321            tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10)
1322        ), 'wrong tagSet'
1323
1324    def testById(self):
1325        self.s1.setComponentByName('name', univ.OctetString('abc'))
1326        assert self.s1.getComponentByName('name') == str2octs('abc'), 'set by name fails'
1327
1328    def testByKey(self):
1329        self.s1['name'] = 'abc'
1330        assert self.s1['name'] == str2octs('abc'), 'set by key fails'
1331
1332    def testContains(self):
1333        assert 'name' in self.s1
1334        assert '<missing>' not in self.s1
1335
1336    def testGetNearPosition(self):
1337        assert self.s1.componentType.getTagMapNearPosition(1).presentTypes == {
1338            univ.OctetString.tagSet: univ.OctetString(''),
1339            univ.Integer.tagSet: univ.Integer(34)
1340        }
1341        assert self.s1.componentType.getPositionNearType(
1342            univ.OctetString.tagSet, 1
1343        ) == 1
1344
1345    def testSetDefaultComponents(self):
1346        self.s1.clear()
1347        self.s1.setComponentByPosition(0, univ.OctetString('Ping'))
1348        self.s1.setComponentByPosition(1, univ.OctetString('Pong'))
1349        assert self.s1.getComponentByPosition(2) == 34
1350
1351    def testClone(self):
1352        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1353        self.s1.setComponentByPosition(1, univ.OctetString('def'))
1354        self.s1.setComponentByPosition(2, univ.Integer(123))
1355        s = self.s1.clone()
1356        assert s.getComponentByPosition(0) != self.s1.getComponentByPosition(0)
1357        assert s.getComponentByPosition(1) != self.s1.getComponentByPosition(1)
1358        assert s.getComponentByPosition(2) != self.s1.getComponentByPosition(2)
1359        s = self.s1.clone(cloneValueFlag=1)
1360        assert s.getComponentByPosition(0) == self.s1.getComponentByPosition(0)
1361        assert s.getComponentByPosition(1) == self.s1.getComponentByPosition(1)
1362        assert s.getComponentByPosition(2) == self.s1.getComponentByPosition(2)
1363
1364    def testComponentTagsMatching(self):
1365        s = self.s1.clone()
1366        s.strictConstraints = True  # This requires types equality
1367        o = univ.OctetString('abc').subtype(explicitTag=tag.Tag(tag.tagClassPrivate, tag.tagFormatSimple, 12))
1368        try:
1369            s.setComponentByName('name', o)
1370        except PyAsn1Error:
1371            pass
1372        else:
1373            assert 0, 'inner supertype tag allowed'
1374
1375    def testComponentConstraintsMatching(self):
1376        s = self.s1.clone()
1377        o = univ.OctetString().subtype(
1378            subtypeSpec=constraint.ConstraintsUnion(constraint.SingleValueConstraint(str2octs('cba'))))
1379        s.strictConstraints = True  # This requires types equality
1380        try:
1381            s.setComponentByName('name', o.clone('cba'))
1382        except PyAsn1Error:
1383            pass
1384        else:
1385            assert 0, 'inner supertype constraint allowed'
1386        s.strictConstraints = False  # This requires subtype relationships
1387        try:
1388            s.setComponentByName('name', o.clone('cba'))
1389        except PyAsn1Error:
1390            assert 0, 'inner supertype constraint disallowed'
1391        else:
1392            pass
1393
1394    def testSetComponents(self):
1395        assert self.s1.clone().setComponents(name='a', nick='b', age=1) == \
1396               self.s1.setComponentByPosition(0, 'a').setComponentByPosition(1, 'b').setComponentByPosition(2, 1)
1397
1398    def testSetToDefault(self):
1399        s = self.s1.clone()
1400        s.setComponentByPosition(0, univ.noValue)
1401        s[2] = univ.noValue
1402        assert s[0] == univ.OctetString('')
1403        assert s[2] == univ.Integer(34)
1404
1405    def testGetItem(self):
1406        s = self.s1.clone()
1407        s['name'] = 'xxx'
1408        assert s['name']
1409        assert s[0]
1410
1411        try:
1412            s['xxx']
1413
1414        except KeyError:
1415            pass
1416
1417        else:
1418            assert False, 'KeyError not raised'
1419
1420        try:
1421            s[100]
1422
1423        except IndexError:
1424            pass
1425
1426        else:
1427            assert False, 'IndexError not raised'
1428
1429    def testSetItem(self):
1430        s = self.s1.clone()
1431        s['name'] = 'xxx'
1432
1433        try:
1434
1435            s['xxx'] = 'xxx'
1436
1437        except KeyError:
1438            pass
1439
1440        else:
1441            assert False, 'KeyError not raised'
1442
1443        try:
1444
1445            s[100] = 'xxx'
1446
1447        except IndexError:
1448            pass
1449
1450        else:
1451            assert False, 'IndexError not raised'
1452
1453    def testIter(self):
1454        assert list(self.s1) == ['name', 'nick', 'age']
1455
1456    def testKeys(self):
1457        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1458        self.s1.setComponentByPosition(1, univ.OctetString('def'))
1459        self.s1.setComponentByPosition(2, univ.Integer(123))
1460        assert list(self.s1.keys()) == ['name', 'nick', 'age']
1461
1462    def testValues(self):
1463        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1464        self.s1.setComponentByPosition(1, univ.OctetString('def'))
1465        self.s1.setComponentByPosition(2, univ.Integer(123))
1466        assert list(self.s1.values()) == [str2octs('abc'), str2octs('def'), 123]
1467
1468    def testItems(self):
1469        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1470        self.s1.setComponentByPosition(1, univ.OctetString('def'))
1471        self.s1.setComponentByPosition(2, univ.Integer(123))
1472        assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'abc'), ('nick', 'def')]] + [('age', 123)]
1473
1474    def testUpdate(self):
1475        self.s1.clear()
1476        assert list(self.s1.values()) == [str2octs(''), str2octs(''), 34]
1477        self.s1.update(**{'name': 'abc', 'nick': 'def', 'age': 123})
1478        assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'abc'), ('nick', 'def')]] + [('age', 123)]
1479        self.s1.update(('name', 'ABC'))
1480        assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'ABC'), ('nick', 'def')]] + [('age', 123)]
1481        self.s1.update(name='CBA')
1482        assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'CBA'), ('nick', 'def')]] + [('age', 123)]
1483
1484    def testStaticDef(self):
1485
1486        class Sequence(univ.Sequence):
1487            componentType = namedtype.NamedTypes(
1488                namedtype.NamedType('name', univ.OctetString('')),
1489                namedtype.OptionalNamedType('nick', univ.OctetString('')),
1490                namedtype.DefaultedNamedType('age', univ.Integer(34))
1491            )
1492
1493        s = Sequence()
1494        s['name'] = 'abc'
1495        assert s['name'] == str2octs('abc')
1496
1497    def testGetComponentWithDefault(self):
1498
1499        class Sequence(univ.Sequence):
1500            componentType = namedtype.NamedTypes(
1501                namedtype.NamedType('name', univ.OctetString('')),
1502                namedtype.OptionalNamedType('nick', univ.OctetString()),
1503            )
1504
1505        s = Sequence()
1506
1507        assert s[0] == str2octs('')
1508        assert s.getComponentByPosition(1, default=None, instantiate=False) is None
1509        assert s.getComponentByName('nick', default=None) is None
1510        s[1] = 'test'
1511        assert s.getComponentByPosition(1, default=None) is not None
1512        assert s.getComponentByPosition(1, default=None) == str2octs('test')
1513        s.clear()
1514        assert s.getComponentByPosition(1, default=None) is None
1515
1516    def testGetComponentWithConstructedDefault(self):
1517
1518        class Sequence(univ.Sequence):
1519            componentType = namedtype.NamedTypes(
1520                namedtype.NamedType('name', univ.OctetString()),
1521                namedtype.DefaultedNamedType('nick', univ.SequenceOf(
1522                    componentType=univ.Integer()
1523                ).setComponentByPosition(0, 1)),
1524            )
1525
1526        s = Sequence()
1527
1528        assert s.getComponentByPosition(1, default=None, instantiate=False) is None
1529        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
1530        assert s.getComponentByPosition(1) == [1]
1531
1532    def testGetComponentNoInstantiation(self):
1533
1534        class Sequence(univ.Sequence):
1535            componentType = namedtype.NamedTypes(
1536                namedtype.NamedType('name', univ.OctetString('')),
1537                namedtype.OptionalNamedType('nick', univ.OctetString()),
1538            )
1539
1540        s = Sequence()
1541        assert s[0] == str2octs('')
1542        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
1543        assert s.getComponentByName('nick', instantiate=False) is univ.noValue
1544        s[1] = 'test'
1545        assert s.getComponentByPosition(1, instantiate=False) is not univ.noValue
1546        assert s.getComponentByPosition(1, instantiate=False) == str2octs('test')
1547        s.clear()
1548        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
1549
1550    def testSchemaWithComponents(self):
1551
1552        class Sequence(univ.Sequence):
1553            componentType = namedtype.NamedTypes(
1554                namedtype.NamedType('name', univ.OctetString())
1555            )
1556
1557        s = Sequence()
1558
1559        assert not s.isValue
1560
1561        s[0] = 'test'
1562
1563        assert s.isValue
1564
1565        s.clear()
1566
1567        assert not s.isValue
1568
1569        s.reset()
1570
1571        assert not s.isValue
1572
1573    def testSchemaWithOptionalComponents(self):
1574
1575        class Sequence(univ.Sequence):
1576            componentType = namedtype.NamedTypes(
1577                namedtype.OptionalNamedType('name', univ.OctetString())
1578            )
1579
1580        s = Sequence()
1581
1582        assert s.isValue
1583
1584        s[0] = 'test'
1585
1586        assert s.isValue
1587
1588        s.clear()
1589
1590        assert s.isValue
1591
1592        s.reset()
1593
1594        assert not s.isValue
1595
1596    def testSchemaWithOptionalComponents(self):
1597
1598        class Sequence(univ.Sequence):
1599            componentType = namedtype.NamedTypes(
1600                namedtype.DefaultedNamedType('name', univ.OctetString(''))
1601            )
1602
1603        s = Sequence()
1604
1605        assert s.isValue
1606
1607        s[0] = 'test'
1608
1609        assert s.isValue
1610
1611        s.clear()
1612
1613        assert s.isValue
1614
1615        s.reset()
1616
1617        assert not s.isValue
1618
1619    def testIsInconsistentWithComponentsConstraint(self):
1620
1621        class Sequence(univ.Sequence):
1622            componentType = namedtype.NamedTypes(
1623                namedtype.OptionalNamedType('name', univ.OctetString()),
1624                namedtype.DefaultedNamedType('age', univ.Integer(65))
1625            )
1626            subtypeSpec = constraint.WithComponentsConstraint(
1627                ('name', constraint.ComponentPresentConstraint()),
1628                ('age', constraint.ComponentAbsentConstraint())
1629            )
1630
1631        s = Sequence()
1632
1633        assert s.isInconsistent
1634
1635        s[0] = 'test'
1636
1637        assert not s.isInconsistent
1638
1639        s[0] = 'test'
1640        s[1] = 23
1641
1642        assert s.isInconsistent
1643
1644        s.clear()
1645
1646        assert s.isInconsistent
1647
1648        s.reset()
1649
1650        assert s.isInconsistent
1651
1652        s[1] = 23
1653
1654        assert s.isInconsistent
1655
1656    def testIsInconsistentSizeConstraint(self):
1657
1658        class Sequence(univ.Sequence):
1659            componentType = namedtype.NamedTypes(
1660                namedtype.OptionalNamedType('name', univ.OctetString()),
1661                namedtype.DefaultedNamedType('age', univ.Integer(65))
1662            )
1663            subtypeSpec = constraint.ValueSizeConstraint(0, 1)
1664
1665        s = Sequence()
1666
1667        assert not s.isInconsistent
1668
1669        s[0] = 'test'
1670
1671        assert not s.isInconsistent
1672
1673        s[0] = 'test'
1674        s[1] = 23
1675
1676        assert s.isInconsistent
1677
1678        s.clear()
1679
1680        assert not s.isInconsistent
1681
1682        s.reset()
1683
1684        assert s.isInconsistent
1685
1686        s[1] = 23
1687
1688        assert not s.isInconsistent
1689
1690
1691class SequenceWithoutSchema(BaseTestCase):
1692
1693    def testGetItem(self):
1694        s = univ.Sequence()
1695        s.setComponentByPosition(0, univ.OctetString('abc'))
1696        s[0] = 'abc'
1697        assert s['field-0']
1698        assert s[0]
1699
1700        try:
1701            s['field-1']
1702
1703        except KeyError:
1704            pass
1705
1706        else:
1707            assert False, 'KeyError not raised'
1708
1709    def testSetItem(self):
1710        s = univ.Sequence()
1711        s.setComponentByPosition(0, univ.OctetString('abc'))
1712        s['field-0'] = 'xxx'
1713
1714        try:
1715
1716            s['field-1'] = 'xxx'
1717
1718        except KeyError:
1719            pass
1720
1721        else:
1722            assert False, 'KeyError not raised'
1723
1724    def testIter(self):
1725        s = univ.Sequence()
1726        s.setComponentByPosition(0, univ.OctetString('abc'))
1727        s.setComponentByPosition(1, univ.Integer(123))
1728        assert list(s) == ['field-0', 'field-1']
1729
1730    def testKeys(self):
1731        s = univ.Sequence()
1732        s.setComponentByPosition(0, univ.OctetString('abc'))
1733        s.setComponentByPosition(1, univ.Integer(123))
1734        assert list(s.keys()) == ['field-0', 'field-1']
1735
1736    def testValues(self):
1737        s = univ.Sequence()
1738        s.setComponentByPosition(0, univ.OctetString('abc'))
1739        s.setComponentByPosition(1, univ.Integer(123))
1740        assert list(s.values()) == [str2octs('abc'), 123]
1741
1742    def testItems(self):
1743        s = univ.Sequence()
1744        s.setComponentByPosition(0, univ.OctetString('abc'))
1745        s.setComponentByPosition(1, univ.Integer(123))
1746        assert list(s.items()) == [('field-0', str2octs('abc')), ('field-1', 123)]
1747
1748    def testUpdate(self):
1749        s = univ.Sequence().clear()
1750        assert not s
1751        s.setComponentByPosition(0, univ.OctetString('abc'))
1752        s.setComponentByPosition(1, univ.Integer(123))
1753        assert s
1754        assert list(s.keys()) == ['field-0', 'field-1']
1755        assert list(s.values()) == [str2octs('abc'), 123]
1756        assert list(s.items()) == [('field-0', str2octs('abc')), ('field-1', 123)]
1757        s['field-0'] = univ.OctetString('def')
1758        assert list(s.values()) == [str2octs('def'), 123]
1759        s['field-1'] = univ.OctetString('ghi')
1760        assert list(s.values()) == [str2octs('def'), str2octs('ghi')]
1761        try:
1762            s['field-2'] = univ.OctetString('xxx')
1763        except KeyError:
1764            pass
1765        else:
1766            assert False, 'unknown field at schema-less object tolerated'
1767        assert 'field-0' in s
1768        s.clear()
1769        assert 'field-0' not in s
1770
1771    def testSchema(self):
1772
1773        class Sequence(univ.Sequence):
1774            pass
1775
1776        s = Sequence()
1777
1778        assert not s.isValue
1779
1780        s[0] = univ.OctetString('test')
1781
1782        assert s.isValue
1783
1784        s.clear()
1785
1786        assert s.isValue
1787
1788        s.reset()
1789
1790        assert not s.isValue
1791
1792
1793class SequencePicklingTestCase(unittest.TestCase):
1794
1795    def testSchemaPickling(self):
1796        old_asn1 = univ.Sequence(
1797            componentType=namedtype.NamedTypes(
1798                namedtype.NamedType('name', univ.OctetString())
1799            )
1800        )
1801        serialised = pickle.dumps(old_asn1)
1802        assert serialised
1803        new_asn1 = pickle.loads(serialised)
1804        assert type(new_asn1) == univ.Sequence
1805        assert old_asn1.isSameTypeWith(new_asn1)
1806
1807    def testValuePickling(self):
1808        old_asn1 = univ.Sequence(
1809            componentType=namedtype.NamedTypes(
1810                namedtype.NamedType('name', univ.OctetString())
1811            )
1812        )
1813        old_asn1['name'] = 'test'
1814        serialised = pickle.dumps(old_asn1)
1815        assert serialised
1816        new_asn1 = pickle.loads(serialised)
1817        assert new_asn1
1818        assert new_asn1['name'] == str2octs('test')
1819
1820
1821class SetOf(BaseTestCase):
1822    def setUp(self):
1823        BaseTestCase.setUp(self)
1824        self.s1 = univ.SetOf(componentType=univ.OctetString(''))
1825
1826    def testTag(self):
1827        assert self.s1.tagSet == tag.TagSet(
1828            (),
1829            tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)
1830        ), 'wrong tagSet'
1831
1832    def testSeq(self):
1833        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
1834        assert self.s1[0] == str2octs('abc'), 'set by idx fails'
1835        self.s1.setComponentByPosition(0, self.s1[0].clone('cba'))
1836        assert self.s1[0] == str2octs('cba'), 'set by idx fails'
1837
1838    def testStaticDef(self):
1839
1840        class SetOf(univ.SequenceOf):
1841            componentType = univ.OctetString('')
1842
1843        s = SetOf()
1844        s[0] = 'abc'
1845        assert len(s) == 1
1846        assert s == [str2octs('abc')]
1847
1848
1849
1850class SetOfPicklingTestCase(unittest.TestCase):
1851
1852    def testSchemaPickling(self):
1853        old_asn1 = univ.SetOf(componentType=univ.OctetString())
1854        serialised = pickle.dumps(old_asn1)
1855        assert serialised
1856        new_asn1 = pickle.loads(serialised)
1857        assert type(new_asn1) == univ.SetOf
1858        assert old_asn1.isSameTypeWith(new_asn1)
1859
1860    def testValuePickling(self):
1861        old_asn1 = univ.SetOf(componentType=univ.OctetString())
1862        old_asn1[0] = 'test'
1863        serialised = pickle.dumps(old_asn1)
1864        assert serialised
1865        new_asn1 = pickle.loads(serialised)
1866        assert new_asn1
1867        assert new_asn1 == [str2octs('test')]
1868
1869
1870class Set(BaseTestCase):
1871    def setUp(self):
1872        BaseTestCase.setUp(self)
1873
1874        self.s1 = univ.Set(
1875            componentType=namedtype.NamedTypes(
1876                namedtype.NamedType('name', univ.OctetString('')),
1877                namedtype.OptionalNamedType('null', univ.Null('')),
1878                namedtype.DefaultedNamedType('age', univ.Integer(34))
1879            )
1880        )
1881        self.s2 = self.s1.clone()
1882
1883    def testTag(self):
1884        assert self.s1.tagSet == tag.TagSet(
1885            (),
1886            tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11)
1887        ), 'wrong tagSet'
1888
1889    def testByTypeWithPythonValue(self):
1890        self.s1.setComponentByType(univ.OctetString.tagSet, 'abc')
1891        assert self.s1.getComponentByType(
1892            univ.OctetString.tagSet
1893        ) == str2octs('abc'), 'set by name fails'
1894
1895    def testByTypeWithInstance(self):
1896        self.s1.setComponentByType(univ.OctetString.tagSet, univ.OctetString('abc'))
1897        assert self.s1.getComponentByType(
1898            univ.OctetString.tagSet
1899        ) == str2octs('abc'), 'set by name fails'
1900
1901    def testGetTagMap(self):
1902        assert self.s1.tagMap.presentTypes == {
1903            univ.Set.tagSet: univ.Set().clear()
1904        }
1905
1906    def testGetComponentTagMap(self):
1907        assert self.s1.componentType.tagMapUnique.presentTypes == {
1908            univ.OctetString.tagSet: univ.OctetString(''),
1909            univ.Null.tagSet: univ.Null(''),
1910            univ.Integer.tagSet: univ.Integer(34)
1911        }
1912
1913    def testGetPositionByType(self):
1914        assert self.s1.componentType.getPositionByType(univ.Null().tagSet) == 1
1915
1916    def testSetToDefault(self):
1917        self.s1.setComponentByName('name', univ.noValue)
1918        assert self.s1['name'] == univ.OctetString('')
1919
1920    def testIter(self):
1921        assert list(self.s1) == ['name', 'null', 'age']
1922
1923    def testStaticDef(self):
1924
1925        class Set(univ.Set):
1926            componentType = namedtype.NamedTypes(
1927                namedtype.NamedType('name', univ.OctetString('')),
1928                namedtype.OptionalNamedType('nick', univ.OctetString('')),
1929                namedtype.DefaultedNamedType('age', univ.Integer(34))
1930            )
1931
1932        s = Set()
1933        s['name'] = 'abc'
1934        assert s['name'] == str2octs('abc')
1935
1936    def testGetComponentWithDefault(self):
1937
1938        class Set(univ.Set):
1939            componentType = namedtype.NamedTypes(
1940                namedtype.NamedType('id', univ.Integer(123)),
1941                namedtype.OptionalNamedType('nick', univ.OctetString()),
1942            )
1943
1944        s = Set()
1945        assert s[0] == 123
1946        assert s.getComponentByPosition(1, default=None, instantiate=False) is None
1947        assert s.getComponentByName('nick', default=None) is None
1948        s[1] = 'test'
1949        assert s.getComponentByPosition(1, default=None) is not None
1950        assert s.getComponentByPosition(1, default=None) == str2octs('test')
1951        s.clear()
1952        assert s.getComponentByPosition(1, default=None) is None
1953
1954    def testGetComponentNoInstantiation(self):
1955
1956        class Set(univ.Set):
1957            componentType = namedtype.NamedTypes(
1958                namedtype.NamedType('id', univ.Integer(123)),
1959                namedtype.OptionalNamedType('nick', univ.OctetString()),
1960            )
1961
1962        s = Set()
1963        assert s[0] == 123
1964        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
1965        assert s.getComponentByName('nick', instantiate=False) is univ.noValue
1966        assert s.getComponentByType(univ.OctetString.tagSet, instantiate=False) is univ.noValue
1967        s[1] = 'test'
1968        assert s.getComponentByPosition(1, instantiate=False) is not univ.noValue
1969        assert s.getComponentByPosition(1, instantiate=False) == str2octs('test')
1970        s.clear()
1971        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
1972
1973
1974class SetPicklingTestCase(unittest.TestCase):
1975
1976    def testSchemaPickling(self):
1977        old_asn1 = univ.Set(
1978            componentType=namedtype.NamedTypes(
1979                namedtype.NamedType('name', univ.OctetString())
1980            )
1981        )
1982        serialised = pickle.dumps(old_asn1)
1983        assert serialised
1984        new_asn1 = pickle.loads(serialised)
1985        assert type(new_asn1) == univ.Set
1986        assert old_asn1.isSameTypeWith(new_asn1)
1987
1988    def testValuePickling(self):
1989        old_asn1 = univ.Set(
1990            componentType=namedtype.NamedTypes(
1991                namedtype.NamedType('name', univ.OctetString())
1992            )
1993        )
1994        old_asn1['name'] = 'test'
1995        serialised = pickle.dumps(old_asn1)
1996        assert serialised
1997        new_asn1 = pickle.loads(serialised)
1998        assert new_asn1
1999        assert new_asn1['name'] == str2octs('test')
2000
2001
2002class Choice(BaseTestCase):
2003    def setUp(self):
2004        BaseTestCase.setUp(self)
2005
2006        innerComp = univ.Choice(
2007            componentType=namedtype.NamedTypes(
2008                namedtype.NamedType('count', univ.Integer()),
2009                namedtype.NamedType('flag', univ.Boolean())
2010            )
2011        )
2012        self.s1 = univ.Choice(
2013            componentType=namedtype.NamedTypes(
2014                namedtype.NamedType('name', univ.OctetString()),
2015                namedtype.NamedType('sex', innerComp)
2016            )
2017        )
2018
2019    def testTag(self):
2020        assert self.s1.tagSet == tag.TagSet(), 'wrong tagSet'
2021
2022    def testRepr(self):
2023        assert 'Choice' in repr(self.s1.clone().setComponents('a'))
2024        s = self.s1.clone().setComponents(
2025                sex=self.s1.setComponentByPosition(1).getComponentByPosition(1).clone().setComponents(count=univ.Integer(123))
2026        )
2027        assert 'Choice' in repr(s)
2028
2029    def testContains(self):
2030        self.s1.setComponentByType(univ.OctetString.tagSet, 'abc')
2031        assert 'name' in self.s1
2032        assert 'sex' not in self.s1
2033
2034        self.s1.setComponentByType(univ.Integer.tagSet, 123, innerFlag=True)
2035        assert 'name' not in self.s1
2036        assert 'sex' in self.s1
2037
2038    def testIter(self):
2039        self.s1.setComponentByType(univ.OctetString.tagSet, 'abc')
2040        assert list(self.s1) == ['name']
2041        self.s1.setComponentByType(univ.Integer.tagSet, 123, innerFlag=True)
2042        assert list(self.s1) == ['sex']
2043
2044    def testOuterByTypeWithPythonValue(self):
2045        self.s1.setComponentByType(univ.OctetString.tagSet, 'abc')
2046        assert self.s1.getComponentByType(
2047            univ.OctetString.tagSet
2048        ) == str2octs('abc')
2049
2050    def testOuterByTypeWithInstanceValue(self):
2051        self.s1.setComponentByType(
2052            univ.OctetString.tagSet, univ.OctetString('abc')
2053        )
2054        assert self.s1.getComponentByType(
2055            univ.OctetString.tagSet
2056        ) == str2octs('abc')
2057
2058    def testInnerByTypeWithPythonValue(self):
2059        self.s1.setComponentByType(univ.Integer.tagSet, 123, innerFlag=True)
2060        assert self.s1.getComponentByType(
2061            univ.Integer.tagSet, 1
2062        ) == 123
2063
2064    def testInnerByTypeWithInstanceValue(self):
2065        self.s1.setComponentByType(
2066            univ.Integer.tagSet, univ.Integer(123), innerFlag=True
2067        )
2068        assert self.s1.getComponentByType(
2069            univ.Integer.tagSet, 1
2070        ) == 123
2071
2072    def testCmp(self):
2073        self.s1.setComponentByName('name', univ.OctetString('abc'))
2074        assert self.s1 == str2octs('abc'), '__cmp__() fails'
2075
2076    def testGetComponent(self):
2077        self.s1.setComponentByType(univ.OctetString.tagSet, 'abc')
2078        assert self.s1.getComponent() == str2octs('abc'), 'getComponent() fails'
2079
2080    def testGetName(self):
2081        self.s1.setComponentByType(univ.OctetString.tagSet, 'abc')
2082        assert self.s1.getName() == 'name', 'getName() fails'
2083
2084    def testSetComponentByPosition(self):
2085        self.s1.setComponentByPosition(0, univ.OctetString('Jim'))
2086        assert self.s1 == str2octs('Jim')
2087
2088    def testClone(self):
2089        self.s1.setComponentByPosition(0, univ.OctetString('abc'))
2090        s = self.s1.clone()
2091        assert len(s) == 0
2092        s = self.s1.clone(cloneValueFlag=1)
2093        assert len(s) == 1
2094        assert s.getComponentByPosition(0) == self.s1.getComponentByPosition(0)
2095
2096    def testSetToDefault(self):
2097        s = self.s1.clone()
2098        s.setComponentByName('sex', univ.noValue)
2099        assert s['sex'] is not univ.noValue
2100
2101    def testStaticDef(self):
2102
2103        class InnerChoice(univ.Choice):
2104            componentType = namedtype.NamedTypes(
2105                namedtype.NamedType('count', univ.Integer()),
2106                namedtype.NamedType('flag', univ.Boolean())
2107            )
2108
2109        class OuterChoice(univ.Choice):
2110            componentType = namedtype.NamedTypes(
2111                namedtype.NamedType('name', univ.OctetString()),
2112                namedtype.NamedType('sex', InnerChoice())
2113            )
2114
2115        c = OuterChoice()
2116
2117        c.setComponentByType(univ.OctetString.tagSet, 'abc')
2118        assert c.getName() == 'name'
2119
2120    def testGetComponentWithDefault(self):
2121
2122        s = univ.Choice(
2123            componentType=namedtype.NamedTypes(
2124                namedtype.NamedType('name', univ.OctetString()),
2125                namedtype.NamedType('id', univ.Integer())
2126            )
2127        )
2128
2129        assert s.getComponentByPosition(0, default=None, instantiate=False) is None
2130        assert s.getComponentByPosition(1, default=None, instantiate=False) is None
2131        assert s.getComponentByName('name', default=None, instantiate=False) is None
2132        assert s.getComponentByName('id', default=None, instantiate=False) is None
2133        assert s.getComponentByType(univ.OctetString.tagSet, default=None) is None
2134        assert s.getComponentByType(univ.Integer.tagSet, default=None) is None
2135        s[1] = 123
2136        assert s.getComponentByPosition(1, default=None) is not None
2137        assert s.getComponentByPosition(1, univ.noValue) == 123
2138        s.clear()
2139        assert s.getComponentByPosition(1, default=None, instantiate=False) is None
2140
2141    def testGetComponentNoInstantiation(self):
2142
2143        s = univ.Choice(
2144            componentType=namedtype.NamedTypes(
2145                namedtype.NamedType('name', univ.OctetString()),
2146                namedtype.NamedType('id', univ.Integer())
2147            )
2148        )
2149
2150        assert s.getComponentByPosition(0, instantiate=False) is univ.noValue
2151        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
2152        assert s.getComponentByName('name', instantiate=False) is univ.noValue
2153        assert s.getComponentByName('id', instantiate=False) is univ.noValue
2154        assert s.getComponentByType(univ.OctetString.tagSet, instantiate=False) is univ.noValue
2155        assert s.getComponentByType(univ.Integer.tagSet, instantiate=False) is univ.noValue
2156        s[1] = 123
2157        assert s.getComponentByPosition(1, instantiate=False) is not univ.noValue
2158        assert s.getComponentByPosition(1, instantiate=False) == 123
2159        s.clear()
2160        assert s.getComponentByPosition(1, instantiate=False) is univ.noValue
2161
2162
2163class ChoicePicklingTestCase(unittest.TestCase):
2164
2165    def testSchemaPickling(self):
2166        old_asn1 = univ.Choice(
2167            componentType=namedtype.NamedTypes(
2168                namedtype.NamedType('name', univ.OctetString()),
2169                namedtype.NamedType('id', univ.Integer())
2170            )
2171        )
2172        serialised = pickle.dumps(old_asn1)
2173        assert serialised
2174        new_asn1 = pickle.loads(serialised)
2175        assert type(new_asn1) == univ.Choice
2176        assert old_asn1.isSameTypeWith(new_asn1)
2177
2178    def testValuePickling(self):
2179        old_asn1 = univ.Choice(
2180            componentType=namedtype.NamedTypes(
2181                namedtype.NamedType('name', univ.OctetString()),
2182                namedtype.NamedType('id', univ.Integer())
2183            )
2184        )
2185        old_asn1['name'] = 'test'
2186        serialised = pickle.dumps(old_asn1)
2187        assert serialised
2188        new_asn1 = pickle.loads(serialised)
2189        assert new_asn1
2190        assert new_asn1['name'] == str2octs('test')
2191
2192
2193suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
2194
2195if __name__ == '__main__':
2196    unittest.TextTestRunner(verbosity=2).run(suite)
2197