Debian Codegraph @

oslo_privsep/tests/unit/test_comm.py

raw
1 # Copyright 2015 Rackspace Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import io
16
17 from oslotest import base
18
19 from oslo_privsep import comm
20
21
22 class BufSock:
23 def __init__(self):
24 self.readpos = 0
25 self.buf = io.BytesIO()
26
27 def recv(self, bufsize):
28 if self.buf.closed:
29 return b''
30 self.buf.seek(self.readpos, 0)
31 data = self.buf.read(bufsize)
32 self.readpos += len(data)
33 return data
34
35 def sendall(self, data):
36 self.buf.seek(0, 2)
37 self.buf.write(data)
38
39 def shutdown(self, _flag):
40 self.buf.close()
41
42
43 class TestSerialization(base.BaseTestCase):
44 def setUp(self):
45 super().setUp()
46
47 sock = BufSock()
48
49 self.input = comm.Serializer(sock) # type: ignore[arg-type]
50 self.output = iter(comm.Deserializer(sock)) # type: ignore[arg-type]
51
52 def send(self, data):
53 self.input.send(data)
54 return next(self.output)
55
56 def assertSendable(self, value):
57 self.assertEqual(value, self.send(value))
58
59 def test_none(self):
60 self.assertSendable(None)
61
62 def test_bool(self):
63 self.assertSendable(True)
64 self.assertSendable(False)
65
66 def test_int(self):
67 self.assertSendable(42)
68 self.assertSendable(-84)
69
70 def test_bytes(self):
71 data = b'\x00\x01\x02\xfd\xfe\xff'
72 self.assertSendable(data)
73
74 def test_unicode(self):
75 data = '\u4e09\u9df9\udc82'
76 self.assertSendable(data)
77
78 def test_tuple(self):
79 self.assertSendable((1, 'foo'))
80
81 def test_list(self):
82 # NB! currently lists get converted to tuples by serialization.
83 self.assertEqual((1, 'foo'), self.send([1, 'foo']))
84
85 def test_dict(self):
86 self.assertSendable(
87 {
88 'a': 'b',
89 1: 2,
90 None: None,
91 (1, 2): (3, 4),
92 }
93 )
94
95 def test_badobj(self):
96 class UnknownClass:
97 pass
98
99 obj = UnknownClass()
100 self.assertRaises(TypeError, self.send, obj)
101
102 def test_eof(self):
103 self.input.close()
104 self.assertRaises(StopIteration, next, self.output)