Debian Codegraph @

third_party/rust/glean-core/src/lib_unit_tests.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 // NOTE: This is a test-only file that contains unit tests for
6 // the lib.rs file.
7
8 use std::collections::HashSet;
9
10 use internal_pings::InternalPings;
11 use serde_json::json;
12
13 use super::*;
14
15 const GLOBAL_APPLICATION_ID: &str = "org.mozilla.glean.test.app";
16 pub fn new_glean(tempdir: Option<tempfile::TempDir>) -> (Glean, tempfile::TempDir) {
17 let _ = env_logger::builder().try_init();
18 let dir = match tempdir {
19 Some(tempdir) => tempdir,
20 None => tempfile::tempdir().unwrap(),
21 };
22 let tmpname = dir.path().display().to_string();
23 let mut glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
24 // Register the builtin pings as enabled.
25 _ = InternalPings::new(true);
26
27 // store{1, 2} is used throughout tests
28 let ping = PingType::new_internal(
29 "store1",
30 true,
31 false,
32 true,
33 true,
34 true,
35 vec![],
36 vec![],
37 true,
38 vec![],
39 );
40 glean.register_ping_type(&ping);
41 let ping = PingType::new_internal(
42 "store2",
43 true,
44 false,
45 true,
46 true,
47 true,
48 vec![],
49 vec![],
50 true,
51 vec![],
52 );
53 glean.register_ping_type(&ping);
54 (glean, dir)
55 }
56
57 #[test]
58 fn path_is_constructed_from_data() {
59 let (glean, _t) = new_glean(None);
60
61 assert_eq!(
62 "/submit/org-mozilla-glean-test-app/baseline/1/this-is-a-docid",
63 glean.make_path("baseline", "this-is-a-docid")
64 );
65 }
66
67 // Experiment's API tests: the next two tests come from glean-ac's
68 // ExperimentsStorageEngineTest.kt.
69 #[test]
70 fn experiment_id_and_branch_get_truncated_if_too_long() {
71 let t = tempfile::tempdir().unwrap();
72 let name = t.path().display().to_string();
73 let glean = Glean::with_options(&name, "org.mozilla.glean.tests", true, true);
74
75 // Generate long strings for the used ids.
76 let very_long_id = "test-experiment-id".repeat(10);
77 let very_long_branch_id = "test-branch-id".repeat(10);
78
79 // Mark the experiment as active.
80 glean.set_experiment_active(
81 very_long_id.clone(),
82 very_long_branch_id.clone(),
83 HashMap::new(),
84 );
85
86 // Generate the expected id and branch strings.
87 let mut expected_id = very_long_id;
88 expected_id.truncate(100);
89 let mut expected_branch_id = very_long_branch_id;
90 expected_branch_id.truncate(100);
91
92 assert!(
93 glean
94 .test_get_experiment_data(expected_id.clone())
95 .is_some(),
96 "An experiment with the truncated id should be available"
97 );
98
99 // Make sure the branch id was truncated as well.
100 let experiment_data = glean.test_get_experiment_data(expected_id);
101 assert!(
102 experiment_data.is_some(),
103 "Experiment data must be available"
104 );
105
106 let experiment_data = experiment_data.unwrap();
107 assert_eq!(expected_branch_id, experiment_data.branch);
108 }
109
110 #[test]
111 fn limits_on_experiments_extras_are_applied_correctly() {
112 let t = tempfile::tempdir().unwrap();
113 let name = t.path().display().to_string();
114 let glean = Glean::with_options(&name, "org.mozilla.glean.tests", true, true);
115
116 let experiment_id = "test-experiment_id".to_string();
117 let branch_id = "test-branch-id".to_string();
118 let mut extras = HashMap::new();
119
120 let too_long_key = "0123456789".repeat(11);
121 let too_long_value = "0123456789".repeat(11);
122
123 // Build and extras HashMap that's a little too long in every way
124 for n in 0..21 {
125 extras.insert(format!("{}-{}", n, too_long_key), too_long_value.clone());
126 }
127
128 // Mark the experiment as active.
129 glean.set_experiment_active(experiment_id.clone(), branch_id, extras);
130
131 // Make sure it is active
132 assert!(
133 glean
134 .test_get_experiment_data(experiment_id.clone())
135 .is_some(),
136 "An experiment with the truncated id should be available"
137 );
138
139 // Get the data
140 let experiment_data = glean.test_get_experiment_data(experiment_id);
141 assert!(
142 experiment_data.is_some(),
143 "Experiment data must be available"
144 );
145
146 // Parse the JSON and validate the lengths
147 let experiment_data = experiment_data.unwrap();
148 assert_eq!(
149 20,
150 experiment_data.extra.as_ref().unwrap().len(),
151 "Experiments extra must be less than max length"
152 );
153
154 for (key, value) in experiment_data.extra.as_ref().unwrap().iter() {
155 assert!(
156 key.len() <= 100,
157 "Experiments extra key must be less than max length"
158 );
159 assert!(
160 value.len() <= 100,
161 "Experiments extra value must be less than max length"
162 );
163 }
164 }
165
166 #[test]
167 fn experiments_status_is_correctly_toggled() {
168 let t = tempfile::tempdir().unwrap();
169 let name = t.path().display().to_string();
170 let glean = Glean::with_options(&name, "org.mozilla.glean.tests", true, true);
171
172 // Define the experiment's data.
173 let experiment_id: String = "test-toggle-experiment".into();
174 let branch_id: String = "test-branch-toggle".into();
175 let extra: HashMap<String, String> = [("test-key".into(), "test-value".into())]
176 .iter()
177 .cloned()
178 .collect();
179
180 // Activate an experiment.
181 glean.set_experiment_active(experiment_id.clone(), branch_id, extra.clone());
182
183 // Check that the experiment is marekd as active.
184 assert!(
185 glean
186 .test_get_experiment_data(experiment_id.clone())
187 .is_some(),
188 "The experiment must be marked as active."
189 );
190
191 // Check that the extra data was stored.
192 let experiment_data = glean.test_get_experiment_data(experiment_id.clone());
193 assert!(
194 experiment_data.is_some(),
195 "Experiment data must be available"
196 );
197
198 let experiment_data = experiment_data.unwrap();
199 assert_eq!(experiment_data.extra.unwrap(), extra);
200
201 // Disable the experiment and check that is no longer available.
202 glean.set_experiment_inactive(experiment_id.clone());
203 assert!(
204 glean.test_get_experiment_data(experiment_id).is_none(),
205 "The experiment must not be available any more."
206 );
207 }
208
209 #[test]
210 fn experimentation_id_is_set_correctly() {
211 let t = tempfile::tempdir().unwrap();
212 let name = t.path().display().to_string();
213
214 // Define an experimentation id to test
215 let experimentation_id = "test-experimentation-id";
216
217 let glean = Glean::new(InternalConfiguration {
218 data_path: name,
219 application_id: GLOBAL_APPLICATION_ID.into(),
220 language_binding_name: "Rust".into(),
221 upload_enabled: true,
222 max_events: None,
223 delay_ping_lifetime_io: false,
224 app_build: "Unknown".into(),
225 use_core_mps: false,
226 trim_data_to_registered_pings: false,
227 log_level: None,
228 rate_limit: None,
229 enable_event_timestamps: true,
230 experimentation_id: Some(experimentation_id.to_string()),
231 enable_internal_pings: true,
232 ping_schedule: Default::default(),
233 ping_lifetime_threshold: 0,
234 ping_lifetime_max_time: 0,
235 })
236 .unwrap();
237
238 // Check that the correct value was stored
239 if let Some(exp_id) = glean
240 .additional_metrics
241 .experimentation_id
242 .get_value(&glean, "all-pings")
243 {
244 assert_eq!(exp_id, experimentation_id, "Experimentation ids must match");
245 } else {
246 panic!("The experimentation id must not be `None`");
247 }
248 }
249
250 #[test]
251 fn client_id_and_first_run_date_must_be_regenerated() {
252 let dir = tempfile::tempdir().unwrap();
253 let tmpname = dir.path().display().to_string();
254 {
255 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
256
257 glean.data_store.as_ref().unwrap().clear_all();
258
259 assert!(glean
260 .core_metrics
261 .client_id
262 .get_value(&glean, "glean_client_info")
263 .is_none());
264 assert!(glean
265 .core_metrics
266 .first_run_date
267 .get_value(&glean, "glean_client_info")
268 .is_none());
269 }
270
271 {
272 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
273 assert!(glean
274 .core_metrics
275 .client_id
276 .get_value(&glean, "glean_client_info")
277 .is_some());
278 assert!(glean
279 .core_metrics
280 .first_run_date
281 .get_value(&glean, "glean_client_info")
282 .is_some());
283 }
284 }
285
286 #[test]
287 fn basic_metrics_should_be_cleared_when_uploading_is_disabled() {
288 let (mut glean, _t) = new_glean(None);
289 let metric = StringMetric::new(CommonMetricData {
290 category: "category".to_string(),
291 name: "string_metric".to_string(),
292 send_in_pings: vec!["baseline".to_string()],
293 ..Default::default()
294 });
295
296 metric.set_sync(&glean, "TEST VALUE");
297 assert!(metric.get_value(&glean, "baseline").is_some());
298
299 glean.set_upload_enabled(false);
300 assert!(metric.get_value(&glean, "baseline").is_none());
301
302 metric.set_sync(&glean, "TEST VALUE");
303 assert!(metric.get_value(&glean, "baseline").is_none());
304
305 glean.set_upload_enabled(true);
306 assert!(metric.get_value(&glean, "baseline").is_none());
307
308 metric.set_sync(&glean, "TEST VALUE");
309 assert!(metric.get_value(&glean, "baseline").is_some());
310 }
311
312 #[test]
313 fn first_run_date_is_managed_correctly_when_toggling_uploading() {
314 let (mut glean, _t) = new_glean(None);
315
316 let original_first_run_date = glean
317 .core_metrics
318 .first_run_date
319 .get_value(&glean, "glean_client_info");
320
321 glean.set_upload_enabled(false);
322 assert_eq!(
323 original_first_run_date,
324 glean
325 .core_metrics
326 .first_run_date
327 .get_value(&glean, "glean_client_info")
328 );
329
330 glean.set_upload_enabled(true);
331 assert_eq!(
332 original_first_run_date,
333 glean
334 .core_metrics
335 .first_run_date
336 .get_value(&glean, "glean_client_info")
337 );
338 }
339
340 #[test]
341 fn client_id_is_managed_correctly_when_toggling_uploading() {
342 let (mut glean, _t) = new_glean(None);
343
344 let original_client_id = glean
345 .core_metrics
346 .client_id
347 .get_value(&glean, "glean_client_info");
348 assert!(original_client_id.is_some());
349 assert_ne!(*KNOWN_CLIENT_ID, original_client_id.unwrap());
350
351 glean.set_upload_enabled(false);
352 assert_eq!(
353 None,
354 glean
355 .core_metrics
356 .client_id
357 .get_value(&glean, "glean_client_info")
358 );
359
360 glean.set_upload_enabled(true);
361 let current_client_id = glean
362 .core_metrics
363 .client_id
364 .get_value(&glean, "glean_client_info");
365 assert!(current_client_id.is_some());
366 assert_ne!(*KNOWN_CLIENT_ID, current_client_id.unwrap());
367 assert_ne!(original_client_id, current_client_id);
368 }
369
370 #[test]
371 fn client_id_is_not_set_when_uploading_disabled_at_start() {
372 let dir = tempfile::tempdir().unwrap();
373 let tmpname = dir.path().display().to_string();
374 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, false, true);
375
376 assert_eq!(
377 None,
378 glean
379 .core_metrics
380 .client_id
381 .get_value(&glean, "glean_client_info")
382 );
383 }
384
385 #[test]
386 fn client_id_is_set_to_random_value_when_uploading_enabled_at_start() {
387 let dir = tempfile::tempdir().unwrap();
388 let tmpname = dir.path().display().to_string();
389 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
390
391 let current_client_id = glean
392 .core_metrics
393 .client_id
394 .get_value(&glean, "glean_client_info");
395 assert!(current_client_id.is_some());
396 assert_ne!(*KNOWN_CLIENT_ID, current_client_id.unwrap());
397 }
398
399 #[test]
400 fn attribution_and_distribution_are_correctly_stored() {
401 let dir = tempfile::tempdir().unwrap();
402 let tmpname = dir.path().display().to_string();
403 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
404
405 // On a fresh Glean, no attribution or distribution information is set.
406 assert_eq!(
407 <AttributionMetrics as Default>::default(),
408 glean.test_get_attribution()
409 );
410 assert_eq!(
411 <DistributionMetrics as Default>::default(),
412 glean.test_get_distribution()
413 );
414
415 let mut attribution = AttributionMetrics {
416 source: Some("source".into()),
417 medium: Some("medium".into()),
418 campaign: Some("campaign".into()),
419 term: Some("term".into()),
420 content: Some("content".into()),
421 };
422 let distribution = DistributionMetrics {
423 name: Some("name".into()),
424 };
425
426 // Set them all at once.
427 glean.update_attribution(attribution.clone());
428 glean.update_distribution(distribution.clone());
429
430 assert_eq!(attribution, glean.test_get_attribution());
431 assert_eq!(distribution, glean.test_get_distribution());
432
433 let attribution_update = AttributionMetrics {
434 campaign: Some("new campaign".into()),
435 ..Default::default()
436 };
437 let distribution_update = DistributionMetrics {
438 name: Some("new name".into()),
439 };
440
441 // Perform updates.
442 glean.update_attribution(attribution_update);
443 glean.update_distribution(distribution_update.clone());
444
445 // Ensure only the updated fields took over
446 attribution.campaign = Some("new campaign".into());
447 assert_eq!(attribution, glean.test_get_attribution());
448 assert_eq!(distribution_update, glean.test_get_distribution());
449 }
450
451 #[test]
452 fn enabling_when_already_enabled_is_a_noop() {
453 let dir = tempfile::tempdir().unwrap();
454 let tmpname = dir.path().display().to_string();
455 let mut glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
456
457 assert!(!glean.set_upload_enabled(true));
458 }
459
460 #[test]
461 fn disabling_when_already_disabled_is_a_noop() {
462 let dir = tempfile::tempdir().unwrap();
463 let tmpname = dir.path().display().to_string();
464 let mut glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, false, true);
465
466 assert!(!glean.set_upload_enabled(false));
467 }
468
469 // Test that the enum variants keep a stable discriminant when serialized.
470 // Discriminant values are taken from a stable ordering from v20.0.0.
471 // New metrics after that should be added in order.
472 #[test]
473 #[rustfmt::skip] // Let's not add newlines unnecessary
474 fn correct_order() {
475 use histogram::Histogram;
476 use metrics::{Metric::*, TimeUnit};
477 use std::time::Duration;
478 use util::local_now_with_offset;
479
480 // Extract the discriminant of the serialized value,
481 // that is: the first 4 bytes.
482 fn discriminant(metric: &metrics::Metric) -> u32 {
483 let ser = bincode::serialize(metric).unwrap();
484 (ser[0] as u32)
485 | ((ser[1] as u32) << 8)
486 | ((ser[2] as u32) << 16)
487 | ((ser[3] as u32) << 24)
488 }
489
490 // One of every metric type. The values are arbitrary and don't matter.
491 let long_string = "0123456789".repeat(200);
492 let all_metrics = vec![
493 Boolean(false),
494 Counter(0),
495 CustomDistributionExponential(Histogram::exponential(1, 500, 10)),
496 CustomDistributionLinear(Histogram::linear(1, 500, 10)),
497 Datetime(local_now_with_offset(), TimeUnit::Second),
498 Experiment(RecordedExperiment { branch: "branch".into(), extra: None, }),
499 Quantity(0),
500 String("glean".into()),
501 StringList(vec!["glean".into()]),
502 Uuid("082c3e52-0a18-11ea-946f-0fe0c98c361c".into()),
503 Timespan(Duration::new(5, 0), TimeUnit::Second),
504 TimingDistribution(Histogram::functional(2.0, 8.0)),
505 MemoryDistribution(Histogram::functional(2.0, 8.0)),
506 Jwe("eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg.48V1_ALb6US04U3b.5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6jiSdiwkIr3ajwQzaBtQD_A.XFBoMYUZodetZdvTiFvSkQ".into()),
507 Rate(0, 0),
508 Text(long_string),
509 Object("{}".into()),
510 ];
511
512 for metric in all_metrics {
513 let disc = discriminant(&metric);
514
515 // DO NOT TOUCH THE EXPECTED VALUE.
516 // If this test fails because of non-equal discriminants, that is a bug in the code, not
517 // the test.
518
519 // We're matching here, thus fail the build if new variants are added.
520 match metric {
521 Boolean(..) => assert_eq!( 0, disc),
522 Counter(..) => assert_eq!( 1, disc),
523 CustomDistributionExponential(..) => assert_eq!( 2, disc),
524 CustomDistributionLinear(..) => assert_eq!( 3, disc),
525 Datetime(..) => assert_eq!( 4, disc),
526 Experiment(..) => assert_eq!( 5, disc),
527 Quantity(..) => assert_eq!( 6, disc),
528 String(..) => assert_eq!( 7, disc),
529 StringList(..) => assert_eq!( 8, disc),
530 Uuid(..) => assert_eq!( 9, disc),
531 Timespan(..) => assert_eq!(10, disc),
532 TimingDistribution(..) => assert_eq!(11, disc),
533 MemoryDistribution(..) => assert_eq!(12, disc),
534 Jwe(..) => assert_eq!(13, disc),
535 Rate(..) => assert_eq!(14, disc),
536 Url(..) => assert_eq!(15, disc),
537 Text(..) => assert_eq!(16, disc),
538 Object(..) => assert_eq!(17, disc),
539 }
540 }
541 }
542
543 #[test]
544 #[rustfmt::skip] // Let's not merge lines
545 fn backwards_compatible_deserialization() {
546 use std::env;
547 use std::time::Duration;
548 use chrono::prelude::*;
549 use histogram::Histogram;
550 use metrics::{Metric::*, TimeUnit};
551
552 // Prepare some data to fill in
553 let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 12);
554
555 let mut custom_dist_exp = Histogram::exponential(1, 500, 10);
556 custom_dist_exp.accumulate(10);
557
558 let mut custom_dist_linear = Histogram::linear(1, 500, 10);
559 custom_dist_linear.accumulate(10);
560
561 let mut time_dist = Histogram::functional(2.0, 8.0);
562 time_dist.accumulate(10);
563
564 let mut mem_dist = Histogram::functional(2.0, 16.0);
565 mem_dist.accumulate(10);
566
567 // One of every metric type. The values are arbitrary, but stable.
568 let all_metrics = vec![
569 (
570 "boolean",
571 vec![0, 0, 0, 0, 1],
572 Boolean(true)
573 ),
574 (
575 "counter",
576 vec![1, 0, 0, 0, 20, 0, 0, 0],
577 Counter(20)
578 ),
579 (
580 "custom exponential distribution",
581 vec![2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 1,
582 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0,
583 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 0, 0, 10, 0,
584 0, 0, 0, 0, 0, 0],
585 CustomDistributionExponential(custom_dist_exp)
586 ),
587 (
588 "custom linear distribution",
589 vec![3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
590 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 1, 0,
591 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0],
592 CustomDistributionLinear(custom_dist_linear)
593 ),
594 (
595 "datetime",
596 vec![4, 0, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 50, 48, 49, 52, 45, 49, 49, 45,
597 50, 56, 84, 50, 49, 58, 52, 53, 58, 53, 57, 46, 48, 48, 48, 48, 48,
598 48, 48, 49, 50, 43, 48, 57, 58, 48, 48, 3, 0, 0, 0],
599 Datetime(dt, TimeUnit::Second),
600 ),
601 (
602 "experiment",
603 vec![5, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 98, 114, 97, 110, 99, 104, 0],
604 Experiment(RecordedExperiment { branch: "branch".into(), extra: None, }),
605 ),
606 (
607 "quantity",
608 vec![6, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0],
609 Quantity(17)
610 ),
611 (
612 "string",
613 vec![7, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 103, 108, 101, 97, 110],
614 String("glean".into())
615 ),
616 (
617 "string list",
618 vec![8, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,
619 103, 108, 101, 97, 110],
620 StringList(vec!["glean".into()])
621 ),
622 (
623 "uuid",
624 vec![9, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 48, 56, 50, 99, 51, 101, 53, 50,
625 45, 48, 97, 49, 56, 45, 49, 49, 101, 97, 45, 57, 52, 54, 102, 45, 48,
626 102, 101, 48, 99, 57, 56, 99, 51, 54, 49, 99],
627 Uuid("082c3e52-0a18-11ea-946f-0fe0c98c361c".into()),
628 ),
629 (
630 "timespan",
631 vec![10, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0],
632 Timespan(Duration::new(5, 0), TimeUnit::Second),
633 ),
634 (
635 "timing distribution",
636 vec![11, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
637 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 123, 81, 125,
638 60, 184, 114, 241, 63],
639 TimingDistribution(time_dist),
640 ),
641 (
642 "memory distribution",
643 vec![12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
644 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 15, 137, 249,
645 108, 88, 181, 240, 63],
646 MemoryDistribution(mem_dist),
647 ),
648 ];
649
650 for (name, data, metric) in all_metrics {
651 // Helper to print serialization data if instructed by environment variable
652 // Run with:
653 //
654 // ```text
655 // PRINT_DATA=1 cargo test -p glean-core --lib -- --nocapture backwards
656 // ```
657 //
658 // This should not be necessary to re-run and change here, unless a bincode upgrade
659 // requires us to also migrate existing data.
660 if env::var("PRINT_DATA").is_ok() {
661 let bindata = bincode::serialize(&metric).unwrap();
662 println!("(\n {:?},\n vec!{:?},", name, bindata);
663 } else {
664 // Otherwise run the test
665 let deserialized = bincode::deserialize(&data).unwrap();
666 if let CustomDistributionExponential(hist) = &deserialized {
667 hist.snapshot_values(); // Force initialization of the ranges
668 }
669 if let CustomDistributionLinear(hist) = &deserialized {
670 hist.snapshot_values(); // Force initialization of the ranges
671 }
672
673 assert_eq!(
674 metric, deserialized,
675 "Expected properly deserialized {}",
676 name
677 );
678 }
679 }
680 }
681
682 #[test]
683 fn test_first_run() {
684 let dir = tempfile::tempdir().unwrap();
685 let tmpname = dir.path().display().to_string();
686 {
687 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
688 // Check that this is indeed the first run.
689 assert!(glean.is_first_run());
690 }
691
692 {
693 // Other runs must be not marked as "first run".
694 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
695 assert!(!glean.is_first_run());
696 }
697 }
698
699 #[test]
700 fn test_dirty_bit() {
701 let _ = env_logger::builder().try_init();
702 let dir = tempfile::tempdir().unwrap();
703 let tmpname = dir.path().display().to_string();
704 {
705 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
706 // The dirty flag must not be set the first time Glean runs.
707 assert!(!glean.is_dirty_flag_set());
708
709 // Set the dirty flag and check that it gets correctly set.
710 glean.set_dirty_flag(true);
711 assert!(glean.is_dirty_flag_set());
712 }
713
714 {
715 // Check that next time Glean runs, it correctly picks up the "dirty flag".
716 // It is expected to be 'true'.
717 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
718 assert!(glean.is_dirty_flag_set());
719
720 // Set the dirty flag to false.
721 glean.set_dirty_flag(false);
722 assert!(!glean.is_dirty_flag_set());
723 }
724
725 {
726 // Check that next time Glean runs, it correctly picks up the "dirty flag".
727 // It is expected to be 'false'.
728 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
729 assert!(!glean.is_dirty_flag_set());
730 }
731 }
732
733 #[test]
734 fn test_change_metric_type_runtime() {
735 let dir = tempfile::tempdir().unwrap();
736
737 let (glean, _t) = new_glean(Some(dir));
738
739 // We attempt to create two metrics: one with a 'string' type and the other
740 // with a 'timespan' type, both being sent in the same pings and having the
741 // same lifetime.
742 let metric_name = "type_swap";
743 let metric_category = "test";
744 let metric_lifetime = Lifetime::Ping;
745 let ping_name = "store1";
746
747 let string_metric = StringMetric::new(CommonMetricData {
748 name: metric_name.into(),
749 category: metric_category.into(),
750 send_in_pings: vec![ping_name.into()],
751 disabled: false,
752 lifetime: metric_lifetime,
753 ..Default::default()
754 });
755
756 let string_value = "definitely-a-string!";
757 string_metric.set_sync(&glean, string_value);
758
759 assert_eq!(
760 string_metric.get_value(&glean, ping_name).unwrap(),
761 string_value,
762 "Expected properly deserialized string"
763 );
764
765 let timespan_metric = TimespanMetric::new(
766 CommonMetricData {
767 name: metric_name.into(),
768 category: metric_category.into(),
769 send_in_pings: vec![ping_name.into()],
770 disabled: false,
771 lifetime: metric_lifetime,
772 ..Default::default()
773 },
774 TimeUnit::Nanosecond,
775 );
776
777 let duration = 60;
778 timespan_metric.set_start(&glean, 0);
779 timespan_metric.set_stop(&glean, duration);
780
781 assert_eq!(
782 timespan_metric.get_value(&glean, ping_name).unwrap(),
783 60,
784 "Expected properly deserialized time"
785 );
786
787 // We expect old data to be lost forever. See the following bug comment
788 // https://bugzilla.mozilla.org/show_bug.cgi?id=1621757#c1 for more context.
789 assert_eq!(None, string_metric.get_value(&glean, ping_name));
790 }
791
792 #[test]
793 fn timing_distribution_truncation() {
794 let dir = tempfile::tempdir().unwrap();
795
796 let (glean, _t) = new_glean(Some(dir));
797 let max_sample_time = 1000 * 1000 * 1000 * 60 * 10;
798
799 for (unit, expected_keys) in &[
800 (
801 TimeUnit::Nanosecond,
802 HashSet::<i64>::from_iter(vec![961_548, 939, 599_512_966_122, 1]),
803 ),
804 (
805 TimeUnit::Microsecond,
806 HashSet::<i64>::from_iter(vec![939, 562_949_953_421_318, 599_512_966_122, 961_548]),
807 ),
808 (
809 TimeUnit::Millisecond,
810 HashSet::<i64>::from_iter(vec![
811 961_548,
812 576_460_752_303_431_040,
813 599_512_966_122,
814 562_949_953_421_318,
815 ]),
816 ),
817 ] {
818 let dist = TimingDistributionMetric::new(
819 CommonMetricData {
820 name: format!("local_metric_{:?}", unit),
821 category: "local".into(),
822 send_in_pings: vec!["baseline".into()],
823 ..Default::default()
824 },
825 *unit,
826 );
827
828 for &value in &[
829 1,
830 1_000,
831 1_000_000,
832 max_sample_time,
833 max_sample_time * 1_000,
834 max_sample_time * 1_000_000,
835 ] {
836 let timer_id = 4u64.into();
837 dist.set_start(timer_id, 0);
838 dist.set_stop_and_accumulate(&glean, timer_id, value);
839 }
840
841 let snapshot = dist.get_value(&glean, "baseline").unwrap();
842
843 let mut keys = HashSet::new();
844 let mut recorded_values = 0;
845
846 for (&key, &value) in &snapshot.values {
847 // A snapshot potentially includes buckets with a 0 count.
848 // We can ignore them here.
849 if value > 0 {
850 assert!((key as u64) < max_sample_time * unit.as_nanos(1));
851 keys.insert(key);
852 recorded_values += 1;
853 }
854 }
855
856 assert_eq!(4, recorded_values);
857 assert_eq!(keys, *expected_keys);
858
859 // The number of samples was originally designed around 1ns to
860 // 10minutes, with 8 steps per power of 2, which works out to 316 items.
861 // This is to ensure that holds even when the time unit is changed.
862 assert!(snapshot.values.len() < 316);
863 }
864 }
865
866 #[test]
867 fn timing_distribution_truncation_accumulate() {
868 let dir = tempfile::tempdir().unwrap();
869
870 let (glean, _t) = new_glean(Some(dir));
871 let max_sample_time = 1000 * 1000 * 1000 * 60 * 10;
872
873 for &unit in &[
874 TimeUnit::Nanosecond,
875 TimeUnit::Microsecond,
876 TimeUnit::Millisecond,
877 ] {
878 let dist = TimingDistributionMetric::new(
879 CommonMetricData {
880 name: format!("local_metric_{:?}", unit),
881 category: "local".into(),
882 send_in_pings: vec!["baseline".into()],
883 ..Default::default()
884 },
885 unit,
886 );
887
888 let samples = [
889 1,
890 1000,
891 100000,
892 max_sample_time,
893 max_sample_time * 1_000,
894 max_sample_time * 1_000_000,
895 ];
896 let timer_id = 4u64.into(); // xkcd#221
897
898 for sample in samples {
899 dist.set_start(timer_id, 0);
900 dist.set_stop_and_accumulate(&glean, timer_id, sample);
901 }
902
903 let snapshot = dist.get_value(&glean, "baseline").unwrap();
904
905 // The number of samples was originally designed around 1ns to
906 // 10minutes, with 8 steps per power of 2, which works out to 316 items.
907 // This is to ensure that holds even when the time unit is changed.
908 assert!(snapshot.values.len() < 316);
909 }
910 }
911
912 #[test]
913 fn test_setting_debug_view_tag() {
914 let dir = tempfile::tempdir().unwrap();
915
916 let (mut glean, _t) = new_glean(Some(dir));
917
918 let valid_tag = "valid-tag";
919 assert!(glean.set_debug_view_tag(valid_tag));
920 assert_eq!(valid_tag, glean.debug_view_tag().unwrap());
921
922 let invalid_tag = "invalid tag";
923 assert!(!glean.set_debug_view_tag(invalid_tag));
924 assert_eq!(valid_tag, glean.debug_view_tag().unwrap());
925 }
926
927 #[test]
928 fn test_setting_log_pings() {
929 let dir = tempfile::tempdir().unwrap();
930
931 let (mut glean, _t) = new_glean(Some(dir));
932 assert!(!glean.log_pings());
933
934 glean.set_log_pings(true);
935 assert!(glean.log_pings());
936
937 glean.set_log_pings(false);
938 assert!(!glean.log_pings());
939 }
940
941 #[test]
942 fn test_set_remote_metric_configuration() {
943 let (glean, _t) = new_glean(None);
944 let metric = StringMetric::new(CommonMetricData {
945 category: "category".to_string(),
946 name: "string_metric".to_string(),
947 send_in_pings: vec!["baseline".to_string()],
948 ..Default::default()
949 });
950 let another_metric = LabeledString::new(
951 LabeledMetricData::Common {
952 cmd: CommonMetricData {
953 category: "category".to_string(),
954 name: "labeled_string_metric".to_string(),
955 send_in_pings: vec!["baseline".to_string()],
956 ..Default::default()
957 },
958 },
959 Some(vec!["label1".into()]),
960 );
961
962 // 1. Set the metrics with a "TEST_VALUE" and ensure it was set
963 metric.set_sync(&glean, "TEST_VALUE");
964 assert_eq!(
965 "TEST_VALUE",
966 metric.get_value(&glean, "baseline").unwrap(),
967 "Initial value must match"
968 );
969 another_metric.get("label1").set_sync(&glean, "TEST_VALUE");
970 assert_eq!(
971 "TEST_VALUE",
972 another_metric
973 .get("label1")
974 .get_value(&glean, "baseline")
975 .unwrap(),
976 "Initial value must match"
977 );
978
979 // 2. Set a configuration to disable the metrics
980 let mut remote_settings_config = json!(
981 {
982 "metrics_enabled": {
983 "category.string_metric": false,
984 "category.labeled_string_metric": false,
985 }
986 }
987 )
988 .to_string();
989 glean
990 .apply_server_knobs_config(RemoteSettingsConfig::try_from(remote_settings_config).unwrap());
991
992 // 3. Since the metrics were disabled, setting a new value will be ignored
993 metric.set_sync(&glean, "VALUE_AFTER_DISABLED");
994 assert_eq!(
995 "TEST_VALUE",
996 metric.get_value(&glean, "baseline").unwrap(),
997 "Shouldn't set when disabled"
998 );
999 another_metric
1000 .get("label1")
1001 .set_sync(&glean, "VALUE_AFTER_DISABLED");
1002 assert_eq!(
1003 "TEST_VALUE",
1004 another_metric
1005 .get("label1")
1006 .get_value(&glean, "baseline")
1007 .unwrap(),
1008 "Shouldn't set when disabled"
1009 );
1010
1011 // 4. Set a new configuration where one metric is enabled
1012 remote_settings_config = json!(
1013 {
1014 "metrics_enabled": {
1015 "category.string_metric": true,
1016 }
1017 }
1018 )
1019 .to_string();
1020 glean
1021 .apply_server_knobs_config(RemoteSettingsConfig::try_from(remote_settings_config).unwrap());
1022
1023 // 5. Since the first metric is enabled, setting a new value should work
1024 // on it but not the second metric
1025 metric.set_sync(&glean, "VALUE_AFTER_REENABLED");
1026 assert_eq!(
1027 "VALUE_AFTER_REENABLED",
1028 metric.get_value(&glean, "baseline").unwrap(),
1029 "Should set when re-enabled"
1030 );
1031 another_metric
1032 .get("label1")
1033 .set_sync(&glean, "VALUE_AFTER_REENABLED");
1034 assert_eq!(
1035 "TEST_VALUE",
1036 another_metric
1037 .get("label1")
1038 .get_value(&glean, "baseline")
1039 .unwrap(),
1040 "Should not set if metric config entry unchanged"
1041 );
1042
1043 // 6. Set a new configuration where the second metric is enabled. This
1044 // should be merged with the existing configuration and then both
1045 // metrics should be enabled at that point.
1046 remote_settings_config = json!(
1047 {
1048 "metrics_enabled": {
1049 "category.labeled_string_metric": true,
1050 }
1051 }
1052 )
1053 .to_string();
1054 glean
1055 .apply_server_knobs_config(RemoteSettingsConfig::try_from(remote_settings_config).unwrap());
1056
1057 // 7. Now both metrics are enabled, setting a new value should work for
1058 // both metrics with the merged configurations
1059 metric.set_sync(&glean, "FINAL VALUE");
1060 assert_eq!(
1061 "FINAL VALUE",
1062 metric.get_value(&glean, "baseline").unwrap(),
1063 "Should set when still enabled"
1064 );
1065 another_metric.get("label1").set_sync(&glean, "FINAL VALUE");
1066 assert_eq!(
1067 "FINAL VALUE",
1068 another_metric
1069 .get("label1")
1070 .get_value(&glean, "baseline")
1071 .unwrap(),
1072 "Should set when re-enabled"
1073 );
1074 }
1075
1076 #[test]
1077 fn test_remote_settings_epoch() {
1078 let (glean, _t) = new_glean(None);
1079
1080 // 1. Ensure the starting epoch
1081 let mut current_epoch = glean.remote_settings_epoch.load(Ordering::Acquire);
1082 assert_eq!(0u8, current_epoch, "Current epoch must start at 0");
1083
1084 // 2. Set a configuration which will trigger incrementing the epoch
1085 let remote_settings_config = json!(
1086 {
1087 "metrics_enabled": {
1088 "category.string_metric": false
1089 }
1090 }
1091 )
1092 .to_string();
1093 glean
1094 .apply_server_knobs_config(RemoteSettingsConfig::try_from(remote_settings_config).unwrap());
1095
1096 // 3. Ensure the epoch updated
1097 current_epoch = glean.remote_settings_epoch.load(Ordering::Acquire);
1098 assert_eq!(1u8, current_epoch, "Current epoch must match");
1099 }
1100
1101 #[test]
1102 fn test_remote_settings_epoch_updates_in_metric() {
1103 let (glean, _t) = new_glean(None);
1104 let metric = StringMetric::new(CommonMetricData {
1105 category: "category".to_string(),
1106 name: "string_metric".to_string(),
1107 send_in_pings: vec!["baseline".to_string()],
1108 ..Default::default()
1109 });
1110
1111 // 1. Set the metric with a "TEST_VALUE" and ensure it was set
1112 metric.set_sync(&glean, "TEST_VALUE");
1113 assert_eq!(
1114 "TEST_VALUE",
1115 metric.get_value(&glean, "baseline").unwrap(),
1116 "Initial value must match"
1117 );
1118
1119 // 2. Set a configuration to disable the `category.string_metric`
1120 let remote_settings_config = json!(
1121 {
1122 "metrics_enabled": {
1123 "category.string_metric": false
1124 }
1125 }
1126 )
1127 .to_string();
1128 glean
1129 .apply_server_knobs_config(RemoteSettingsConfig::try_from(remote_settings_config).unwrap());
1130
1131 // 3. Ensure the epoch was updated
1132 let current_epoch = glean.remote_settings_epoch.load(Ordering::Acquire);
1133 assert_eq!(1u8, current_epoch, "Current epoch must update");
1134
1135 // 4. Since the metric was disabled, setting a new value will be ignored
1136 // AND the metric should update its epoch to match the `current_epoch`
1137 metric.set_sync(&glean, "VALUE_AFTER_DISABLED");
1138 assert_eq!(
1139 "TEST_VALUE",
1140 metric.get_value(&glean, "baseline").unwrap(),
1141 "Shouldn't set when disabled"
1142 );
1143
1144 use crate::metrics::MetricType;
1145 // The "epoch" resides in the upper nibble of the `inner.disabled` field
1146 let epoch = metric.meta().disabled.load(Ordering::Acquire) >> 4;
1147 assert_eq!(
1148 current_epoch, epoch,
1149 "Epoch must match between metric and Glean core"
1150 );
1151 }
1152
1153 #[test]
1154 #[should_panic]
1155 fn test_empty_application_id() {
1156 let dir = tempfile::tempdir().unwrap();
1157 let tmpname = dir.path().display().to_string();
1158
1159 let glean = Glean::with_options(&tmpname, "", true, true);
1160 // Check that this is indeed the first run.
1161 assert!(glean.is_first_run());
1162 }
1163
1164 #[test]
1165 fn records_database_file_size() {
1166 let _ = env_logger::builder().is_test(true).try_init();
1167
1168 // Note: We don't use `new_glean` because we need to re-use the database directory.
1169
1170 let dir = tempfile::tempdir().unwrap();
1171 let tmpname = dir.path().display().to_string();
1172
1173 // Initialize Glean once to ensure we create the database and did not error.
1174 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
1175 let database_size = &glean.database_metrics.size;
1176 let data = database_size.get_value(&glean, "metrics");
1177
1178 assert!(data.is_none());
1179
1180 drop(glean);
1181
1182 // Initialize Glean again to record file size.
1183 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, true);
1184
1185 let database_size = &glean.database_metrics.size;
1186 let data = database_size.get_value(&glean, "metrics");
1187 assert!(data.is_some());
1188 let data = data.unwrap();
1189
1190 // We should see the database containing some data.
1191 assert!(data.sum > 0);
1192
1193 let rkv_load_state = &glean.database_metrics.rkv_load_error;
1194 let rkv_load_error = rkv_load_state.get_value(&glean, "metrics");
1195
1196 assert_eq!(rkv_load_error, None);
1197 }
1198
1199 #[cfg(not(target_os = "windows"))]
1200 #[test]
1201 fn records_io_errors() {
1202 use std::fs;
1203 let _ = env_logger::builder().is_test(true).try_init();
1204
1205 let (glean, _data_dir) = new_glean(None);
1206 let pending_pings_dir = glean.get_data_path().join(crate::PENDING_PINGS_DIRECTORY);
1207 fs::create_dir_all(&pending_pings_dir).unwrap();
1208 let attr = fs::metadata(&pending_pings_dir).unwrap();
1209 let original_permissions = attr.permissions();
1210
1211 // Remove write permissions on the pending_pings directory.
1212 let mut permissions = original_permissions.clone();
1213 permissions.set_readonly(true);
1214 fs::set_permissions(&pending_pings_dir, permissions).unwrap();
1215
1216 // Writing the ping file should fail.
1217 let submitted = glean.internal_pings.baseline.submit_sync(&glean, None);
1218 // But the return value is still `true` because we enqueue the ping anyway.
1219 assert!(submitted);
1220
1221 let metric = &glean.additional_metrics.io_errors;
1222 assert_eq!(
1223 1,
1224 metric.get_value(&glean, Some("metrics")).unwrap(),
1225 "Should have recorded an IO error"
1226 );
1227
1228 // Restore write permissions.
1229 fs::set_permissions(&pending_pings_dir, original_permissions).unwrap();
1230
1231 // Now we can submit a ping
1232 let submitted = glean.internal_pings.metrics.submit_sync(&glean, None);
1233 assert!(submitted);
1234 }
1235
1236 #[test]
1237 fn test_activity_api() {
1238 let _ = env_logger::builder().is_test(true).try_init();
1239
1240 let dir = tempfile::tempdir().unwrap();
1241 let (mut glean, _t) = new_glean(Some(dir));
1242
1243 // Signal that the client was active.
1244 glean.handle_client_active();
1245
1246 // Check that we set everything we needed for the 'active' status.
1247 assert!(glean.is_dirty_flag_set());
1248
1249 // Signal back that client is ianctive.
1250 glean.handle_client_inactive();
1251
1252 // Check that we set everything we needed for the 'inactive' status.
1253 assert!(!glean.is_dirty_flag_set());
1254 }
1255
1256 #[test]
1257 fn disabled_pings_are_not_submitted() {
1258 let _ = env_logger::builder().is_test(true).try_init();
1259
1260 let dir = tempfile::tempdir().unwrap();
1261 let (mut glean, _t) = new_glean(Some(dir));
1262
1263 let ping = PingType::new_internal(
1264 "custom-disabled",
1265 true,
1266 false,
1267 true,
1268 true,
1269 false,
1270 vec![],
1271 vec![],
1272 true,
1273 vec![],
1274 );
1275 glean.register_ping_type(&ping);
1276
1277 // We need to store a metric as an empty ping is not stored.
1278 let counter = CounterMetric::new(CommonMetricData {
1279 name: "counter".into(),
1280 category: "local".into(),
1281 send_in_pings: vec!["custom-disabled".into()],
1282 ..Default::default()
1283 });
1284 counter.add_sync(&glean, 1);
1285
1286 assert!(!ping.submit_sync(&glean, None));
1287 }
1288
1289 #[test]
1290 fn internal_pings_can_be_disabled() {
1291 let _ = env_logger::builder().is_test(true).try_init();
1292
1293 let dir = tempfile::tempdir().unwrap();
1294 let tmpname = dir.path().display().to_string();
1295 let glean = Glean::with_options(&tmpname, GLOBAL_APPLICATION_ID, true, false);
1296
1297 // We need to store a metric as an empty ping is not stored.
1298 let counter = CounterMetric::new(CommonMetricData {
1299 name: "counter".into(),
1300 category: "local".into(),
1301 send_in_pings: vec!["baseline".into()],
1302 ..Default::default()
1303 });
1304 counter.add_sync(&glean, 1);
1305
1306 let submitted = glean.internal_pings.baseline.submit_sync(&glean, None);
1307 assert!(!submitted);
1308 }
1309
1310 #[test]
1311 fn pings_are_controllable_from_remote_settings_config() {
1312 let _ = env_logger::builder().is_test(true).try_init();
1313
1314 let dir = tempfile::tempdir().unwrap();
1315 let (mut glean, _t) = new_glean(Some(dir));
1316
1317 let disabled_ping = PingType::new(
1318 "custom-disabled",
1319 true,
1320 true,
1321 true,
1322 true,
1323 false,
1324 vec![],
1325 vec![],
1326 true,
1327 vec![],
1328 );
1329 glean.register_ping_type(&disabled_ping);
1330 let enabled_ping = PingType::new(
1331 "custom-enabled",
1332 true,
1333 true,
1334 true,
1335 true,
1336 true,
1337 vec![],
1338 vec![],
1339 true,
1340 vec![],
1341 );
1342 glean.register_ping_type(&enabled_ping);
1343
1344 assert!(!disabled_ping.submit_sync(&glean, None));
1345 assert!(enabled_ping.submit_sync(&glean, None));
1346
1347 // Now, create a configuration to switch the enabled state of the two pings
1348 let remote_settings_config = json!(
1349 {
1350 "pings_enabled": {
1351 "custom-disabled": true,
1352 "custom-enabled": false
1353 }
1354 }
1355 )
1356 .to_string();
1357 glean
1358 .apply_server_knobs_config(RemoteSettingsConfig::try_from(remote_settings_config).unwrap());
1359
1360 assert!(disabled_ping.submit_sync(&glean, None));
1361 assert!(!enabled_ping.submit_sync(&glean, None));
1362 }