Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-app-core/src/events/tests.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
3
use super::*;
4
5
33
fn event(name: &str, payload: Value) -> WidgetEvent {
6
33
    WidgetEvent {
7
33
        name: name.to_string(),
8
33
        payload,
9
33
    }
10
33
}
11
12
/// Every subscribed topic must be granted by a requested scope, or the daemon
13
/// refuses the whole stream with `403 scope_denied`. The mapping lives in
14
/// super-voice-shared, pinned to the daemon's `Topic::required_scope`.
15
#[test]
16
1
fn the_scopes_cover_the_topics() {
17
    use super_voice_shared::daemon::widget_subscription::uncovered_topic;
18
1
    assert_eq!(uncovered_topic(SETTINGS_SCOPES, TOPICS), None);
19
1
}
20
21
#[test]
22
1
fn a_status_event_keeps_its_timestamp_and_data() {
23
1
    let e = event(
24
1
        "daemon_status_changed",
25
1
        serde_json::json!({
26
1
            "status": "ready",
27
1
            "model_loaded": true,
28
1
            "timestamp": "2026-05-22T12:35:14Z",
29
1
        }),
30
1
    );
31
1
    let n = notification(&e).expect("a notification");
32
1
    assert_eq!(n.event_type, "daemon_status_changed");
33
1
    assert_eq!(n.timestamp, "2026-05-22T12:35:14Z");
34
1
    assert_eq!(n.data["status"], "ready");
35
1
}
36
37
#[test]
38
1
fn a_status_event_without_a_string_timestamp_is_dropped() {
39
1
    let missing = event(
40
1
        "daemon_status_changed",
41
1
        serde_json::json!({ "status": "ready" }),
42
1
    );
43
1
    assert!(notification(&missing).is_none());
44
1
    let number = event(
45
1
        "download_progress",
46
1
        serde_json::json!({ "percentage": 25.0, "timestamp": 1_716_393_314_i64 }),
47
1
    );
48
1
    assert!(notification(&number).is_none());
49
1
}
50
51
6
fn status(name: &str, feature: &str) -> WidgetEvent {
52
6
    event(
53
6
        name,
54
6
        serde_json::json!({
55
6
            "feature": feature,
56
6
            "status": "ready",
57
6
            "timestamp": "2026-11-04T12:00:00Z",
58
6
        }),
59
6
    )
60
6
}
61
62
#[test]
63
1
fn each_features_status_events_are_read() {
64
1
    for name in ["daemon_status_changed", "download_progress"] {
65
2
        for feature in ["stt", "tts"] {
66
4
            assert!(
67
4
                matches!(parse(&status(name, feature)), Some(Event::Status(_))),
68
                "{name} from {feature} must reach the app"
69
            );
70
        }
71
    }
72
1
}
73
74
/// The daemon's own news names no feature, and is everyone's.
75
#[test]
76
1
fn the_daemons_own_status_events_are_read() {
77
1
    let e = event(
78
1
        "daemon_status_changed",
79
1
        serde_json::json!({
80
1
            "status": "settings_changed",
81
1
            "setting": "language",
82
1
            "timestamp": "2026-11-04T12:00:00Z",
83
1
        }),
84
1
    );
85
1
    assert!(matches!(parse(&e), Some(Event::Status(_))));
86
1
}
87
88
#[test]
89
1
fn an_unknown_features_status_events_are_dropped() {
90
1
    for name in ["daemon_status_changed", "download_progress"] {
91
2
        assert!(
92
2
            parse(&status(name, "ocr")).is_none(),
93
            "{name} from a feature the app doesn't know isn't its own"
94
        );
95
    }
96
1
}
97
98
#[test]
99
1
fn speaking_carries_its_utterance() {
100
1
    let e = event(
101
1
        "speaking_state",
102
1
        serde_json::json!({ "is_speaking": true, "utterance_id": "u1" }),
103
1
    );
104
1
    assert!(matches!(
105
1
        parse(&e),
106
1
        Some(Event::Speaking { is_speaking: true, utterance_id: Some(id) }) if id == "u1"
107
    ));
108
1
}
109
110
#[test]
111
1
fn a_level_is_on_the_meters_scale() {
112
1
    assert!((level_percent(0.0) - 0.0).abs() < f32::EPSILON);
113
1
    assert!((level_percent(0.1) - 1.0).abs() < f32::EPSILON);
114
1
    let speech = level_percent(0.005);
115
1
    assert!((0.55..0.6).contains(&speech), "{speech}");
116
1
    let e = event(
117
1
        "playback_frequency_bands",
118
1
        serde_json::json!({ "total_energy": 0.005 }),
119
1
    );
120
1
    assert!(matches!(
121
1
        parse(&e),
122
        Some(Event::PlaybackLevel {
123
            is_speech: true,
124
            ..
125
        })
126
    ));
127
1
}
128
129
/// Either feature's settings change names the setting.
130
#[test]
131
1
fn a_settings_change_names_its_setting() {
132
    let changed =
133
3
        |payload| notification(&event("daemon_status_changed", payload)).map(Event::Status);
134
1
    let stt = changed(serde_json::json!({
135
1
        "status": "settings_changed",
136
1
        "setting": "idle_unload",
137
1
        "timestamp": "2026-05-22T12:35:14Z",
138
1
    }))
139
1
    .expect("an event");
140
1
    assert_eq!(setting_changed(&stt), Some("idle_unload"));
141
1
    let tts = changed(serde_json::json!({
142
1
        "feature": "tts",
143
1
        "status": "settings_changed",
144
1
        "setting": "voice",
145
1
        "timestamp": "2026-05-22T12:35:14Z",
146
1
    }))
147
1
    .expect("an event");
148
1
    assert_eq!(setting_changed(&tts), Some("voice"));
149
1
    let ready = changed(serde_json::json!({
150
1
        "status": "ready",
151
1
        "timestamp": "2026-05-22T12:35:14Z",
152
1
    }))
153
1
    .expect("an event");
154
1
    assert_eq!(setting_changed(&ready), None);
155
1
    assert_eq!(setting_changed(&Event::Connected), None);
156
1
}
157
158
/// A dropped stream is heard, so an app can ask the daemon at once whether
159
/// it is gone; a token asked for again is not.
160
#[test]
161
1
fn a_dropped_stream_is_heard() {
162
1
    assert!(matches!(
163
1
        from_update(WidgetSubscriptionUpdate::Disconnected {
164
1
            reason: "connection reset".into()
165
1
        }),
166
        Some(Event::Disconnected)
167
    ));
168
1
    assert!(matches!(
169
1
        from_update(WidgetSubscriptionUpdate::Connected),
170
        Some(Event::Connected)
171
    ));
172
1
    assert!(
173
1
        from_update(WidgetSubscriptionUpdate::NeedsReauth {
174
1
            reason: "expired".into()
175
1
        })
176
1
        .is_none()
177
    );
178
1
}
179
180
/// A dictation that went to the clipboard reaches the app with its words and
181
/// why; a reason this app doesn't know is the plain one.
182
#[test]
183
1
fn a_dictation_that_was_not_typed_is_heard() {
184
1
    let e = event(
185
1
        "typing_failed",
186
1
        serde_json::json!({
187
1
            "client_id": "daemon_recorder",
188
1
            "timestamp": "2026-11-26T10:00:00Z",
189
1
            "reason": "not_allowed",
190
1
            "copied": true,
191
1
            "text": "Call the landlord about the heater before Friday.",
192
1
        }),
193
1
    );
194
1
    assert_eq!(
195
1
        parse(&e).map(|e| match e {
196
1
            Event::TypingFailed(failed) => Some(failed),
197
0
            _ => None,
198
1
        }),
199
1
        Some(Some(TypingFailed {
200
1
            reason: TypingFailure::NotAllowed,
201
1
            copied: true,
202
1
            text: "Call the landlord about the heater before Friday.".to_string(),
203
1
        }))
204
    );
205
1
    assert_eq!(
206
1
        TypingFailure::from_wire("secure_input"),
207
1
        TypingFailure::SecureInput
208
    );
209
1
    assert_eq!(
210
1
        TypingFailure::from_wire("a reason from later"),
211
1
        TypingFailure::Failed
212
    );
213
1
}
214
215
#[test]
216
1
fn only_an_unknown_topic_drops_one() {
217
1
    assert_eq!(fewer_topics("invalid_topic (HTTP 400)", 8), Some(7));
218
1
    assert_eq!(
219
1
        fewer_topics("invalid_topic: unknown topic (HTTP 400)", 3),
220
1
        Some(2)
221
    );
222
1
    assert_eq!(fewer_topics("stream ended", 8), None);
223
1
    assert_eq!(fewer_topics("scope_denied (HTTP 403)", 8), None);
224
    // The daemon refuses an empty list too: the last topic stays.
225
1
    assert_eq!(fewer_topics("invalid_topic (HTTP 400)", 1), None);
226
1
}
227
228
/// A daemon that knows every topic but the newest: it refuses the full list,
229
/// and takes the rest. Each subscription's topics are kept in `asked`; the
230
/// first one it takes drops once, as when the daemon restarts.
231
2
fn older_daemon(
232
2
    asked: std::sync::Arc<std::sync::Mutex<Vec<Vec<&'static str>>>>,
233
2
) -> impl Fn(
234
2
    &'static [&'static str],
235
2
) -> futures_util::stream::BoxStream<'static, WidgetSubscriptionUpdate>
236
2
+ Send
237
2
+ 'static {
238
6
    move |topics| {
239
6
        let mut asked = asked.lock().expect("the list of subscriptions");
240
6
        asked.push(topics.to_vec());
241
13
        let taken = 
asked.iter()6
.filter(|t| t.len() < TOPICS.len()).count();
242
6
        let updates = if topics.contains(&TOPICS[TOPICS.len() - 1]) {
243
3
            vec![WidgetSubscriptionUpdate::Disconnected {
244
3
                reason: "invalid_topic (HTTP 400)".to_string(),
245
3
            }]
246
        } else {
247
3
            let mut updates = vec![
248
3
                WidgetSubscriptionUpdate::Connected,
249
3
                WidgetSubscriptionUpdate::Event(event(
250
3
                    "recording_state",
251
3
                    serde_json::json!({ "is_recording": true }),
252
3
                )),
253
            ];
254
3
            if taken == 1 {
255
2
                updates.push(WidgetSubscriptionUpdate::Disconnected {
256
2
                    reason: "stream ended".to_string(),
257
2
                });
258
1
            }
259
3
            updates
260
        };
261
6
        futures_util::stream::iter(updates)
262
6
            .chain(futures_util::stream::pending())
263
6
            .boxed()
264
6
    }
265
2
}
266
267
#[tokio::test]
268
1
async fn an_older_daemon_is_subscribed_to_without_the_newest_topic() {
269
1
    let asked = std::sync::Arc::default();
270
1
    let events: Vec<Event> = subscribe_with(older_daemon(std::sync::Arc::clone(&asked)))
271
1
        .take(2)
272
1
        .collect()
273
1
        .await;
274
275
1
    assert!(matches!(events[0], Event::Connected), "{events:?}");
276
1
    assert!(matches!(events[1], Event::Recording(true)), "{events:?}");
277
1
    let asked = asked.lock().expect("the list of subscriptions");
278
1
    assert_eq!(asked[0], TOPICS);
279
1
    assert_eq!(asked[1], TOPICS[..TOPICS.len() - 1]);
280
1
    assert_eq!(asked.len(), 2);
281
1
}
282
283
#[tokio::test]
284
1
async fn a_dropped_stream_asks_for_every_topic_again() {
285
1
    let asked = std::sync::Arc::default();
286
1
    let events: Vec<Event> = subscribe_with(older_daemon(std::sync::Arc::clone(&asked)))
287
1
        .take(5)
288
1
        .collect()
289
1
        .await;
290
291
1
    assert!(matches!(events[2], Event::Disconnected), "{events:?}");
292
1
    assert!(matches!(events[3], Event::Connected), "{events:?}");
293
1
    let asked = asked.lock().expect("the list of subscriptions");
294
1
    let lengths: Vec<usize> = asked.iter().map(Vec::len).collect();
295
1
    let all = TOPICS.len();
296
1
    assert_eq!(lengths, [all, all - 1, all, all - 1]);
297
1
}
298
299
#[test]
300
1
fn an_event_is_said_without_its_words() {
301
1
    let said = summary(&serde_json::json!({
302
1
        "reason": "not_allowed",
303
1
        "copied": true,
304
1
        "text": "Call the landlord about the heater before Friday.",
305
1
        "timestamp": "2026-11-26T10:00:00Z",
306
1
    }));
307
1
    assert_eq!(said, "reason=not_allowed, copied=true, text=49 chars");
308
1
    assert!(!said.contains("landlord"));
309
1
    assert_eq!(
310
1
        summary(&serde_json::json!({ "status": "downloading", "percentage": 42.857 })),
311
1
        "status=downloading, percentage=42.9"
312
    );
313
1
    assert_eq!(summary(&serde_json::json!({})), "no details");
314
1
}
315
316
#[test]
317
1
fn a_downloads_ticks_are_said_once_a_phase() {
318
1
    let mut said = Said::default();
319
3
    let tick = |status: &str, percentage: f64| {
320
3
        event(
321
3
            "download_progress",
322
3
            serde_json::json!({ "feature": "stt", "stage": 1, "status": status, "percentage": percentage }),
323
3
        )
324
3
    };
325
1
    assert_eq!(said.level(&tick("downloading", 1.0)), log::Level::Debug);
326
1
    assert_eq!(said.level(&tick("downloading", 2.0)), log::Level::Trace);
327
1
    assert_eq!(said.level(&tick("loading_model", 100.0)), log::Level::Debug);
328
1
    let meter = event(
329
1
        "frequency_bands",
330
1
        serde_json::json!({ "total_energy": 0.01 }),
331
1
    );
332
1
    assert_eq!(said.level(&meter), log::Level::Trace);
333
1
    let recording = event(
334
1
        "recording_state",
335
1
        serde_json::json!({ "is_recording": true }),
336
1
    );
337
1
    assert_eq!(said.level(&recording), log::Level::Debug);
338
1
}
339
340
/// `bands_b64` as the daemon sends it: the bands' little-endian f32s, in base64.
341
1
fn bands_payload(bands: &[f32]) -> Value {
342
    use base64::Engine as _;
343
3
    let bytes: Vec<u8> = 
bands.iter()1
.flat_map(|b| b.to_le_bytes()).collect();
344
1
    serde_json::json!({
345
1
        "bands_b64": base64::engine::general_purpose::STANDARD.encode(bytes),
346
1
        "total_energy": 0.005,
347
    })
348
1
}
349
350
#[test]
351
1
fn bands_are_decoded() {
352
1
    let payload = bands_payload(&[0.5, 1.0, 2.0]);
353
    let Some(Event::MicrophoneLevel {
354
        level,
355
        bands,
356
        total_energy,
357
        ..
358
1
    }) = parse(&event("frequency_bands", payload.clone()))
359
    else {
360
0
        panic!("not a microphone level");
361
    };
362
1
    assert_eq!(bands, vec![0.5, 1.0, 2.0]);
363
1
    assert!((total_energy - 0.005).abs() < f32::EPSILON);
364
1
    assert!((level - level_percent(0.005)).abs() < f32::EPSILON);
365
    let Some(Event::PlaybackLevel {
366
        level,
367
        bands,
368
        total_energy,
369
        ..
370
1
    }) = parse(&event("playback_frequency_bands", payload))
371
    else {
372
0
        panic!("not a playback level");
373
    };
374
1
    assert_eq!(bands, vec![0.5, 1.0, 2.0]);
375
1
    assert!((total_energy - 0.005).abs() < f32::EPSILON);
376
1
    assert!((level - level_percent(0.005)).abs() < f32::EPSILON);
377
1
}
378
379
#[test]
380
1
fn bad_bands_are_empty() {
381
    use base64::Engine as _;
382
1
    let five = base64::engine::general_purpose::STANDARD.encode([1_u8; 5]);
383
1
    for payload in [
384
1
        serde_json::json!({ "total_energy": 0.005 }),
385
1
        serde_json::json!({ "bands_b64": "not base64!" }),
386
1
        serde_json::json!({ "bands_b64": five }),
387
1
    ] {
388
3
        let Some(Event::MicrophoneLevel { bands, .. }) = parse(&event("frequency_bands", payload))
389
        else {
390
0
            panic!("not a microphone level");
391
        };
392
3
        assert!(bands.is_empty());
393
    }
394
1
}
395
396
#[test]
397
1
fn transcription_is_heard() {
398
2
    let say = |name| parse(&event(name, serde_json::json!({})));
399
1
    assert!(matches!(
400
1
        say("transcribing_started"),
401
        Some(Event::Transcribing(true))
402
    ));
403
1
    assert!(matches!(
404
1
        say("transcribing_stopped"),
405
        Some(Event::Transcribing(false))
406
    ));
407
1
}
408
409
#[test]
410
1
fn speech_progress_is_heard() {
411
2
    let say = |payload| parse(&event("speech_progress", payload));
412
1
    assert!(matches!(
413
1
        say(serde_json::json!({ "spoken_ms": 120 })),
414
        Some(Event::SpeechProgress { spoken_ms: 120 })
415
    ));
416
1
    assert!(matches!(
417
1
        say(serde_json::json!({})),
418
        Some(Event::SpeechProgress { spoken_ms: 0 })
419
    ));
420
1
}