clawspec_core/
yaml.rs

1//! YAML serialization support using serde-saphyr.
2//!
3//! This module provides YAML serialization capabilities for OpenAPI specifications
4//! and split results. It is only available when the `yaml` feature is enabled.
5//!
6//! # Example
7//!
8//! ```rust,ignore
9//! use clawspec_core::{ApiClient, ToYaml};
10//!
11//! let mut client = ApiClient::builder()
12//!     .with_host("api.example.com")
13//!     .build()?;
14//!
15//! // ... make API calls ...
16//!
17//! let spec = client.collected_openapi().await;
18//! let yaml_string = spec.to_yaml()?;
19//!
20//! std::fs::write("openapi.yml", yaml_string)?;
21//! ```
22
23use serde::Serialize;
24
25/// Error type for YAML serialization operations.
26pub type YamlError = serde_saphyr::ser_error::Error;
27
28/// Extension trait for serializing types to YAML.
29///
30/// This trait is implemented for all types that implement [`Serialize`].
31/// It provides a convenient `to_yaml()` method for generating YAML strings.
32///
33/// # Example
34///
35/// ```rust,ignore
36/// use clawspec_core::ToYaml;
37/// use utoipa::openapi::OpenApi;
38///
39/// let spec: OpenApi = /* ... */;
40/// let yaml = spec.to_yaml()?;
41/// println!("{yaml}");
42/// ```
43pub trait ToYaml: Serialize + Sized {
44    /// Serializes this value to a YAML string.
45    ///
46    /// # Errors
47    ///
48    /// Returns a [`YamlError`] if serialization fails.
49    fn to_yaml(&self) -> Result<String, YamlError> {
50        serde_saphyr::to_string(self)
51    }
52}
53
54impl<T: Serialize + Sized> ToYaml for T {}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use insta::assert_snapshot;
60    use utoipa::openapi::{InfoBuilder, OpenApiBuilder};
61
62    #[test]
63    fn should_serialize_openapi_to_yaml() {
64        let spec = OpenApiBuilder::new()
65            .info(
66                InfoBuilder::new()
67                    .title("Test API")
68                    .version("1.0.0")
69                    .build(),
70            )
71            .build();
72
73        let yaml = spec.to_yaml().expect("should serialize to YAML");
74
75        assert_snapshot!(yaml, @r"
76        openapi: 3.1.0
77        info:
78          title: Test API
79          version: 1.0.0
80        paths: {}
81        ");
82    }
83
84    #[test]
85    fn should_serialize_simple_struct_to_yaml() {
86        #[derive(Serialize)]
87        struct Config {
88            name: String,
89            version: u32,
90        }
91
92        let config = Config {
93            name: "test".to_string(),
94            version: 1,
95        };
96
97        let yaml = config.to_yaml().expect("should serialize to YAML");
98
99        assert_snapshot!(yaml, @r"
100        name: test
101        version: 1
102        ");
103    }
104}