Skip to main content

progenitor_impl/
httpmock.rs

1// Copyright 2025 Oxide Computer Company
2
3//! Generation of mocking extensions for `httpmock`
4
5use openapiv3::OpenAPI;
6use proc_macro2::TokenStream;
7use quote::{format_ident, quote, ToTokens};
8
9use crate::{
10    method::{
11        BodyContentType, HttpMethod, OperationParameter, OperationParameterKind,
12        OperationParameterType, OperationResponse, OperationResponseStatus,
13    },
14    to_schema::ToSchema,
15    util::{sanitize, Case},
16    validate_openapi, Generator, Result,
17};
18
19struct MockOp {
20    when: TokenStream,
21    when_impl: TokenStream,
22    then: TokenStream,
23    then_impl: TokenStream,
24}
25
26impl Generator {
27    /// Generate a strongly-typed mocking extension to the `httpmock` crate.
28    ///
29    /// The `crate_path` parameter should be a valid Rust path corresponding to
30    /// the SDK. This can include `::` and instances of `-` in the crate name
31    /// should be converted to `_`.
32    pub fn httpmock(&mut self, spec: &OpenAPI, crate_path: &str) -> Result<TokenStream> {
33        validate_openapi(spec)?;
34
35        // Convert our components dictionary to schemars
36        let schemas = spec.components.iter().flat_map(|components| {
37            components
38                .schemas
39                .iter()
40                .map(|(name, ref_or_schema)| (name.clone(), ref_or_schema.to_schema()))
41        });
42
43        self.type_space.add_ref_types(schemas)?;
44
45        let raw_methods = spec
46            .paths
47            .iter()
48            .flat_map(|(path, ref_or_item)| {
49                // Exclude externally defined path items.
50                let item = ref_or_item.as_item().unwrap();
51                item.iter().map(move |(method, operation)| {
52                    (path.as_str(), method, operation, &item.parameters)
53                })
54            })
55            .map(|(path, method, operation, path_parameters)| {
56                self.process_operation(operation, &spec.components, path, method, path_parameters)
57            })
58            .collect::<Result<Vec<_>>>()?;
59
60        let methods = raw_methods
61            .iter()
62            .map(|method| self.httpmock_method(method))
63            .collect::<Vec<_>>();
64
65        let op = raw_methods
66            .iter()
67            .map(|method| format_ident!("{}", &method.operation_id))
68            .collect::<Vec<_>>();
69        let when = methods.iter().map(|op| &op.when).collect::<Vec<_>>();
70        let when_impl = methods.iter().map(|op| &op.when_impl).collect::<Vec<_>>();
71        let then = methods.iter().map(|op| &op.then).collect::<Vec<_>>();
72        let then_impl = methods.iter().map(|op| &op.then_impl).collect::<Vec<_>>();
73
74        let crate_path = syn::TypePath {
75            qself: None,
76            path: syn::parse_str(crate_path)
77                .unwrap_or_else(|_| panic!("{} is not a valid identifier", crate_path)),
78        };
79
80        let code = quote! {
81            pub mod operations {
82
83                //! [`When`](::httpmock::When) and [`Then`](::httpmock::Then)
84                //! wrappers for each operation. Each can be converted to
85                //! its inner type with a call to `into_inner()`. This can
86                //! be used to explicitly deviate from permitted values.
87
88                use #crate_path::*;
89
90                #(
91                    pub struct #when(::httpmock::When);
92                    #when_impl
93
94                    pub struct #then(::httpmock::Then);
95                    #then_impl
96                )*
97            }
98
99            /// An extension trait for [`MockServer`](::httpmock::MockServer) that
100            /// adds a method for each operation. These are the equivalent of
101            /// type-checked [`mock()`](::httpmock::MockServer::mock) calls.
102            pub trait MockServerExt {
103                #(
104                    fn #op<F>(&self, config_fn: F) -> ::httpmock::Mock<'_>
105                    where
106                        F: FnOnce(operations::#when, operations::#then);
107                )*
108            }
109
110            impl MockServerExt for ::httpmock::MockServer {
111                #(
112                    fn #op<F>(&self, config_fn: F) -> ::httpmock::Mock<'_>
113                    where
114                        F: FnOnce(operations::#when, operations::#then)
115                    {
116                        self.mock(|when, then| {
117                            config_fn(
118                                operations::#when::new(when),
119                                operations::#then::new(then),
120                            )
121                        })
122                    }
123                )*
124            }
125        };
126        Ok(code)
127    }
128
129    fn httpmock_method(&mut self, method: &crate::method::OperationMethod) -> MockOp {
130        let when_name = sanitize(&format!("{}-when", method.operation_id), Case::Pascal);
131        let when = format_ident!("{}", when_name).to_token_stream();
132        let then_name = sanitize(&format!("{}-then", method.operation_id), Case::Pascal);
133        let then = format_ident!("{}", then_name).to_token_stream();
134
135        let http_method = match &method.method {
136            HttpMethod::Get => quote! { ::httpmock::Method::GET },
137            HttpMethod::Put => quote! { ::httpmock::Method::PUT },
138            HttpMethod::Post => quote! { ::httpmock::Method::POST },
139            HttpMethod::Delete => quote! { ::httpmock::Method::DELETE },
140            HttpMethod::Options => quote! { ::httpmock::Method::OPTIONS },
141            HttpMethod::Head => quote! { ::httpmock::Method::HEAD },
142            HttpMethod::Patch => quote! { ::httpmock::Method::PATCH },
143            HttpMethod::Trace => quote! { ::httpmock::Method::TRACE },
144        };
145
146        let path_re = method.path.as_wildcard();
147
148        // Generate methods corresponding to each parameter so that callers
149        // can specify a prescribed value for that parameter.
150        let when_methods = method.params.iter().map(
151            |OperationParameter {
152                 name,
153                 typ,
154                 kind,
155                 api_name,
156                 description: _,
157             }| {
158                let arg_type_name = match typ {
159                    OperationParameterType::Type(arg_type_id) => self
160                        .type_space
161                        .get_type(arg_type_id)
162                        .unwrap()
163                        .parameter_ident(),
164                    OperationParameterType::RawBody => match kind {
165                        OperationParameterKind::Body(BodyContentType::OctetStream) => quote! {
166                            ::serde_json::Value
167                        },
168                        OperationParameterKind::Body(BodyContentType::Text(_)) => quote! {
169                            String
170                        },
171                        _ => unreachable!(),
172                    },
173                };
174
175                let name_ident = format_ident!("{}", name);
176                let (required, handler) = match kind {
177                    OperationParameterKind::Path => {
178                        let re_fmt = method.path.as_wildcard_param(api_name);
179                        (
180                            true,
181                            quote! {
182                                let re = regex::Regex::new(
183                                    &format!(#re_fmt, value.to_string())
184                                ).unwrap();
185                                Self(self.0.path_matches(re))
186                            },
187                        )
188                    }
189                    OperationParameterKind::Query(true) => (
190                        true,
191                        quote! {
192                            Self(self.0.query_param(#api_name, value.to_string()))
193                        },
194                    ),
195                    OperationParameterKind::Header(true) => (
196                        true,
197                        quote! {
198                            Self(self.0.header(#api_name, value.to_string()))
199                        },
200                    ),
201
202                    OperationParameterKind::Query(false) => (
203                        false,
204                        quote! {
205                            if let Some(value) = value.into() {
206                                Self(self.0.query_param(
207                                    #api_name,
208                                    value.to_string(),
209                                ))
210                            } else {
211                                Self(self.0.query_param_missing(#api_name))
212                            }
213                        },
214                    ),
215                    OperationParameterKind::Header(false) => (
216                        false,
217                        quote! {
218                            if let Some(value) = value.into() {
219                                Self(self.0.header(
220                                    #api_name,
221                                    value.to_string()
222                                ))
223                            } else {
224                                Self(self.0.header_missing(#api_name))
225                            }
226                        },
227                    ),
228                    OperationParameterKind::Body(body_content_type) => match typ {
229                        OperationParameterType::Type(_) => (
230                            true,
231                            quote! {
232                                Self(self.0.json_body_obj(value))
233                            },
234                        ),
235                        OperationParameterType::RawBody => match body_content_type {
236                            BodyContentType::OctetStream => (
237                                true,
238                                quote! {
239                                    Self(self.0.json_body(value))
240                                },
241                            ),
242                            BodyContentType::Text(_) => (
243                                true,
244                                quote! {
245                                    Self(self.0.body(value))
246                                },
247                            ),
248                            _ => unreachable!(),
249                        },
250                    },
251                };
252
253                if required {
254                    // The value is required so we just check for a simple
255                    // match.
256                    quote! {
257                        pub fn #name_ident(self, value: #arg_type_name) -> Self {
258                            #handler
259                        }
260                    }
261                } else {
262                    // For optional values we permit an input that's an
263                    // `Into<Option<T>`. This allows callers to specify a value
264                    // or specify that the parameter must be absent with None.
265
266                    // If the type is a ref, augment it with a lifetime that
267                    // we'll also use in the function
268                    let (lifetime, arg_type_name) = if let syn::Type::Reference(mut rr) =
269                        syn::parse2::<syn::Type>(arg_type_name.clone()).unwrap()
270                    {
271                        rr.lifetime =
272                            Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site()));
273                        (Some(quote! { 'a, }), rr.to_token_stream())
274                    } else {
275                        (None, arg_type_name)
276                    };
277
278                    quote! {
279                        pub fn #name_ident<#lifetime T>(
280                            self,
281                            value: T,
282                        ) -> Self
283                        where
284                            T: Into<Option<#arg_type_name>>,
285                        {
286                            #handler
287                        }
288                    }
289                }
290            },
291        );
292
293        let when_impl = quote! {
294            impl #when {
295                pub fn new(inner: ::httpmock::When) -> Self {
296                    Self(inner
297                        .method(#http_method)
298                        .path_matches(regex::Regex::new(#path_re).unwrap()))
299                }
300
301                pub fn into_inner(self) -> ::httpmock::When {
302                    self.0
303                }
304
305                #(#when_methods)*
306            }
307        };
308
309        // Methods for each discrete response. For specific status codes we use
310        // the name of that code; for classes of codes we use the class name
311        // and require a status code that must be within the prescribed range.
312        let then_methods = method.responses.iter().map(
313            |OperationResponse {
314                 status_code, typ, ..
315             }| {
316                let (value_param, value_use) = match typ {
317                    crate::method::OperationResponseKind::Type(arg_type_id) => {
318                        let arg_type = self.type_space.get_type(arg_type_id).unwrap();
319                        let arg_type_ident = arg_type.parameter_ident();
320                        (
321                            quote! {
322                                value: #arg_type_ident,
323                            },
324                            quote! {
325                                .header("content-type", "application/json")
326                                .json_body_obj(value)
327                            },
328                        )
329                    }
330                    crate::method::OperationResponseKind::None => Default::default(),
331                    crate::method::OperationResponseKind::Raw => (
332                        quote! {
333                            value: ::serde_json::Value,
334                        },
335                        quote! {
336                            .header("content-type", "application/json")
337                            .json_body(value)
338                        },
339                    ),
340                    crate::method::OperationResponseKind::Upgrade => Default::default(),
341                };
342
343                match status_code {
344                    OperationResponseStatus::Code(status_code) => {
345                        let canonical_reason = http::StatusCode::from_u16(*status_code)
346                            .unwrap()
347                            .canonical_reason()
348                            .unwrap();
349                        let fn_name = format_ident!("{}", &sanitize(canonical_reason, Case::Snake));
350
351                        quote! {
352                            pub fn #fn_name(self, #value_param) -> Self {
353                                Self(self.0
354                                    .status(#status_code)
355                                    #value_use
356                                )
357                            }
358                        }
359                    }
360                    OperationResponseStatus::Range(status_type) => {
361                        let status_string = match status_type {
362                            1 => "informational",
363                            2 => "success",
364                            3 => "redirect",
365                            4 => "client_error",
366                            5 => "server_error",
367                            _ => unreachable!(),
368                        };
369                        let fn_name = format_ident!("{}", status_string);
370                        quote! {
371                            pub fn #fn_name(self, status: u16, #value_param) -> Self {
372                                assert_eq!(status / 100u16, #status_type);
373                                Self(self.0
374                                    .status(status)
375                                    #value_use
376                                )
377                            }
378                        }
379                    }
380                    OperationResponseStatus::Default => quote! {
381                        pub fn default_response(self, status: u16, #value_param) -> Self {
382                            Self(self.0
383                                .status(status)
384                                #value_use
385                            )
386                        }
387                    },
388                }
389            },
390        );
391
392        let then_impl = quote! {
393            impl #then {
394                pub fn new(inner: ::httpmock::Then) -> Self {
395                    Self(inner)
396                }
397
398                pub fn into_inner(self) -> ::httpmock::Then {
399                    self.0
400                }
401
402                #(#then_methods)*
403            }
404        };
405
406        MockOp {
407            when,
408            when_impl,
409            then,
410            then_impl,
411        }
412    }
413}