Debian Codegraph @

debian/missing-sources/time/tests/integration/serde/error_conditions.rs

raw
1 use serde::{Deserialize, Serialize, Serializer};
2 use serde_test::{assert_ser_tokens_error, Token};
3 use time::macros::{datetime, format_description};
4 use time::{error, OffsetDateTime};
5
6 /// Trigger `time::error::Format::StdIo` errors.
7 ///
8 /// `StdIo` won't be reached during normal serde operation: it's instantiated
9 /// only during calls to `format_into()`, but most `Serializable`
10 /// implementations will only call `format()` because serde `Serializer`
11 /// interface doesn't expose the underlying `io::Write`.
12 ///
13 /// Therefore, we need a contrived serializer to trigger coverage.
14 fn serialize<S: Serializer>(datetime: &OffsetDateTime, _serializer: S) -> Result<S::Ok, S::Error> {
15 Err(datetime
16 .format_into(
17 &mut [0u8; 0].as_mut_slice(),
18 format_description!("nonempty format description"),
19 )
20 .map_err(error::Format::into_invalid_serde_value::<S>)
21 .expect_err("Writing to a zero-length buffer should always error."))
22 }
23
24 #[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
25 struct TestBadIo {
26 #[serde(serialize_with = "serialize")]
27 dt: OffsetDateTime,
28 }
29
30 #[test]
31 fn custom_serialize_io_error() {
32 let value = TestBadIo {
33 dt: datetime!(2000-01-01 00:00 -4:00),
34 };
35 assert_ser_tokens_error::<TestBadIo>(
36 &value,
37 &[
38 Token::Struct {
39 name: "TestBadIo",
40 len: 1,
41 },
42 Token::Str("dt"),
43 ],
44 "failed to write whole buffer",
45 );
46 }