Debian Codegraph @

third_party/rust/glean/src/test.rs

raw
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5 use std::io::Read;
6 use std::sync::{Arc, Barrier, Mutex};
7 use std::thread::{self, ThreadId};
8 use std::time::{Duration, Instant};
9
10 use crossbeam_channel::RecvTimeoutError;
11 use flate2::read::GzDecoder;
12 use glean_core::glean_test_get_experimentation_id;
13 use serde_json::Value as JsonValue;
14
15 use crate::private::PingType;
16 use crate::private::{BooleanMetric, CounterMetric, EventMetric, StringMetric, TextMetric};
17
18 use super::*;
19 use crate::common_test::{lock_test, new_glean, GLOBAL_APPLICATION_ID};
20
21 fn new_test_ping(name: &str) -> PingType {
22 PingType::new(
23 name,
24 true,
25 true,
26 true,
27 true,
28 true,
29 vec![],
30 vec![],
31 true,
32 vec![],
33 )
34 }
35
36 #[test]
37 fn send_a_ping() {
38 let _lock = lock_test();
39
40 let (s, r) = crossbeam_channel::bounded::<net::PingUploadRequest>(1);
41
42 // Define a fake uploader that reports back the ping upload request.
43 #[derive(Debug)]
44 pub struct FakeUploader {
45 sender: crossbeam_channel::Sender<net::PingUploadRequest>,
46 }
47 impl net::PingUploader for FakeUploader {
48 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
49 let upload_request = upload_request.capable(|_| true).unwrap();
50 self.sender.send(upload_request).unwrap();
51 net::UploadResult::http_status(200)
52 }
53 }
54
55 // Create a custom configuration to use a fake uploader.
56 let dir = tempfile::tempdir().unwrap();
57 let tmpname = dir.path().to_path_buf();
58
59 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
60 .with_server_endpoint("invalid-test-host")
61 .with_uploader(FakeUploader { sender: s })
62 .build();
63
64 let _t = new_glean(Some(cfg), true);
65
66 // Define a new ping and submit it.
67 const PING_NAME: &str = "test-ping";
68 let custom_ping = new_test_ping(PING_NAME);
69 custom_ping.submit(None);
70
71 // Wait for the ping to arrive.
72 let upload_request = r.recv().unwrap();
73 assert!(upload_request.body_has_info_sections);
74 assert_eq!(upload_request.ping_name, PING_NAME);
75 assert!(upload_request.url.contains(PING_NAME));
76 }
77
78 #[test]
79 fn send_a_ping_without_info_sections() {
80 let _lock = lock_test();
81
82 let (s, r) = crossbeam_channel::bounded::<net::PingUploadRequest>(1);
83
84 // Define a fake uploader that reports back the ping upload request.
85 #[derive(Debug)]
86 pub struct FakeUploader {
87 sender: crossbeam_channel::Sender<net::PingUploadRequest>,
88 }
89 impl net::PingUploader for FakeUploader {
90 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
91 let upload_request = upload_request.capable(|_| true).unwrap();
92 self.sender.send(upload_request).unwrap();
93 net::UploadResult::http_status(200)
94 }
95 }
96
97 // Create a custom configuration to use a fake uploader.
98 let dir = tempfile::tempdir().unwrap();
99 let tmpname = dir.path().to_path_buf();
100
101 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
102 .with_server_endpoint("invalid-test-host")
103 .with_uploader(FakeUploader { sender: s })
104 .build();
105
106 let _t = new_glean(Some(cfg), true);
107
108 // Define a new ping and submit it.
109 const PING_NAME: &str = "noinfo-ping";
110 let custom_ping = PingType::new(
111 PING_NAME,
112 true,
113 true,
114 true,
115 /* include_info_sections */ false,
116 true,
117 vec![],
118 vec![],
119 true,
120 vec![],
121 );
122 custom_ping.submit(None);
123
124 // Wait for the ping to arrive.
125 let upload_request = r.recv().unwrap();
126 assert!(!upload_request.body_has_info_sections);
127 assert_eq!(upload_request.ping_name, PING_NAME);
128 }
129
130 #[test]
131 fn disabling_upload_disables_metrics_recording() {
132 let _lock = lock_test();
133
134 let _t = new_glean(None, true);
135
136 let metric = BooleanMetric::new(CommonMetricData {
137 name: "bool_metric".into(),
138 category: "test".into(),
139 send_in_pings: vec!["store1".into()],
140 lifetime: Lifetime::Application,
141 disabled: false,
142 dynamic_label: None,
143 });
144
145 crate::set_upload_enabled(false);
146
147 assert!(metric.test_get_value(Some("store1".into())).is_none())
148 }
149
150 #[test]
151 fn test_experiments_recording() {
152 let _lock = lock_test();
153
154 let _t = new_glean(None, true);
155
156 set_experiment_active("experiment_test".to_string(), "branch_a".to_string(), None);
157 let mut extra = HashMap::new();
158 extra.insert("test_key".to_string(), "value".to_string());
159 set_experiment_active(
160 "experiment_api".to_string(),
161 "branch_b".to_string(),
162 Some(extra),
163 );
164 assert!(test_is_experiment_active("experiment_test".to_string()));
165 assert!(test_is_experiment_active("experiment_api".to_string()));
166 set_experiment_inactive("experiment_test".to_string());
167 assert!(!test_is_experiment_active("experiment_test".to_string()));
168 assert!(test_is_experiment_active("experiment_api".to_string()));
169 let stored_data = test_get_experiment_data("experiment_api".to_string()).unwrap();
170 assert_eq!("branch_b", stored_data.branch);
171 assert_eq!("value", stored_data.extra.unwrap()["test_key"]);
172 }
173
174 #[test]
175 fn test_experiments_recording_before_glean_inits() {
176 let _lock = lock_test();
177 let dir = tempfile::tempdir().unwrap();
178 let tmpname = dir.path().to_path_buf();
179
180 destroy_glean(true, &tmpname);
181
182 set_experiment_active(
183 "experiment_set_preinit".to_string(),
184 "branch_a".to_string(),
185 None,
186 );
187 set_experiment_active(
188 "experiment_preinit_disabled".to_string(),
189 "branch_a".to_string(),
190 None,
191 );
192 set_experiment_inactive("experiment_preinit_disabled".to_string());
193
194 test_reset_glean(
195 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
196 .with_server_endpoint("invalid-test-host")
197 .build(),
198 ClientInfoMetrics::unknown(),
199 false,
200 );
201
202 assert!(test_is_experiment_active(
203 "experiment_set_preinit".to_string()
204 ));
205 assert!(!test_is_experiment_active(
206 "experiment_preinit_disabled".to_string()
207 ));
208 }
209
210 #[test]
211 fn test_experimentation_id_recording() {
212 let _lock = lock_test();
213 let dir = tempfile::tempdir().unwrap();
214 let tmpname = dir.path().to_path_buf();
215
216 destroy_glean(true, &tmpname);
217
218 test_reset_glean(
219 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
220 .with_server_endpoint("invalid-test-host")
221 .with_experimentation_id("alpha-beta-gamma-delta".to_string())
222 .build(),
223 ClientInfoMetrics::unknown(),
224 false,
225 );
226
227 let exp_id = glean_test_get_experimentation_id().expect("Experimentation id must not be None");
228 assert_eq!(
229 "alpha-beta-gamma-delta".to_string(),
230 exp_id,
231 "Experimentation id must match"
232 );
233 }
234
235 #[test]
236 fn sending_of_foreground_background_pings() {
237 let _lock = lock_test();
238
239 let click: EventMetric<traits::NoExtraKeys> = private::EventMetric::new(CommonMetricData {
240 name: "click".into(),
241 category: "ui".into(),
242 send_in_pings: vec!["events".into()],
243 lifetime: Lifetime::Ping,
244 disabled: false,
245 ..Default::default()
246 });
247
248 // Define a fake uploader that reports back the submission headers
249 // using a crossbeam channel.
250 let (s, r) = crossbeam_channel::bounded::<String>(3);
251
252 #[derive(Debug)]
253 pub struct FakeUploader {
254 sender: crossbeam_channel::Sender<String>,
255 }
256 impl net::PingUploader for FakeUploader {
257 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
258 let upload_request = upload_request.capable(|_| true).unwrap();
259 self.sender.send(upload_request.url).unwrap();
260 net::UploadResult::http_status(200)
261 }
262 }
263
264 // Create a custom configuration to use a fake uploader.
265 let dir = tempfile::tempdir().unwrap();
266 let tmpname = dir.path().to_path_buf();
267
268 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
269 .with_server_endpoint("invalid-test-host")
270 .with_uploader(FakeUploader { sender: s })
271 .build();
272
273 let _t = new_glean(Some(cfg), true);
274
275 // Simulate becoming active.
276 handle_client_active();
277
278 // We expect a baseline ping to be generated here (reason: 'active').
279 let url = r.recv().unwrap();
280 assert!(url.contains("baseline"));
281
282 // Recording an event so that an "events" ping will contain data.
283 click.record(None);
284
285 // Simulate becoming inactive
286 handle_client_inactive();
287
288 // Wait for the pings to arrive.
289 let mut expected_pings = vec!["baseline", "events"];
290 for _ in 0..2 {
291 let url = r.recv().unwrap();
292 // If the url contains the expected reason, remove it from the list.
293 expected_pings.retain(|&name| !url.contains(name));
294 }
295 // We received all the expected pings.
296 assert_eq!(0, expected_pings.len());
297
298 // Simulate becoming active again.
299 handle_client_active();
300
301 // We expect a baseline ping to be generated here (reason: 'active').
302 let url = r.recv().unwrap();
303 assert!(url.contains("baseline"));
304 }
305
306 #[test]
307 fn sending_of_startup_baseline_ping() {
308 let _lock = lock_test();
309
310 // Create an instance of Glean and then flip the dirty
311 // bit to true.
312 let data_dir = new_glean(None, true);
313
314 glean_core::glean_set_dirty_flag(true);
315
316 // Restart glean and wait for a baseline ping to be generated.
317 let (s, r) = crossbeam_channel::bounded::<String>(1);
318
319 // Define a fake uploader that reports back the submission URL
320 // using a crossbeam channel.
321 #[derive(Debug)]
322 pub struct FakeUploader {
323 sender: crossbeam_channel::Sender<String>,
324 }
325 impl net::PingUploader for FakeUploader {
326 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
327 let upload_request = upload_request.capable(|_| true).unwrap();
328 self.sender.send(upload_request.url).unwrap();
329 net::UploadResult::http_status(200)
330 }
331 }
332
333 // Create a custom configuration to use a fake uploader.
334 let tmpname = data_dir.path().to_path_buf();
335
336 // Now reset Glean: it should still send a baseline ping with reason
337 // dirty_startup when starting, because of the dirty bit being set.
338 test_reset_glean(
339 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
340 .with_server_endpoint("invalid-test-host")
341 .with_uploader(FakeUploader { sender: s })
342 .build(),
343 ClientInfoMetrics::unknown(),
344 false,
345 );
346
347 // Wait for the ping to arrive.
348 let url = r.recv().unwrap();
349 assert!(url.contains("baseline"));
350 }
351
352 #[test]
353 fn no_dirty_baseline_on_clean_shutdowns() {
354 let _lock = lock_test();
355
356 // Create an instance of Glean, wait for init and then flip the dirty
357 // bit to true.
358 let data_dir = new_glean(None, true);
359
360 glean_core::glean_set_dirty_flag(true);
361
362 crate::shutdown();
363
364 // Restart glean and wait for a baseline ping to be generated.
365 let (s, r) = crossbeam_channel::bounded::<String>(1);
366
367 // Define a fake uploader that reports back the submission URL
368 // using a crossbeam channel.
369 #[derive(Debug)]
370 pub struct FakeUploader {
371 sender: crossbeam_channel::Sender<String>,
372 }
373 impl net::PingUploader for FakeUploader {
374 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
375 let upload_request = upload_request.capable(|_| true).unwrap();
376 self.sender.send(upload_request.url).unwrap();
377 net::UploadResult::http_status(200)
378 }
379 }
380
381 // Create a custom configuration to use a fake uploader.
382 let tmpname = data_dir.path().to_path_buf();
383
384 // Now reset Glean: it should not send a baseline ping, because
385 // we cleared the dirty bit.
386 test_reset_glean(
387 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
388 .with_server_endpoint("invalid-test-host")
389 .with_uploader(FakeUploader { sender: s })
390 .build(),
391 ClientInfoMetrics::unknown(),
392 false,
393 );
394
395 // We don't expect a startup ping.
396 assert_eq!(r.try_recv(), Err(crossbeam_channel::TryRecvError::Empty));
397 }
398
399 #[test]
400 fn initialize_must_not_crash_if_data_dir_is_messed_up() {
401 let _lock = lock_test();
402
403 let dir = tempfile::tempdir().unwrap();
404 let tmpdirname = dir.path();
405 // Create a file in the temporary dir and use that as the
406 // name of the Glean data dir.
407 let file_path = tmpdirname.to_path_buf().join("notadir");
408 std::fs::write(file_path.clone(), "test").expect("The test Glean dir file must be created");
409
410 let cfg = ConfigurationBuilder::new(true, file_path, GLOBAL_APPLICATION_ID)
411 .with_server_endpoint("invalid-test-host")
412 .build();
413
414 test_reset_glean(cfg, ClientInfoMetrics::unknown(), false);
415
416 // We don't need to sleep here.
417 // The `test_reset_glean` already waited on the initialize task.
418 }
419
420 #[test]
421 fn queued_recorded_metrics_correctly_record_during_init() {
422 let _lock = lock_test();
423 let dir = tempfile::tempdir().unwrap();
424 let tmpname = dir.path().to_path_buf();
425
426 destroy_glean(true, &tmpname);
427
428 let metric = CounterMetric::new(CommonMetricData {
429 name: "counter_metric".into(),
430 category: "test".into(),
431 send_in_pings: vec!["store1".into()],
432 lifetime: Lifetime::Application,
433 disabled: false,
434 dynamic_label: None,
435 });
436
437 // This will queue 3 tasks that will add to the metric value once Glean is initialized
438 for _ in 0..3 {
439 metric.add(1);
440 }
441
442 // TODO: To be fixed in bug 1677150.
443 // Ensure that no value has been stored yet since the tasks have only been queued
444 // and not executed yet
445
446 // Calling `new_glean` here will cause Glean to be initialized and should cause the queued
447 // tasks recording metrics to execute
448 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
449 .with_server_endpoint("invalid-test-host")
450 .build();
451 let _t = new_glean(Some(cfg), false);
452
453 // Verify that the callback was executed by testing for the correct value
454 assert!(metric.test_get_value(None).is_some(), "Value must exist");
455 assert_eq!(3, metric.test_get_value(None).unwrap(), "Value must match");
456 }
457
458 #[test]
459 fn initializing_twice_is_a_noop() {
460 let _lock = lock_test();
461
462 let dir = tempfile::tempdir().unwrap();
463 let tmpname = dir.path().to_path_buf();
464
465 test_reset_glean(
466 ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
467 .with_server_endpoint("invalid-test-host")
468 .build(),
469 ClientInfoMetrics::unknown(),
470 true,
471 );
472
473 // Glean was initialized and it waited for a full initialization to finish.
474 // We now just want to try to initialize again.
475 // This will bail out early.
476
477 crate::initialize(
478 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
479 .with_server_endpoint("invalid-test-host")
480 .build(),
481 ClientInfoMetrics::unknown(),
482 );
483
484 // We don't need to sleep here.
485 // The `test_reset_glean` already waited on the initialize task,
486 // and the 2nd initialize will bail out early.
487 //
488 // All we tested is that this didn't crash.
489 }
490
491 #[test]
492 fn dont_handle_events_when_uninitialized() {
493 let _lock = lock_test();
494 let dir = tempfile::tempdir().unwrap();
495 let tmpname = dir.path().to_path_buf();
496
497 test_reset_glean(
498 ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
499 .with_server_endpoint("invalid-test-host")
500 .build(),
501 ClientInfoMetrics::unknown(),
502 true,
503 );
504
505 // Ensure there's at least one event recorded,
506 // otherwise the ping is not sent.
507 let click: EventMetric<traits::NoExtraKeys> = private::EventMetric::new(CommonMetricData {
508 name: "click".into(),
509 category: "ui".into(),
510 send_in_pings: vec!["events".into()],
511 lifetime: Lifetime::Ping,
512 disabled: false,
513 ..Default::default()
514 });
515 click.record(None);
516 // Wait for the dispatcher.
517 assert_ne!(None, click.test_get_value(None));
518
519 // Now destroy Glean. We test submission when not initialized.
520 destroy_glean(false, &tmpname);
521
522 // We reach into `glean_core` to test this,
523 // only there we can synchronously submit and get a return value.
524 assert!(!glean_core::glean_submit_ping_by_name_sync(
525 "events".to_string(),
526 None
527 ));
528 }
529
530 // TODO: Should probably move into glean-core.
531 #[test]
532 fn the_app_channel_must_be_correctly_set_if_requested() {
533 let _lock = lock_test();
534
535 let dir = tempfile::tempdir().unwrap();
536 let tmpname = dir.path().to_path_buf();
537
538 // Internal metric, replicated here for testing.
539 let app_channel = StringMetric::new(CommonMetricData {
540 name: "app_channel".into(),
541 category: "".into(),
542 send_in_pings: vec!["glean_client_info".into()],
543 lifetime: Lifetime::Application,
544 disabled: false,
545 ..Default::default()
546 });
547
548 // No app_channel reported.
549 let client_info = ClientInfoMetrics {
550 channel: None,
551 ..ClientInfoMetrics::unknown()
552 };
553 test_reset_glean(
554 ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
555 .with_server_endpoint("invalid-test-host")
556 .build(),
557 client_info,
558 true,
559 );
560 assert!(app_channel.test_get_value(None).is_none());
561
562 // Custom app_channel reported.
563 let client_info = ClientInfoMetrics {
564 channel: Some("testing".into()),
565 ..ClientInfoMetrics::unknown()
566 };
567 test_reset_glean(
568 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
569 .with_server_endpoint("invalid-test-host")
570 .build(),
571 client_info,
572 true,
573 );
574 assert_eq!("testing", app_channel.test_get_value(None).unwrap());
575 }
576
577 #[test]
578 fn ping_collection_must_happen_after_concurrently_scheduled_metrics_recordings() {
579 // Given the following block of code:
580 //
581 // Metric.A.set("SomeTestValue")
582 // Glean.submitPings(listOf("custom-ping-1"))
583 //
584 // This test ensures that "custom-ping-1" contains "metric.a" with a value of "SomeTestValue"
585 // when the ping is collected.
586
587 let _lock = lock_test();
588
589 let (s, r) = crossbeam_channel::bounded(1);
590
591 // Define a fake uploader that reports back the submission URL
592 // using a crossbeam channel.
593 #[derive(Debug)]
594 pub struct FakeUploader {
595 sender: crossbeam_channel::Sender<(String, JsonValue)>,
596 }
597 impl net::PingUploader for FakeUploader {
598 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
599 let net::PingUploadRequest { body, url, .. } =
600 upload_request.capable(|_| true).unwrap();
601 // Decode the gzipped body.
602 let mut gzip_decoder = GzDecoder::new(&body[..]);
603 let mut s = String::with_capacity(body.len());
604
605 let data = gzip_decoder
606 .read_to_string(&mut s)
607 .ok()
608 .map(|_| &s[..])
609 .or_else(|| std::str::from_utf8(&body).ok())
610 .and_then(|payload| serde_json::from_str(payload).ok())
611 .unwrap();
612 self.sender.send((url, data)).unwrap();
613 net::UploadResult::http_status(200)
614 }
615 }
616
617 let dir = tempfile::tempdir().unwrap();
618 let tmpname = dir.path().to_path_buf();
619 test_reset_glean(
620 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
621 .with_server_endpoint("invalid-test-host")
622 .with_uploader(FakeUploader { sender: s })
623 .build(),
624 ClientInfoMetrics::unknown(),
625 true,
626 );
627
628 let ping_name = "custom_ping_1";
629 let ping = new_test_ping(ping_name);
630 let metric = private::StringMetric::new(CommonMetricData {
631 name: "string_metric".into(),
632 category: "telemetry".into(),
633 send_in_pings: vec![ping_name.into()],
634 lifetime: Lifetime::Ping,
635 disabled: false,
636 ..Default::default()
637 });
638
639 let test_value = "SomeTestValue";
640 metric.set(test_value.to_string());
641 ping.submit(None);
642
643 // Wait for the ping to arrive.
644 let (url, body) = r.recv().unwrap();
645 assert!(url.contains(ping_name));
646
647 assert_eq!(
648 test_value,
649 body["metrics"]["string"]["telemetry.string_metric"]
650 );
651 }
652
653 #[test]
654 fn basic_metrics_should_be_cleared_when_disabling_uploading() {
655 let _lock = lock_test();
656
657 let _t = new_glean(None, false);
658
659 let metric = private::StringMetric::new(CommonMetricData {
660 name: "string_metric".into(),
661 category: "telemetry".into(),
662 send_in_pings: vec!["store1".into()],
663 lifetime: Lifetime::Ping,
664 disabled: false,
665 ..Default::default()
666 });
667
668 assert!(metric.test_get_value(None).is_none());
669
670 metric.set("TEST VALUE".into());
671 assert!(metric.test_get_value(None).is_some());
672
673 set_upload_enabled(false);
674 assert!(metric.test_get_value(None).is_none());
675 metric.set("TEST VALUE".into());
676 assert!(metric.test_get_value(None).is_none());
677
678 set_upload_enabled(true);
679 assert!(metric.test_get_value(None).is_none());
680 metric.set("TEST VALUE".into());
681 assert_eq!("TEST VALUE", metric.test_get_value(None).unwrap());
682 }
683
684 #[test]
685 fn core_metrics_are_not_cleared_when_disabling_and_enabling_uploading() {
686 let _lock = lock_test();
687
688 let dir = tempfile::tempdir().unwrap();
689 let tmpname = dir.path().to_path_buf();
690
691 // No app_channel reported.
692 test_reset_glean(
693 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
694 .with_server_endpoint("invalid-test-host")
695 .build(),
696 ClientInfoMetrics::unknown(),
697 true,
698 );
699
700 // Internal metric, replicated here for testing.
701 let os_version = StringMetric::new(CommonMetricData {
702 name: "os_version".into(),
703 category: "".into(),
704 send_in_pings: vec!["glean_client_info".into()],
705 lifetime: Lifetime::Application,
706 disabled: false,
707 ..Default::default()
708 });
709
710 assert!(os_version.test_get_value(None).is_some());
711 let initial_value = os_version.test_get_value(None).unwrap();
712
713 set_upload_enabled(false);
714 assert_eq!(initial_value, os_version.test_get_value(None).unwrap());
715
716 set_upload_enabled(true);
717 assert_eq!(initial_value, os_version.test_get_value(None).unwrap());
718 }
719
720 #[test]
721 fn sending_deletion_ping_if_disabled_outside_of_run() {
722 let _lock = lock_test();
723
724 let (s, r) = crossbeam_channel::bounded::<String>(1);
725
726 // Define a fake uploader that reports back the submission URL
727 // using a crossbeam channel.
728 #[derive(Debug)]
729 pub struct FakeUploader {
730 sender: crossbeam_channel::Sender<String>,
731 }
732 impl net::PingUploader for FakeUploader {
733 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
734 let upload_request = upload_request.capable(|_| true).unwrap();
735 self.sender.send(upload_request.url).unwrap();
736 net::UploadResult::http_status(200)
737 }
738 }
739
740 // Create a custom configuration to use a fake uploader.
741 let dir = tempfile::tempdir().unwrap();
742 let tmpname = dir.path().to_path_buf();
743
744 let cfg = ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
745 .with_server_endpoint("invalid-test-host")
746 .build();
747
748 let _t = new_glean(Some(cfg), true);
749
750 // Now reset Glean and disable upload: it should still send a deletion request
751 // ping even though we're just starting.
752 test_reset_glean(
753 ConfigurationBuilder::new(false, tmpname, GLOBAL_APPLICATION_ID)
754 .with_server_endpoint("invalid-test-host")
755 .with_uploader(FakeUploader { sender: s })
756 .build(),
757 ClientInfoMetrics::unknown(),
758 false,
759 );
760
761 // Wait for the ping to arrive.
762 let url = r.recv().unwrap();
763 assert!(url.contains("deletion-request"));
764 }
765
766 #[test]
767 fn no_sending_of_deletion_ping_if_unchanged_outside_of_run() {
768 let _lock = lock_test();
769
770 let (s, r) = crossbeam_channel::bounded::<String>(1);
771
772 // Define a fake uploader that reports back the submission URL
773 // using a crossbeam channel.
774 #[derive(Debug)]
775 pub struct FakeUploader {
776 sender: crossbeam_channel::Sender<String>,
777 }
778 impl net::PingUploader for FakeUploader {
779 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
780 let upload_request = upload_request.capable(|_| true).unwrap();
781 self.sender.send(upload_request.url).unwrap();
782 net::UploadResult::http_status(200)
783 }
784 }
785
786 // Create a custom configuration to use a fake uploader.
787 let dir = tempfile::tempdir().unwrap();
788 let tmpname = dir.path().to_path_buf();
789
790 let cfg = ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
791 .with_server_endpoint("invalid-test-host")
792 .build();
793
794 let _t = new_glean(Some(cfg), true);
795
796 // Now reset Glean and keep upload enabled: no deletion-request
797 // should be sent.
798 test_reset_glean(
799 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
800 .with_server_endpoint("invalid-test-host")
801 .with_uploader(FakeUploader { sender: s })
802 .build(),
803 ClientInfoMetrics::unknown(),
804 false,
805 );
806
807 assert_eq!(0, r.len());
808 }
809
810 #[test]
811 fn deletion_request_ping_contains_experimentation_id() {
812 let _lock = lock_test();
813
814 let (s, r) = crossbeam_channel::bounded::<JsonValue>(1);
815
816 // Define a fake uploader that reports back the submission URL
817 // using a crossbeam channel.
818 #[derive(Debug)]
819 pub struct FakeUploader {
820 sender: crossbeam_channel::Sender<JsonValue>,
821 }
822 impl net::PingUploader for FakeUploader {
823 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
824 let upload_request = upload_request.capable(|_| true).unwrap();
825 let body = upload_request.body;
826 let mut gzip_decoder = GzDecoder::new(&body[..]);
827 let mut body_str = String::with_capacity(body.len());
828 let data: JsonValue = gzip_decoder
829 .read_to_string(&mut body_str)
830 .ok()
831 .map(|_| &body_str[..])
832 .or_else(|| std::str::from_utf8(&body).ok())
833 .and_then(|payload| serde_json::from_str(payload).ok())
834 .unwrap();
835 self.sender.send(data).unwrap();
836 net::UploadResult::http_status(200)
837 }
838 }
839
840 // Create a custom configuration to use a fake uploader.
841 let dir = tempfile::tempdir().unwrap();
842 let tmpname = dir.path().to_path_buf();
843
844 let cfg = ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
845 .with_server_endpoint("invalid-test-host")
846 .with_experimentation_id("alpha-beta-gamma-delta".to_string())
847 .build();
848
849 let _t = new_glean(Some(cfg), true);
850
851 // Now reset Glean and disable upload: it should still send a deletion request
852 // ping even though we're just starting.
853 test_reset_glean(
854 ConfigurationBuilder::new(false, tmpname, GLOBAL_APPLICATION_ID)
855 .with_server_endpoint("invalid-test-host")
856 .with_uploader(FakeUploader { sender: s })
857 .with_experimentation_id("alpha-beta-gamma-delta".to_string())
858 .build(),
859 ClientInfoMetrics::unknown(),
860 false,
861 );
862
863 // Wait for the ping to arrive and check the experimentation id matches
864 let url = r.recv().unwrap();
865 let metrics = url.get("metrics").unwrap();
866 let strings = metrics.get("string").unwrap();
867 assert_eq!(
868 "alpha-beta-gamma-delta",
869 strings
870 .get("glean.client.annotation.experimentation_id")
871 .unwrap()
872 );
873 }
874
875 #[test]
876 fn test_sending_of_startup_baseline_ping_with_application_lifetime_metric() {
877 let _lock = lock_test();
878
879 let (s, r) = crossbeam_channel::bounded(1);
880
881 // Define a fake uploader that reports back the submission URL
882 // using a crossbeam channel.
883 #[derive(Debug)]
884 pub struct FakeUploader {
885 sender: crossbeam_channel::Sender<(String, JsonValue)>,
886 }
887 impl net::PingUploader for FakeUploader {
888 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
889 let net::PingUploadRequest { url, body, .. } =
890 upload_request.capable(|_| true).unwrap();
891 // Decode the gzipped body.
892 let mut gzip_decoder = GzDecoder::new(&body[..]);
893 let mut s = String::with_capacity(body.len());
894
895 let data = gzip_decoder
896 .read_to_string(&mut s)
897 .ok()
898 .map(|_| &s[..])
899 .or_else(|| std::str::from_utf8(&body).ok())
900 .and_then(|payload| serde_json::from_str(payload).ok())
901 .unwrap();
902 self.sender.send((url, data)).unwrap();
903 net::UploadResult::http_status(200)
904 }
905 }
906
907 let dir = tempfile::tempdir().unwrap();
908 let tmpname = dir.path().to_path_buf();
909 test_reset_glean(
910 ConfigurationBuilder::new(true, tmpname.clone(), GLOBAL_APPLICATION_ID)
911 .with_server_endpoint("invalid-test-host")
912 .build(),
913 ClientInfoMetrics::unknown(),
914 true,
915 );
916
917 // Reaching into the core.
918 glean_core::glean_set_dirty_flag(true);
919
920 let metric = private::StringMetric::new(CommonMetricData {
921 name: "app_lifetime".into(),
922 category: "telemetry".into(),
923 send_in_pings: vec!["baseline".into()],
924 lifetime: Lifetime::Application,
925 disabled: false,
926 ..Default::default()
927 });
928 let test_value = "HELLOOOOO!";
929 metric.set(test_value.into());
930 assert_eq!(test_value, metric.test_get_value(None).unwrap());
931
932 // Restart glean and don't clear the stores.
933 test_reset_glean(
934 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
935 .with_server_endpoint("invalid-test-host")
936 .with_uploader(FakeUploader { sender: s })
937 .build(),
938 ClientInfoMetrics::unknown(),
939 false,
940 );
941
942 let (url, body) = r.recv().unwrap();
943 assert!(url.contains("/baseline/"));
944
945 // We set the dirty bit above.
946 assert_eq!("dirty_startup", body["ping_info"]["reason"]);
947 assert_eq!(
948 test_value,
949 body["metrics"]["string"]["telemetry.app_lifetime"]
950 );
951 }
952
953 #[test]
954 fn setting_debug_view_tag_before_initialization_should_not_crash() {
955 let _lock = lock_test();
956 let dir = tempfile::tempdir().unwrap();
957 let tmpname = dir.path().to_path_buf();
958
959 destroy_glean(true, &tmpname);
960
961 // Define a fake uploader that reports back the submission headers
962 // using a crossbeam channel.
963 let (s, r) = crossbeam_channel::bounded::<Vec<(String, String)>>(1);
964
965 #[derive(Debug)]
966 pub struct FakeUploader {
967 sender: crossbeam_channel::Sender<Vec<(String, String)>>,
968 }
969 impl net::PingUploader for FakeUploader {
970 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
971 let upload_request = upload_request.capable(|_| true).unwrap();
972 self.sender.send(upload_request.headers).unwrap();
973 net::UploadResult::http_status(200)
974 }
975 }
976
977 // Attempt to set a debug view tag before Glean is initialized.
978 set_debug_view_tag("valid-tag");
979
980 // Create a custom configuration to use a fake uploader.
981 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
982 .with_server_endpoint("invalid-test-host")
983 .with_uploader(FakeUploader { sender: s })
984 .build();
985
986 let _t = new_glean(Some(cfg), true);
987
988 // Submit a baseline ping.
989 submit_ping_by_name("baseline", Some("inactive"));
990
991 // Wait for the ping to arrive.
992 let headers = r.recv().unwrap();
993 assert_eq!(
994 "valid-tag",
995 headers.iter().find(|&kv| kv.0 == "X-Debug-ID").unwrap().1
996 );
997 }
998
999 #[test]
1000 fn setting_source_tags_before_initialization_should_not_crash() {
1001 let _lock = lock_test();
1002 let dir = tempfile::tempdir().unwrap();
1003 let tmpname = dir.path().to_path_buf();
1004
1005 destroy_glean(true, &tmpname);
1006 //assert!(!was_initialize_called());
1007
1008 // Define a fake uploader that reports back the submission headers
1009 // using a crossbeam channel.
1010 let (s, r) = crossbeam_channel::bounded::<Vec<(String, String)>>(1);
1011
1012 #[derive(Debug)]
1013 pub struct FakeUploader {
1014 sender: crossbeam_channel::Sender<Vec<(String, String)>>,
1015 }
1016 impl net::PingUploader for FakeUploader {
1017 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1018 let upload_request = upload_request.capable(|_| true).unwrap();
1019 self.sender.send(upload_request.headers).unwrap();
1020 net::UploadResult::http_status(200)
1021 }
1022 }
1023
1024 // Attempt to set source tags before Glean is initialized.
1025 set_source_tags(vec!["valid-tag1".to_string(), "valid-tag2".to_string()]);
1026
1027 // Create a custom configuration to use a fake uploader.
1028 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1029 .with_server_endpoint("invalid-test-host")
1030 .with_uploader(FakeUploader { sender: s })
1031 .build();
1032
1033 let _t = new_glean(Some(cfg), true);
1034
1035 // Submit a baseline ping.
1036 submit_ping_by_name("baseline", Some("inactive"));
1037
1038 // Wait for the ping to arrive.
1039 let headers = r.recv().unwrap();
1040 assert_eq!(
1041 "valid-tag1,valid-tag2",
1042 headers
1043 .iter()
1044 .find(|&kv| kv.0 == "X-Source-Tags")
1045 .unwrap()
1046 .1
1047 );
1048 }
1049
1050 #[test]
1051 fn setting_source_tags_after_initialization_should_not_crash() {
1052 let _lock = lock_test();
1053
1054 // Define a fake uploader that reports back the submission headers
1055 // using a crossbeam channel.
1056 let (s, r) = crossbeam_channel::bounded::<Vec<(String, String)>>(1);
1057
1058 #[derive(Debug)]
1059 pub struct FakeUploader {
1060 sender: crossbeam_channel::Sender<Vec<(String, String)>>,
1061 }
1062 impl net::PingUploader for FakeUploader {
1063 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1064 let upload_request = upload_request.capable(|_| true).unwrap();
1065 self.sender.send(upload_request.headers).unwrap();
1066 net::UploadResult::http_status(200)
1067 }
1068 }
1069
1070 // Create a custom configuration to use a fake uploader.
1071 let dir = tempfile::tempdir().unwrap();
1072 let tmpname = dir.path().to_path_buf();
1073
1074 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1075 .with_server_endpoint("invalid-test-host")
1076 .with_uploader(FakeUploader { sender: s })
1077 .build();
1078
1079 let _t = new_glean(Some(cfg), true);
1080
1081 // Attempt to set source tags after `Glean.initialize` is called,
1082 // but before Glean is fully initialized.
1083 //assert!(was_initialize_called());
1084 set_source_tags(vec!["valid-tag1".to_string(), "valid-tag2".to_string()]);
1085
1086 // Submit a baseline ping.
1087 submit_ping_by_name("baseline", Some("inactive"));
1088
1089 // Wait for the ping to arrive.
1090 let headers = r.recv().unwrap();
1091 assert_eq!(
1092 "valid-tag1,valid-tag2",
1093 headers
1094 .iter()
1095 .find(|&kv| kv.0 == "X-Source-Tags")
1096 .unwrap()
1097 .1
1098 );
1099 }
1100
1101 #[test]
1102 fn flipping_upload_enabled_respects_order_of_events() {
1103 // NOTES(janerik):
1104 // I'm reasonably sure this test is excercising the right code paths
1105 // and from the log output it does the right thing:
1106 //
1107 // * It fully initializes with the assumption uploadEnabled=true
1108 // * It then disables upload
1109 // * Then it submits the custom ping, which rightfully is ignored because uploadEnabled=false.
1110 //
1111 // The test passes.
1112 let _lock = lock_test();
1113
1114 let (s, r) = crossbeam_channel::bounded::<String>(1);
1115
1116 // Define a fake uploader that reports back the submission URL
1117 // using a crossbeam channel.
1118 #[derive(Debug)]
1119 pub struct FakeUploader {
1120 sender: crossbeam_channel::Sender<String>,
1121 }
1122 impl net::PingUploader for FakeUploader {
1123 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1124 let upload_request = upload_request.capable(|_| true).unwrap();
1125 self.sender.send(upload_request.url).unwrap();
1126 net::UploadResult::http_status(200)
1127 }
1128 }
1129
1130 // Create a custom configuration to use a fake uploader.
1131 let dir = tempfile::tempdir().unwrap();
1132 let tmpname = dir.path().to_path_buf();
1133
1134 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1135 .with_server_endpoint("invalid-test-host")
1136 .with_uploader(FakeUploader { sender: s })
1137 .build();
1138
1139 // We create a ping and a metric before we initialize Glean
1140 let sample_ping = new_test_ping("sample-ping-1");
1141 let metric = private::StringMetric::new(CommonMetricData {
1142 name: "string_metric".into(),
1143 category: "telemetry".into(),
1144 send_in_pings: vec!["sample-ping-1".into()],
1145 lifetime: Lifetime::Ping,
1146 disabled: false,
1147 ..Default::default()
1148 });
1149
1150 let _t = new_glean(Some(cfg), true);
1151
1152 // Glean might still be initializing. Disable upload.
1153 set_upload_enabled(false);
1154
1155 // Set data and try to submit a custom ping.
1156 metric.set("some-test-value".into());
1157 sample_ping.submit(None);
1158
1159 // Wait for the ping to arrive.
1160 let url = r.recv().unwrap();
1161 assert!(url.contains("deletion-request"));
1162 }
1163
1164 #[test]
1165 fn registering_pings_before_init_must_work() {
1166 let _lock = lock_test();
1167
1168 // Define a fake uploader that reports back the submission headers
1169 // using a crossbeam channel.
1170 let (s, r) = crossbeam_channel::bounded::<String>(1);
1171
1172 #[derive(Debug)]
1173 pub struct FakeUploader {
1174 sender: crossbeam_channel::Sender<String>,
1175 }
1176 impl net::PingUploader for FakeUploader {
1177 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1178 let upload_request = upload_request.capable(|_| true).unwrap();
1179 self.sender.send(upload_request.url).unwrap();
1180 net::UploadResult::http_status(200)
1181 }
1182 }
1183
1184 // Create a custom ping and attempt its registration.
1185 let sample_ping = new_test_ping("pre-register");
1186
1187 // Create a custom configuration to use a fake uploader.
1188 let dir = tempfile::tempdir().unwrap();
1189 let tmpname = dir.path().to_path_buf();
1190
1191 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1192 .with_server_endpoint("invalid-test-host")
1193 .with_uploader(FakeUploader { sender: s })
1194 .build();
1195
1196 let _t = new_glean(Some(cfg), true);
1197
1198 // Submit a test ping.
1199 sample_ping.submit(None);
1200
1201 // Wait for the ping to arrive.
1202 let url = r.recv().unwrap();
1203 assert!(url.contains("pre-register"));
1204 }
1205
1206 #[test]
1207 fn test_a_ping_before_submission() {
1208 let _lock = lock_test();
1209
1210 // Define a fake uploader that reports back the submission headers
1211 // using a crossbeam channel.
1212 let (s, r) = crossbeam_channel::bounded::<String>(1);
1213
1214 #[derive(Debug)]
1215 pub struct FakeUploader {
1216 sender: crossbeam_channel::Sender<String>,
1217 }
1218 impl net::PingUploader for FakeUploader {
1219 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1220 let upload_request = upload_request.capable(|_| true).unwrap();
1221 self.sender.send(upload_request.url).unwrap();
1222 net::UploadResult::http_status(200)
1223 }
1224 }
1225
1226 // Create a custom configuration to use a fake uploader.
1227 let dir = tempfile::tempdir().unwrap();
1228 let tmpname = dir.path().to_path_buf();
1229
1230 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1231 .with_server_endpoint("invalid-test-host")
1232 .with_uploader(FakeUploader { sender: s })
1233 .build();
1234
1235 let _t = new_glean(Some(cfg), true);
1236
1237 // Create a custom ping and register it.
1238 let sample_ping = new_test_ping("custom1");
1239
1240 let metric = CounterMetric::new(CommonMetricData {
1241 name: "counter_metric".into(),
1242 category: "test".into(),
1243 send_in_pings: vec!["custom1".into()],
1244 lifetime: Lifetime::Application,
1245 disabled: false,
1246 dynamic_label: None,
1247 });
1248
1249 metric.add(1);
1250
1251 sample_ping.test_before_next_submit(move |reason| {
1252 assert_eq!(None, reason);
1253 assert_eq!(1, metric.test_get_value(None).unwrap());
1254 });
1255
1256 // Submit a baseline ping.
1257 sample_ping.submit(None);
1258
1259 // Wait for the ping to arrive.
1260 let url = r.recv().unwrap();
1261 assert!(url.contains("custom1"));
1262 }
1263
1264 #[test]
1265 fn test_boolean_get_num_errors() {
1266 let _lock = lock_test();
1267
1268 let _t = new_glean(None, false);
1269
1270 let metric = BooleanMetric::new(CommonMetricData {
1271 name: "counter_metric".into(),
1272 category: "test".into(),
1273 send_in_pings: vec!["custom1".into()],
1274 lifetime: Lifetime::Application,
1275 disabled: false,
1276 dynamic_label: Some(str::to_string("asdf")),
1277 });
1278
1279 // Check specifically for an invalid label
1280 let result = metric.test_get_num_recorded_errors(ErrorType::InvalidLabel);
1281
1282 assert_eq!(result, 0);
1283 }
1284
1285 #[test]
1286 fn test_text_can_hold_long_string() {
1287 let _lock = lock_test();
1288
1289 let _t = new_glean(None, false);
1290
1291 let metric = TextMetric::new(CommonMetricData {
1292 name: "text_metric".into(),
1293 category: "test".into(),
1294 send_in_pings: vec!["custom1".into()],
1295 lifetime: Lifetime::Application,
1296 disabled: false,
1297 dynamic_label: Some(str::to_string("text")),
1298 });
1299
1300 // 216 characters, which would overflow StringMetric
1301 metric.set("I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark near the Tannhäuser Gate. All those moments will be lost in time, like tears in rain".into());
1302
1303 let result = metric.test_get_num_recorded_errors(ErrorType::InvalidValue);
1304 assert_eq!(result, 0);
1305
1306 let result = metric.test_get_num_recorded_errors(ErrorType::InvalidOverflow);
1307 assert_eq!(result, 0);
1308 }
1309
1310 #[test]
1311 fn signaling_done() {
1312 let _lock = lock_test();
1313
1314 // Define a fake uploader that reports back the submission URL
1315 // using a crossbeam channel.
1316 #[derive(Debug)]
1317 pub struct FakeUploader {
1318 barrier: Arc<Barrier>,
1319 counter: Arc<Mutex<HashMap<ThreadId, u32>>>,
1320 }
1321 impl net::PingUploader for FakeUploader {
1322 fn upload(&self, _upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1323 let mut map = self.counter.lock().unwrap();
1324 *map.entry(thread::current().id()).or_insert(0) += 1;
1325
1326 // Wait for the sync.
1327 self.barrier.wait();
1328
1329 // Signal that this uploader thread is done.
1330 net::UploadResult::done()
1331 }
1332 }
1333
1334 // Create a custom configuration to use a fake uploader.
1335 let dir = tempfile::tempdir().unwrap();
1336 let tmpname = dir.path().to_path_buf();
1337
1338 // We use a barrier to sync this test thread with the uploader thread.
1339 let barrier = Arc::new(Barrier::new(2));
1340 // We count how many times `upload` was invoked per thread.
1341 let call_count = Arc::new(Mutex::default());
1342
1343 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1344 .with_server_endpoint("invalid-test-host")
1345 .with_uploader(FakeUploader {
1346 barrier: Arc::clone(&barrier),
1347 counter: Arc::clone(&call_count),
1348 })
1349 .build();
1350
1351 let _t = new_glean(Some(cfg), true);
1352
1353 // Define a new ping and submit it.
1354 const PING_NAME: &str = "test-ping";
1355 let custom_ping = new_test_ping(PING_NAME);
1356 custom_ping.submit(None);
1357 custom_ping.submit(None);
1358
1359 // Sync up with the upload thread.
1360 barrier.wait();
1361
1362 // Submit another ping and wait for it to do work.
1363 custom_ping.submit(None);
1364
1365 // Sync up with the upload thread again.
1366 // This will not be the same thread as the one before (hopefully).
1367 barrier.wait();
1368
1369 // No one's ever gonna wait for the uploader thread (the RLB doesn't store the handle to it),
1370 // so all we can do is hope it finishes within time.
1371 std::thread::sleep(std::time::Duration::from_millis(100));
1372
1373 let map = call_count.lock().unwrap();
1374 assert_eq!(2, map.len(), "should have launched 2 uploader threads");
1375 for &count in map.values() {
1376 assert_eq!(1, count, "each thread should call upload only once");
1377 }
1378 }
1379
1380 #[test]
1381 fn configure_ping_throttling() {
1382 let _lock = lock_test();
1383
1384 let (s, r) = crossbeam_channel::bounded::<String>(1);
1385
1386 // Define a fake uploader that reports back the submission URL
1387 // using a crossbeam channel.
1388 #[derive(Debug)]
1389 pub struct FakeUploader {
1390 sender: crossbeam_channel::Sender<String>,
1391 done: Arc<std::sync::atomic::AtomicBool>,
1392 }
1393 impl net::PingUploader for FakeUploader {
1394 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1395 let upload_request = upload_request.capable(|_| true).unwrap();
1396 if self.done.load(std::sync::atomic::Ordering::SeqCst) {
1397 // If we've outlived the test, just lie.
1398 return net::UploadResult::http_status(200);
1399 }
1400 self.sender.send(upload_request.url).unwrap();
1401 net::UploadResult::http_status(200)
1402 }
1403 }
1404
1405 // Create a custom configuration to use a fake uploader.
1406 let dir = tempfile::tempdir().unwrap();
1407 let tmpname = dir.path().to_path_buf();
1408
1409 let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
1410 let mut cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1411 .with_server_endpoint("invalid-test-host")
1412 .with_uploader(FakeUploader {
1413 sender: s,
1414 done: Arc::clone(&done),
1415 })
1416 .build();
1417 let pings_per_interval = 10;
1418 cfg.rate_limit = Some(crate::PingRateLimit {
1419 seconds_per_interval: 1,
1420 pings_per_interval,
1421 });
1422
1423 let _t = new_glean(Some(cfg), true);
1424
1425 // Define a new ping.
1426 const PING_NAME: &str = "test-ping";
1427 let custom_ping = new_test_ping(PING_NAME);
1428
1429 // Submit and receive it `pings_per_interval` times.
1430 for _ in 0..pings_per_interval {
1431 custom_ping.submit(None);
1432
1433 // Wait for the ping to arrive.
1434 let url = r.recv().unwrap();
1435 assert!(url.contains(PING_NAME));
1436 }
1437
1438 // Submit one ping more than the rate limit permits.
1439 custom_ping.submit(None);
1440
1441 // We'd expect it to be received within 250ms if it weren't throttled.
1442 let now = Instant::now();
1443 assert_eq!(
1444 r.recv_deadline(now + Duration::from_millis(250)),
1445 Err(RecvTimeoutError::Timeout)
1446 );
1447
1448 // We still have to deal with that eleventh ping.
1449 // When it eventually processes after the throttle interval, this'll tell
1450 // it that it's done.
1451 done.store(true, std::sync::atomic::Ordering::SeqCst);
1452 // Unfortunately, we'll still be stuck waiting the full
1453 // `seconds_per_interval` before running the next test, since shutting down
1454 // will wait for the queue to clear.
1455 }
1456
1457 #[test]
1458 fn pings_ride_along_builtin_pings() {
1459 let _lock = lock_test();
1460
1461 // Define a fake uploader that reports back the submission headers
1462 // using a crossbeam channel.
1463 let (s, r) = crossbeam_channel::bounded::<String>(3);
1464
1465 #[derive(Debug)]
1466 pub struct FakeUploader {
1467 sender: crossbeam_channel::Sender<String>,
1468 }
1469 impl net::PingUploader for FakeUploader {
1470 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
1471 let upload_request = upload_request.capable(|_| true).unwrap();
1472 self.sender.send(upload_request.url).unwrap();
1473 net::UploadResult::http_status(200)
1474 }
1475 }
1476
1477 // Create a custom configuration to use a fake uploader.
1478 let dir = tempfile::tempdir().unwrap();
1479 let tmpname = dir.path().to_path_buf();
1480
1481 let ping_schedule = HashMap::from([("baseline".to_string(), vec!["ride-along".to_string()])]);
1482
1483 let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1484 .with_server_endpoint("invalid-test-host")
1485 .with_uploader(FakeUploader { sender: s })
1486 .with_ping_schedule(ping_schedule)
1487 .build();
1488
1489 let _t = new_glean(Some(cfg), true);
1490
1491 let _ride_along_ping = new_test_ping("ride-along");
1492
1493 // Simulate becoming active.
1494 handle_client_active();
1495
1496 // We expect a baseline ping to be generated here (reason: 'active').
1497 let url = r.recv().unwrap();
1498 assert!(url.contains("baseline"));
1499
1500 // We expect a ride-along ping to ride along.
1501 let url = r.recv().unwrap();
1502 assert!(url.contains("ride-along"));
1503 }
1504
1505 #[test]
1506 fn test_attribution_and_distribution_updates_before_glean_inits() {
1507 let _lock = lock_test();
1508 let dir = tempfile::tempdir().unwrap();
1509 let tmpname = dir.path().to_path_buf();
1510
1511 destroy_glean(true, &tmpname);
1512
1513 // No Glean, let's set and update some attribution + distribution.
1514 let mut attribution = AttributionMetrics {
1515 source: Some("source".into()),
1516 medium: Some("medium".into()),
1517 campaign: Some("campaign".into()),
1518 term: Some("term".into()),
1519 content: Some("content".into()),
1520 };
1521 let distribution = DistributionMetrics {
1522 name: Some("name".into()),
1523 };
1524 update_attribution(attribution.clone());
1525 update_distribution(distribution);
1526
1527 let attribution_update = AttributionMetrics {
1528 term: Some("new term".into()),
1529 ..Default::default()
1530 };
1531 let distribution_update = DistributionMetrics {
1532 name: Some("different name".into()),
1533 };
1534 update_attribution(attribution_update);
1535 update_distribution(distribution_update.clone());
1536
1537 test_reset_glean(
1538 ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID)
1539 .with_server_endpoint("invalid-test-host")
1540 .build(),
1541 ClientInfoMetrics::unknown(),
1542 false,
1543 );
1544
1545 // Ensure the updated attribution + distribution are correctly stored.
1546 attribution.term = Some("new term".into());
1547 assert_eq!(attribution, test_get_attribution());
1548 assert_eq!(distribution_update, test_get_distribution());
1549 }