apache_avro_derive/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18mod case;
19use case::RenameRule;
20use darling::FromAttributes;
21use proc_macro2::{Span, TokenStream};
22use quote::quote;
23
24use syn::{
25    AttrStyle, Attribute, DeriveInput, Ident, Meta, Type, TypePath, parse_macro_input,
26    spanned::Spanned,
27};
28
29#[derive(darling::FromAttributes)]
30#[darling(attributes(avro))]
31struct FieldOptions {
32    #[darling(default)]
33    doc: Option<String>,
34    #[darling(default)]
35    default: Option<String>,
36    #[darling(multiple)]
37    alias: Vec<String>,
38    #[darling(default)]
39    rename: Option<String>,
40    #[darling(default)]
41    skip: Option<bool>,
42}
43
44#[derive(darling::FromAttributes)]
45#[darling(attributes(avro))]
46struct VariantOptions {
47    #[darling(default)]
48    rename: Option<String>,
49}
50
51#[derive(darling::FromAttributes)]
52#[darling(attributes(avro))]
53struct NamedTypeOptions {
54    #[darling(default)]
55    namespace: Option<String>,
56    #[darling(default)]
57    doc: Option<String>,
58    #[darling(multiple)]
59    alias: Vec<String>,
60    #[darling(default)]
61    rename_all: Option<String>,
62}
63
64#[proc_macro_derive(AvroSchema, attributes(avro))]
65// Templated from Serde
66pub fn proc_macro_derive_avro_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
67    let mut input = parse_macro_input!(input as DeriveInput);
68    derive_avro_schema(&mut input)
69        .unwrap_or_else(to_compile_errors)
70        .into()
71}
72
73fn derive_avro_schema(input: &mut DeriveInput) -> Result<TokenStream, Vec<syn::Error>> {
74    let named_type_options =
75        NamedTypeOptions::from_attributes(&input.attrs[..]).map_err(darling_to_syn)?;
76
77    let rename_all = parse_case(named_type_options.rename_all.as_deref(), input.span())?;
78
79    let full_schema_name = vec![named_type_options.namespace, Some(input.ident.to_string())]
80        .into_iter()
81        .flatten()
82        .collect::<Vec<String>>()
83        .join(".");
84    let schema_def = match &input.data {
85        syn::Data::Struct(s) => get_data_struct_schema_def(
86            &full_schema_name,
87            named_type_options
88                .doc
89                .or_else(|| extract_outer_doc(&input.attrs)),
90            named_type_options.alias,
91            rename_all,
92            s,
93            input.ident.span(),
94        )?,
95        syn::Data::Enum(e) => get_data_enum_schema_def(
96            &full_schema_name,
97            named_type_options
98                .doc
99                .or_else(|| extract_outer_doc(&input.attrs)),
100            named_type_options.alias,
101            rename_all,
102            e,
103            input.ident.span(),
104        )?,
105        _ => {
106            return Err(vec![syn::Error::new(
107                input.ident.span(),
108                "AvroSchema derive only works for structs and simple enums ",
109            )]);
110        }
111    };
112    let ident = &input.ident;
113    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
114    Ok(quote! {
115        #[automatically_derived]
116        impl #impl_generics apache_avro::schema::derive::AvroSchemaComponent for #ident #ty_generics #where_clause {
117            fn get_schema_in_ctxt(named_schemas: &mut std::collections::HashMap<apache_avro::schema::Name, apache_avro::schema::Schema>, enclosing_namespace: &Option<String>) -> apache_avro::schema::Schema {
118                let name =  apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to parse schema name {}", #full_schema_name)[..]).fully_qualified_name(enclosing_namespace);
119                let enclosing_namespace = &name.namespace;
120                if named_schemas.contains_key(&name) {
121                    apache_avro::schema::Schema::Ref{name: name.clone()}
122                } else {
123                    named_schemas.insert(name.clone(), apache_avro::schema::Schema::Ref{name: name.clone()});
124                    #schema_def
125                }
126            }
127        }
128    })
129}
130
131fn get_data_struct_schema_def(
132    full_schema_name: &str,
133    record_doc: Option<String>,
134    aliases: Vec<String>,
135    rename_all: RenameRule,
136    s: &syn::DataStruct,
137    error_span: Span,
138) -> Result<TokenStream, Vec<syn::Error>> {
139    let mut record_field_exprs = vec![];
140    match s.fields {
141        syn::Fields::Named(ref a) => {
142            let mut index: usize = 0;
143            for field in a.named.iter() {
144                let mut name = field.ident.as_ref().unwrap().to_string(); // we know everything has a name
145                if let Some(raw_name) = name.strip_prefix("r#") {
146                    name = raw_name.to_string();
147                }
148                let field_attrs =
149                    FieldOptions::from_attributes(&field.attrs[..]).map_err(darling_to_syn)?;
150                let doc =
151                    preserve_optional(field_attrs.doc.or_else(|| extract_outer_doc(&field.attrs)));
152                match (field_attrs.rename, rename_all) {
153                    (Some(rename), _) => {
154                        name = rename;
155                    }
156                    (None, rename_all) if !matches!(rename_all, RenameRule::None) => {
157                        name = rename_all.apply_to_field(&name);
158                    }
159                    _ => {}
160                }
161                if let Some(true) = field_attrs.skip {
162                    continue;
163                }
164                let default_value = match field_attrs.default {
165                    Some(default_value) => {
166                        let _: serde_json::Value = serde_json::from_str(&default_value[..])
167                            .map_err(|e| {
168                                vec![syn::Error::new(
169                                    field.ident.span(),
170                                    format!("Invalid avro default json: \n{e}"),
171                                )]
172                            })?;
173                        quote! {
174                            Some(serde_json::from_str(#default_value).expect(format!("Invalid JSON: {:?}", #default_value).as_str()))
175                        }
176                    }
177                    None => quote! { None },
178                };
179                let aliases = preserve_vec(field_attrs.alias);
180                let schema_expr = type_to_schema_expr(&field.ty)?;
181                let position = index;
182                record_field_exprs.push(quote! {
183                    apache_avro::schema::RecordField {
184                            name: #name.to_string(),
185                            doc: #doc,
186                            default: #default_value,
187                            aliases: #aliases,
188                            schema: #schema_expr,
189                            order: apache_avro::schema::RecordFieldOrder::Ascending,
190                            position: #position,
191                            custom_attributes: Default::default(),
192                        }
193                });
194                index += 1;
195            }
196        }
197        syn::Fields::Unnamed(_) => {
198            return Err(vec![syn::Error::new(
199                error_span,
200                "AvroSchema derive does not work for tuple structs",
201            )]);
202        }
203        syn::Fields::Unit => {
204            return Err(vec![syn::Error::new(
205                error_span,
206                "AvroSchema derive does not work for unit structs",
207            )]);
208        }
209    }
210    let record_doc = preserve_optional(record_doc);
211    let record_aliases = preserve_vec(aliases);
212    Ok(quote! {
213        let schema_fields = vec![#(#record_field_exprs),*];
214        let name = apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to parse struct name for schema {}", #full_schema_name)[..]);
215        let lookup: std::collections::BTreeMap<String, usize> = schema_fields
216            .iter()
217            .map(|field| (field.name.to_owned(), field.position))
218            .collect();
219        apache_avro::schema::Schema::Record(apache_avro::schema::RecordSchema {
220            name,
221            aliases: #record_aliases,
222            doc: #record_doc,
223            fields: schema_fields,
224            lookup,
225            attributes: Default::default(),
226        })
227    })
228}
229
230fn get_data_enum_schema_def(
231    full_schema_name: &str,
232    doc: Option<String>,
233    aliases: Vec<String>,
234    rename_all: RenameRule,
235    e: &syn::DataEnum,
236    error_span: Span,
237) -> Result<TokenStream, Vec<syn::Error>> {
238    let doc = preserve_optional(doc);
239    let enum_aliases = preserve_vec(aliases);
240    if e.variants.iter().all(|v| syn::Fields::Unit == v.fields) {
241        let default_value = default_enum_variant(e, error_span)?;
242        let default = preserve_optional(default_value);
243        let mut symbols = Vec::new();
244        for variant in &e.variants {
245            let field_attrs =
246                VariantOptions::from_attributes(&variant.attrs[..]).map_err(darling_to_syn)?;
247            let name = match (field_attrs.rename, rename_all) {
248                (Some(rename), _) => rename,
249                (None, rename_all) if !matches!(rename_all, RenameRule::None) => {
250                    rename_all.apply_to_variant(&variant.ident.to_string())
251                }
252                _ => variant.ident.to_string(),
253            };
254            symbols.push(name);
255        }
256        Ok(quote! {
257            apache_avro::schema::Schema::Enum(apache_avro::schema::EnumSchema {
258                name: apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to parse enum name for schema {}", #full_schema_name)[..]),
259                aliases: #enum_aliases,
260                doc: #doc,
261                symbols: vec![#(#symbols.to_owned()),*],
262                default: #default,
263                attributes: Default::default(),
264            })
265        })
266    } else {
267        Err(vec![syn::Error::new(
268            error_span,
269            "AvroSchema derive does not work for enums with non unit structs",
270        )])
271    }
272}
273
274/// Takes in the Tokens of a type and returns the tokens of an expression with return type `Schema`
275fn type_to_schema_expr(ty: &Type) -> Result<TokenStream, Vec<syn::Error>> {
276    if let Type::Path(p) = ty {
277        let type_string = p.path.segments.last().unwrap().ident.to_string();
278
279        let schema = match &type_string[..] {
280            "bool" => quote! {apache_avro::schema::Schema::Boolean},
281            "i8" | "i16" | "i32" | "u8" | "u16" => quote! {apache_avro::schema::Schema::Int},
282            "u32" | "i64" => quote! {apache_avro::schema::Schema::Long},
283            "f32" => quote! {apache_avro::schema::Schema::Float},
284            "f64" => quote! {apache_avro::schema::Schema::Double},
285            "String" | "str" => quote! {apache_avro::schema::Schema::String},
286            "char" => {
287                return Err(vec![syn::Error::new_spanned(
288                    ty,
289                    "AvroSchema: Cannot guarantee successful deserialization of this type",
290                )]);
291            }
292            "u64" => {
293                return Err(vec![syn::Error::new_spanned(
294                    ty,
295                    "Cannot guarantee successful serialization of this type due to overflow concerns",
296                )]);
297            } // Can't guarantee serialization type
298            _ => {
299                // Fails when the type does not implement AvroSchemaComponent directly
300                // TODO check and error report with something like https://docs.rs/quote/1.0.15/quote/macro.quote_spanned.html#example
301                type_path_schema_expr(p)
302            }
303        };
304        Ok(schema)
305    } else if let Type::Array(ta) = ty {
306        let inner_schema_expr = type_to_schema_expr(&ta.elem)?;
307        Ok(quote! {apache_avro::schema::Schema::array(#inner_schema_expr)})
308    } else if let Type::Reference(tr) = ty {
309        type_to_schema_expr(&tr.elem)
310    } else {
311        Err(vec![syn::Error::new_spanned(
312            ty,
313            format!("Unable to generate schema for type: {ty:?}"),
314        )])
315    }
316}
317
318fn default_enum_variant(
319    data_enum: &syn::DataEnum,
320    error_span: Span,
321) -> Result<Option<String>, Vec<syn::Error>> {
322    match data_enum
323        .variants
324        .iter()
325        .filter(|v| v.attrs.iter().any(is_default_attr))
326        .collect::<Vec<_>>()
327    {
328        variants if variants.is_empty() => Ok(None),
329        single if single.len() == 1 => Ok(Some(single[0].ident.to_string())),
330        multiple => Err(vec![syn::Error::new(
331            error_span,
332            format!(
333                "Multiple defaults defined: {:?}",
334                multiple
335                    .iter()
336                    .map(|v| v.ident.to_string())
337                    .collect::<Vec<String>>()
338            ),
339        )]),
340    }
341}
342
343fn is_default_attr(attr: &Attribute) -> bool {
344    matches!(attr, Attribute { meta: Meta::Path(path), .. } if path.get_ident().map(Ident::to_string).as_deref() == Some("default"))
345}
346
347/// Generates the schema def expression for fully qualified type paths using the associated function
348/// - `A -> <A as apache_avro::schema::derive::AvroSchemaComponent>::get_schema_in_ctxt()`
349/// - `A<T> -> <A<T> as apache_avro::schema::derive::AvroSchemaComponent>::get_schema_in_ctxt()`
350fn type_path_schema_expr(p: &TypePath) -> TokenStream {
351    quote! {<#p as apache_avro::schema::derive::AvroSchemaComponent>::get_schema_in_ctxt(named_schemas, enclosing_namespace)}
352}
353
354/// Stolen from serde
355fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {
356    let compile_errors = errors.iter().map(syn::Error::to_compile_error);
357    quote!(#(#compile_errors)*)
358}
359
360fn extract_outer_doc(attributes: &[Attribute]) -> Option<String> {
361    let doc = attributes
362        .iter()
363        .filter(|attr| attr.style == AttrStyle::Outer && attr.path().is_ident("doc"))
364        .filter_map(|attr| {
365            let name_value = attr.meta.require_name_value();
366            match name_value {
367                Ok(name_value) => match &name_value.value {
368                    syn::Expr::Lit(expr_lit) => match expr_lit.lit {
369                        syn::Lit::Str(ref lit_str) => Some(lit_str.value().trim().to_string()),
370                        _ => None,
371                    },
372                    _ => None,
373                },
374                Err(_) => None,
375            }
376        })
377        .collect::<Vec<String>>()
378        .join("\n");
379    if doc.is_empty() { None } else { Some(doc) }
380}
381
382fn preserve_optional(op: Option<impl quote::ToTokens>) -> TokenStream {
383    match op {
384        Some(tt) => quote! {Some(#tt.into())},
385        None => quote! {None},
386    }
387}
388
389fn preserve_vec(op: Vec<impl quote::ToTokens>) -> TokenStream {
390    let items: Vec<TokenStream> = op.iter().map(|tt| quote! {#tt.into()}).collect();
391    if items.is_empty() {
392        quote! {None}
393    } else {
394        quote! {Some(vec![#(#items),*])}
395    }
396}
397
398fn darling_to_syn(e: darling::Error) -> Vec<syn::Error> {
399    let msg = format!("{e}");
400    let token_errors = e.write_errors();
401    vec![syn::Error::new(token_errors.span(), msg)]
402}
403
404fn parse_case(case: Option<&str>, span: Span) -> Result<RenameRule, Vec<syn::Error>> {
405    match case {
406        None => Ok(RenameRule::None),
407        Some(case) => {
408            Ok(RenameRule::from_str(case)
409                .map_err(|e| vec![syn::Error::new(span, e.to_string())])?)
410        }
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    #[test]
418    fn basic_case() {
419        let test_struct = quote! {
420            struct A {
421                a: i32,
422                b: String
423            }
424        };
425
426        match syn::parse2::<DeriveInput>(test_struct) {
427            Ok(mut input) => {
428                assert!(derive_avro_schema(&mut input).is_ok())
429            }
430            Err(error) => panic!(
431                "Failed to parse as derive input when it should be able to. Error: {error:?}"
432            ),
433        };
434    }
435
436    #[test]
437    fn tuple_struct_unsupported() {
438        let test_tuple_struct = quote! {
439            struct B (i32, String);
440        };
441
442        match syn::parse2::<DeriveInput>(test_tuple_struct) {
443            Ok(mut input) => {
444                assert!(derive_avro_schema(&mut input).is_err())
445            }
446            Err(error) => panic!(
447                "Failed to parse as derive input when it should be able to. Error: {error:?}"
448            ),
449        };
450    }
451
452    #[test]
453    fn unit_struct_unsupported() {
454        let test_tuple_struct = quote! {
455            struct AbsoluteUnit;
456        };
457
458        match syn::parse2::<DeriveInput>(test_tuple_struct) {
459            Ok(mut input) => {
460                assert!(derive_avro_schema(&mut input).is_err())
461            }
462            Err(error) => panic!(
463                "Failed to parse as derive input when it should be able to. Error: {error:?}"
464            ),
465        };
466    }
467
468    #[test]
469    fn struct_with_optional() {
470        let struct_with_optional = quote! {
471            struct Test4 {
472                a : Option<i32>
473            }
474        };
475        match syn::parse2::<DeriveInput>(struct_with_optional) {
476            Ok(mut input) => {
477                assert!(derive_avro_schema(&mut input).is_ok())
478            }
479            Err(error) => panic!(
480                "Failed to parse as derive input when it should be able to. Error: {error:?}"
481            ),
482        };
483    }
484
485    #[test]
486    fn test_basic_enum() {
487        let basic_enum = quote! {
488            enum Basic {
489                A,
490                B,
491                C,
492                D
493            }
494        };
495        match syn::parse2::<DeriveInput>(basic_enum) {
496            Ok(mut input) => {
497                assert!(derive_avro_schema(&mut input).is_ok())
498            }
499            Err(error) => panic!(
500                "Failed to parse as derive input when it should be able to. Error: {error:?}"
501            ),
502        };
503    }
504
505    #[test]
506    fn avro_3687_basic_enum_with_default() {
507        let basic_enum = quote! {
508            enum Basic {
509                #[default]
510                A,
511                B,
512                C,
513                D
514            }
515        };
516        match syn::parse2::<DeriveInput>(basic_enum) {
517            Ok(mut input) => {
518                let derived = derive_avro_schema(&mut input);
519                assert!(derived.is_ok());
520                assert_eq!(derived.unwrap().to_string(), quote! {
521                    #[automatically_derived]
522                    impl apache_avro::schema::derive::AvroSchemaComponent for Basic {
523                        fn get_schema_in_ctxt(
524                            named_schemas: &mut std::collections::HashMap<
525                                apache_avro::schema::Name,
526                                apache_avro::schema::Schema
527                            >,
528                            enclosing_namespace: &Option<String>
529                        ) -> apache_avro::schema::Schema {
530                            let name = apache_avro::schema::Name::new("Basic")
531                                .expect(&format!("Unable to parse schema name {}", "Basic")[..])
532                                .fully_qualified_name(enclosing_namespace);
533                            let enclosing_namespace = &name.namespace;
534                            if named_schemas.contains_key(&name) {
535                                apache_avro::schema::Schema::Ref { name: name.clone() }
536                            } else {
537                                named_schemas.insert(
538                                    name.clone(),
539                                    apache_avro::schema::Schema::Ref { name: name.clone() }
540                                );
541                                apache_avro::schema::Schema::Enum(apache_avro::schema::EnumSchema {
542                                    name: apache_avro::schema::Name::new("Basic").expect(
543                                        &format!("Unable to parse enum name for schema {}", "Basic")[..]
544                                    ),
545                                    aliases: None,
546                                    doc: None,
547                                    symbols: vec![
548                                        "A".to_owned(),
549                                        "B".to_owned(),
550                                        "C".to_owned(),
551                                        "D".to_owned()
552                                    ],
553                                    default: Some("A".into()),
554                                    attributes: Default::default(),
555                                })
556                            }
557                        }
558                    }
559                }.to_string());
560            }
561            Err(error) => panic!(
562                "Failed to parse as derive input when it should be able to. Error: {error:?}"
563            ),
564        };
565    }
566
567    #[test]
568    fn avro_3687_basic_enum_with_default_twice() {
569        let non_basic_enum = quote! {
570            enum Basic {
571                #[default]
572                A,
573                B,
574                #[default]
575                C,
576                D
577            }
578        };
579        match syn::parse2::<DeriveInput>(non_basic_enum) {
580            Ok(mut input) => match derive_avro_schema(&mut input) {
581                Ok(_) => {
582                    panic!("Should not be able to derive schema for enum with multiple defaults")
583                }
584                Err(errors) => {
585                    assert_eq!(errors.len(), 1);
586                    assert_eq!(
587                        errors[0].to_string(),
588                        r#"Multiple defaults defined: ["A", "C"]"#
589                    );
590                }
591            },
592            Err(error) => panic!(
593                "Failed to parse as derive input when it should be able to. Error: {error:?}"
594            ),
595        };
596    }
597
598    #[test]
599    fn test_non_basic_enum() {
600        let non_basic_enum = quote! {
601            enum Basic {
602                A(i32),
603                B,
604                C,
605                D
606            }
607        };
608        match syn::parse2::<DeriveInput>(non_basic_enum) {
609            Ok(mut input) => {
610                assert!(derive_avro_schema(&mut input).is_err())
611            }
612            Err(error) => panic!(
613                "Failed to parse as derive input when it should be able to. Error: {error:?}"
614            ),
615        };
616    }
617
618    #[test]
619    fn test_namespace() {
620        let test_struct = quote! {
621            #[avro(namespace = "namespace.testing")]
622            struct A {
623                a: i32,
624                b: String
625            }
626        };
627
628        match syn::parse2::<DeriveInput>(test_struct) {
629            Ok(mut input) => {
630                let schema_token_stream = derive_avro_schema(&mut input);
631                assert!(&schema_token_stream.is_ok());
632                assert!(
633                    schema_token_stream
634                        .unwrap()
635                        .to_string()
636                        .contains("namespace.testing")
637                )
638            }
639            Err(error) => panic!(
640                "Failed to parse as derive input when it should be able to. Error: {error:?}"
641            ),
642        };
643    }
644
645    #[test]
646    fn test_reference() {
647        let test_reference_struct = quote! {
648            struct A<'a> {
649                a: &'a Vec<i32>,
650                b: &'static str
651            }
652        };
653
654        match syn::parse2::<DeriveInput>(test_reference_struct) {
655            Ok(mut input) => {
656                assert!(derive_avro_schema(&mut input).is_ok())
657            }
658            Err(error) => panic!(
659                "Failed to parse as derive input when it should be able to. Error: {error:?}"
660            ),
661        };
662    }
663
664    #[test]
665    fn test_trait_cast() {
666        assert_eq!(type_path_schema_expr(&syn::parse2::<TypePath>(quote!{i32}).unwrap()).to_string(), quote!{<i32 as apache_avro::schema::derive::AvroSchemaComponent>::get_schema_in_ctxt(named_schemas, enclosing_namespace)}.to_string());
667        assert_eq!(type_path_schema_expr(&syn::parse2::<TypePath>(quote!{Vec<T>}).unwrap()).to_string(), quote!{<Vec<T> as apache_avro::schema::derive::AvroSchemaComponent>::get_schema_in_ctxt(named_schemas, enclosing_namespace)}.to_string());
668        assert_eq!(type_path_schema_expr(&syn::parse2::<TypePath>(quote!{AnyType}).unwrap()).to_string(), quote!{<AnyType as apache_avro::schema::derive::AvroSchemaComponent>::get_schema_in_ctxt(named_schemas, enclosing_namespace)}.to_string());
669    }
670
671    #[test]
672    fn test_avro_3709_record_field_attributes() {
673        let test_struct = quote! {
674            struct A {
675                #[avro(alias = "a1", alias = "a2", doc = "a doc", default = "123", rename = "a3")]
676                a: i32
677            }
678        };
679
680        match syn::parse2::<DeriveInput>(test_struct) {
681            Ok(mut input) => {
682                let schema_res = derive_avro_schema(&mut input);
683                let expected_token_stream = r#"let schema_fields = vec ! [apache_avro :: schema :: RecordField { name : "a3" . to_string () , doc : Some ("a doc" . into ()) , default : Some (serde_json :: from_str ("123") . expect (format ! ("Invalid JSON: {:?}" , "123") . as_str ())) , aliases : Some (vec ! ["a1" . into () , "a2" . into ()]) , schema : apache_avro :: schema :: Schema :: Int , order : apache_avro :: schema :: RecordFieldOrder :: Ascending , position : 0usize , custom_attributes : Default :: default () , }] ;"#;
684                let schema_token_stream = schema_res.unwrap().to_string();
685                assert!(schema_token_stream.contains(expected_token_stream));
686            }
687            Err(error) => panic!(
688                "Failed to parse as derive input when it should be able to. Error: {error:?}"
689            ),
690        };
691
692        let test_enum = quote! {
693            enum A {
694                #[avro(rename = "A3")]
695                Item1,
696            }
697        };
698
699        match syn::parse2::<DeriveInput>(test_enum) {
700            Ok(mut input) => {
701                let schema_res = derive_avro_schema(&mut input);
702                let expected_token_stream = r#"let name = apache_avro :: schema :: Name :: new ("A") . expect (& format ! ("Unable to parse schema name {}" , "A") [..]) . fully_qualified_name (enclosing_namespace) ; let enclosing_namespace = & name . namespace ; if named_schemas . contains_key (& name) { apache_avro :: schema :: Schema :: Ref { name : name . clone () } } else { named_schemas . insert (name . clone () , apache_avro :: schema :: Schema :: Ref { name : name . clone () }) ; apache_avro :: schema :: Schema :: Enum (apache_avro :: schema :: EnumSchema { name : apache_avro :: schema :: Name :: new ("A") . expect (& format ! ("Unable to parse enum name for schema {}" , "A") [..]) , aliases : None , doc : None , symbols : vec ! ["A3" . to_owned ()] , default : None , attributes : Default :: default () , })"#;
703                let schema_token_stream = schema_res.unwrap().to_string();
704                assert!(schema_token_stream.contains(expected_token_stream));
705            }
706            Err(error) => panic!(
707                "Failed to parse as derive input when it should be able to. Error: {error:?}"
708            ),
709        };
710    }
711
712    #[test]
713    fn test_avro_rs_207_rename_all_attribute() {
714        let test_struct = quote! {
715            #[avro(rename_all="SCREAMING_SNAKE_CASE")]
716            struct A {
717                item: i32,
718                double_item: i32
719            }
720        };
721
722        match syn::parse2::<DeriveInput>(test_struct) {
723            Ok(mut input) => {
724                let schema_res = derive_avro_schema(&mut input);
725                let expected_token_stream = r#"let name = apache_avro :: schema :: Name :: new ("A") . expect (& format ! ("Unable to parse schema name {}" , "A") [..]) . fully_qualified_name (enclosing_namespace) ; let enclosing_namespace = & name . namespace ; if named_schemas . contains_key (& name) { apache_avro :: schema :: Schema :: Ref { name : name . clone () } } else { named_schemas . insert (name . clone () , apache_avro :: schema :: Schema :: Ref { name : name . clone () }) ; let schema_fields = vec ! [apache_avro :: schema :: RecordField { name : "ITEM" . to_string () , doc : None , default : None , aliases : None , schema : apache_avro :: schema :: Schema :: Int , order : apache_avro :: schema :: RecordFieldOrder :: Ascending , position : 0usize , custom_attributes : Default :: default () , } , apache_avro :: schema :: RecordField { name : "DOUBLE_ITEM" . to_string () , doc : None , default : None , aliases : None , schema : apache_avro :: schema :: Schema :: Int , order : apache_avro :: schema :: RecordFieldOrder :: Ascending , position : 1usize , custom_attributes : Default :: default () , }] ;"#;
726                let schema_token_stream = schema_res.unwrap().to_string();
727                assert!(schema_token_stream.contains(expected_token_stream));
728            }
729            Err(error) => panic!(
730                "Failed to parse as derive input when it should be able to. Error: {error:?}"
731            ),
732        };
733
734        let test_enum = quote! {
735            #[avro(rename_all="SCREAMING_SNAKE_CASE")]
736            enum B {
737                Item,
738                DoubleItem,
739            }
740        };
741
742        match syn::parse2::<DeriveInput>(test_enum) {
743            Ok(mut input) => {
744                let schema_res = derive_avro_schema(&mut input);
745                let expected_token_stream = r#"let name = apache_avro :: schema :: Name :: new ("B") . expect (& format ! ("Unable to parse schema name {}" , "B") [..]) . fully_qualified_name (enclosing_namespace) ; let enclosing_namespace = & name . namespace ; if named_schemas . contains_key (& name) { apache_avro :: schema :: Schema :: Ref { name : name . clone () } } else { named_schemas . insert (name . clone () , apache_avro :: schema :: Schema :: Ref { name : name . clone () }) ; apache_avro :: schema :: Schema :: Enum (apache_avro :: schema :: EnumSchema { name : apache_avro :: schema :: Name :: new ("B") . expect (& format ! ("Unable to parse enum name for schema {}" , "B") [..]) , aliases : None , doc : None , symbols : vec ! ["ITEM" . to_owned () , "DOUBLE_ITEM" . to_owned ()] , default : None , attributes : Default :: default () , })"#;
746                let schema_token_stream = schema_res.unwrap().to_string();
747                assert!(schema_token_stream.contains(expected_token_stream));
748            }
749            Err(error) => panic!(
750                "Failed to parse as derive input when it should be able to. Error: {error:?}"
751            ),
752        };
753    }
754
755    #[test]
756    fn test_avro_rs_207_rename_attr_has_priority_over_rename_all_attribute() {
757        let test_struct = quote! {
758            #[avro(rename_all="SCREAMING_SNAKE_CASE")]
759            struct A {
760                item: i32,
761                #[avro(rename="DoubleItem")]
762                double_item: i32
763            }
764        };
765
766        match syn::parse2::<DeriveInput>(test_struct) {
767            Ok(mut input) => {
768                let schema_res = derive_avro_schema(&mut input);
769                let expected_token_stream = r#"let name = apache_avro :: schema :: Name :: new ("A") . expect (& format ! ("Unable to parse schema name {}" , "A") [..]) . fully_qualified_name (enclosing_namespace) ; let enclosing_namespace = & name . namespace ; if named_schemas . contains_key (& name) { apache_avro :: schema :: Schema :: Ref { name : name . clone () } } else { named_schemas . insert (name . clone () , apache_avro :: schema :: Schema :: Ref { name : name . clone () }) ; let schema_fields = vec ! [apache_avro :: schema :: RecordField { name : "ITEM" . to_string () , doc : None , default : None , aliases : None , schema : apache_avro :: schema :: Schema :: Int , order : apache_avro :: schema :: RecordFieldOrder :: Ascending , position : 0usize , custom_attributes : Default :: default () , } , apache_avro :: schema :: RecordField { name : "DoubleItem" . to_string () , doc : None , default : None , aliases : None , schema : apache_avro :: schema :: Schema :: Int , order : apache_avro :: schema :: RecordFieldOrder :: Ascending , position : 1usize , custom_attributes : Default :: default () , }] ;"#;
770                let schema_token_stream = schema_res.unwrap().to_string();
771                assert!(schema_token_stream.contains(expected_token_stream));
772            }
773            Err(error) => panic!(
774                "Failed to parse as derive input when it should be able to. Error: {error:?}"
775            ),
776        };
777    }
778}