File: test_interface_generator.py

package info (click to toggle)
python-sdbus 0.14.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 996 kB
  • sloc: python: 7,911; ansic: 2,507; makefile: 9; sh: 4
file content (343 lines) | stat: -rw-r--r-- 11,217 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# SPDX-License-Identifier: LGPL-2.1-or-later

# Copyright (C) 2020, 2021 igo95862

# This file is part of python-sdbus

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
from __future__ import annotations

from importlib.util import find_spec
from unittest import SkipTest, TestCase, main
from unittest.mock import MagicMock, patch

from sdbus.__main__ import generator_main
from sdbus.interface_generator import (
    DbusSigToTyping,
    camel_case_to_snake_case,
    generate_py_file,
    interface_name_to_class,
    interfaces_from_str,
)
from sdbus.unittest import IsolatedDbusTestCase

test_xml = """
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
  "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node name="/com/example/sample_object0">
    <interface name="com.example.SampleInterface0">
      <method name="Frobate">
        <arg name="foo" type="i" direction="in"/>
        <arg name="bar" type="s" direction="out"/>
        <arg name="baz" type="a{us}" direction="out"/>
        <annotation name="org.freedesktop.DBus.Deprecated" value="true"/>
        <annotation name="org.freedesktop.systemd1.Privileged" value="true"/>
      </method>
      <method name="Bazify">
        <arg name="bar" type="(iiu)" direction="in"/>
        <arg name="bar" type="v" direction="out"/>
      </method>
      <method name="Mogrify">
        <arg name="bar" type="(iiav)" direction="in"/>
      </method>
      <signal name="Changed">
        <arg name="new_value" type="b"/>
      </signal>
      <property name="Bar" type="y" access="readwrite"/>
      <property name="FooFoo" type="as" access="read">
        <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal"
        value="false"/>
      </property>
      <property name="BoundBy" type="as" access="read">
        <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal"
        value="const"/>
      </property>
      <property name="FooInvalidates" type="s" access="read">
        <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal"
        value="invalidates"/>
      </property>
    </interface>
    <node name="child_of_sample_object"/>
    <node name="another_child_of_sample_object"/>
</node>
"""


class TestConverter(TestCase):
    def test_camel_to_snake(self) -> None:
        with self.subTest("CamelCase"):
            self.assertEqual(
                'activate_connection',
                camel_case_to_snake_case('ActivateConnection'),
            )

        with self.subTest("Already snake case"):
            self.assertEqual(
                'activate_connection',
                camel_case_to_snake_case('activate_connection'),
            )

        with self.subTest("Upper snake case"):
            self.assertEqual(
                'activate_connection',
                camel_case_to_snake_case('ACTIVATE_CONNECTION'),
            )

    def test_interface_name_to_class(self) -> None:
        self.assertEqual(
            'ComExampleSampleInterface0',
            interface_name_to_class('com.example.SampleInterface0'),
        )

    def test_signature_to_typing(self) -> None:
        with self.subTest('Parse basic'):
            self.assertEqual(
                'str', DbusSigToTyping.typing_basic('s')
            )

            self.assertRaises(
                KeyError, DbusSigToTyping.typing_basic, 'v')

        with self.subTest('Parse variant'):
            self.assertEqual(
                'tuple[str, Any]', DbusSigToTyping.typing_complete('v')
            )

        with self.subTest('Splitter test'):
            self.assertEqual(
                ['v', 'as', '(uisa{sx})', 'h', 'a(ss)', 'a{ss}', 'ay'],
                DbusSigToTyping.split_sig('vas(uisa{sx})ha(ss)a{ss}ay')
            )

        with self.subTest('Parse struct'):
            self.assertEqual(
                DbusSigToTyping.typing_complete('(sx)'),
                'tuple[str, int]',
            )

        with self.subTest('Parse list'):
            self.assertEqual(
                DbusSigToTyping.typing_complete('a(sx)'),
                'list[tuple[str, int]]',
            )

        with self.subTest('Parse dict'):
            self.assertEqual(
                DbusSigToTyping.typing_complete('a{s(xh)}'),
                'dict[str, tuple[int, int]]',
            )

        with self.subTest('Parse signature'):
            self.assertEqual(
                DbusSigToTyping.sig_to_typing('a{s(xh)}'),
                'dict[str, tuple[int, int]]',
            )

            self.assertEqual(
                DbusSigToTyping.sig_to_typing('a{s(xh)}xs'),
                'tuple[dict[str, tuple[int, int]], int, str]',
            )

            self.assertEqual(
                DbusSigToTyping.sig_to_typing('a{s(xh)}xs'),
                'tuple[dict[str, tuple[int, int]], int, str]',
            )

            self.assertEqual(
                DbusSigToTyping.sig_to_typing('as'),
                'list[str]',
            )

            self.assertEqual(
                DbusSigToTyping.sig_to_typing(''),
                'None',
            )

    def test_parsing(self) -> None:
        if find_spec('jinja2') is None:
            raise SkipTest('Jinja2 not installed')

        interfaces_intro = interfaces_from_str(test_xml)

        with self.subTest('Test introspection details'):
            test_interface = interfaces_intro[0]

            for test_property in test_interface.properties:
                if test_property.method_name == 'BoundBy':
                    self.assertEqual(
                        test_property.emits_changed,
                        'const',
                    )
                elif test_property.method_name == 'Bar':
                    self.assertEqual(
                        test_property.emits_changed,
                        True,
                    )
                elif test_property.method_name == 'FooInvalidates':
                    self.assertEqual(
                        test_property.emits_changed,
                        'invalidates',
                    )
                elif test_property.method_name == 'FooFoo':
                    self.assertEqual(
                        test_property.emits_changed,
                        False,
                    )

        generated = generate_py_file(interfaces_intro)
        self.assertIn('flags=DbusPropertyEmitsInvalidationFlag', generated)
        self.assertIn('flags=DbusPropertyConstFlag', generated)


class TestGeneratorAgainstDbus(IsolatedDbusTestCase):
    def setUp(self) -> None:
        if find_spec('jinja2') is None:
            raise SkipTest('Jinja2 not installed')

        super().setUp()

    def test_generate_from_connection(self) -> None:
        with patch("sdbus.__main__.stdout") as stdout_mock:
            generator_main(
                [
                    "gen-from-connection",
                    "org.freedesktop.DBus",
                    "/org/freedesktop/DBus",
                ]
            )

        write_mock: MagicMock = stdout_mock.write
        write_mock.assert_called_once()

        generated_interface = write_mock.call_args.args[0]

        self.assertIn(
            "OrgFreedesktopDBusDebugStatsInterface",
            generated_interface,
        )
        self.assertIn(
            "get_connection_unix_process_id",
            generated_interface,
        )
        self.assertIn(
            "async",
            generated_interface,
        )

    def test_generate_from_connection_blocking(self) -> None:
        with patch("sdbus.__main__.stdout") as stdout_mock:
            generator_main(
                [
                    "gen-from-connection",
                    "--block",
                    "org.freedesktop.DBus",
                    "/org/freedesktop/DBus",
                ]
            )

        write_mock: MagicMock = stdout_mock.write
        write_mock.assert_called_once()

        generated_interface = write_mock.call_args.args[0]

        self.assertNotIn(
            "async",
            generated_interface,
        )
        self.assertIn(
            "dbus_property",
            generated_interface,
        )


INTERFACE_NO_MEMBERS_XML = """
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
  "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node name="/com/example/sample_object0">
    <interface name="com.example.SampleInterface1">
    </interface>
    <node name="child_of_sample_object"/>
    <node name="another_child_of_sample_object"/>
</node>
"""


class TestGeneratorSyntaxCompile(TestCase):
    def setUp(self) -> None:
        if find_spec('jinja2') is None:
            raise SkipTest('Jinja2 not installed')

        super().setUp()

    def test_syntax_compile_async(self) -> None:
        source_code = generate_py_file(
            interfaces_from_str(test_xml),
            do_async=True,
        )
        compile(source_code, filename="<string>", mode="exec")

    def test_syntax_compile_block(self) -> None:
        source_code = generate_py_file(
            interfaces_from_str(test_xml),
            do_async=False,
        )
        compile(source_code, filename="<string>", mode="exec")

    def test_syntax_no_members_interface(self) -> None:

        regular_interface = interfaces_from_str(test_xml)
        no_members_interface = interfaces_from_str(INTERFACE_NO_MEMBERS_XML)

        self.assertFalse(no_members_interface[0].methods)
        self.assertFalse(no_members_interface[0].properties)
        self.assertFalse(no_members_interface[0].signals)

        compile(
            generate_py_file(
                regular_interface + no_members_interface,
                do_async=True,
            ),
            filename="<string>",
            mode="exec",
        )
        compile(
            generate_py_file(
                no_members_interface + regular_interface,
                do_async=True,
            ),
            filename="<string>",
            mode="exec",
        )

        compile(
            generate_py_file(
                regular_interface + no_members_interface,
                do_async=False,
            ),
            filename="<string>",
            mode="exec",
        )
        compile(
            generate_py_file(
                no_members_interface + regular_interface,
                do_async=False,
            ),
            filename="<string>",
            mode="exec",
        )


if __name__ == "__main__":
    main()