File: tests.rs

package info (click to toggle)
rust-zbus-macros 5.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 296 kB
  • sloc: makefile: 2
file content (390 lines) | stat: -rw-r--r-- 12,013 bytes parent folder | download
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*use futures_util::{
    future::{select, Either},
    stream::StreamExt,
};
use std::future::ready;
use zbus::{block_on, fdo, object_server::SignalEmitter, proxy::CacheProperties};
use zbus_macros::{interface, proxy, DBusError};

mod param {
    #[zbus_macros::proxy(
        interface = "org.freedesktop.zbus_macros.ProxyParam",
        default_service = "org.freedesktop.zbus_macros",
        default_path = "/org/freedesktop/zbus_macros/test"
    )]
    trait ProxyParam {
        #[zbus(object = "super::test::Test")]
        fn some_method<T>(&self, test: &T);
    }
}

mod test {
    use zbus::{
        fdo,
        zvariant::{OwnedStructure, Structure},
    };

    #[zbus_macros::proxy(
        assume_defaults = false,
        interface = "org.freedesktop.zbus_macros.Test",
        default_service = "org.freedesktop.zbus_macros"
    )]
    pub(super) trait Test {
        /// comment for a_test()
        fn a_test(&self, val: &str) -> zbus::Result<u32>;

        /// The generated proxies implement both `zvariant::Type` and `serde::ser::Serialize`
        /// which is useful to pass in a proxy as a param. It serializes it as an `ObjectPath`.
        fn some_method<T>(&self, object_path: &T) -> zbus::Result<()>;

        /// A call accepting an argument that only implements DynamicType and Serialize.
        fn test_dyn_type(&self, arg: Structure<'_>, arg2: u32) -> zbus::Result<()>;

        /// A call returning an type that only implements DynamicDeserialize
        fn test_dyn_ret(&self) -> zbus::Result<OwnedStructure>;

        #[zbus(name = "CheckRENAMING")]
        fn check_renaming(&self) -> zbus::Result<Vec<u8>>;

        #[zbus(property)]
        fn property(&self) -> fdo::Result<Vec<String>>;

        #[zbus(property(emits_changed_signal = "const"))]
        fn a_const_property(&self) -> fdo::Result<Vec<String>>;

        #[zbus(property(emits_changed_signal = "false"))]
        fn a_live_property(&self) -> fdo::Result<Vec<String>>;

        #[zbus(property)]
        fn set_property(&self, val: u16) -> fdo::Result<()>;

        #[zbus(signal)]
        fn a_signal<T>(&self, arg: u8, other: T) -> fdo::Result<()>
        where
            T: AsRef<str>;
    }
}

#[test]
fn test_proxy() {
    block_on(async move {
        let connection = zbus::Connection::session().await.unwrap();
        let proxy = test::TestProxy::builder(&connection)
            .path("/org/freedesktop/zbus_macros/test")
            .unwrap()
            .cache_properties(CacheProperties::No)
            .build()
            .await
            .unwrap();
        fdo::DBusProxy::builder(&connection)
            .build()
            .await
            .unwrap()
            .request_name(
                "org.freedesktop.zbus_macros".try_into().unwrap(),
                fdo::RequestNameFlags::DoNotQueue.into(),
            )
            .await
            .unwrap();
        let mut stream = proxy.receive_a_signal().await.unwrap();

        let left_future = async move {
            // These calls will never happen so just testing the build mostly.
            let signal = stream.next().await.unwrap();
            let args = signal.args::<&str>().unwrap();
            assert_eq!(*args.arg(), 0u8);
            assert_eq!(*args.other(), "whatever");
        };
        futures_util::pin_mut!(left_future);
        let right_future = async {
            ready(()).await;
        };
        futures_util::pin_mut!(right_future);

        if let Either::Left((_, _)) = select(left_future, right_future).await {
            panic!("Shouldn't be receiving our dummy signal: `ASignal`");
        }
    });
}

#[ignore]
#[test]
fn test_derive_error() {
    #[allow(unused)]
    #[derive(Debug, DBusError)]
    #[zbus(prefix = "org.freedesktop.zbus")]
    enum Test {
        #[zbus(error)]
        ZBus(zbus::Error),
        SomeExcuse,
        #[zbus(name = "I.Am.Sorry.Dave")]
        IAmSorryDave(String),
        LetItBe {
            desc: String,
        },
    }
}

#[test]
fn test_interface() {
    use serde::{Deserialize, Serialize};
    use zbus::{
        object_server::Interface,
        zvariant::{Type, Value},
    };

    // Test write-only property
    struct TestWriteOnlyProperty;

    #[interface(proxy)]
    impl TestWriteOnlyProperty {
        #[zbus(property)]
        fn set_my_property(&self, _val: u32) {}
    }

    let mut writer = String::new();
    TestWriteOnlyProperty.introspect_to_writer(&mut writer, 0);
    assert_eq!(
        writer,
        r#"<interface name="org.freedesktop.TestWriteOnlyProperty">
  <property name="MyProperty" type="u" access="write">
    <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
  </property>
</interface>
"#
    );

    struct Test<T> {
        something: String,
        generic: T,
    }

    #[derive(Serialize, Deserialize, Type, Value)]
    struct MyCustomPropertyType(u32);

    #[interface(name = "org.freedesktop.zbus.Test", spawn = false)]
    impl<T: 'static> Test<T>
    where
        T: serde::ser::Serialize + zbus::zvariant::Type + Send + Sync,
    {
        /// Testing `no_arg` documentation is reflected in XML.
        fn no_arg(&self) {
            unimplemented!()
        }

        // Also tests that mut argument bindings work for regular methods
        #[allow(unused_assignments)]
        fn str_u32(&self, mut val: &str) -> zbus::fdo::Result<u32> {
            let res = val
                .parse()
                .map_err(|e| zbus::fdo::Error::Failed(format!("Invalid val: {e}")));
            val = "test mut";
            res
        }

        // TODO: naming output arguments after "RFC: Structural Records #2584"
        fn many_output(&self) -> zbus::fdo::Result<(&T, String)> {
            Ok((&self.generic, self.something.clone()))
        }

        fn pair_output(&self) -> zbus::fdo::Result<((u32, String),)> {
            unimplemented!()
        }

        #[zbus(property)]
        fn my_custom_property(&self) -> MyCustomPropertyType {
            unimplemented!()
        }

        // Also tests that mut argument bindings work for properties
        #[zbus(property)]
        fn set_my_custom_property(&self, mut _value: MyCustomPropertyType) {
            _value = MyCustomPropertyType(42);
        }

        // Test that the emits_changed_signal property results in the correct annotation
        #[zbus(property(emits_changed_signal = "false"))]
        fn my_custom_property_emits_false(&self) -> MyCustomPropertyType {
            unimplemented!()
        }

        #[zbus(property(emits_changed_signal = "invalidates"))]
        fn my_custom_property_emits_invalidates(&self) -> MyCustomPropertyType {
            unimplemented!()
        }

        #[zbus(property(emits_changed_signal = "const"))]
        fn my_custom_property_emits_const(&self) -> MyCustomPropertyType {
            unimplemented!()
        }

        #[zbus(name = "CheckVEC")]
        fn check_vec(&self) -> Vec<u8> {
            unimplemented!()
        }

        /// Testing my_prop documentation is reflected in XML.
        ///
        /// And that too.
        #[zbus(property)]
        fn my_prop(&self) -> u16 {
            unimplemented!()
        }

        #[zbus(property)]
        fn set_my_prop(&mut self, _val: u16) {
            unimplemented!()
        }

        /// Emit a signal.
        #[zbus(signal)]
        async fn signal(emitter: &SignalEmitter<'_>, arg: u8, other: &str) -> zbus::Result<()>;
    }

    const EXPECTED_XML: &str = r#"<interface name="org.freedesktop.zbus.Test">
  <!--
   Testing `no_arg` documentation is reflected in XML.
   -->
  <method name="NoArg">
  </method>
  <method name="StrU32">
    <arg name="val" type="s" direction="in"/>
    <arg type="u" direction="out"/>
  </method>
  <method name="ManyOutput">
    <arg type="u" direction="out"/>
    <arg type="s" direction="out"/>
  </method>
  <method name="PairOutput">
    <arg type="(us)" direction="out"/>
  </method>
  <method name="CheckVEC">
    <arg type="ay" direction="out"/>
  </method>
  <!--
   Emit a signal.
   -->
  <signal name="Signal">
    <arg name="arg" type="y"/>
    <arg name="other" type="s"/>
  </signal>
  <property name="MyCustomProperty" type="u" access="readwrite"/>
  <property name="MyCustomPropertyEmitsConst" type="u" access="read">
    <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="const"/>
  </property>
  <property name="MyCustomPropertyEmitsFalse" type="u" access="read">
    <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="false"/>
  </property>
  <property name="MyCustomPropertyEmitsInvalidates" type="u" access="read">
    <annotation name="org.freedesktop.DBus.Property.EmitsChangedSignal" value="invalidates"/>
  </property>
  <!--
   Testing my_prop documentation is reflected in XML.

   And that too.
   -->
  <property name="MyProp" type="q" access="readwrite"/>
</interface>
"#;
    let t = Test {
        something: String::from("somewhere"),
        generic: 42u32,
    };
    let mut xml = String::new();
    t.introspect_to_writer(&mut xml, 0);
    assert_eq!(xml, EXPECTED_XML);

    assert_eq!(Test::<u32>::name(), "org.freedesktop.zbus.Test");

    if false {
        block_on(async {
            // check compilation
            let c = zbus::Connection::session().await.unwrap();
            let s = c.object_server();
            let m = zbus::message::Message::method_call("/", "StrU32")
                .unwrap()
                .build(&(42,))
                .unwrap();
            let _ = t.call(s, &c, &m, "StrU32".try_into().unwrap());
            let ctxt = SignalEmitter::new(&c, "/does/not/matter").unwrap();
            ctxt.signal(23, "ergo sum").await.unwrap();
        });
    }
}

mod signal_from_message {
    use super::*;
    use zbus::message::Message;

    #[proxy(
        interface = "org.freedesktop.zbus_macros.Test",
        default_service = "org.freedesktop.zbus_macros",
        default_path = "/org/freedesktop/zbus_macros/test"
    )]
    trait Test {
        #[zbus(signal)]
        fn signal_u8(&self, arg: u8) -> fdo::Result<()>;

        #[zbus(signal)]
        fn signal_string(&self, arg: String) -> fdo::Result<()>;
    }

    #[test]
    fn signal_u8() {
        let message = Message::signal(
            "/org/freedesktop/zbus_macros/test",
            "org.freedesktop.zbus_macros.Test",
            "SignalU8",
        )
        .expect("Failed to create signal message builder")
        .build(&(1u8,))
        .expect("Failed to build signal message");

        assert!(
            SignalU8::from_message(message.clone()).is_some(),
            "Message is a SignalU8"
        );
        assert!(
            SignalString::from_message(message).is_none(),
            "Message is not a SignalString"
        );
    }

    #[test]
    fn signal_string() {
        let message = Message::signal(
            "/org/freedesktop/zbus_macros/test",
            "org.freedesktop.zbus_macros.Test",
            "SignalString",
        )
        .expect("Failed to create signal message builder")
        .build(&(String::from("test"),))
        .expect("Failed to build signal message");

        assert!(
            SignalString::from_message(message.clone()).is_some(),
            "Message is a SignalString"
        );
        assert!(
            SignalU8::from_message(message).is_none(),
            "Message is not a SignalU8"
        );
    }

    #[test]
    fn wrong_data() {
        let message = Message::signal(
            "/org/freedesktop/zbus_macros/test",
            "org.freedesktop.zbus_macros.Test",
            "SignalU8",
        )
        .expect("Failed to create signal message builder")
        .build(&(String::from("test"),))
        .expect("Failed to build signal message");

        let signal = SignalU8::from_message(message).expect("Message is a SignalU8");
        signal
            .args()
            .expect_err("Message does not have correct data");
    }
}*/