Debian Codegraph @

src/tests/modules/bson.rs

raw ◀ ▶
1 Debian patch touch this file
•1 use std::{
2 convert::TryFrom,
3 time::{Duration, SystemTime},
4 };
5
6 use crate::{
7 doc,
8 oid::ObjectId,
9 spec::BinarySubtype,
10 tests::LOCK,
11 Binary,
12 Bson,
13 DateTime,
14 Document,
15 JavaScriptCodeWithScope,
16 Regex,
17 Timestamp,
18 };
19
20 use serde_json::{json, Value};
21
22 #[test]
23 fn to_json() {
24 let _guard = LOCK.run_concurrently();
25 let mut doc = Document::new();
26 doc.insert(
27 "_id",
28 Bson::ObjectId(ObjectId::from_bytes(*b"abcdefghijkl")),
29 );
30 doc.insert("first", Bson::Int32(1));
31 doc.insert("second", Bson::String("foo".to_owned()));
32 doc.insert("alphanumeric", Bson::String("bar".to_owned()));
33 let data: Value = Bson::Document(doc).into();
34
35 assert!(data.is_object());
36 let obj = data.as_object().unwrap();
37
38 let id = obj.get("_id").unwrap();
39 assert!(id.is_object());
40 let id_val = id.get("$oid").unwrap();
41 assert!(id_val.is_string());
42 assert_eq!(id_val, "6162636465666768696a6b6c");
43
44 let first = obj.get("first").unwrap();
45 assert!(first.is_number());
46 assert_eq!(first.as_i64().unwrap(), 1);
47
48 let second = obj.get("second").unwrap();
49 assert!(second.is_string());
50 assert_eq!(second.as_str().unwrap(), "foo");
51
52 let alphanumeric = obj.get("alphanumeric").unwrap();
53 assert!(alphanumeric.is_string());
54 assert_eq!(alphanumeric.as_str().unwrap(), "bar");
55 }
56
57 #[test]
58 fn bson_default() {
59 let _guard = LOCK.run_concurrently();
60 let bson1 = Bson::default();
61 assert_eq!(bson1, Bson::Null);
62 }
63
64 #[test]
65 fn test_display_timestamp_type() {
66 let x = Timestamp {
67 time: 100,
68 increment: 200,
69 };
70 let output = "Timestamp(100, 200)";
71 assert_eq!(format!("{}", x), output);
72 assert_eq!(format!("{}", Bson::from(x)), output);
73 }
74
75 #[test]
76 fn test_display_regex_type() {
77 let x = Regex {
78 pattern: String::from("pattern"),
79 options: String::from("options"),
80 };
81 let output = "/pattern/options";
82 assert_eq!(format!("{}", x), output);
83 assert_eq!(format!("{}", Bson::from(x)), output);
84 }
85
86 #[test]
87 fn test_display_jscodewithcontext_type() {
88 let x = JavaScriptCodeWithScope {
89 code: String::from("code"),
90 scope: doc! {"x": 2},
91 };
92 let output = "code";
93 assert_eq!(format!("{}", x), output);
94 assert_eq!(format!("{}", Bson::from(x)), output);
95 }
96
97 #[test]
98 fn test_display_binary_type() {
99 let encoded_bytes = "aGVsbG8gd29ybGQ=";
100 let bytes = base64::decode(encoded_bytes).unwrap();
101 let x = Binary {
102 subtype: BinarySubtype::Generic,
103 bytes,
104 };
105 let output = format!("Binary(0x0, {})", encoded_bytes);
106 assert_eq!(format!("{}", x), output);
107 assert_eq!(format!("{}", Bson::from(x)), output);
108 }
109
110 #[test]
111 fn document_default() {
112 let _guard = LOCK.run_concurrently();
113 let doc1 = Document::default();
114 assert_eq!(doc1.keys().count(), 0);
115 assert_eq!(doc1, Document::new());
116 }
117
118 #[test]
119 fn from_impls() {
120 let _guard = LOCK.run_concurrently();
121 assert_eq!(Bson::from(1.5f32), Bson::Double(1.5));
122 assert_eq!(Bson::from(2.25f64), Bson::Double(2.25));
123 assert_eq!(Bson::from("data"), Bson::String(String::from("data")));
124 assert_eq!(
125 Bson::from(String::from("data")),
126 Bson::String(String::from("data"))
127 );
128 assert_eq!(Bson::from(doc! {}), Bson::Document(Document::new()));
129 assert_eq!(Bson::from(false), Bson::Boolean(false));
130 assert_eq!(
131 Bson::from(Regex {
132 pattern: String::from("\\s+$"),
133 options: String::from("i")
134 }),
135 Bson::RegularExpression(Regex {
136 pattern: String::from("\\s+$"),
137 options: String::from("i")
138 })
139 );
140 assert_eq!(
141 Bson::from(JavaScriptCodeWithScope {
142 code: String::from("alert(\"hi\");"),
143 scope: doc! {}
144 }),
145 Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope {
146 code: String::from("alert(\"hi\");"),
147 scope: doc! {}
148 })
149 );
150 //
151 assert_eq!(
152 Bson::from(Binary {
153 subtype: BinarySubtype::Generic,
154 bytes: vec![1, 2, 3]
155 }),
156 Bson::Binary(Binary {
157 subtype: BinarySubtype::Generic,
158 bytes: vec![1, 2, 3]
159 })
160 );
161 assert_eq!(Bson::from(-48i32), Bson::Int32(-48));
162 assert_eq!(Bson::from(-96i64), Bson::Int64(-96));
163 assert_eq!(Bson::from(152u32), Bson::Int32(152));
164
165 let oid = ObjectId::new();
166 assert_eq!(
167 Bson::from(b"abcdefghijkl"),
168 Bson::ObjectId(ObjectId::from_bytes(*b"abcdefghijkl"))
169 );
170 assert_eq!(Bson::from(oid), Bson::ObjectId(oid));
171 assert_eq!(
172 Bson::from(vec![1, 2, 3]),
173 Bson::Array(vec![Bson::Int32(1), Bson::Int32(2), Bson::Int32(3)])
174 );
175 assert_eq!(
176 Bson::try_from(json!({"_id": {"$oid": oid.to_hex()}, "name": ["bson-rs"]})).unwrap(),
177 Bson::Document(doc! {"_id": &oid, "name": ["bson-rs"]})
178 );
179
180 // References
181 assert_eq!(Bson::from(&24i32), Bson::Int32(24));
182 #[allow(clippy::unnecessary_fallible_conversions)]
183 {
184 assert_eq!(
185 Bson::try_from(&String::from("data")).unwrap(),
186 Bson::String(String::from("data"))
187 );
188 }
189 assert_eq!(Bson::from(&oid), Bson::ObjectId(oid));
190 assert_eq!(
191 Bson::from(&doc! {"a": "b"}),
192 Bson::Document(doc! {"a": "b"})
193 );
194
195 // Optionals
196 assert_eq!(Bson::from(Some(4)), Bson::Int32(4));
197 assert_eq!(
198 Bson::from(Some(String::from("data"))),
199 Bson::String(String::from("data"))
200 );
201 assert_eq!(Bson::from(None::<i32>), Bson::Null);
202 assert_eq!(Bson::from(None::<String>), Bson::Null);
203 assert_eq!(doc! {"x": Some(4)}, doc! {"x": 4});
204 assert_eq!(doc! {"x": None::<i32>}, doc! {"x": Bson::Null});
205
206 let db_pointer = Bson::try_from(json!({
207 "$dbPointer": {
208 "$ref": "db.coll",
209 "$id": { "$oid": "507f1f77bcf86cd799439011" },
210 }
211 }))
212 .unwrap();
213 let db_pointer = db_pointer.as_db_pointer().unwrap();
214 assert_eq!(Bson::from(db_pointer), Bson::DbPointer(db_pointer.clone()));
215 }
216
217 #[test]
218 fn timestamp_ordering() {
219 let _guard = LOCK.run_concurrently();
220 let ts1 = Timestamp {
221 time: 0,
222 increment: 1,
223 };
224 let ts2 = Timestamp {
225 time: 0,
226 increment: 2,
227 };
228 let ts3 = Timestamp {
229 time: 1,
230 increment: 0,
231 };
232 assert!(ts1 < ts2);
233 assert!(ts1 < ts3);
234 assert!(ts2 < ts3);
235 }
236
237 #[test]
238 fn from_external_datetime() {
239 use time::macros::datetime;
240
241 let _guard = LOCK.run_concurrently();
242
243 fn assert_millisecond_precision(dt: DateTime) {
244 assert!(dt.to_time_0_3().microsecond() % 1000 == 0);
245 }
246 fn assert_subsec_millis(dt: DateTime, millis: u32) {
247 assert_eq!(dt.to_time_0_3().millisecond() as u32, millis)
248 }
249
250 let now = time::OffsetDateTime::now_utc();
251 let dt = DateTime::from_time_0_3(now);
252 assert_millisecond_precision(dt);
253
254 #[cfg(feature = "time-0_3")]
255 {
256 let bson = Bson::from(now);
257 assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
258
259 let from_time = DateTime::from(now);
260 assert_millisecond_precision(from_time);
261 }
262 #[cfg(feature = "chrono-0_4")]
263 {
264 let now = chrono::Utc::now();
265 let bson = Bson::from(now);
266 assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
267
268 let from_chrono = DateTime::from(now);
269 assert_millisecond_precision(from_chrono);
270 }
271
272 let no_subsec_millis = datetime!(2014-11-28 12:00:09 UTC);
273 let dt = DateTime::from_time_0_3(no_subsec_millis);
274 assert_millisecond_precision(dt);
275 assert_subsec_millis(dt, 0);
276
277 #[cfg(feature = "time-0_3")]
278 {
279 let bson = Bson::from(dt);
280 assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
281 assert_subsec_millis(bson.as_datetime().unwrap().to_owned(), 0);
282 }
283 #[cfg(feature = "chrono-0_4")]
284 {
285 let no_subsec_millis: chrono::DateTime<chrono::Utc> =
286 "2014-11-28T12:00:09Z".parse().unwrap();
287 let dt = DateTime::from(no_subsec_millis);
288 assert_millisecond_precision(dt);
289 assert_subsec_millis(dt, 0);
290
291 let bson = Bson::from(dt);
292 assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
293 assert_subsec_millis(bson.as_datetime().unwrap().to_owned(), 0);
294 }
295
296 for s in &[
297 "2014-11-28T12:00:09.123Z",
298 "2014-11-28T12:00:09.123456Z",
299 "2014-11-28T12:00:09.123456789Z",
300 ] {
301 let time_dt =
302 time::OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339).unwrap();
303 let dt = DateTime::from_time_0_3(time_dt);
304 assert_millisecond_precision(dt);
305 assert_subsec_millis(dt, 123);
306
307 #[cfg(feature = "time-0_3")]
308 {
309 let bson = Bson::from(time_dt);
310 assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
311 assert_subsec_millis(bson.as_datetime().unwrap().to_owned(), 123);
312 }
313 #[cfg(feature = "chrono-0_4")]
314 {
315 let chrono_dt: chrono::DateTime<chrono::Utc> = s.parse().unwrap();
316 let dt = DateTime::from(chrono_dt);
317 assert_millisecond_precision(dt);
318 assert_subsec_millis(dt, 123);
319
320 let bson = Bson::from(chrono_dt);
321 assert_millisecond_precision(bson.as_datetime().unwrap().to_owned());
322 assert_subsec_millis(bson.as_datetime().unwrap().to_owned(), 123);
323 }
324 }
325
326 #[cfg(feature = "time-0_3")]
327 {
328 let max = time::PrimitiveDateTime::MAX.assume_utc();
329 let bdt = DateTime::from(max);
330 assert_eq!(
331 bdt.to_time_0_3().unix_timestamp_nanos() / 1_000_000, // truncate to millis
332 max.unix_timestamp_nanos() / 1_000_000
333 );
334
335 let min = time::PrimitiveDateTime::MIN.assume_utc();
336 let bdt = DateTime::from(min);
337 assert_eq!(
338 bdt.to_time_0_3().unix_timestamp_nanos() / 1_000_000,
339 min.unix_timestamp_nanos() / 1_000_000
340 );
341
342 let bdt = DateTime::MAX;
343 assert_eq!(bdt.to_time_0_3(), max);
344
345 let bdt = DateTime::MIN;
346 assert_eq!(bdt.to_time_0_3(), min);
347 }
348 #[cfg(feature = "chrono-0_4")]
349 {
350 use chrono::Utc;
351
352 let bdt = DateTime::from(chrono::DateTime::<Utc>::MAX_UTC);
353 assert_eq!(
354 bdt.to_chrono().timestamp_millis(),
355 chrono::DateTime::<Utc>::MAX_UTC.timestamp_millis()
356 );
357
358 let bdt = DateTime::from(chrono::DateTime::<Utc>::MIN_UTC);
359 assert_eq!(
360 bdt.to_chrono().timestamp_millis(),
361 chrono::DateTime::<Utc>::MIN_UTC.timestamp_millis()
362 );
363
364 let bdt = DateTime::MAX;
365 assert_eq!(bdt.to_chrono(), chrono::DateTime::<Utc>::MAX_UTC);
366
367 let bdt = DateTime::MIN;
368 assert_eq!(bdt.to_chrono(), chrono::DateTime::<Utc>::MIN_UTC);
369 }
370 }
371
372 #[test]
373 fn from_datetime_builder() {
374 {
375 let dt = DateTime::builder()
376 .year(2022)
377 .month(9)
378 .day(15)
379 .minute(2)
380 .millisecond(1)
381 .build();
382 assert!(dt.is_ok());
383 assert_eq!(
384 DateTime::from_time_0_3(time::macros::datetime!(2022 - 09 - 15 00:02:00.001 UTC)),
385 dt.unwrap()
386 );
387 }
388
389 {
390 let dt = DateTime::builder()
391 .year(2022)
392 .month(18)
393 .day(15)
394 .minute(2)
395 .millisecond(1)
396 .build();
397 assert!(dt.is_err());
398 }
399
400 {
401 let dt = DateTime::builder()
402 .year(2022)
403 .day(15)
404 .month(18)
405 .minute(83)
406 .millisecond(1)
407 .build();
408 assert!(dt.is_err());
409 }
410 }
411
412 #[test]
413 fn system_time() {
414 let _guard = LOCK.run_concurrently();
415
416 let st = SystemTime::now();
417 let bt_into: crate::DateTime = st.into();
418 let bt_from = crate::DateTime::from_system_time(st);
419
420 assert_eq!(bt_into, bt_from);
421 assert_eq!(
422 bt_into.timestamp_millis(),
423 st.duration_since(SystemTime::UNIX_EPOCH)
424 .unwrap()
425 .as_millis() as i64
426 );
427
428 let st = SystemTime::UNIX_EPOCH
429 .checked_add(Duration::from_millis(1234))
430 .unwrap();
431 let bt = crate::DateTime::from_system_time(st);
432 assert_eq!(bt.timestamp_millis(), 1234);
433 assert_eq!(bt.to_system_time(), st);
434
435 assert_eq!(
436 crate::DateTime::MAX.to_system_time(),
437 SystemTime::UNIX_EPOCH + Duration::from_millis(i64::MAX as u64)
438 );
439 assert_eq!(
440 crate::DateTime::MIN.to_system_time(),
441 SystemTime::UNIX_EPOCH - Duration::from_millis((i64::MIN as i128).unsigned_abs() as u64)
442 );
443
444 assert_eq!(
445 crate::DateTime::from_system_time(SystemTime::UNIX_EPOCH).timestamp_millis(),
446 0
447 );
448 }
449
450 #[test]
451 fn debug_print() {
452 let oid = ObjectId::parse_str("000000000000000000000000").unwrap();
453
454 let doc = doc! {
455 "oid": oid,
456 "arr": Bson::Array(vec! [
457 Bson::Null,
458 Bson::Timestamp(Timestamp { time: 1, increment: 1 }),
459 ]),
460 "doc": doc! { "a": 1, "b": "data"},
461 };
462 let normal_print = "Document({\"oid\": ObjectId(\"000000000000000000000000\"), \"arr\": \
463 Array([Null, Timestamp { time: 1, increment: 1 }]), \"doc\": \
464 Document({\"a\": Int32(1), \"b\": String(\"data\")})})";
465 let pretty_print = "Document({
466 \"oid\": ObjectId(
467 \"000000000000000000000000\",
468 ),
469 \"arr\": Array([
470 Null,
471 Timestamp {
472 time: 1,
473 increment: 1,
474 },
475 ]),
476 \"doc\": Document({
477 \"a\": Int32(
478 1,
479 ),
480 \"b\": String(
481 \"data\",
482 ),
483 }),
484 })";
485
486 assert_eq!(format!("{:?}", doc), normal_print);
487 assert_eq!(format!("{:#?}", doc), pretty_print);
488 }