Skip to content

Commit

Permalink
Decanoncalize std types in the expected and actual ASTs
Browse files Browse the repository at this point in the history
Based on a PR comment from @ahl.  Remove some ugly special-case
handling, and unconditionally decanonicalize all `std`-prefixed types in
both the generated code as well as the original types' ASTs.  With this
in place, we can expect the two ASTs to match exactly, which some of the
tests assert.
  • Loading branch information
anelson committed Dec 1, 2024
1 parent 4bfc9ac commit def2173
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions typify-impl/src/test_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ fn validate_output_impl<T: JsonSchema + Schema>(ignore_variant_names: bool) {
let output = output.into_stream();

let expected = T::schema();

// A few test cases use structs that use the fully-qualified path to a std type like
// `::std::collections::HashMap`. Decanonicalize those types so that later in this function
// when we also decanonicalize the types generated by typify, we can compare the two and expect
// their ASTs to match exactly
let expected = decanonicalize_std_types(expected);

// We may generate more than one item for a given schema. For example, we
// may generate `impl`s with convenient functions. We do the somewhat
// arcane dance here of parsing the full output, extracting the first item,
Expand All @@ -81,7 +88,8 @@ fn validate_output_impl<T: JsonSchema + Schema>(ignore_variant_names: bool) {
assert!(!file.items.is_empty(), "{}", output.to_string());
let actual = parse2::<DeriveInput>(file.items.first().unwrap().to_token_stream()).unwrap();

// Fun hack to make sure we're comparing apples to apples
// Decanonicalize the types generated by typify so that we can compare them to the original
// Rust types' ASTs that definitely do not use canonicalized std types.
let actual = decanonicalize_std_types(actual);

// Make sure they match.
Expand Down Expand Up @@ -118,18 +126,11 @@ fn decanonicalize_std_types(mut input: DeriveInput) -> DeriveInput {
&& !path.segments.is_empty()
&& path.segments[0].ident == "std"
{
// Fun additional hack to keep you on your toes:
// The test structs that have a HashMap for some reason *do* declare it with the
// fully-qualified type name, so don't mess with HashMap
if *path
!= syn::parse_quote! { ::std::collections::HashMap<::std::string::String, ::std::string::String> }
{
if let Some(last_segment) = path.segments.last().cloned() {
// Replace the entire path with just the last segment
path.leading_colon = None;
path.segments.clear();
path.segments.push(last_segment);
}
if let Some(last_segment) = path.segments.last().cloned() {
// Replace the entire path with just the last segment
path.leading_colon = None;
path.segments.clear();
path.segments.push(last_segment);
}
}

Expand Down

0 comments on commit def2173

Please sign in to comment.