1use serde::Serialize;
15
16use crate::{
17 assertion::{Assertion, AssertionBase, AssertionData, AssertionDecodeError},
18 error::{Error, Result},
19};
20
21#[derive(Debug, Default, Serialize)]
23pub struct User {
24 label: String,
25 data: String,
26}
27
28impl User {
29 pub fn new(label: &str, data: &str) -> User {
31 User {
32 label: label.to_owned(),
33 data: data.to_owned(),
34 }
35 }
36}
37
38impl AssertionBase for User {
39 fn label(&self) -> &str {
41 &self.label
42 }
43
44 fn to_assertion(&self) -> Result<Assertion> {
45 let _json_value: serde_json::Value = serde_json::from_str(&self.data)
47 .map_err(|err| Error::AssertionEncoding(err.to_string()))?;
48 let data = AssertionData::Json(self.data.to_owned());
50 Ok(Assertion::new(&self.label, None, data).set_content_type("application/json"))
51 }
52
53 fn from_assertion(assertion: &Assertion) -> Result<Self> {
54 match assertion.decode_data() {
55 AssertionData::Json(data) => {
56 let _value: serde_json::Value = serde_json::from_str(data).map_err(|e| {
58 Error::AssertionDecoding(AssertionDecodeError::from_assertion_and_json_err(
59 assertion, e,
60 ))
61 })?;
62
63 Ok(User::new(&assertion.label(), data))
64 }
65 ad => Err(AssertionDecodeError::from_assertion_unexpected_data_type(
66 assertion, ad, "json",
67 )
68 .into()),
69 }
70 }
71}
72
73#[cfg(test)]
74pub mod tests {
75 #![allow(clippy::expect_used)]
76 #![allow(clippy::unwrap_used)]
77
78 use super::*;
79 const LABEL: &str = "user_test_assertion";
80 const DATA: &str = r#"{ "l1":"some data", "l2":"some other data" }"#;
81 const INVALID_JSON: &str = "={this isn't valid{";
82
83 #[test]
84 fn assertion_user() {
85 let original = User::new(LABEL, DATA);
86 let assertion = original.to_assertion().expect("build_assertion");
87 assert_eq!(assertion.mime_type(), "application/json");
88 assert_eq!(assertion.label(), LABEL);
89 let result = User::from_assertion(&assertion).expect("from_assertion");
90 assert_eq!(original.data, result.data);
91 }
92
93 #[test]
94 fn assertion_user_invalid_json_to() {
95 let original = User::new(LABEL, INVALID_JSON);
96 original
97 .to_assertion()
98 .expect_err("Assertion encoding error expected");
99 }
100
101 #[test]
102 fn assertion_user_invalid_json_from() {
103 let data = AssertionData::Json(INVALID_JSON.to_owned());
104 let assertion = Assertion::new(LABEL, None, data);
105 let _result =
106 User::from_assertion(&assertion).expect_err("Assertion decoding error expected");
107 }
108}