1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdio.h>
4
5 #include "sd-bus.h"
6
7 #include "bus-internal.h"
8 #include "bus-message.h"
9 #include "tests.h"
10
11 static bool use_system_bus = false;
12
test_bus_new(void)13 static void test_bus_new(void) {
14 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
15
16 assert_se(sd_bus_new(&bus) == 0);
17 assert_se(bus->n_ref == 1);
18 }
19
test_bus_open(void)20 static int test_bus_open(void) {
21 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
22 int r;
23
24 r = sd_bus_open_user(&bus);
25 if (IN_SET(r, -ECONNREFUSED, -ENOENT, -ENOMEDIUM)) {
26 r = sd_bus_open_system(&bus);
27 if (IN_SET(r, -ECONNREFUSED, -ENOENT))
28 return r;
29 use_system_bus = true;
30 }
31
32 assert_se(r >= 0);
33 assert_se(bus->n_ref >= 1); /* we send a hello message when opening, so the count is above 1 */
34
35 return 0;
36 }
37
test_bus_new_method_call(void)38 static void test_bus_new_method_call(void) {
39 sd_bus *bus = NULL;
40 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
41
42 assert_se(use_system_bus ? sd_bus_open_system(&bus) >= 0 : sd_bus_open_user(&bus) >= 0);
43
44 assert_se(sd_bus_message_new_method_call(bus, &m, "a.service.name", "/an/object/path", "an.interface.name", "AMethodName") >= 0);
45
46 assert_se(m->n_ref == 1); /* We hold the only reference to the message */
47 assert_se(bus->n_ref >= 2);
48 sd_bus_flush_close_unref(bus);
49 assert_se(m->n_ref == 1);
50 }
51
test_bus_new_signal(void)52 static void test_bus_new_signal(void) {
53 sd_bus *bus = NULL;
54 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
55
56 assert_se(use_system_bus ? sd_bus_open_system(&bus) >= 0 : sd_bus_open_user(&bus) >= 0);
57
58 assert_se(sd_bus_message_new_signal(bus, &m, "/an/object/path", "an.interface.name", "Name") >= 0);
59
60 assert_se(m->n_ref == 1); /* We hold the only reference to the message */
61 assert_se(bus->n_ref >= 2);
62 sd_bus_flush_close_unref(bus);
63 assert_se(m->n_ref == 1);
64 }
65
main(int argc,char ** argv)66 int main(int argc, char **argv) {
67 test_setup_logging(LOG_INFO);
68
69 test_bus_new();
70
71 if (test_bus_open() < 0)
72 return log_tests_skipped("Failed to connect to bus");
73
74 test_bus_new_method_call();
75 test_bus_new_signal();
76
77 return EXIT_SUCCESS;
78 }
79