Debian Codegraph @

third_party/rust/glean-core/tests/ping_maker.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 mod common;
6 use crate::common::*;
7 use glean_core::{AttributionMetrics, DistributionMetrics};
8 use serde_json::json;
9
10 use glean_core::metrics::*;
11 use glean_core::ping::PingMaker;
12 use glean_core::{CommonMetricData, Glean, Lifetime};
13
14 fn set_up_basic_ping() -> (Glean, PingMaker, PingType, tempfile::TempDir) {
15 let (tempdir, _) = tempdir();
16 let (mut glean, t) = new_glean(Some(tempdir));
17 let ping_maker = PingMaker::new();
18 let ping_type = new_test_ping(&mut glean, "store1");
19
20 // Record something, so the ping will have data
21 let metric = BooleanMetric::new(CommonMetricData {
22 name: "boolean_metric".into(),
23 category: "telemetry".into(),
24 send_in_pings: vec!["store1".into()],
25 disabled: false,
26 lifetime: Lifetime::User,
27 ..Default::default()
28 });
29 metric.set_sync(&glean, true);
30
31 (glean, ping_maker, ping_type, t)
32 }
33
34 #[test]
35 fn ping_info_must_contain_a_nonempty_start_and_end_time() {
36 let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();
37
38 let ping = ping_maker
39 .collect(&glean, &ping_type, None, "", "")
40 .unwrap();
41 let ping_info = ping.content["ping_info"].as_object().unwrap();
42
43 let start_time_str = ping_info["start_time"].as_str().unwrap();
44 let start_time_date = iso8601_to_chrono(&iso8601::datetime(start_time_str).unwrap());
45
46 let end_time_str = ping_info["end_time"].as_str().unwrap();
47 let end_time_date = iso8601_to_chrono(&iso8601::datetime(end_time_str).unwrap());
48
49 assert!(start_time_date <= end_time_date);
50 }
51
52 #[test]
53 fn get_ping_info_must_report_all_the_required_fields() {
54 let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();
55
56 let ping = ping_maker
57 .collect(&glean, &ping_type, None, "", "")
58 .unwrap();
59 let ping_info = ping.content["ping_info"].as_object().unwrap();
60
61 assert!(ping_info.get("start_time").is_some());
62 assert!(ping_info.get("end_time").is_some());
63 assert!(ping_info.get("seq").is_some());
64 }
65
66 #[test]
67 fn get_client_info_must_report_all_the_available_data() {
68 let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();
69
70 let ping = ping_maker
71 .collect(&glean, &ping_type, None, "", "")
72 .unwrap();
73 let client_info = ping.content["client_info"].as_object().unwrap();
74
75 client_info["telemetry_sdk_build"].as_str().unwrap();
76 }
77
78 #[test]
79 fn test_metrics_must_report_experimentation_id() {
80 let (tempdir, _) = tempdir();
81 let mut glean = Glean::new(glean_core::InternalConfiguration {
82 data_path: tempdir.path().display().to_string(),
83 application_id: GLOBAL_APPLICATION_ID.into(),
84 language_binding_name: "Rust".into(),
85 upload_enabled: true,
86 max_events: None,
87 delay_ping_lifetime_io: false,
88 app_build: "Unknown".into(),
89 use_core_mps: false,
90 trim_data_to_registered_pings: false,
91 log_level: None,
92 rate_limit: None,
93 enable_event_timestamps: true,
94 experimentation_id: Some("test-experimentation-id".to_string()),
95 enable_internal_pings: true,
96 ping_schedule: Default::default(),
97 ping_lifetime_threshold: 0,
98 ping_lifetime_max_time: 0,
99 })
100 .unwrap();
101 let ping_maker = PingMaker::new();
102 let ping_type = PingBuilder::new("store1").build();
103 glean.register_ping_type(&ping_type);
104
105 // Record something, so the ping will have data
106 let metric = BooleanMetric::new(CommonMetricData {
107 name: "boolean_metric".into(),
108 category: "telemetry".into(),
109 send_in_pings: vec!["store1".into()],
110 disabled: false,
111 lifetime: Lifetime::User,
112 ..Default::default()
113 });
114 metric.set_sync(&glean, true);
115
116 let ping = ping_maker
117 .collect(&glean, &ping_type, None, "", "")
118 .unwrap();
119 let metrics = ping.content["metrics"].as_object().unwrap();
120
121 let strings = metrics["string"].as_object().unwrap();
122 assert_eq!(
123 strings["glean.client.annotation.experimentation_id"]
124 .as_str()
125 .unwrap(),
126 "test-experimentation-id",
127 "experimentation ids must match"
128 );
129 }
130
131 #[test]
132 fn experimentation_id_is_removed_if_send_if_empty_is_false() {
133 // Initialize Glean with an experimentation id, it should be removed if the ping is empty
134 // and send_if_empty is false.
135 let (tempdir, _) = tempdir();
136 let mut glean = Glean::new(glean_core::InternalConfiguration {
137 data_path: tempdir.path().display().to_string(),
138 application_id: GLOBAL_APPLICATION_ID.into(),
139 language_binding_name: "Rust".into(),
140 upload_enabled: true,
141 max_events: None,
142 delay_ping_lifetime_io: false,
143 app_build: "Unknown".into(),
144 use_core_mps: false,
145 trim_data_to_registered_pings: false,
146 log_level: None,
147 rate_limit: None,
148 enable_event_timestamps: true,
149 experimentation_id: Some("test-experimentation-id".to_string()),
150 enable_internal_pings: true,
151 ping_schedule: Default::default(),
152 ping_lifetime_threshold: 0,
153 ping_lifetime_max_time: 0,
154 })
155 .unwrap();
156 let ping_maker = PingMaker::new();
157
158 let unknown_ping_type = PingBuilder::new("unknown").build();
159 glean.register_ping_type(&unknown_ping_type);
160
161 assert!(ping_maker
162 .collect(&glean, &unknown_ping_type, None, "", "")
163 .is_none());
164 }
165
166 #[test]
167 fn collect_must_report_none_when_no_data_is_stored() {
168 // NOTE: This is a behavior change from glean-ac which returned an empty
169 // string in this case. As this is an implementation detail and not part of
170 // the public API, it's safe to change this.
171
172 let (mut glean, ping_maker, ping_type, _t) = set_up_basic_ping();
173
174 let unknown_ping_type = PingBuilder::new("unknown").build();
175 glean.register_ping_type(&ping_type);
176
177 assert!(ping_maker
178 .collect(&glean, &unknown_ping_type, None, "", "")
179 .is_none());
180 }
181
182 #[test]
183 fn seq_number_must_be_sequential() {
184 let (mut glean, ping_maker, _ping_type, _t) = set_up_basic_ping();
185
186 let metric = BooleanMetric::new(CommonMetricData {
187 name: "boolean_metric".into(),
188 category: "telemetry".into(),
189 send_in_pings: vec!["store2".into()],
190 disabled: false,
191 lifetime: Lifetime::User,
192 ..Default::default()
193 });
194 metric.set_sync(&glean, true);
195
196 for i in 0..=1 {
197 for ping_name in ["store1", "store2"].iter() {
198 let ping_type = PingBuilder::new(ping_name).build();
199 let ping = ping_maker
200 .collect(&glean, &ping_type, None, "", "")
201 .unwrap();
202 let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
203 // Ensure sequence numbers in different stores are independent of
204 // each other
205 assert_eq!(i, seq_num);
206 }
207 }
208
209 // Test that ping sequence numbers increase independently.
210 {
211 let ping_type = new_test_ping(&mut glean, "store1");
212
213 // 3rd ping of store1
214 let ping = ping_maker
215 .collect(&glean, &ping_type, None, "", "")
216 .unwrap();
217 let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
218 assert_eq!(2, seq_num);
219
220 // 4th ping of store1
221 let ping = ping_maker
222 .collect(&glean, &ping_type, None, "", "")
223 .unwrap();
224 let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
225 assert_eq!(3, seq_num);
226 }
227
228 {
229 let ping_type = new_test_ping(&mut glean, "store2");
230
231 // 3rd ping of store2
232 let ping = ping_maker
233 .collect(&glean, &ping_type, None, "", "")
234 .unwrap();
235 let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
236 assert_eq!(2, seq_num);
237 }
238
239 {
240 let ping_type = new_test_ping(&mut glean, "store1");
241
242 // 5th ping of store1
243 let ping = ping_maker
244 .collect(&glean, &ping_type, None, "", "")
245 .unwrap();
246 let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
247 assert_eq!(4, seq_num);
248 }
249 }
250
251 #[test]
252 fn clear_pending_pings() {
253 let (mut glean, _t) = new_glean(None);
254 let ping_maker = PingMaker::new();
255 let ping_type = new_test_ping(&mut glean, "store1");
256
257 // Record something, so the ping will have data
258 let metric = BooleanMetric::new(CommonMetricData {
259 name: "boolean_metric".into(),
260 category: "telemetry".into(),
261 send_in_pings: vec!["store1".into()],
262 disabled: false,
263 lifetime: Lifetime::User,
264 ..Default::default()
265 });
266 metric.set_sync(&glean, true);
267
268 assert!(ping_type.submit_sync(&glean, None));
269 assert_eq!(1, get_queued_pings(glean.get_data_path()).unwrap().len());
270
271 let disabled_pings = &["store1"][..];
272 assert!(ping_maker
273 .clear_pending_pings(glean.get_data_path(), disabled_pings)
274 .is_ok());
275 assert_eq!(0, get_queued_pings(glean.get_data_path()).unwrap().len());
276 }
277
278 #[test]
279 fn no_pings_submitted_if_upload_disabled() {
280 // Regression test, bug 1603571
281
282 let (mut glean, _t) = new_glean(None);
283 let ping_type = PingBuilder::new("store1").with_send_if_empty(true).build();
284 glean.register_ping_type(&ping_type);
285
286 assert!(ping_type.submit_sync(&glean, None));
287 assert_eq!(1, get_queued_pings(glean.get_data_path()).unwrap().len());
288
289 // Disable upload, then try to sumbit
290 glean.set_upload_enabled(false);
291
292 // Test again through the direct call
293 assert!(!ping_type.submit_sync(&glean, None));
294 assert_eq!(0, get_queued_pings(glean.get_data_path()).unwrap().len());
295 }
296
297 #[test]
298 fn metadata_is_correctly_added_when_necessary() {
299 let (mut glean, _t) = new_glean(None);
300 glean.set_debug_view_tag("valid-tag");
301 let ping_type = PingBuilder::new("store1").with_send_if_empty(true).build();
302 glean.register_ping_type(&ping_type);
303
304 assert!(ping_type.submit_sync(&glean, None));
305
306 let (_, _, metadata) = &get_queued_pings(glean.get_data_path()).unwrap()[0];
307 let headers = metadata.as_ref().unwrap().get("headers").unwrap();
308 assert_eq!(headers.get("X-Debug-ID").unwrap(), "valid-tag");
309 }
310
311 #[test]
312 fn attribution_and_distribution_appear_in_client_info() {
313 let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();
314
315 let attribution = AttributionMetrics {
316 source: Some("source".into()),
317 medium: Some("medium".into()),
318 campaign: Some("campaign".into()),
319 term: Some("term".into()),
320 content: Some("content".into()),
321 };
322 let distribution = DistributionMetrics {
323 name: Some("name".into()),
324 };
325 glean.update_attribution(attribution);
326 glean.update_distribution(distribution);
327
328 let ping = ping_maker
329 .collect(&glean, &ping_type, None, "", "")
330 .unwrap();
331 let client_info = ping.content["client_info"].as_object().unwrap();
332
333 assert_eq!(json!({"name": "name"}), client_info["distribution"]);
334 assert_eq!(
335 json!({
336 "source": "source",
337 "medium": "medium",
338 "campaign": "campaign",
339 "term": "term",
340 "content": "content",
341 }),
342 client_info["attribution"]
343 );
344
345 // Now let's test updated values.
346 let attribution_update = AttributionMetrics {
347 content: Some("what a boring word".into()),
348 ..Default::default()
349 };
350 let distribution_update = DistributionMetrics {
351 name: Some("what's in a name".into()),
352 };
353 glean.update_attribution(attribution_update);
354 glean.update_distribution(distribution_update);
355
356 let ping = ping_maker
357 .collect(&glean, &ping_type, None, "", "")
358 .unwrap();
359 let client_info = ping.content["client_info"].as_object().unwrap();
360
361 assert_eq!(
362 json!({"name": "what's in a name"}),
363 client_info["distribution"]
364 );
365 assert_eq!(
366 json!({
367 "source": "source",
368 "medium": "medium",
369 "campaign": "campaign",
370 "term": "term",
371 "content": "what a boring word",
372 }),
373 client_info["attribution"]
374 );
375 }