Debian Codegraph @

src/tests/serde.rs

raw ◀ ▶
1 Debian patch touch this file
•1 #![allow(clippy::disallowed_names)]
2
3 use crate::{
4 bson,
5 doc,
6 from_bson,
7 from_document,
8 oid::ObjectId,
9 serde_helpers,
10 serde_helpers::{
11 bson_datetime_as_rfc3339_string,
12 hex_string_as_object_id,
13 i64_as_bson_datetime,
14 rfc3339_string_as_bson_datetime,
15 serialize_object_id_as_hex_string,
16 timestamp_as_u32,
17 u32_as_timestamp,
18 },
19 spec::BinarySubtype,
20 tests::LOCK,
21 to_bson,
22 to_document,
23 Binary,
24 Bson,
25 DateTime,
26 Deserializer,
27 Document,
28 Serializer,
29 Timestamp,
30 };
31
32 use serde::{Deserialize, Serialize};
33 use serde_json::json;
34
35 use std::{
36 collections::BTreeMap,
37 convert::{TryFrom, TryInto},
38 };
39
40 #[test]
41 fn test_ser_vec() {
42 let _guard = LOCK.run_concurrently();
43 let vec = vec![1, 2, 3];
44
45 let serializer = Serializer::new();
46 let result = vec.serialize(serializer).unwrap();
47
48 let expected = bson!([1, 2, 3]);
49 assert_eq!(expected, result);
50 }
51
52 #[test]
53 fn test_ser_map() {
54 let _guard = LOCK.run_concurrently();
55 let mut map = BTreeMap::new();
56 map.insert("x", 0);
57 map.insert("y", 1);
58
59 let serializer = Serializer::new();
60 let result = map.serialize(serializer).unwrap();
61
62 let expected = bson!({ "x": 0, "y": 1 });
63 assert_eq!(expected, result);
64 }
65
66 #[test]
67 fn test_de_vec() {
68 let _guard = LOCK.run_concurrently();
69 let bson = bson!([1, 2, 3]);
70
71 let deserializer = Deserializer::new(bson);
72 let vec = Vec::<i32>::deserialize(deserializer).unwrap();
73
74 let expected = vec![1, 2, 3];
75 assert_eq!(expected, vec);
76 }
77
78 #[test]
79 fn test_de_map() {
80 let _guard = LOCK.run_concurrently();
81 let bson = bson!({ "x": 0, "y": 1 });
82
83 let deserializer = Deserializer::new(bson);
84 let map = BTreeMap::<String, i32>::deserialize(deserializer).unwrap();
85
86 let mut expected = BTreeMap::new();
87 expected.insert("x".to_string(), 0);
88 expected.insert("y".to_string(), 1);
89 assert_eq!(expected, map);
90 }
91
92 #[test]
93 fn test_ser_timestamp() {
94 let _guard = LOCK.run_concurrently();
95 use bson::Timestamp;
96
97 #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
98 struct Foo {
99 ts: Timestamp,
100 }
101
102 let foo = Foo {
103 ts: Timestamp {
104 time: 12,
105 increment: 10,
106 },
107 };
108
109 let x = to_bson(&foo).unwrap();
110 assert_eq!(
111 x.as_document().unwrap(),
112 &doc! { "ts": Bson::Timestamp(Timestamp { time: 0x0000_000C, increment: 0x0000_000A }) }
113 );
114
115 let xfoo: Foo = from_bson(x).unwrap();
116 assert_eq!(xfoo, foo);
117 }
118
119 #[test]
120 fn test_de_timestamp() {
121 let _guard = LOCK.run_concurrently();
122 use bson::Timestamp;
123
124 #[derive(Deserialize, Eq, PartialEq, Debug)]
125 struct Foo {
126 ts: Timestamp,
127 }
128
129 let foo: Foo = from_bson(Bson::Document(doc! {
130 "ts": Bson::Timestamp(Timestamp { time: 0x0000_000C, increment: 0x0000_000A }),
131 }))
132 .unwrap();
133
134 assert_eq!(
135 foo.ts,
136 Timestamp {
137 time: 12,
138 increment: 10
139 }
140 );
141 }
142
143 #[test]
144 fn test_ser_regex() {
145 let _guard = LOCK.run_concurrently();
146 use bson::Regex;
147
148 #[derive(Serialize, Deserialize, PartialEq, Debug)]
149 struct Foo {
150 regex: Regex,
151 }
152
153 let regex = Regex {
154 pattern: "12".into(),
155 options: "01".into(),
156 };
157
158 let foo = Foo {
159 regex: regex.clone(),
160 };
161
162 let x = to_bson(&foo).unwrap();
163 assert_eq!(
164 x.as_document().unwrap(),
165 &doc! { "regex": Bson::RegularExpression(regex) }
166 );
167
168 let xfoo: Foo = from_bson(x).unwrap();
169 assert_eq!(xfoo, foo);
170 }
171
172 #[test]
173 fn test_de_regex() {
174 let _guard = LOCK.run_concurrently();
175 use bson::Regex;
176
177 #[derive(Deserialize, PartialEq, Debug)]
178 struct Foo {
179 regex: Regex,
180 }
181
182 let regex = Regex {
183 pattern: "12".into(),
184 options: "01".into(),
185 };
186
187 let foo: Foo = from_bson(Bson::Document(doc! {
188 "regex": Bson::RegularExpression(regex.clone()),
189 }))
190 .unwrap();
191
192 assert_eq!(foo.regex, regex);
193 }
194
195 #[test]
196 fn test_ser_code_with_scope() {
197 let _guard = LOCK.run_concurrently();
198 use bson::JavaScriptCodeWithScope;
199
200 #[derive(Serialize, Deserialize, PartialEq, Debug)]
201 struct Foo {
202 code_with_scope: JavaScriptCodeWithScope,
203 }
204
205 let code_with_scope = JavaScriptCodeWithScope {
206 code: "x".into(),
207 scope: doc! { "x": 12 },
208 };
209
210 let foo = Foo {
211 code_with_scope: code_with_scope.clone(),
212 };
213
214 let x = to_bson(&foo).unwrap();
215 assert_eq!(
216 x.as_document().unwrap(),
217 &doc! { "code_with_scope": Bson::JavaScriptCodeWithScope(code_with_scope) }
218 );
219
220 let xfoo: Foo = from_bson(x).unwrap();
221 assert_eq!(xfoo, foo);
222 }
223
224 #[test]
225 fn test_de_code_with_scope() {
226 let _guard = LOCK.run_concurrently();
227 use bson::JavaScriptCodeWithScope;
228
229 #[derive(Deserialize, PartialEq, Debug)]
230 struct Foo {
231 code_with_scope: JavaScriptCodeWithScope,
232 }
233
234 let code_with_scope = JavaScriptCodeWithScope {
235 code: "x".into(),
236 scope: doc! { "x": 12 },
237 };
238
239 let foo: Foo = from_bson(Bson::Document(doc! {
240 "code_with_scope": Bson::JavaScriptCodeWithScope(code_with_scope.clone()),
241 }))
242 .unwrap();
243
244 assert_eq!(foo.code_with_scope, code_with_scope);
245 }
246
247 #[test]
248 fn test_ser_datetime() {
249 let _guard = LOCK.run_concurrently();
250 use crate::DateTime;
251
252 #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
253 struct Foo {
254 date: DateTime,
255 }
256
257 let now = DateTime::now();
258
259 let foo = Foo { date: now };
260
261 let x = to_bson(&foo).unwrap();
262 assert_eq!(
263 x.as_document().unwrap(),
264 &doc! { "date": (Bson::DateTime(now)) }
265 );
266
267 let xfoo: Foo = from_bson(x).unwrap();
268 assert_eq!(xfoo, foo);
269 }
270
271 #[test]
272 fn test_binary_generic_roundtrip() {
273 let _guard = LOCK.run_concurrently();
274 #[derive(Serialize, Deserialize, Debug, PartialEq)]
275 pub struct Foo {
276 data: Bson,
277 }
278
279 let x = Foo {
280 data: Bson::Binary(Binary {
281 subtype: BinarySubtype::Generic,
282 bytes: b"12345abcde".to_vec(),
283 }),
284 };
285
286 let b = to_bson(&x).unwrap();
287 assert_eq!(
288 b.as_document().unwrap(),
289 &doc! {"data": Bson::Binary(Binary { subtype: BinarySubtype::Generic, bytes: b"12345abcde".to_vec() })}
290 );
291
292 let f = from_bson::<Foo>(b).unwrap();
293 assert_eq!(x, f);
294 }
295
296 #[test]
297 fn test_binary_non_generic_roundtrip() {
298 let _guard = LOCK.run_concurrently();
299 #[derive(Serialize, Deserialize, Debug, PartialEq)]
300 pub struct Foo {
301 data: Bson,
302 }
303
304 let x = Foo {
305 data: Bson::Binary(Binary {
306 subtype: BinarySubtype::BinaryOld,
307 bytes: b"12345abcde".to_vec(),
308 }),
309 };
310
311 let b = to_bson(&x).unwrap();
312 assert_eq!(
313 b.as_document().unwrap(),
314 &doc! {"data": Bson::Binary(Binary { subtype: BinarySubtype::BinaryOld, bytes: b"12345abcde".to_vec() })}
315 );
316
317 let f = from_bson::<Foo>(b).unwrap();
318 assert_eq!(x, f);
319 }
320
321 #[test]
322 fn test_binary_helper_generic_roundtrip() {
323 let _guard = LOCK.run_concurrently();
324 #[derive(Serialize, Deserialize, Debug, PartialEq)]
325 pub struct Foo {
326 data: Binary,
327 }
328
329 let x = Foo {
330 data: Binary {
331 subtype: BinarySubtype::Generic,
332 bytes: b"12345abcde".to_vec(),
333 },
334 };
335
336 let b = to_bson(&x).unwrap();
337 assert_eq!(
338 b.as_document().unwrap(),
339 &doc! {"data": Bson::Binary(Binary { subtype: BinarySubtype::Generic, bytes: b"12345abcde".to_vec() })}
340 );
341
342 let f = from_bson::<Foo>(b).unwrap();
343 assert_eq!(x, f);
344 }
345
346 #[test]
347 fn test_binary_helper_non_generic_roundtrip() {
348 let _guard = LOCK.run_concurrently();
349 #[derive(Serialize, Deserialize, Debug, PartialEq)]
350 pub struct Foo {
351 data: Binary,
352 }
353
354 let x = Foo {
355 data: Binary {
356 subtype: BinarySubtype::BinaryOld,
357 bytes: b"12345abcde".to_vec(),
358 },
359 };
360
361 let b = to_bson(&x).unwrap();
362 assert_eq!(
363 b.as_document().unwrap(),
364 &doc! {"data": Bson::Binary(Binary { subtype: BinarySubtype::BinaryOld, bytes: b"12345abcde".to_vec() })}
365 );
366
367 let f = from_bson::<Foo>(b).unwrap();
368 assert_eq!(x, f);
369 }
370
371 #[test]
372 fn test_byte_vec() {
373 let _guard = LOCK.run_concurrently();
374 #[derive(Serialize, Debug, Eq, PartialEq)]
375 pub struct AuthChallenge<'a> {
376 #[serde(with = "serde_bytes")]
377 pub challenge: &'a [u8],
378 }
379
380 let x = AuthChallenge {
381 challenge: b"18762b98b7c34c25bf9dc3154e4a5ca3",
382 };
383
384 let b = to_bson(&x).unwrap();
385 assert_eq!(
386 b,
387 Bson::Document(
388 doc! { "challenge": (Bson::Binary(Binary { subtype: BinarySubtype::Generic, bytes: x.challenge.to_vec() }))}
389 )
390 );
391
392 // let mut buf = Vec::new();
393 // b.as_document().unwrap().to_writer(&mut buf).unwrap();
394
395 // let xb = Document::from_reader(&mut Cursor::new(buf)).unwrap();
396 // assert_eq!(b.as_document().unwrap(), &xb);
397 }
398
399 #[test]
400 fn test_serde_bytes() {
401 let _guard = LOCK.run_concurrently();
402 #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
403 pub struct Foo {
404 #[serde(with = "serde_bytes")]
405 data: Vec<u8>,
406 }
407
408 let x = Foo {
409 data: b"12345abcde".to_vec(),
410 };
411
412 let b = to_bson(&x).unwrap();
413 assert_eq!(
414 b.as_document().unwrap(),
415 &doc! {"data": Bson::Binary(Binary { subtype: BinarySubtype::Generic, bytes: b"12345abcde".to_vec() })}
416 );
417
418 let f = from_bson::<Foo>(b).unwrap();
419 assert_eq!(x, f);
420 }
421
422 #[test]
423 fn test_serde_newtype_struct() {
424 let _guard = LOCK.run_concurrently();
425 #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
426 struct Email(String);
427
428 let email_1 = Email(String::from("[email protected]"));
429 let b = to_bson(&email_1).unwrap();
430 assert_eq!(b, Bson::String(email_1.0));
431
432 let s = String::from("[email protected]");
433 let de = Bson::String(s.clone());
434 let email_2 = from_bson::<Email>(de).unwrap();
435 assert_eq!(email_2, Email(s));
436 }
437
438 #[test]
439 fn test_serde_tuple_struct() {
440 let _guard = LOCK.run_concurrently();
441 #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
442 struct Name(String, String); // first, last
443
444 let name_1 = Name(String::from("Graydon"), String::from("Hoare"));
445 let b = to_bson(&name_1).unwrap();
446 assert_eq!(b, bson!([name_1.0.clone(), name_1.1]));
447
448 let (first, last) = (String::from("Donald"), String::from("Knuth"));
449 let de = bson!([first.clone(), last.clone()]);
450 let name_2 = from_bson::<Name>(de).unwrap();
451 assert_eq!(name_2, Name(first, last));
452 }
453
454 #[test]
455 fn test_serde_newtype_variant() {
456 let _guard = LOCK.run_concurrently();
457 #[derive(Debug, PartialEq, Serialize, Deserialize)]
458 #[serde(tag = "type", content = "value")]
459 enum Number {
460 Int(i64),
461 Float(f64),
462 }
463
464 let n = 42;
465 let num_1 = Number::Int(n);
466 let b = to_bson(&num_1).unwrap();
467 assert_eq!(b, bson!({ "type": "Int", "value": n }));
468
469 let x = 1337.0;
470 let de = bson!({ "type": "Float", "value": x });
471 let num_2 = from_bson::<Number>(de).unwrap();
472 assert_eq!(num_2, Number::Float(x));
473 }
474
475 #[test]
476 fn test_serde_tuple_variant() {
477 let _guard = LOCK.run_concurrently();
478 #[derive(Debug, PartialEq, Serialize, Deserialize)]
479 enum Point {
480 TwoDim(f64, f64),
481 ThreeDim(f64, f64, f64),
482 }
483
484 #[allow(clippy::approx_constant)]
485 let (x1, y1) = (3.14, -2.71);
486 let p1 = Point::TwoDim(x1, y1);
487 let b = to_bson(&p1).unwrap();
488 assert_eq!(b, bson!({ "TwoDim": [x1, y1] }));
489
490 let (x2, y2, z2) = (0.0, -13.37, 4.2);
491 let de = bson!({ "ThreeDim": [x2, y2, z2] });
492 let p2 = from_bson::<Point>(de).unwrap();
493 assert_eq!(p2, Point::ThreeDim(x2, y2, z2));
494 }
495
496 #[test]
497 fn test_ser_db_pointer() {
498 let _guard = LOCK.run_concurrently();
499 use bson::DbPointer;
500
501 #[derive(Serialize, Deserialize, PartialEq, Debug)]
502 struct Foo {
503 db_pointer: DbPointer,
504 }
505
506 let db_pointer = Bson::try_from(json!({
507 "$dbPointer": {
508 "$ref": "db.coll",
509 "$id": { "$oid": "507f1f77bcf86cd799439011" },
510 }
511 }))
512 .unwrap();
513
514 let db_pointer = db_pointer.as_db_pointer().unwrap();
515
516 let foo = Foo {
517 db_pointer: db_pointer.clone(),
518 };
519
520 let x = to_bson(&foo).unwrap();
521 assert_eq!(
522 x.as_document().unwrap(),
523 &doc! {"db_pointer": Bson::DbPointer(db_pointer.clone()) }
524 );
525
526 let xfoo: Foo = from_bson(x).unwrap();
527 assert_eq!(xfoo, foo);
528 }
529
530 #[test]
531 fn test_de_db_pointer() {
532 let _guard = LOCK.run_concurrently();
533 use bson::DbPointer;
534
535 #[derive(Deserialize, PartialEq, Debug)]
536 struct Foo {
537 db_pointer: DbPointer,
538 }
539
540 let db_pointer = Bson::try_from(json!({
541 "$dbPointer": {
542 "$ref": "db.coll",
543 "$id": { "$oid": "507f1f77bcf86cd799439011" },
544 }
545 }))
546 .unwrap();
547 let db_pointer = db_pointer.as_db_pointer().unwrap();
548
549 let foo: Foo = from_bson(Bson::Document(
550 doc! {"db_pointer": Bson::DbPointer(db_pointer.clone())},
551 ))
552 .unwrap();
553
554 assert_eq!(foo.db_pointer, db_pointer.clone());
555 }
556
557 #[cfg(feature = "uuid-0_8")]
558 #[test]
559 fn test_serde_legacy_uuid_0_8() {
560 use uuid_0_8::Uuid;
561
562 let _guard = LOCK.run_concurrently();
563
564 #[derive(Serialize, Deserialize)]
565 struct Foo {
566 #[serde(with = "serde_helpers::uuid_as_java_legacy_binary")]
567 java_legacy: Uuid,
568 #[serde(with = "serde_helpers::uuid_as_python_legacy_binary")]
569 python_legacy: Uuid,
570 #[serde(with = "serde_helpers::uuid_as_c_sharp_legacy_binary")]
571 csharp_legacy: Uuid,
572 }
573 let uuid = Uuid::parse_str("00112233445566778899AABBCCDDEEFF").unwrap();
574 let foo = Foo {
575 java_legacy: uuid,
576 python_legacy: uuid,
577 csharp_legacy: uuid,
578 };
579
580 let x = to_bson(&foo).unwrap();
581 assert_eq!(
582 x.as_document().unwrap(),
583 &doc! {
584 "java_legacy": Bson::Binary(Binary{
585 subtype:BinarySubtype::UuidOld,
586 bytes: hex::decode("7766554433221100FFEEDDCCBBAA9988").unwrap(),
587 }),
588 "python_legacy": Bson::Binary(Binary{
589 subtype:BinarySubtype::UuidOld,
590 bytes: hex::decode("00112233445566778899AABBCCDDEEFF").unwrap(),
591 }),
592 "csharp_legacy": Bson::Binary(Binary{
593 subtype:BinarySubtype::UuidOld,
594 bytes: hex::decode("33221100554477668899AABBCCDDEEFF").unwrap(),
595 })
596 }
597 );
598
599 let foo: Foo = from_bson(x).unwrap();
600 assert_eq!(foo.java_legacy, uuid);
601 assert_eq!(foo.python_legacy, uuid);
602 assert_eq!(foo.csharp_legacy, uuid);
603 }
604
605 #[cfg(feature = "uuid-1")]
606 #[test]
607 fn test_serde_legacy_uuid_1() {
608 use uuid::Uuid;
609
610 let _guard = LOCK.run_concurrently();
611
612 #[derive(Serialize, Deserialize)]
613 struct Foo {
614 #[serde(with = "serde_helpers::uuid_1_as_java_legacy_binary")]
615 java_legacy: Uuid,
616 #[serde(with = "serde_helpers::uuid_1_as_python_legacy_binary")]
617 python_legacy: Uuid,
618 #[serde(with = "serde_helpers::uuid_1_as_c_sharp_legacy_binary")]
619 csharp_legacy: Uuid,
620 }
621 let uuid = Uuid::parse_str("00112233445566778899AABBCCDDEEFF").unwrap();
622 let foo = Foo {
623 java_legacy: uuid,
624 python_legacy: uuid,
625 csharp_legacy: uuid,
626 };
627
628 let x = to_bson(&foo).unwrap();
629 assert_eq!(
630 x.as_document().unwrap(),
631 &doc! {
632 "java_legacy": Bson::Binary(Binary{
633 subtype:BinarySubtype::UuidOld,
634 bytes: hex::decode("7766554433221100FFEEDDCCBBAA9988").unwrap(),
635 }),
636 "python_legacy": Bson::Binary(Binary{
637 subtype:BinarySubtype::UuidOld,
638 bytes: hex::decode("00112233445566778899AABBCCDDEEFF").unwrap(),
639 }),
640 "csharp_legacy": Bson::Binary(Binary{
641 subtype:BinarySubtype::UuidOld,
642 bytes: hex::decode("33221100554477668899AABBCCDDEEFF").unwrap(),
643 })
644 }
645 );
646
647 let foo: Foo = from_bson(x).unwrap();
648 assert_eq!(foo.java_legacy, uuid);
649 assert_eq!(foo.python_legacy, uuid);
650 assert_eq!(foo.csharp_legacy, uuid);
651 }
652
653 #[test]
654 fn test_de_oid_string() {
655 let _guard = LOCK.run_concurrently();
656
657 #[derive(Debug, Deserialize)]
658 struct Foo {
659 pub oid: ObjectId,
660 }
661
662 let foo: Foo = serde_json::from_str("{ \"oid\": \"507f1f77bcf86cd799439011\" }").unwrap();
663 let oid = ObjectId::parse_str("507f1f77bcf86cd799439011").unwrap();
664 assert_eq!(foo.oid, oid);
665 }
666
667 #[test]
668 fn test_serialize_deserialize_unsigned_numbers() {
669 let _guard = LOCK.run_concurrently();
670
671 let num = 1;
672 let json = format!("{{ \"num\": {} }}", num);
673 let doc: Document = serde_json::from_str(&json).unwrap();
674 assert_eq!(doc.get_i32("num").unwrap(), num);
675
676 let num = i32::MAX as u64 + 1;
677 let json = format!("{{ \"num\": {} }}", num);
678 let doc: Document = serde_json::from_str(&json).unwrap();
679 assert_eq!(doc.get_i64("num").unwrap(), num as i64);
680
681 let num = u64::MAX;
682 let json = format!("{{ \"num\": {} }}", num);
683 let doc_result: Result<Document, serde_json::Error> = serde_json::from_str(&json);
684 assert!(doc_result.is_err());
685 }
686
687 #[test]
688 fn test_unsigned_helpers() {
689 let _guard = LOCK.run_concurrently();
690
691 #[derive(Serialize)]
692 struct A {
693 #[serde(serialize_with = "serde_helpers::serialize_u32_as_i32")]
694 num_1: u32,
695 #[serde(serialize_with = "serde_helpers::serialize_u64_as_i32")]
696 num_2: u64,
697 }
698
699 let a = A { num_1: 1, num_2: 2 };
700 let doc = to_document(&a).unwrap();
701 assert!(doc.get_i32("num_1").unwrap() == 1);
702 assert!(doc.get_i32("num_2").unwrap() == 2);
703
704 let a = A {
705 num_1: u32::MAX,
706 num_2: 1,
707 };
708 let doc_result = to_document(&a);
709 assert!(doc_result.is_err());
710
711 let a = A {
712 num_1: 1,
713 num_2: u64::MAX,
714 };
715 let doc_result = to_document(&a);
716 assert!(doc_result.is_err());
717
718 #[derive(Serialize)]
719 struct B {
720 #[serde(serialize_with = "serde_helpers::serialize_u32_as_i64")]
721 num_1: u32,
722 #[serde(serialize_with = "serde_helpers::serialize_u64_as_i64")]
723 num_2: u64,
724 }
725
726 let b = B {
727 num_1: u32::MAX,
728 num_2: i64::MAX as u64,
729 };
730 let doc = to_document(&b).unwrap();
731 assert!(doc.get_i64("num_1").unwrap() == u32::MAX as i64);
732 assert!(doc.get_i64("num_2").unwrap() == i64::MAX);
733
734 let b = B {
735 num_1: 1,
736 num_2: i64::MAX as u64 + 1,
737 };
738 let doc_result = to_document(&b);
739 assert!(doc_result.is_err());
740
741 #[derive(Deserialize, Serialize, Debug, PartialEq)]
742 struct F {
743 #[serde(with = "serde_helpers::u32_as_f64")]
744 num_1: u32,
745 #[serde(with = "serde_helpers::u64_as_f64")]
746 num_2: u64,
747 }
748
749 let f = F {
750 num_1: 101,
751 num_2: 12345,
752 };
753 let doc = to_document(&f).unwrap();
754 assert!((doc.get_f64("num_1").unwrap() - 101.0).abs() < f64::EPSILON);
755 assert!((doc.get_f64("num_2").unwrap() - 12345.0).abs() < f64::EPSILON);
756
757 let back: F = from_document(doc).unwrap();
758 assert_eq!(back, f);
759
760 let f = F {
761 num_1: 1,
762 // f64 cannot represent many large integers exactly, u64::MAX included
763 num_2: u64::MAX,
764 };
765 let doc_result = to_document(&f);
766 assert!(doc_result.is_err());
767
768 let f = F {
769 num_1: 1,
770 num_2: u64::MAX - 255,
771 };
772 let doc_result = to_document(&f);
773 assert!(doc_result.is_err());
774 }
775
776 #[test]
777 fn test_datetime_helpers() {
778 use time::{format_description::well_known::Rfc3339, OffsetDateTime};
779
780 let _guard = LOCK.run_concurrently();
781
782 #[derive(Deserialize, Serialize)]
783 struct A {
784 #[serde(with = "bson_datetime_as_rfc3339_string")]
785 pub date: DateTime,
786 }
787
788 let iso = "1996-12-20T00:39:57Z";
789 let date = OffsetDateTime::parse(iso, &Rfc3339).unwrap();
790 let a = A {
791 date: crate::DateTime::from_time_0_3(date),
792 };
793 let doc = to_document(&a).unwrap();
794 assert_eq!(doc.get_str("date").unwrap(), iso);
795 let a: A = from_document(doc).unwrap();
796 assert_eq!(a.date.to_time_0_3(), date);
797
798 #[cfg(feature = "time-0_3")]
799 {
800 use time::macros::datetime;
801
802 #[derive(Deserialize, Serialize)]
803 struct B {
804 #[serde(with = "serde_helpers::time_0_3_offsetdatetime_as_bson_datetime")]
805 pub date: time::OffsetDateTime,
806 }
807
808 let date = r#"
809 {
810 "date": {
811 "$date": {
812 "$numberLong": "1591700287095"
813 }
814 }
815 }"#;
816 let json: serde_json::Value = serde_json::from_str(date).unwrap();
817 let b: B = serde_json::from_value(json).unwrap();
818 let expected = datetime!(2020-06-09 10:58:07.095 UTC);
819 assert_eq!(b.date, expected);
820 let doc = to_document(&b).unwrap();
821 assert_eq!(doc.get_datetime("date").unwrap().to_time_0_3(), expected);
822 let b: B = from_document(doc).unwrap();
823 assert_eq!(b.date, expected);
824 }
825
826 #[cfg(feature = "chrono-0_4")]
827 {
828 use std::str::FromStr;
829 #[derive(Deserialize, Serialize)]
830 struct B {
831 #[serde(with = "serde_helpers::chrono_datetime_as_bson_datetime")]
832 pub date: chrono::DateTime<chrono::Utc>,
833 }
834
835 let date = r#"
836 {
837 "date": {
838 "$date": {
839 "$numberLong": "1591700287095"
840 }
841 }
842 }"#;
843 let json: serde_json::Value = serde_json::from_str(date).unwrap();
844 let b: B = serde_json::from_value(json).unwrap();
845 let expected: chrono::DateTime<chrono::Utc> =
846 chrono::DateTime::from_str("2020-06-09 10:58:07.095 UTC").unwrap();
847 assert_eq!(b.date, expected);
848 let doc = to_document(&b).unwrap();
849 assert_eq!(doc.get_datetime("date").unwrap().to_chrono(), expected);
850 let b: B = from_document(doc).unwrap();
851 assert_eq!(b.date, expected);
852 }
853
854 #[derive(Deserialize, Serialize)]
855 struct C {
856 #[serde(with = "rfc3339_string_as_bson_datetime")]
857 pub date: String,
858 }
859
860 let date = "2020-06-09T10:58:07.095Z";
861 let c = C {
862 date: date.to_string(),
863 };
864 let doc = to_document(&c).unwrap();
865 assert!(doc.get_datetime("date").is_ok());
866 let c: C = from_document(doc).unwrap();
867 assert_eq!(c.date.as_str(), date);
868 }
869
870 #[test]
871 fn test_oid_helpers() {
872 let _guard = LOCK.run_concurrently();
873
874 #[derive(Serialize, Deserialize)]
875 struct A {
876 #[serde(with = "hex_string_as_object_id")]
877 oid: String,
878 }
879
880 let oid = ObjectId::new();
881 let a = A {
882 oid: oid.to_string(),
883 };
884 let doc = to_document(&a).unwrap();
885 assert_eq!(doc.get_object_id("oid").unwrap(), oid);
886 let a: A = from_document(doc).unwrap();
887 assert_eq!(a.oid, oid.to_string());
888 }
889
890 #[test]
891 fn test_i64_as_bson_datetime() {
892 let _guard = LOCK.run_concurrently();
893
894 #[derive(Serialize, Deserialize)]
895 struct A {
896 #[serde(with = "i64_as_bson_datetime")]
897 now: i64,
898 }
899
900 let now = DateTime::now();
901 let a = A {
902 now: now.timestamp_millis(),
903 };
904 let doc = to_document(&a).unwrap();
905 assert_eq!(doc.get_datetime("now").unwrap(), &now);
906 let a: A = from_document(doc).unwrap();
907 assert_eq!(a.now, now.timestamp_millis());
908 }
909
910 #[test]
911 #[cfg(feature = "uuid-0_8")]
912 fn test_uuid_0_8_helpers() {
913 use serde_helpers::uuid_as_binary;
914 use uuid_0_8::Uuid;
915
916 let _guard = LOCK.run_concurrently();
917
918 #[derive(Serialize, Deserialize)]
919 struct A {
920 #[serde(with = "uuid_as_binary")]
921 uuid: Uuid,
922 }
923
924 let uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
925 let a = A { uuid };
926 let doc = to_document(&a).unwrap();
927 match doc.get("uuid").unwrap() {
928 Bson::Binary(bin) => {
929 assert_eq!(bin.subtype, BinarySubtype::Uuid);
930 assert_eq!(bin.bytes, uuid.as_bytes());
931 }
932 _ => panic!("expected Bson::Binary"),
933 }
934 let a: A = from_document(doc).unwrap();
935 assert_eq!(a.uuid, uuid);
936 }
937
938 #[test]
939 #[cfg(feature = "uuid-1")]
940 fn test_uuid_1_helpers() {
941 use serde_helpers::uuid_1_as_binary;
942 use uuid::Uuid;
943
944 let _guard = LOCK.run_concurrently();
945
946 #[derive(Serialize, Deserialize)]
947 struct A {
948 #[serde(with = "uuid_1_as_binary")]
949 uuid: Uuid,
950 }
951
952 let uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
953 let a = A { uuid };
954 let doc = to_document(&a).unwrap();
955 match doc.get("uuid").unwrap() {
956 Bson::Binary(bin) => {
957 assert_eq!(bin.subtype, BinarySubtype::Uuid);
958 assert_eq!(bin.bytes, uuid.as_bytes());
959 }
960 _ => panic!("expected Bson::Binary"),
961 }
962 let a: A = from_document(doc).unwrap();
963 assert_eq!(a.uuid, uuid);
964 }
965
966 #[test]
967 fn test_timestamp_helpers() {
968 let _guard = LOCK.run_concurrently();
969
970 #[derive(Deserialize, Serialize)]
971 struct A {
972 #[serde(with = "u32_as_timestamp")]
973 pub time: u32,
974 }
975
976 let time = 12345;
977 let a = A { time };
978 let doc = to_document(&a).unwrap();
979 let timestamp = doc.get_timestamp("time").unwrap();
980 assert_eq!(timestamp.time, time);
981 assert_eq!(timestamp.increment, 0);
982 let a: A = from_document(doc).unwrap();
983 assert_eq!(a.time, time);
984
985 #[derive(Deserialize, Serialize)]
986 struct B {
987 #[serde(with = "timestamp_as_u32")]
988 pub timestamp: Timestamp,
989 }
990
991 let time = 12345;
992 let timestamp = Timestamp { time, increment: 0 };
993 let b = B { timestamp };
994 let val = serde_json::to_value(b).unwrap();
995 assert_eq!(val["timestamp"], time);
996 let b: B = serde_json::from_value(val).unwrap();
997 assert_eq!(b.timestamp, timestamp);
998
999 let timestamp = Timestamp {
1000 time: 12334,
1001 increment: 1,
1002 };
1003 let b = B { timestamp };
1004 assert!(serde_json::to_value(b).is_err());
1005 }
1006
1007 #[test]
1008 fn large_dates() {
1009 let _guard = LOCK.run_concurrently();
1010
1011 let json = json!({ "d": { "$date": { "$numberLong": i64::MAX.to_string() } } });
1012 let d = serde_json::from_value::<Document>(json.clone()).unwrap();
1013 assert_eq!(d.get_datetime("d").unwrap(), &DateTime::MAX);
1014 let d: Bson = json.try_into().unwrap();
1015 assert_eq!(
1016 d.as_document().unwrap().get_datetime("d").unwrap(),
1017 &DateTime::MAX
1018 );
1019
1020 let json = json!({ "d": { "$date": { "$numberLong": i64::MIN.to_string() } } });
1021 let d = serde_json::from_value::<Document>(json.clone()).unwrap();
1022 assert_eq!(d.get_datetime("d").unwrap(), &DateTime::MIN);
1023 let d: Bson = json.try_into().unwrap();
1024 assert_eq!(
1025 d.as_document().unwrap().get_datetime("d").unwrap(),
1026 &DateTime::MIN
1027 );
1028 }
1029
1030 #[test]
1031 fn oid_as_hex_string() {
1032 let _guard = LOCK.run_concurrently();
1033
1034 #[derive(Serialize)]
1035 struct Foo {
1036 #[serde(serialize_with = "serialize_object_id_as_hex_string")]
1037 oid: ObjectId,
1038 }
1039
1040 let oid = ObjectId::new();
1041 let foo = Foo { oid };
1042 let doc = to_document(&foo).unwrap();
1043 assert_eq!(doc.get_str("oid").unwrap(), oid.to_hex());
1044 }
1045
1046 #[test]
1047 fn fuzz_regression_00() {
1048 let buf: &[u8] = &[227, 0, 35, 4, 2, 0, 255, 255, 255, 127, 255, 255, 255, 47];
1049 let _ = crate::from_slice::<Document>(buf);
1050 }