oparl-types 0.7.1

Type definitions for the OParl protocol
Documentation
// SPDX-FileCopyrightText: Politik im Blick developers
// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
//
// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2

#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    derive_more::AsRef,
    derive_more::Display,
    derive_more::From,
    derive_more::FromStr,
    derive_more::Into,
    serde::Serialize,
    serde::Deserialize,
)]
#[cfg_attr(feature = "sea-orm", derive(sea_orm::DeriveValueType))]
pub struct BodyClassification(String);

impl From<&str> for BodyClassification {
    fn from(value: &str) -> Self {
        Self(value.into())
    }
}

impl BodyClassification {
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

#[cfg(feature = "sea-orm")]
mod sea_orm_impls {
    use sea_orm::{ActiveValue, IntoActiveValue};

    use super::BodyClassification;

    impl IntoActiveValue<BodyClassification> for BodyClassification {
        fn into_active_value(self) -> ActiveValue<BodyClassification> {
            ActiveValue::Set(self)
        }
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::BodyClassification;

    #[test]
    fn from_str() {
        assert_eq!(
            BodyClassification("Beispiel-System".to_string()),
            "Beispiel-System"
                .parse()
                .expect("value must be a parseable name")
        );
    }
}

#[cfg(test)]
mod serde_tests {
    use pretty_assertions::assert_eq;
    use serde_json::json;

    use super::BodyClassification;

    #[test]
    fn serialize() {
        assert_eq!(
            json!(BodyClassification("Kreisfreie Stadt".to_string())),
            json!("Kreisfreie Stadt")
        );
    }

    #[test]
    fn deserialize_good() {
        let deserialized: BodyClassification = serde_json::from_value(json!("Kreisfreie Stadt"))
            .expect("value must be deserializable as BodyClassification");
        assert_eq!(deserialized, BodyClassification::from("Kreisfreie Stadt"));
    }

    #[test]
    fn deserialize_bad() {
        assert!(serde_json::from_value::<BodyClassification>(json!([])).is_err());
        assert!(serde_json::from_value::<BodyClassification>(json!({})).is_err());
        assert!(serde_json::from_value::<BodyClassification>(json!(true)).is_err());
        assert!(serde_json::from_value::<BodyClassification>(json!(123)).is_err());
    }
}