Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing enum variant examples #538

Merged
merged 2 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions utoipa-gen/src/component/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use syn::{
Token, Variant, Visibility,
};

use crate::{component::features::Rename, doc_comment::CommentAttributes, Array};
use crate::{component::features::{Rename, Example}, doc_comment::CommentAttributes, Array};

use self::{
enum_variant::{
Expand Down Expand Up @@ -151,6 +151,7 @@ impl ToTokens for Schema<'_> {
}
}

#[cfg_attr(feature = "debug", derive(Debug))]
enum SchemaVariant<'a> {
Named(NamedStructSchema<'a>),
Unnamed(UnnamedStructSchema<'a>),
Expand Down Expand Up @@ -236,6 +237,7 @@ impl ToTokens for SchemaVariant<'_> {
}
}

#[cfg_attr(feature = "debug", derive(Debug))]
struct UnitStructVariant;

impl ToTokens for UnitStructVariant {
Expand Down Expand Up @@ -934,9 +936,12 @@ impl ComplexEnum<'_> {
rename_all,
);

let example = pop_feature!(named_struct_features => Feature::Example(_));

self::enum_variant::Variant::to_tokens(&ObjectVariant {
name: variant_name.unwrap_or(Cow::Borrowed(&name)),
title: title_features.first().map(ToTokens::to_token_stream),
example: example.as_ref().map(ToTokens::to_token_stream),
item: NamedStructSchema {
struct_name: Cow::Borrowed(&*self.enum_name),
attributes: &variant.attrs,
Expand Down Expand Up @@ -964,9 +969,12 @@ impl ComplexEnum<'_> {
rename_all,
);

let example = pop_feature!(unnamed_struct_features => Feature::Example(_));

self::enum_variant::Variant::to_tokens(&ObjectVariant {
name: variant_name.unwrap_or(Cow::Borrowed(&name)),
title: title_features.first().map(ToTokens::to_token_stream),
example: example.as_ref().map(ToTokens::to_token_stream),
item: UnnamedStructSchema {
struct_name: Cow::Borrowed(&*self.enum_name),
attributes: &variant.attrs,
Expand All @@ -982,7 +990,8 @@ impl ComplexEnum<'_> {
Ok(parse_features!(
input as super::features::Title,
RenameAll,
Rename
Rename,
Example
))
})
.unwrap_or_default();
Expand All @@ -995,13 +1004,16 @@ impl ComplexEnum<'_> {
rename_all,
);

let example = pop_feature!(unit_features => Feature::Example(_));

// Unit variant is just simple enum with single variant.
Enum::new([SimpleEnumVariant {
value: variant_name
.unwrap_or(Cow::Borrowed(&name))
.to_token_stream(),
}])
.with_title(title.as_ref().map(ToTokens::to_token_stream))
.with_example(example.as_ref().map(ToTokens::to_token_stream))
.to_token_stream()
}
}
Expand Down
13 changes: 13 additions & 0 deletions utoipa-gen/src/component/schema/enum_variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ where
pub struct ObjectVariant<'o, T: ToTokens> {
pub item: T,
pub title: Option<TokenStream>,
pub example: Option<TokenStream>,
pub name: Cow<'o, str>,
}

Expand All @@ -67,12 +68,14 @@ where
{
fn to_tokens(&self) -> TokenStream {
let title = &self.title;
let example = &self.example;
let variant = &self.item;
let name = &self.name;

quote! {
utoipa::openapi::schema::ObjectBuilder::new()
#title
#example
.property(#name, #variant)
.required(#name)
}
Expand All @@ -81,6 +84,7 @@ where

pub struct Enum<'e, V: Variant> {
title: Option<TokenStream>,
example: Option<TokenStream>,
len: usize,
items: Array<'e, TokenStream>,
schema_type: TokenStream,
Expand All @@ -98,6 +102,12 @@ impl<V: Variant> Enum<'_, V> {

self
}

pub fn with_example<I: Into<TokenStream>>(mut self, example: Option<I>) -> Self {
self.example = example.map(|example| example.into());

self
}
}

impl<T> ToTokens for Enum<'_, T>
Expand All @@ -107,13 +117,15 @@ where
fn to_tokens(&self, tokens: &mut TokenStream) {
let len = &self.len;
let title = &self.title;
let example = &self.example;
let items = &self.items;
let schema_type = &self.schema_type;
let enum_type = &self.enum_type;

tokens.extend(quote! {
utoipa::openapi::ObjectBuilder::new()
#title
#example
.schema_type(#schema_type)
.enum_values::<[#enum_type; #len], #enum_type>(Some(#items))
})
Expand All @@ -140,6 +152,7 @@ impl<V: Variant> FromIterator<V> for Enum<'_, V> {

Self {
title: None,
example: None,
len,
items,
schema_type,
Expand Down
65 changes: 65 additions & 0 deletions utoipa-gen/tests/schema_derive_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1339,6 +1339,71 @@ fn derive_complex_enum_title() {
);
}

#[test]
fn derive_complex_enum_example() {
#[derive(Serialize)]
struct Foo(String);

let value: Value = api_doc! {
#[derive(Serialize)]
enum EnumWithExample {
#[schema(example = "EX: Unit")]
UnitValue,
#[schema(example = "EX: Named")]
NamedFields {
#[schema(example = "EX: Named id field")]
id: &'static str,
},
#[schema(example = "EX: Unnamed")]
UnnamedFields(Foo),
}
};

assert_json_eq!(
value,
json!({
"oneOf": [
{
"type": "string",
"example": "EX: Unit",
"enum": [
"UnitValue",
],
},
{
"type": "object",
"example": "EX: Named",
"properties": {
"NamedFields": {
"type": "object",
"properties": {
"id": {
"type": "string",
"example": "EX: Named id field",
},
},
"required": [
"id",
],
},
},
"required": ["NamedFields"]
},
{
"type": "object",
"example": "EX: Unnamed",
"properties": {
"UnnamedFields": {
"$ref": "#/components/schemas/Foo",
},
},
"required": ["UnnamedFields"]
},
],
})
);
}

#[test]
fn derive_complex_enum_serde_rename_all() {
#[derive(Serialize)]
Expand Down