Debian Codegraph @

glib/gio/tests/codegen.py

raw
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright © 2018, 2019 Endless Mobile, Inc.
5 #
6 # SPDX-License-Identifier: LGPL-2.1-or-later
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 # MA 02110-1301 USA
22
23 """Integration tests for gdbus-codegen utility."""
24
25 import collections
26 import os
27 import shutil
28 import subprocess
29 import sys
30 import tempfile
31 import textwrap
32 import unittest
33 import xml.etree.ElementTree as ET
34
35 import taptestrunner
36
37 # Disable line length warnings as wrapping the C code templates would be hard
38 # flake8: noqa: E501
39
40
41 Result = collections.namedtuple("Result", ("info", "out", "err", "subs"))
42
43
44 def on_win32():
45 return sys.platform.find("win") != -1
46
47
48 class TestCodegen(unittest.TestCase):
49 """Integration test for running gdbus-codegen.
50
51 This can be run when installed or uninstalled. When uninstalled, it
52 requires G_TEST_BUILDDIR and G_TEST_SRCDIR to be set.
53
54 The idea with this test harness is to test the gdbus-codegen utility, its
55 handling of command line arguments, its exit statuses, and its handling of
56 various C source codes. In future we could split out tests for the core
57 parsing and generation code of gdbus-codegen into separate unit tests, and
58 just test command line behaviour in this integration test.
59 """
60
61 # Track the cwd, we want to back out to that to clean up our tempdir
62 cwd = ""
63
64 ARGUMENTS_TYPES = {
65 "b": {"value_type": "boolean"},
66 "y": {"value_type": "uchar"},
67 "n": {"value_type": "int"},
68 "q": {"value_type": "uint"},
69 "i": {"value_type": "int"},
70 "u": {"value_type": "uint"},
71 "x": {"value_type": "int64", "lacks_marshaller": True},
72 "t": {"value_type": "uint64", "lacks_marshaller": True},
73 "d": {"value_type": "double"},
74 "s": {"value_type": "string"},
75 "o": {"value_type": "string"},
76 "g": {"value_type": "string"},
77 "h": {"value_type": "variant"},
78 "ay": {"value_type": "string"},
79 "as": {"value_type": "boxed"},
80 "ao": {"value_type": "boxed"},
81 "aay": {"value_type": "boxed"},
82 "asv": {"value_type": "variant", "variant_type": "a{sv}"},
83 }
84
85 def setUp(self):
86 self.timeout_seconds = 6 # seconds per test
87 self.tmpdir = tempfile.TemporaryDirectory()
88 self.cwd = os.getcwd()
89 os.chdir(self.tmpdir.name)
90 print("tmpdir:", self.tmpdir.name)
91 if "G_TEST_BUILDDIR" in os.environ:
92 self.__codegen = os.path.join(
93 os.environ["G_TEST_BUILDDIR"],
94 "..",
95 "gdbus-2.0",
96 "codegen",
97 "gdbus-codegen",
98 )
99 else:
100 self.__codegen = shutil.which("gdbus-codegen")
101 print("codegen:", self.__codegen)
102
103 def tearDown(self):
104 os.chdir(self.cwd)
105 self.tmpdir.cleanup()
106
107 def runCodegen(self, *args):
108 argv = [self.__codegen]
109
110 # shebang lines are not supported on native
111 # Windows consoles
112 if os.name == "nt":
113 argv.insert(0, sys.executable)
114
115 argv.extend(args)
116 print("Running:", argv)
117
118 env = os.environ.copy()
119 env["LC_ALL"] = "C.UTF-8"
120 env["G_DEBUG"] = "fatal-warnings"
121 print("Environment:", env)
122
123 # We want to ensure consistent line endings...
124 info = subprocess.run(
125 argv,
126 timeout=self.timeout_seconds,
127 stdout=subprocess.PIPE,
128 stderr=subprocess.PIPE,
129 env=env,
130 universal_newlines=True,
131 )
132 info.check_returncode()
133 out = info.stdout.strip()
134 err = info.stderr.strip()
135
136 # Known substitutions for standard boilerplate
137 subs = {
138 "standard_top_comment": "/*\n"
139 " * This file is generated by gdbus-codegen, do not modify it.\n"
140 " *\n"
141 " * The license of this code is the same as for the D-Bus interface description\n"
142 " * it was derived from. Note that it links to GLib, so must comply with the\n"
143 " * LGPL linking clauses.\n"
144 " */",
145 "standard_config_h_include": "#ifdef HAVE_CONFIG_H\n"
146 '# include "config.h"\n'
147 "#endif",
148 "standard_header_includes": "#include <string.h>\n"
149 "#ifdef G_OS_UNIX\n"
150 "# include <gio/gunixfdlist.h>\n"
151 "#endif",
152 "private_gvalues_getters": """#ifdef G_ENABLE_DEBUG
153 #define g_marshal_value_peek_boolean(v) g_value_get_boolean (v)
154 #define g_marshal_value_peek_char(v) g_value_get_schar (v)
155 #define g_marshal_value_peek_uchar(v) g_value_get_uchar (v)
156 #define g_marshal_value_peek_int(v) g_value_get_int (v)
157 #define g_marshal_value_peek_uint(v) g_value_get_uint (v)
158 #define g_marshal_value_peek_long(v) g_value_get_long (v)
159 #define g_marshal_value_peek_ulong(v) g_value_get_ulong (v)
160 #define g_marshal_value_peek_int64(v) g_value_get_int64 (v)
161 #define g_marshal_value_peek_uint64(v) g_value_get_uint64 (v)
162 #define g_marshal_value_peek_enum(v) g_value_get_enum (v)
163 #define g_marshal_value_peek_flags(v) g_value_get_flags (v)
164 #define g_marshal_value_peek_float(v) g_value_get_float (v)
165 #define g_marshal_value_peek_double(v) g_value_get_double (v)
166 #define g_marshal_value_peek_string(v) (char*) g_value_get_string (v)
167 #define g_marshal_value_peek_param(v) g_value_get_param (v)
168 #define g_marshal_value_peek_boxed(v) g_value_get_boxed (v)
169 #define g_marshal_value_peek_pointer(v) g_value_get_pointer (v)
170 #define g_marshal_value_peek_object(v) g_value_get_object (v)
171 #define g_marshal_value_peek_variant(v) g_value_get_variant (v)
172 #else /* !G_ENABLE_DEBUG */
173 /* WARNING: This code accesses GValues directly, which is UNSUPPORTED API.
174 * Do not access GValues directly in your code. Instead, use the
175 * g_value_get_*() functions
176 */
177 #define g_marshal_value_peek_boolean(v) (v)->data[0].v_int
178 #define g_marshal_value_peek_char(v) (v)->data[0].v_int
179 #define g_marshal_value_peek_uchar(v) (v)->data[0].v_uint
180 #define g_marshal_value_peek_int(v) (v)->data[0].v_int
181 #define g_marshal_value_peek_uint(v) (v)->data[0].v_uint
182 #define g_marshal_value_peek_long(v) (v)->data[0].v_long
183 #define g_marshal_value_peek_ulong(v) (v)->data[0].v_ulong
184 #define g_marshal_value_peek_int64(v) (v)->data[0].v_int64
185 #define g_marshal_value_peek_uint64(v) (v)->data[0].v_uint64
186 #define g_marshal_value_peek_enum(v) (v)->data[0].v_long
187 #define g_marshal_value_peek_flags(v) (v)->data[0].v_ulong
188 #define g_marshal_value_peek_float(v) (v)->data[0].v_float
189 #define g_marshal_value_peek_double(v) (v)->data[0].v_double
190 #define g_marshal_value_peek_string(v) (v)->data[0].v_pointer
191 #define g_marshal_value_peek_param(v) (v)->data[0].v_pointer
192 #define g_marshal_value_peek_boxed(v) (v)->data[0].v_pointer
193 #define g_marshal_value_peek_pointer(v) (v)->data[0].v_pointer
194 #define g_marshal_value_peek_object(v) (v)->data[0].v_pointer
195 #define g_marshal_value_peek_variant(v) (v)->data[0].v_pointer
196 #endif /* !G_ENABLE_DEBUG */""",
197 "standard_typedefs_and_helpers": "typedef struct\n"
198 "{\n"
199 " GDBusArgInfo parent_struct;\n"
200 " gboolean use_gvariant;\n"
201 "} _ExtendedGDBusArgInfo;\n"
202 "\n"
203 "typedef struct\n"
204 "{\n"
205 " GDBusMethodInfo parent_struct;\n"
206 " const gchar *signal_name;\n"
207 " gboolean pass_fdlist;\n"
208 "} _ExtendedGDBusMethodInfo;\n"
209 "\n"
210 "typedef struct\n"
211 "{\n"
212 " GDBusSignalInfo parent_struct;\n"
213 " const gchar *signal_name;\n"
214 "} _ExtendedGDBusSignalInfo;\n"
215 "\n"
216 "typedef struct\n"
217 "{\n"
218 " GDBusPropertyInfo parent_struct;\n"
219 " const gchar *hyphen_name;\n"
220 " guint use_gvariant : 1;\n"
221 " guint emits_changed_signal : 1;\n"
222 "} _ExtendedGDBusPropertyInfo;\n"
223 "\n"
224 "typedef struct\n"
225 "{\n"
226 " GDBusInterfaceInfo parent_struct;\n"
227 " const gchar *hyphen_name;\n"
228 "} _ExtendedGDBusInterfaceInfo;\n"
229 "\n"
230 "typedef struct\n"
231 "{\n"
232 " const _ExtendedGDBusPropertyInfo *info;\n"
233 " guint prop_id;\n"
234 " GValue orig_value; /* the value before the change */\n"
235 "} ChangedProperty;\n"
236 "\n"
237 "static void\n"
238 "_changed_property_free (ChangedProperty *data)\n"
239 "{\n"
240 " g_value_unset (&data->orig_value);\n"
241 " g_free (data);\n"
242 "}\n"
243 "\n"
244 "static gboolean\n"
245 "_g_strv_equal0 (gchar **a, gchar **b)\n"
246 "{\n"
247 " gboolean ret = FALSE;\n"
248 " guint n;\n"
249 " if (a == NULL && b == NULL)\n"
250 " {\n"
251 " ret = TRUE;\n"
252 " goto out;\n"
253 " }\n"
254 " if (a == NULL || b == NULL)\n"
255 " goto out;\n"
256 " if (g_strv_length (a) != g_strv_length (b))\n"
257 " goto out;\n"
258 " for (n = 0; a[n] != NULL; n++)\n"
259 " if (g_strcmp0 (a[n], b[n]) != 0)\n"
260 " goto out;\n"
261 " ret = TRUE;\n"
262 "out:\n"
263 " return ret;\n"
264 "}\n"
265 "\n"
266 "static gboolean\n"
267 "_g_variant_equal0 (GVariant *a, GVariant *b)\n"
268 "{\n"
269 " gboolean ret = FALSE;\n"
270 " if (a == NULL && b == NULL)\n"
271 " {\n"
272 " ret = TRUE;\n"
273 " goto out;\n"
274 " }\n"
275 " if (a == NULL || b == NULL)\n"
276 " goto out;\n"
277 " ret = g_variant_equal (a, b);\n"
278 "out:\n"
279 " return ret;\n"
280 "}\n"
281 "\n"
282 "G_GNUC_UNUSED static gboolean\n"
283 "_g_value_equal (const GValue *a, const GValue *b)\n"
284 "{\n"
285 " gboolean ret = FALSE;\n"
286 " g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b));\n"
287 " switch (G_VALUE_TYPE (a))\n"
288 " {\n"
289 " case G_TYPE_BOOLEAN:\n"
290 " ret = (g_value_get_boolean (a) == g_value_get_boolean (b));\n"
291 " break;\n"
292 " case G_TYPE_UCHAR:\n"
293 " ret = (g_value_get_uchar (a) == g_value_get_uchar (b));\n"
294 " break;\n"
295 " case G_TYPE_INT:\n"
296 " ret = (g_value_get_int (a) == g_value_get_int (b));\n"
297 " break;\n"
298 " case G_TYPE_UINT:\n"
299 " ret = (g_value_get_uint (a) == g_value_get_uint (b));\n"
300 " break;\n"
301 " case G_TYPE_INT64:\n"
302 " ret = (g_value_get_int64 (a) == g_value_get_int64 (b));\n"
303 " break;\n"
304 " case G_TYPE_UINT64:\n"
305 " ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b));\n"
306 " break;\n"
307 " case G_TYPE_DOUBLE:\n"
308 " {\n"
309 " /* Avoid -Wfloat-equal warnings by doing a direct bit compare */\n"
310 " gdouble da = g_value_get_double (a);\n"
311 " gdouble db = g_value_get_double (b);\n"
312 " ret = memcmp (&da, &db, sizeof (gdouble)) == 0;\n"
313 " }\n"
314 " break;\n"
315 " case G_TYPE_STRING:\n"
316 " ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0);\n"
317 " break;\n"
318 " case G_TYPE_VARIANT:\n"
319 " ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b));\n"
320 " break;\n"
321 " default:\n"
322 " if (G_VALUE_TYPE (a) == G_TYPE_STRV)\n"
323 " ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b));\n"
324 " else\n"
325 ' g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a)));\n'
326 " break;\n"
327 " }\n"
328 " return ret;\n"
329 "}",
330 }
331
332 result = Result(info, out, err, subs)
333
334 print("Output:", result.out)
335 return result
336
337 def runCodegenWithInterface(self, interface_contents, *args):
338 with tempfile.NamedTemporaryFile(
339 dir=self.tmpdir.name, suffix=".xml", delete=False
340 ) as interface_file:
341 # Write out the interface.
342 interface_file.write(interface_contents.encode("utf-8"))
343 print(interface_file.name + ":", interface_contents)
344 interface_file.flush()
345
346 return self.runCodegen(interface_file.name, *args)
347
348 def test_help(self):
349 """Test the --help argument."""
350 result = self.runCodegen("--help")
351 self.assertIn("usage: gdbus-codegen", result.out)
352
353 def test_no_args(self):
354 """Test running with no arguments at all."""
355 with self.assertRaises(subprocess.CalledProcessError):
356 self.runCodegen()
357
358 @unittest.skipIf(on_win32(), "requires /dev/stdout")
359 def test_empty_interface_header(self):
360 """Test generating a header with an empty interface file."""
361 result = self.runCodegenWithInterface("", "--output", "/dev/stdout", "--header")
362 self.assertEqual("", result.err)
363 self.assertEqual(
364 """{standard_top_comment}
365
366 #ifndef __STDOUT__
367 #define __STDOUT__
368
369 #include <gio/gio.h>
370
371 G_BEGIN_DECLS
372
373
374 G_END_DECLS
375
376 #endif /* __STDOUT__ */""".format(
377 **result.subs
378 ),
379 result.out.strip(),
380 )
381
382 @unittest.skipIf(on_win32(), "requires /dev/stdout")
383 def test_empty_interface_body(self):
384 """Test generating a body with an empty interface file."""
385 result = self.runCodegenWithInterface("", "--output", "/dev/stdout", "--body")
386 self.assertEqual("", result.err)
387 self.assertEqual(
388 """{standard_top_comment}
389
390 {standard_config_h_include}
391
392 #include "stdout.h"
393
394 {standard_header_includes}
395
396 {private_gvalues_getters}
397
398 {standard_typedefs_and_helpers}""".format(
399 **result.subs
400 ),
401 result.out.strip(),
402 )
403
404 @unittest.skipIf(on_win32(), "requires /dev/stdout")
405 def test_reproducible(self):
406 """Test builds are reproducible regardless of file ordering."""
407 xml_contents1 = """
408 <node>
409 <interface name="com.acme.Coyote">
410 <method name="Run"/>
411 <method name="Sleep"/>
412 <method name="Attack"/>
413 <signal name="Surprised"/>
414 <property name="Mood" type="s" access="read"/>
415 </interface>
416 </node>
417 """
418
419 xml_contents2 = """
420 <node>
421 <interface name="org.project.Bar.Frobnicator">
422 <method name="RandomMethod"/>
423 </interface>
424 </node>
425 """
426
427 with tempfile.NamedTemporaryFile(
428 dir=self.tmpdir.name, suffix="1.xml", delete=False
429 ) as xml_file1, tempfile.NamedTemporaryFile(
430 dir=self.tmpdir.name, suffix="2.xml", delete=False
431 ) as xml_file2:
432 # Write out the interfaces.
433 xml_file1.write(xml_contents1.encode("utf-8"))
434 xml_file2.write(xml_contents2.encode("utf-8"))
435
436 xml_file1.flush()
437 xml_file2.flush()
438
439 # Repeat this for headers and bodies.
440 for header_or_body in ["--header", "--body"]:
441 # Run gdbus-codegen with the interfaces in one order, and then
442 # again in another order.
443 result1 = self.runCodegen(
444 xml_file1.name,
445 xml_file2.name,
446 "--output",
447 "/dev/stdout",
448 header_or_body,
449 )
450 self.assertEqual("", result1.err)
451
452 result2 = self.runCodegen(
453 xml_file2.name,
454 xml_file1.name,
455 "--output",
456 "/dev/stdout",
457 header_or_body,
458 )
459 self.assertEqual("", result2.err)
460
461 # The output should be the same.
462 self.assertEqual(result1.out, result2.out)
463
464 def test_generate_docbook(self):
465 """Test the basic functionality of the docbook generator."""
466 xml_contents = """
467 <node>
468 <interface name="org.project.Bar.Frobnicator">
469 <method name="RandomMethod"/>
470 </interface>
471 </node>
472 """
473 res = self.runCodegenWithInterface(
474 xml_contents,
475 "--generate-docbook",
476 "test",
477 )
478 self.assertEqual("", res.err)
479 self.assertEqual("", res.out)
480 with open("test-org.project.Bar.Frobnicator.xml", "r") as f:
481 xml_data = f.readlines()
482 self.assertTrue(len(xml_data) != 0)
483
484 def test_generate_md(self):
485 """Test the basic functionality of the markdown generator."""
486 xml_contents = """
487 <node>
488 <interface name="org.project.Bar.Frobnicator">
489 <method name="RandomMethod"/>
490 </interface>
491 </node>
492 """
493 res = self.runCodegenWithInterface(
494 xml_contents,
495 "--generate-md",
496 "test",
497 )
498 self.assertEqual("", res.err)
499 self.assertEqual("", res.out)
500 with open("test-org.project.Bar.Frobnicator.md", "r") as f:
501 rst = f.readlines()
502 self.assertTrue(len(rst) != 0)
503
504 def test_generate_rst(self):
505 """Test the basic functionality of the rst generator."""
506 xml_contents = """
507 <node>
508 <interface name="org.project.Bar.Frobnicator">
509 <method name="RandomMethod"/>
510 </interface>
511 </node>
512 """
513 res = self.runCodegenWithInterface(
514 xml_contents,
515 "--generate-rst",
516 "test",
517 )
518 self.assertEqual("", res.err)
519 self.assertEqual("", res.out)
520 with open("test-org.project.Bar.Frobnicator.rst", "r") as f:
521 rst = f.readlines()
522 self.assertTrue(len(rst) != 0)
523
524 def test_generate_rst_method(self):
525 """Test generating a method documentation with the rst generator."""
526 xml_contents = """
527 <node>
528 <interface name="org.project.Bar.Frobnicator">
529 <!-- RandomMethod:
530
531 A random test method.
532 -->
533 <method name="RandomMethod"/>
534 </interface>
535 </node>
536 """
537 res = self.runCodegenWithInterface(
538 xml_contents,
539 "--generate-rst",
540 "test",
541 )
542 self.assertEqual("", res.err)
543 self.assertEqual("", res.out)
544 with open("test-org.project.Bar.Frobnicator.rst", "r") as f:
545 rst = f.read()
546 self.assertIn(
547 textwrap.dedent(
548 """
549 -------
550 Methods
551 -------
552
553 .. _org.project.Bar.Frobnicator.RandomMethod:
554
555 org.project.Bar.Frobnicator.RandomMethod
556 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
557
558 ::
559
560 RandomMethod ()
561
562
563 A random test method."""
564 ),
565 rst,
566 )
567
568 def test_generate_rst_signal(self):
569 """Test generating a signal documentation with the rst generator."""
570 xml_contents = """
571 <node>
572 <interface name="org.project.Bar.Frobnicator">
573 <!-- RandomSignal:
574
575 A random test signal.
576 -->
577 <signal name="RandomSignal"/>
578 </interface>
579 </node>
580 """
581 res = self.runCodegenWithInterface(
582 xml_contents,
583 "--generate-rst",
584 "test",
585 )
586 self.assertEqual("", res.err)
587 self.assertEqual("", res.out)
588 with open("test-org.project.Bar.Frobnicator.rst", "r") as f:
589 rst = f.read()
590 self.assertIn(
591 textwrap.dedent(
592 """
593 -------
594 Signals
595 -------
596
597 .. _org.project.Bar.Frobnicator::RandomSignal:
598
599 org.project.Bar.Frobnicator::RandomSignal
600 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
601
602 ::
603
604 RandomSignal ()
605
606
607 A random test signal."""
608 ),
609 rst,
610 )
611
612 def test_generate_rst_property(self):
613 """Test generating a property documentation with the rst generator."""
614 xml_contents = """
615 <node>
616 <interface name="org.project.Bar.Frobnicator">
617 <!-- RandomProperty:
618
619 A random test property.
620 -->
621 <property type="s" name="RandomProperty" access="read"/>
622 </interface>
623 </node>
624 """
625 res = self.runCodegenWithInterface(
626 xml_contents,
627 "--generate-rst",
628 "test",
629 )
630 self.assertEqual("", res.err)
631 self.assertEqual("", res.out)
632 with open("test-org.project.Bar.Frobnicator.rst", "r") as f:
633 rst = f.read()
634 self.assertIn(
635 textwrap.dedent(
636 """
637 ----------
638 Properties
639 ----------
640
641 .. _org.project.Bar.Frobnicator:RandomProperty:
642
643 org.project.Bar.Frobnicator:RandomProperty
644 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
645
646 ::
647
648 RandomProperty readable s
649
650
651 A random test property."""
652 ),
653 rst,
654 )
655
656 @unittest.skipIf(on_win32(), "requires /dev/stdout")
657 def test_glib_min_required_invalid(self):
658 """Test running with an invalid --glib-min-required."""
659 with self.assertRaises(subprocess.CalledProcessError):
660 self.runCodegenWithInterface(
661 "",
662 "--output",
663 "/dev/stdout",
664 "--body",
665 "--glib-min-required",
666 "hello mum",
667 )
668
669 @unittest.skipIf(on_win32(), "requires /dev/stdout")
670 def test_glib_min_required_too_low(self):
671 """Test running with a --glib-min-required which is too low (and hence
672 probably a typo)."""
673 with self.assertRaises(subprocess.CalledProcessError):
674 self.runCodegenWithInterface(
675 "", "--output", "/dev/stdout", "--body", "--glib-min-required", "2.6"
676 )
677
678 @unittest.skipIf(on_win32(), "requires /dev/stdout")
679 def test_glib_min_required_major_only(self):
680 """Test running with a --glib-min-required which contains only a major version."""
681 result = self.runCodegenWithInterface(
682 "",
683 "--output",
684 "/dev/stdout",
685 "--header",
686 "--glib-min-required",
687 "3",
688 "--glib-max-allowed",
689 "3.2",
690 )
691 self.assertEqual("", result.err)
692 self.assertNotEqual("", result.out.strip())
693
694 @unittest.skipIf(on_win32(), "requires /dev/stdout")
695 def test_glib_min_required_with_micro(self):
696 """Test running with a --glib-min-required which contains a micro version."""
697 result = self.runCodegenWithInterface(
698 "", "--output", "/dev/stdout", "--header", "--glib-min-required", "2.46.2"
699 )
700 self.assertEqual("", result.err)
701 self.assertNotEqual("", result.out.strip())
702
703 @unittest.skipIf(on_win32(), "requires /dev/stdout")
704 def test_glib_max_allowed_too_low(self):
705 """Test running with a --glib-max-allowed which is too low (and hence
706 probably a typo)."""
707 with self.assertRaises(subprocess.CalledProcessError):
708 self.runCodegenWithInterface(
709 "", "--output", "/dev/stdout", "--body", "--glib-max-allowed", "2.6"
710 )
711
712 @unittest.skipIf(on_win32(), "requires /dev/stdout")
713 def test_glib_max_allowed_major_only(self):
714 """Test running with a --glib-max-allowed which contains only a major version."""
715 result = self.runCodegenWithInterface(
716 "", "--output", "/dev/stdout", "--header", "--glib-max-allowed", "3"
717 )
718 self.assertEqual("", result.err)
719 self.assertNotEqual("", result.out.strip())
720
721 @unittest.skipIf(on_win32(), "requires /dev/stdout")
722 def test_glib_max_allowed_with_micro(self):
723 """Test running with a --glib-max-allowed which contains a micro version."""
724 result = self.runCodegenWithInterface(
725 "", "--output", "/dev/stdout", "--header", "--glib-max-allowed", "2.46.2"
726 )
727 self.assertEqual("", result.err)
728 self.assertNotEqual("", result.out.strip())
729
730 @unittest.skipIf(on_win32(), "requires /dev/stdout")
731 def test_glib_max_allowed_unstable(self):
732 """Test running with a --glib-max-allowed which is unstable. It should
733 be rounded up to the next stable version number, and hence should not
734 end up less than --glib-min-required."""
735 result = self.runCodegenWithInterface(
736 "",
737 "--output",
738 "/dev/stdout",
739 "--header",
740 "--glib-max-allowed",
741 "2.63",
742 "--glib-min-required",
743 "2.64",
744 )
745 self.assertEqual("", result.err)
746 self.assertNotEqual("", result.out.strip())
747
748 @unittest.skipIf(on_win32(), "requires /dev/stdout")
749 def test_glib_max_allowed_less_than_min_required(self):
750 """Test running with a --glib-max-allowed which is less than
751 --glib-min-required."""
752 with self.assertRaises(subprocess.CalledProcessError):
753 self.runCodegenWithInterface(
754 "",
755 "--output",
756 "/dev/stdout",
757 "--body",
758 "--glib-max-allowed",
759 "2.62",
760 "--glib-min-required",
761 "2.64",
762 )
763
764 @unittest.skipIf(on_win32(), "requires /dev/stdout")
765 def test_dbus_types(self):
766 bad_types = [
767 "{vs}", # Bad dictionary key type
768 "(ss(s{{sv}s}))", # Bad dictionary key types
769 "{s", # Unterminated dictionary
770 "(s{sss})", # Unterminated dictionary
771 "z", # Bad type
772 "(ssms)", # Bad type
773 "(", # Unterminated tuple
774 "(((ss))", # Unterminated tuple
775 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
776 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas", # Too much recursion
777 "(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((("
778 "(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((s))"
779 "))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))"
780 "))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))", # Too much recursion
781 "{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{"
782 "{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{sv}"
783 "}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"
784 "}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}", # Too much recursion
785 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
786 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaa{sv})", # Too much recursion
787 "(ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
788 "ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
789 "ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
790 "ssssssssssssssssssssssssssssssssssssssssssssssssssssssssss)", # Too long
791 ]
792 for t in bad_types:
793 interface_xml = f"""
794 <node>
795 <interface name="BadTypes">
796 <property type="{t}" name="BadPropertyType" access="read" />
797 </interface>
798 </node>"""
799 with self.assertRaises(subprocess.CalledProcessError):
800 self.runCodegenWithInterface(
801 interface_xml, "--output", "/dev/stdout", "--body"
802 )
803 good_types = [
804 "si{s{b(ybnqiuxtdh)}}{yv}{nv}{dv}",
805 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
806 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas", # 128 Levels of recursion
807 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
808 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa{sv})", # 128 Levels of recursion
809 ]
810 for t in good_types:
811 interface_xml = f"""
812 <node>
813 <interface name="GoodTypes">
814 <property type="{t}" name="GoodPropertyType" access="read" />
815 </interface>
816 </node>"""
817 result = self.runCodegenWithInterface(
818 interface_xml, "--output", "/dev/stdout", "--body"
819 )
820 self.assertEqual("", result.err)
821
822 @unittest.skipIf(on_win32(), "requires /dev/stdout")
823 def test_unix_fd_types_and_annotations(self):
824 """Test an interface with `h` arguments, no annotation, and GLib < 2.64.
825
826 See issue #1726.
827 """
828 interface_xml = """
829 <node>
830 <interface name="FDPassing">
831 <method name="HelloFD">
832 <annotation name="org.gtk.GDBus.C.UnixFD" value="1"/>
833 <arg name="greeting" direction="in" type="s"/>
834 <arg name="response" direction="out" type="s"/>
835 </method>
836 <method name="NoAnnotation">
837 <arg name="greeting" direction="in" type="h"/>
838 <arg name="greeting_locale" direction="in" type="s"/>
839 <arg name="response" direction="out" type="h"/>
840 <arg name="response_locale" direction="out" type="s"/>
841 </method>
842 <method name="NoAnnotationNested">
843 <arg name="files" type="a{sh}" direction="in"/>
844 </method>
845 </interface>
846 </node>"""
847
848 # Try without specifying --glib-min-required.
849 result = self.runCodegenWithInterface(
850 interface_xml, "--output", "/dev/stdout", "--header"
851 )
852 self.assertEqual("", result.err)
853 self.assertEqual(result.out.strip().count("GUnixFDList"), 6)
854
855 # Specify an old --glib-min-required.
856 result = self.runCodegenWithInterface(
857 interface_xml,
858 "--output",
859 "/dev/stdout",
860 "--header",
861 "--glib-min-required",
862 "2.32",
863 )
864 self.assertEqual("", result.err)
865 self.assertEqual(result.out.strip().count("GUnixFDList"), 6)
866
867 # Specify a --glib-min-required ≥ 2.64. There should be more
868 # mentions of `GUnixFDList` now, since the annotation is not needed to
869 # trigger its use.
870 result = self.runCodegenWithInterface(
871 interface_xml,
872 "--output",
873 "/dev/stdout",
874 "--header",
875 "--glib-min-required",
876 "2.64",
877 )
878 self.assertEqual("", result.err)
879 self.assertEqual(result.out.strip().count("GUnixFDList"), 18)
880
881 @unittest.skipIf(on_win32(), "requires /dev/stdout")
882 def test_call_flags_and_timeout_method_args(self):
883 """Test that generated method call functions have @call_flags and
884 @timeout_msec args if and only if GLib >= 2.64.
885 """
886 interface_xml = """
887 <node>
888 <interface name="org.project.UsefulInterface">
889 <method name="UsefulMethod"/>
890 </interface>
891 </node>"""
892
893 # Try without specifying --glib-min-required.
894 result = self.runCodegenWithInterface(
895 interface_xml, "--output", "/dev/stdout", "--header"
896 )
897 self.assertEqual("", result.err)
898 self.assertEqual(result.out.strip().count("GDBusCallFlags call_flags,"), 0)
899 self.assertEqual(result.out.strip().count("gint timeout_msec,"), 0)
900
901 # Specify an old --glib-min-required.
902 result = self.runCodegenWithInterface(
903 interface_xml,
904 "--output",
905 "/dev/stdout",
906 "--header",
907 "--glib-min-required",
908 "2.32",
909 )
910 self.assertEqual("", result.err)
911 self.assertEqual(result.out.strip().count("GDBusCallFlags call_flags,"), 0)
912 self.assertEqual(result.out.strip().count("gint timeout_msec,"), 0)
913
914 # Specify a --glib-min-required ≥ 2.64. The two arguments should be
915 # present for both the async and sync method call functions.
916 result = self.runCodegenWithInterface(
917 interface_xml,
918 "--output",
919 "/dev/stdout",
920 "--header",
921 "--glib-min-required",
922 "2.64",
923 )
924 self.assertEqual("", result.err)
925 self.assertEqual(result.out.strip().count("GDBusCallFlags call_flags,"), 2)
926 self.assertEqual(result.out.strip().count("gint timeout_msec,"), 2)
927
928 @unittest.skipIf(on_win32(), "requires /dev/stdout")
929 def test_generate_signal_id_simple_signal(self):
930 """Test that signals IDs are used to emit signals"""
931 interface_xml = """
932 <node>
933 <interface name="org.project.UsefulInterface">
934 <signal name="SimpleSignal"/>
935 </interface>
936 <interface name="org.project.OtherIface">
937 <signal name="SimpleSignal"/>
938 </interface>
939 </node>"""
940
941 result = self.runCodegenWithInterface(
942 interface_xml, "--output", "/dev/stdout", "--body"
943 )
944 stripped_out = result.out.strip()
945 self.assertFalse(result.err)
946 self.assertIs(stripped_out.count("g_signal_emit_by_name ("), 0)
947
948 for iface in ["USEFUL_INTERFACE", "OTHER_IFACE"]:
949 enum_name = f"_ORG_PROJECT_{iface}_SIGNALS"
950 enum_item = f"_ORG_PROJECT_{iface}_SIMPLE_SIGNAL"
951 self.assertIs(stripped_out.count(f"{enum_item},"), 1)
952 self.assertIs(stripped_out.count(f"{enum_name}[{enum_item}] ="), 1)
953 self.assertIs(
954 stripped_out.count(
955 f" g_signal_emit (object, {enum_name}[{enum_item}], 0);"
956 ),
957 1,
958 )
959
960 @unittest.skipIf(on_win32(), "requires /dev/stdout")
961 def test_generate_signal_id_multiple_signals_types(self):
962 """Test that signals IDs are used to emit signals for all types"""
963
964 signal_template = "<signal name='{}'><arg name='{}' type='{}'/></signal>"
965 generated_signals = [
966 signal_template.format(
967 f"SingleArgSignal{t.upper()}", f"an_{t}", props.get("variant_type", t)
968 )
969 for t, props in self.ARGUMENTS_TYPES.items()
970 ]
971
972 interface_xml = f"""
973 <node>
974 <interface name="org.project.SignalingIface">
975 <signal name="NoArgSignal" />
976 {''.join(generated_signals)}
977 </interface>
978 </node>"""
979
980 result = self.runCodegenWithInterface(
981 interface_xml, "--output", "/dev/stdout", "--body"
982 )
983 stripped_out = result.out.strip()
984 self.assertFalse(result.err)
985 self.assertIs(stripped_out.count("g_signal_emit_by_name ("), 0)
986
987 iface = "SIGNALING_IFACE"
988 for t in self.ARGUMENTS_TYPES.keys():
989 enum_name = f"_ORG_PROJECT_{iface}_SIGNALS"
990 enum_item = f"_ORG_PROJECT_{iface}_SINGLE_ARG_SIGNAL_{t.upper()}"
991 self.assertIs(stripped_out.count(f"{enum_item},"), 1)
992 self.assertIs(stripped_out.count(f"{enum_name}[{enum_item}] ="), 1)
993 self.assertIs(
994 stripped_out.count(
995 f" g_signal_emit (object, {enum_name}[{enum_item}], 0, arg_an_{t});"
996 ),
997 1,
998 )
999
1000 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1001 def test_generate_signal_id_multiple_signal_args_types(self):
1002 """Test that signals IDs are used to emit signals for all types"""
1003
1004 generated_args = [
1005 f"<arg name='an_{t}' type='{props.get('variant_type', t)}'/>\n"
1006 for t, props in self.ARGUMENTS_TYPES.items()
1007 ]
1008
1009 interface_xml = f"""
1010 <node>
1011 <interface name="org.project.SignalingIface">
1012 <signal name="SignalWithManyArgs">
1013 {''.join(generated_args)}
1014 </signal>
1015 </interface>
1016 </node>"""
1017
1018 result = self.runCodegenWithInterface(
1019 interface_xml, "--output", "/dev/stdout", "--body"
1020 )
1021 stripped_out = result.out.strip()
1022 self.assertFalse(result.err)
1023 self.assertIs(stripped_out.count("g_signal_emit_by_name ("), 0)
1024
1025 iface = "SIGNALING_IFACE"
1026 enum_name = f"_ORG_PROJECT_{iface}_SIGNALS"
1027 enum_item = f"_ORG_PROJECT_{iface}_SIGNAL_WITH_MANY_ARGS"
1028 self.assertIs(stripped_out.count(f"{enum_item},"), 1)
1029 self.assertIs(stripped_out.count(f"{enum_name}[{enum_item}] ="), 1)
1030
1031 args = ", ".join([f"arg_an_{t}" for t in self.ARGUMENTS_TYPES.keys()])
1032 self.assertIs(
1033 stripped_out.count(
1034 f" g_signal_emit (object, {enum_name}[{enum_item}], 0, {args});"
1035 ),
1036 1,
1037 )
1038
1039 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1040 def test_generate_signals_marshaller_simple_signal(self):
1041 """Test that signals marshaller is generated for simple signal"""
1042 interface_xml = """
1043 <node>
1044 <interface name="org.project.SignalingIface">
1045 <signal name="SimpleSignal"/>
1046 </interface>
1047 <interface name="org.project.OtherSignalingIface">
1048 <signal name="SimpleSignal"/>
1049 </interface>
1050 </node>"""
1051
1052 result = self.runCodegenWithInterface(
1053 interface_xml, "--output", "/dev/stdout", "--body"
1054 )
1055 stripped_out = result.out.strip()
1056 self.assertFalse(result.err)
1057 self.assertIs(stripped_out.count("g_cclosure_marshal_generic"), 0)
1058
1059 func_name = "org_project_signaling_iface_signal_marshal_simple_signal"
1060 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1061 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1062 self.assertIs(stripped_out.count("g_cclosure_marshal_VOID__VOID (closure"), 2)
1063
1064 func_name = "org_project_other_signaling_iface_signal_marshal_simple_signal"
1065 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1066 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1067 self.assertIs(stripped_out.count("g_cclosure_marshal_VOID__VOID (closure"), 2)
1068
1069 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1070 def test_generate_signals_marshaller_single_typed_args(self):
1071 """Test that signals marshaller is generated for each known type"""
1072 for t, props in self.ARGUMENTS_TYPES.items():
1073 camel_type = t[0].upper() + t[1:]
1074 interface_xml = f"""
1075 <node>
1076 <interface name="org.project.SignalingIface">
1077 <signal name="SimpleSignal"/>
1078 <signal name="SingleArgSignal{camel_type}">
1079 <arg name="arg_{t}" type="{props.get("variant_type", t)}"/>
1080 </signal>
1081 </interface>
1082 </node>"""
1083
1084 result = self.runCodegenWithInterface(
1085 interface_xml, "--output", "/dev/stdout", "--body"
1086 )
1087 stripped_out = result.out.strip()
1088 self.assertFalse(result.err)
1089 self.assertEqual(stripped_out.count("g_cclosure_marshal_generic"), 0)
1090
1091 self.assertIs(
1092 stripped_out.count("g_cclosure_marshal_VOID__VOID (closure"), 1
1093 )
1094
1095 func_name = (
1096 f"org_project_signaling_iface_signal_marshal_single_arg_signal_{t}"
1097 )
1098 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1099 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1100
1101 if props.get("lacks_marshaller", False):
1102 self.assertIs(
1103 stripped_out.count(
1104 f"g_marshal_value_peek_{props['value_type']} (param_values + 1)"
1105 ),
1106 1,
1107 )
1108 else:
1109 self.assertIs(
1110 stripped_out.count(
1111 f"g_cclosure_marshal_VOID__{props['value_type'].upper()} (closure"
1112 ),
1113 1,
1114 )
1115
1116 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1117 def test_generate_signals_marshallers_multiple_args(self):
1118 """Test that signals marshallers are generated"""
1119 generated_args = [
1120 f"<arg name='an_{t}' type='{props.get('variant_type', t)}'/>\n"
1121 for t, props in self.ARGUMENTS_TYPES.items()
1122 ]
1123
1124 interface_xml = f"""
1125 <node>
1126 <interface name="org.project.SignalingIface">
1127 <signal name="SimpleSignal"/>
1128 <signal name="SignalWithManyArgs">
1129 {''.join(generated_args)}
1130 </signal>
1131 </interface>
1132 </node>"""
1133
1134 result = self.runCodegenWithInterface(
1135 interface_xml, "--output", "/dev/stdout", "--body"
1136 )
1137 stripped_out = result.out.strip()
1138 self.assertFalse(result.err)
1139 self.assertIs(stripped_out.count("g_cclosure_marshal_generic"), 0)
1140
1141 func_name = f"org_project_signaling_iface_signal_marshal_simple_signal"
1142 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1143 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1144
1145 func_name = f"org_project_signaling_iface_signal_marshal_signal_with_many_args"
1146 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1147 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1148
1149 # Check access to MultipleArgsSignal arguments
1150 index = 1
1151 for props in self.ARGUMENTS_TYPES.values():
1152 self.assertIs(
1153 stripped_out.count(
1154 f"g_marshal_value_peek_{props['value_type']} (param_values + {index})"
1155 ),
1156 1,
1157 )
1158 index += 1
1159
1160 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1161 def test_generate_methods_marshaller_simple_method(self):
1162 """Test that methods marshaller is generated for simple method"""
1163 interface_xml = """
1164 <node>
1165 <interface name="org.project.CallableIface">
1166 <method name="SimpleMethod"/>
1167 </interface>
1168 <interface name="org.project.OtherCallableIface">
1169 <method name="SimpleMethod"/>
1170 </interface>
1171 </node>"""
1172
1173 result = self.runCodegenWithInterface(
1174 interface_xml, "--output", "/dev/stdout", "--body"
1175 )
1176 stripped_out = result.out.strip()
1177 self.assertFalse(result.err)
1178 self.assertIs(stripped_out.count("g_cclosure_marshal_generic"), 0)
1179
1180 func_name = "org_project_callable_iface_method_marshal_simple_method"
1181 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1182 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1183
1184 func_name = "org_project_other_callable_iface_method_marshal_simple_method"
1185 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1186 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1187
1188 self.assertIs(
1189 stripped_out.count("g_marshal_value_peek_object (param_values + 1)"), 1
1190 )
1191 self.assertIs(
1192 stripped_out.count("g_value_set_boolean (return_value, v_return);"), 1
1193 )
1194
1195 self.assertIs(
1196 stripped_out.count(
1197 "_g_dbus_codegen_marshal_BOOLEAN__OBJECT (\n GClosure"
1198 ),
1199 1,
1200 )
1201 self.assertIs(
1202 stripped_out.count("_g_dbus_codegen_marshal_BOOLEAN__OBJECT (closure"), 2
1203 )
1204
1205 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1206 def test_generate_methods_marshaller_single_typed_in_args(self):
1207 """Test that methods marshallers are generated for each known type"""
1208 for t, props in self.ARGUMENTS_TYPES.items():
1209 camel_type = t[0].upper() + t[1:]
1210 interface_xml = f"""
1211 <node>
1212 <interface name="org.project.UsefulInterface">
1213 <method name="SingleArgMethod{camel_type}">
1214 <arg name="arg_{t}" type="{props.get("variant_type", t)}"/>
1215 </method>
1216 </interface>
1217 </node>"""
1218
1219 result = self.runCodegenWithInterface(
1220 interface_xml, "--output", "/dev/stdout", "--body"
1221 )
1222 stripped_out = result.out.strip()
1223 self.assertFalse(result.err)
1224 self.assertEqual(stripped_out.count("g_cclosure_marshal_generic"), 0)
1225
1226 func_name = (
1227 f"org_project_useful_interface_method_marshal_single_arg_method_{t}"
1228 )
1229 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1230 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1231 self.assertIs(
1232 stripped_out.count("g_marshal_value_peek_object (param_values + 1)"), 1
1233 )
1234 self.assertIs(
1235 stripped_out.count("g_value_set_boolean (return_value, v_return);"), 1
1236 )
1237 self.assertIs(
1238 stripped_out.count(
1239 f"g_marshal_value_peek_{props['value_type']} (param_values + 2)"
1240 ),
1241 1,
1242 )
1243
1244 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1245 def test_generate_methods_marshaller_single_typed_out_args(self):
1246 """Test that methods marshallers are generated for each known type"""
1247 for t, props in self.ARGUMENTS_TYPES.items():
1248 camel_type = t[0].upper() + t[1:]
1249 interface_xml = f"""
1250 <node>
1251 <interface name="org.project.UsefulInterface">
1252 <method name="SingleArgMethod{camel_type}">
1253 <arg name="arg_{t}" type="{props.get("variant_type", t)}" direction="out"/>
1254 </method>
1255 </interface>
1256 </node>"""
1257
1258 result = self.runCodegenWithInterface(
1259 interface_xml, "--output", "/dev/stdout", "--body"
1260 )
1261 stripped_out = result.out.strip()
1262 self.assertFalse(result.err)
1263 self.assertEqual(stripped_out.count("g_cclosure_marshal_generic"), 0)
1264
1265 func_name = (
1266 f"org_project_useful_interface_method_marshal_single_arg_method_{t}"
1267 )
1268 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1269 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1270 self.assertIs(
1271 stripped_out.count("g_marshal_value_peek_object (param_values + 1)"), 1
1272 )
1273 self.assertIs(
1274 stripped_out.count("g_value_set_boolean (return_value, v_return);"), 1
1275 )
1276 self.assertIs(stripped_out.count("(param_values + 2)"), 0)
1277
1278 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1279 def test_generate_methods_marshallers_multiple_in_args(self):
1280 """Test that methods marshallers are generated"""
1281 generated_args = [
1282 f"<arg name='an_{t}' type='{props.get('variant_type', t)}'/>\n"
1283 for t, props in self.ARGUMENTS_TYPES.items()
1284 ]
1285
1286 interface_xml = f"""
1287 <node>
1288 <interface name="org.project.CallableIface">
1289 <method name="MethodWithManyArgs">
1290 {''.join(generated_args)}
1291 </method>
1292 <method name="SameMethodWithManyArgs">
1293 {''.join(generated_args)}
1294 </method>
1295 </interface>
1296 <interface name="org.project.OtherCallableIface">
1297 <method name="MethodWithManyArgs">
1298 {''.join(generated_args)}
1299 </method>
1300 </interface>
1301 </node>"""
1302
1303 result = self.runCodegenWithInterface(
1304 interface_xml, "--output", "/dev/stdout", "--body"
1305 )
1306 stripped_out = result.out.strip()
1307 self.assertFalse(result.err)
1308 self.assertIs(stripped_out.count("g_cclosure_marshal_generic"), 0)
1309
1310 func_name = f"org_project_callable_iface_method_marshal_method_with_many_args"
1311 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1312 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1313
1314 # Check access to MultipleArgsMethod arguments
1315 index = 1
1316 self.assertIs(
1317 stripped_out.count(f"g_marshal_value_peek_object (param_values + {index})"),
1318 1,
1319 )
1320 index += 1
1321
1322 for props in self.ARGUMENTS_TYPES.values():
1323 self.assertIs(
1324 stripped_out.count(
1325 f"g_marshal_value_peek_{props['value_type']} (param_values + {index})"
1326 ),
1327 1,
1328 )
1329 index += 1
1330
1331 self.assertIs(
1332 stripped_out.count("g_value_set_boolean (return_value, v_return);"), 1
1333 )
1334 func_types = "_".join(
1335 [p["value_type"].upper() for p in self.ARGUMENTS_TYPES.values()]
1336 )
1337 func_name = f"_g_dbus_codegen_marshal_BOOLEAN__OBJECT_{func_types}"
1338 self.assertIs(stripped_out.count(f"{func_name} (\n GClosure"), 1)
1339 self.assertIs(stripped_out.count(f"{func_name} (closure"), 3)
1340
1341 func_name = (
1342 f"org_project_other_callable_iface_method_marshal_method_with_many_args"
1343 )
1344 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1345 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1346
1347 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1348 def test_generate_methods_marshallers_multiple_out_args(self):
1349 """Test that methods marshallers are generated"""
1350 generated_args = [
1351 f"<arg name='an_{t}' type='{props.get('variant_type', t)}' direction='out'/>\n"
1352 for t, props in self.ARGUMENTS_TYPES.items()
1353 ]
1354
1355 interface_xml = f"""
1356 <node>
1357 <interface name="org.project.CallableIface">
1358 <method name="MethodWithManyArgs">
1359 {''.join(generated_args)}
1360 </method>
1361 </interface>
1362 </node>"""
1363
1364 result = self.runCodegenWithInterface(
1365 interface_xml, "--output", "/dev/stdout", "--body"
1366 )
1367 stripped_out = result.out.strip()
1368 self.assertFalse(result.err)
1369 self.assertIs(stripped_out.count("g_cclosure_marshal_generic"), 0)
1370
1371 func_name = f"org_project_callable_iface_method_marshal_method_with_many_args"
1372 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1373 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1374
1375 # Check access to MultipleArgsMethod arguments
1376 index = 1
1377 self.assertIs(
1378 stripped_out.count(f"g_marshal_value_peek_object (param_values + {index})"),
1379 1,
1380 )
1381 index += 1
1382
1383 for index in range(index, len(self.ARGUMENTS_TYPES)):
1384 self.assertIs(stripped_out.count(f"(param_values + {index})"), 0)
1385
1386 self.assertIs(
1387 stripped_out.count("g_value_set_boolean (return_value, v_return);"), 1
1388 )
1389
1390 self.assertIs(
1391 stripped_out.count("_g_dbus_codegen_marshal_BOOLEAN__OBJECT (closure"),
1392 1,
1393 )
1394
1395 @unittest.skipIf(on_win32(), "requires /dev/stdout")
1396 def test_generate_methods_marshallers_with_unix_fds(self):
1397 """Test an interface with `h` arguments"""
1398 interface_xml = """
1399 <node>
1400 <interface name="test.FDPassing">
1401 <method name="HelloFD">
1402 <annotation name="org.gtk.GDBus.C.UnixFD" value="1"/>
1403 <arg name="greeting" direction="in" type="s"/>
1404 <arg name="response" direction="out" type="s"/>
1405 </method>
1406 </interface>
1407 </node>"""
1408
1409 result = self.runCodegenWithInterface(
1410 interface_xml, "--output", "/dev/stdout", "--body"
1411 )
1412 stripped_out = result.out.strip()
1413 self.assertFalse(result.err)
1414 self.assertIs(stripped_out.count("g_cclosure_marshal_generic"), 0)
1415
1416 func_name = f"test_fdpassing_method_marshal_hello_fd"
1417 self.assertIs(stripped_out.count(f"{func_name},"), 1)
1418 self.assertIs(stripped_out.count(f"{func_name} ("), 1)
1419
1420 index = 1
1421 self.assertIs(
1422 stripped_out.count(f"g_marshal_value_peek_object (param_values + {index})"),
1423 1,
1424 )
1425 index += 1
1426
1427 self.assertIs(
1428 stripped_out.count(f"g_marshal_value_peek_object (param_values + {index})"),
1429 1,
1430 )
1431
1432 index += 1
1433 self.assertIs(
1434 stripped_out.count(f"g_marshal_value_peek_string (param_values + {index})"),
1435 1,
1436 )
1437 index += 1
1438
1439 self.assertIs(
1440 stripped_out.count("g_value_set_boolean (return_value, v_return);"), 1
1441 )
1442
1443 def test_generate_valid_docbook(self):
1444 """Test the basic functionality of the docbook generator."""
1445 xml_contents = """
1446 <node>
1447 <interface name="org.project.Bar.Frobnicator">
1448 <!-- Resize:
1449 @size: New partition size in bytes, 0 for maximal size.
1450 @options: Options.
1451 @since 2.7.2
1452
1453 Resizes the partition.
1454
1455 The partition will not change its position but might be slightly bigger
1456 than requested due to sector counts and alignment (e.g. 1MiB).
1457 If the requested size can't be allocated it results in an error.
1458 The maximal size can automatically be set by using 0 as size.
1459 -->
1460 <method name="Resize">
1461 <arg name="size" direction="in" type="t"/>
1462 <arg name="options" direction="in" type="a{sv}"/>
1463 </method>
1464 </interface>
1465 </node>
1466 """
1467 res = self.runCodegenWithInterface(
1468 xml_contents,
1469 "--generate-docbook",
1470 "test",
1471 )
1472 self.assertEqual("", res.err)
1473 self.assertEqual("", res.out)
1474 with open("test-org.project.Bar.Frobnicator.xml", "r") as f:
1475 self.assertTrue(ET.parse(f) is not None)
1476
1477 def test_indentation_preservation_in_comments(self):
1478 """Test if the parser preserves relative indentation in XML comments"""
1479 markup_list = """\
1480 - The mnemonic key activates the object if it is presently enabled onscreen.
1481 This typically corresponds to the underlined letter within the widget.
1482 Example: "n" in a traditional "New..." menu item or the "a" in "Apply" for
1483 a button."""
1484
1485 xml_contents = """
1486 <node>
1487 <interface name="org.project.Bar.Frobnicator">
1488 <!-- GetKeyBinding:
1489 @index: 0-based index of the action to query.
1490
1491 Gets the keybinding which can be used to activate this action, if one
1492 exists. The string returned should contain localized, human-readable,
1493 key sequences as they would appear when displayed on screen. It must
1494 be in the format "mnemonic;sequence;shortcut".
1495
1496 - The mnemonic key activates the object if it is presently enabled onscreen.
1497 This typically corresponds to the underlined letter within the widget.
1498 Example: "n" in a traditional "New..." menu item or the "a" in "Apply" for
1499 a button.
1500
1501 If there is no key binding for this action, return "".
1502 -->
1503 <method name="GetKeyBinding">
1504 <arg type="i" name="index" direction="in"/>
1505 <arg type="s" direction="out"/>
1506 </method>
1507 </interface>
1508 </node>
1509 """
1510 for format, ext in [("rst", "rst"), ("md", "md"), ("docbook", "xml")]:
1511 res = self.runCodegenWithInterface(
1512 xml_contents, f"--generate-{format}", "test"
1513 )
1514 self.assertFalse(res.err)
1515 self.assertFalse(res.out)
1516 with open(f"test-org.project.Bar.Frobnicator.{ext}", "r") as f:
1517 self.assertIn(markup_list, f.read())
1518
1519
1520 if __name__ == "__main__":
1521 unittest.main(testRunner=taptestrunner.TAPTestRunner())