Debian Codegraph @

third_party/rust/glean-core/tests/common/mod.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 // #[allow(dead_code)] is required on this module as a workaround for
6 // https://github.com/rust-lang/rust/issues/46379
7 #![allow(dead_code)]
8 use glean_core::{Glean, PingType, Result};
9
10 use std::fs::{read_dir, File};
11 use std::io::{BufRead, BufReader};
12 use std::path::Path;
13
14 use chrono::offset::TimeZone;
15 use iso8601::Date::YMD;
16 use serde_json::Value as JsonValue;
17
18 use ctor::ctor;
19
20 /// Initialize the logger for all tests without individual tests requiring to call the init code.
21 /// Log output can be controlled via the environment variable `RUST_LOG` for the `glean_core` crate,
22 /// e.g.:
23 ///
24 /// ```
25 /// export RUST_LOG=glean_core=debug
26 /// ```
27 #[ctor]
28 fn enable_test_logging() {
29 // When testing we want all logs to go to stdout/stderr by default,
30 // without requiring each individual test to activate it.
31 // This only applies to glean-core tests, users of the main library still need to call
32 // `glean_enable_logging` of the FFI component (automatically done by the platform wrappers).
33 let _ = env_logger::builder().is_test(true).try_init();
34 }
35
36 pub fn tempdir() -> (tempfile::TempDir, String) {
37 let t = tempfile::tempdir().unwrap();
38 let name = t.path().display().to_string();
39 (t, name)
40 }
41
42 pub const GLOBAL_APPLICATION_ID: &str = "org.mozilla.glean.test.app";
43
44 // Creates a new instance of Glean with a temporary directory.
45 // We need to keep the `TempDir` alive, so that it's not deleted before we stop using it.
46 pub fn new_glean(tempdir: Option<tempfile::TempDir>) -> (Glean, tempfile::TempDir) {
47 let dir = match tempdir {
48 Some(tempdir) => tempdir,
49 None => tempfile::tempdir().unwrap(),
50 };
51
52 let cfg = glean_core::InternalConfiguration {
53 data_path: dir.path().display().to_string(),
54 application_id: GLOBAL_APPLICATION_ID.into(),
55 language_binding_name: "Rust".into(),
56 upload_enabled: true,
57 max_events: None,
58 delay_ping_lifetime_io: false,
59 app_build: "Unknown".into(),
60 use_core_mps: false,
61 trim_data_to_registered_pings: false,
62 log_level: None,
63 rate_limit: None,
64 enable_event_timestamps: false,
65 experimentation_id: None,
66 enable_internal_pings: true,
67 ping_schedule: Default::default(),
68 ping_lifetime_threshold: 0,
69 ping_lifetime_max_time: 0,
70 };
71 let mut glean = Glean::new(cfg).unwrap();
72
73 // store{1,2} is used throughout tests
74 _ = new_test_ping(&mut glean, "store1");
75 _ = new_test_ping(&mut glean, "store2");
76
77 (glean, dir)
78 }
79
80 pub fn new_test_ping(glean: &mut Glean, name: &str) -> PingType {
81 let ping = PingBuilder::new(name).build();
82 glean.register_ping_type(&ping);
83 ping
84 }
85
86 pub struct PingBuilder {
87 name: String,
88 include_client_id: bool,
89 send_if_empty: bool,
90 precise_timestamps: bool,
91 include_info_sections: bool,
92 enabled: bool,
93 schedules_pings: Vec<String>,
94 reason_codes: Vec<String>,
95 follows_collection_enabled: bool,
96 uploader_capabilities: Vec<String>,
97 }
98
99 impl PingBuilder {
100 pub fn new(name: &str) -> Self {
101 Self {
102 name: name.to_string(),
103 include_client_id: true,
104 send_if_empty: false,
105 precise_timestamps: true,
106 include_info_sections: true,
107 enabled: true,
108 schedules_pings: vec![],
109 reason_codes: vec![],
110 follows_collection_enabled: true,
111 uploader_capabilities: vec![],
112 }
113 }
114
115 pub fn build(self) -> PingType {
116 PingType::new(
117 self.name,
118 self.include_client_id,
119 self.send_if_empty,
120 self.precise_timestamps,
121 self.include_info_sections,
122 self.enabled,
123 self.schedules_pings,
124 self.reason_codes,
125 self.follows_collection_enabled,
126 self.uploader_capabilities,
127 )
128 }
129
130 pub fn with_send_if_empty(mut self, value: bool) -> Self {
131 self.send_if_empty = value;
132 self
133 }
134
135 pub fn with_include_info_sections(mut self, value: bool) -> Self {
136 self.include_info_sections = value;
137 self
138 }
139
140 pub fn with_enabled(mut self, value: bool) -> Self {
141 self.enabled = value;
142 self
143 }
144
145 pub fn with_follows_collection_enabled(mut self, value: bool) -> Self {
146 self.follows_collection_enabled = value;
147 self
148 }
149
150 pub fn with_schedules_pings(mut self, value: Vec<String>) -> Self {
151 self.schedules_pings = value;
152 self
153 }
154
155 pub fn with_reasons(mut self, value: Vec<String>) -> Self {
156 self.reason_codes = value;
157 self
158 }
159 }
160
161 /// Converts an iso8601::DateTime to a chrono::DateTime<FixedOffset>
162 pub fn iso8601_to_chrono(datetime: &iso8601::DateTime) -> chrono::DateTime<chrono::FixedOffset> {
163 if let YMD { year, month, day } = datetime.date {
164 return chrono::FixedOffset::east(datetime.time.tz_offset_hours * 3600)
165 .ymd(year, month, day)
166 .and_hms_milli(
167 datetime.time.hour,
168 datetime.time.minute,
169 datetime.time.second,
170 datetime.time.millisecond,
171 );
172 };
173 panic!("Unsupported datetime format");
174 }
175
176 /// Gets a vector of the currently queued pings.
177 ///
178 /// # Arguments
179 ///
180 /// * `data_path` - Glean's data path, as returned from Glean::get_data_path()
181 ///
182 /// # Returns
183 ///
184 /// A vector of all queued pings.
185 ///
186 /// Each entry is a pair `(url, json_data, metadata)`,
187 /// where `url` is the endpoint the ping will go to, `json_data` is the JSON payload
188 /// and metadata is optional persisted data related to the ping.
189 pub fn get_queued_pings(data_path: &Path) -> Result<Vec<(String, JsonValue, Option<JsonValue>)>> {
190 get_pings(&data_path.join("pending_pings"))
191 }
192
193 /// Gets a vector of the currently queued `deletion-request` pings.
194 ///
195 /// # Arguments
196 ///
197 /// * `data_path` - Glean's data path, as returned from Glean::get_data_path()
198 ///
199 /// # Returns
200 ///
201 /// A vector of all queued pings.
202 ///
203 /// Each entry is a pair `(url, json_data, metadata)`,
204 /// where `url` is the endpoint the ping will go to, `json_data` is the JSON payload
205 /// and metadata is optional persisted data related to the ping.
206 pub fn get_deletion_pings(data_path: &Path) -> Result<Vec<(String, JsonValue, Option<JsonValue>)>> {
207 get_pings(&data_path.join("deletion_request"))
208 }
209
210 fn get_pings(pings_dir: &Path) -> Result<Vec<(String, JsonValue, Option<JsonValue>)>> {
211 let entries = read_dir(pings_dir)?;
212 Ok(entries
213 .filter_map(|entry| entry.ok())
214 .filter(|entry| match entry.file_type() {
215 Ok(file_type) => file_type.is_file(),
216 Err(_) => false,
217 })
218 .filter_map(|entry| File::open(entry.path()).ok())
219 .filter_map(|file| {
220 let mut lines = BufReader::new(file).lines();
221 if let (Some(Ok(url)), Some(Ok(body)), Ok(metadata)) =
222 (lines.next(), lines.next(), lines.next().transpose())
223 {
224 let parsed_metadata = metadata.map(|m| {
225 serde_json::from_str::<JsonValue>(&m).expect("metadata should be valid JSON")
226 });
227 if let Ok(parsed_body) = serde_json::from_str::<JsonValue>(&body) {
228 Some((url, parsed_body, parsed_metadata))
229 } else {
230 None
231 }
232 } else {
233 None
234 }
235 })
236 .collect())
237 }