use crate::common::helpers::{Context, ValidateWithContext, validate_required_string};
use crate::v2::external_documentation::ExternalDocumentation;
use crate::v2::spec::Spec;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct Tag {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_docs: Option<ExternalDocumentation>,
#[serde(flatten)]
#[serde(with = "crate::common::extensions")]
#[serde(skip_serializing_if = "Option::is_none")]
pub extensions: Option<BTreeMap<String, serde_json::Value>>,
}
impl ValidateWithContext<Spec> for Tag {
fn validate_with_context(&self, ctx: &mut Context<Spec>, path: String) {
validate_required_string(&self.name, ctx, format!("{path}.name"));
if let Some(doc) = &self.external_docs {
doc.validate_with_context(ctx, format!("{path}.externalDocs"));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize() {
assert_eq!(
serde_json::from_value::<Tag>(serde_json::json!({
"name": "pet",
"description": "Pets operations",
}))
.unwrap(),
Tag {
name: String::from("pet"),
description: Some(String::from("Pets operations")),
..Default::default()
},
"deserialize",
);
}
#[test]
fn serialize() {
assert_eq!(
serde_json::to_value(Tag {
name: String::from("pet"),
description: Some(String::from("Pets operations")),
..Default::default()
})
.unwrap(),
serde_json::json!({
"name": "pet",
"description":"Pets operations",
}),
"serialize",
);
}
#[test]
fn validate() {
let spec = Spec::default();
let mut ctx = Context::new(&spec, Default::default());
Tag {
name: String::from("pet"),
description: Some(String::from("Pets operations")),
external_docs: Some(ExternalDocumentation {
description: Some(String::from("Find more info here")),
url: String::from("https://example.com/about"),
..Default::default()
}),
..Default::default()
}
.validate_with_context(&mut ctx, String::from("tag"));
assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);
Tag {
name: String::from("pet"),
description: Some(String::from("Pets operations")),
..Default::default()
}
.validate_with_context(&mut ctx, String::from("tag"));
assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);
Tag {
name: String::from("pet"),
..Default::default()
}
.validate_with_context(&mut ctx, String::from("tag"));
assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);
Tag {
..Default::default()
}
.validate_with_context(&mut ctx, String::from("tag"));
assert_eq!(
ctx.errors,
vec!["tag.name: must not be empty"],
"name error: {:?}",
ctx.errors
);
}
}