1use 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 pub fn httpmock(&mut self, spec: &OpenAPI, crate_path: &str) -> Result<TokenStream> {
33 validate_openapi(spec)?;
34
35 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 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 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 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 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 handler = match kind {
177 OperationParameterKind::Path => {
178 let re_fmt = method.path.as_wildcard_param(api_name);
179 quote! {
180 let re = regex::Regex::new(
181 &format!(#re_fmt, value.to_string())
182 ).unwrap();
183 Self(self.0.path_matches(re))
184 }
185 }
186 OperationParameterKind::Query(true) => quote! {
187 Self(self.0.query_param(#name, value.to_string()))
188 },
189
190 OperationParameterKind::Query(false) => {
191 let (lifetime, arg_type_name) = if let syn::Type::Reference(mut rr) =
193 syn::parse2::<syn::Type>(arg_type_name.clone()).unwrap()
194 {
195 rr.lifetime =
196 Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site()));
197 (Some(quote! { 'a, }), rr.to_token_stream())
198 } else {
199 (None, arg_type_name)
200 };
201
202 return quote! {
203 pub fn #name_ident<#lifetime T>(
204 self,
205 value: T,
206 ) -> Self
207 where
208 T: Into<Option<#arg_type_name>>,
209 {
210 if let Some(value) = value.into() {
211 Self(self.0.query_param(
212 #name,
213 value.to_string(),
214 ))
215 } else {
216 Self(self.0.matches(|req| {
217 req.query_params
218 .as_ref()
219 .and_then(|qs| {
220 qs.iter().find(
221 |(key, _)| key == #name)
222 })
223 .is_none()
224 }))
225 }
226 }
227 };
228 }
229 OperationParameterKind::Header(_) => quote! { todo!() },
230 OperationParameterKind::Body(body_content_type) => match typ {
231 OperationParameterType::Type(_) => quote! {
232 Self(self.0.json_body_obj(value))
233
234 },
235 OperationParameterType::RawBody => match body_content_type {
236 BodyContentType::OctetStream => quote! {
237 Self(self.0.json_body(value))
238 },
239 BodyContentType::Text(_) => quote! {
240 Self(self.0.body(value))
241 },
242 _ => unreachable!(),
243 },
244 },
245 };
246 quote! {
247 pub fn #name_ident(self, value: #arg_type_name) -> Self {
248 #handler
249 }
250 }
251 },
252 );
253
254 let when_impl = quote! {
255 impl #when {
256 pub fn new(inner: ::httpmock::When) -> Self {
257 Self(inner
258 .method(#http_method)
259 .path_matches(regex::Regex::new(#path_re).unwrap()))
260 }
261
262 pub fn into_inner(self) -> ::httpmock::When {
263 self.0
264 }
265
266 #(#when_methods)*
267 }
268 };
269
270 let then_methods = method.responses.iter().map(
274 |OperationResponse {
275 status_code, typ, ..
276 }| {
277 let (value_param, value_use) = match typ {
278 crate::method::OperationResponseKind::Type(arg_type_id) => {
279 let arg_type = self.type_space.get_type(arg_type_id).unwrap();
280 let arg_type_ident = arg_type.parameter_ident();
281 (
282 quote! {
283 value: #arg_type_ident,
284 },
285 quote! {
286 .header("content-type", "application/json")
287 .json_body_obj(value)
288 },
289 )
290 }
291 crate::method::OperationResponseKind::None => Default::default(),
292 crate::method::OperationResponseKind::Raw => (
293 quote! {
294 value: serde_json::Value,
295 },
296 quote! {
297 .header("content-type", "application/json")
298 .json_body(value)
299 },
300 ),
301 crate::method::OperationResponseKind::Upgrade => Default::default(),
302 };
303
304 match status_code {
305 OperationResponseStatus::Code(status_code) => {
306 let canonical_reason = http::StatusCode::from_u16(*status_code)
307 .unwrap()
308 .canonical_reason()
309 .unwrap();
310 let fn_name = format_ident!("{}", &sanitize(canonical_reason, Case::Snake));
311
312 quote! {
313 pub fn #fn_name(self, #value_param) -> Self {
314 Self(self.0
315 .status(#status_code)
316 #value_use
317 )
318 }
319 }
320 }
321 OperationResponseStatus::Range(status_type) => {
322 let status_string = match status_type {
323 1 => "informational",
324 2 => "success",
325 3 => "redirect",
326 4 => "client_error",
327 5 => "server_error",
328 _ => unreachable!(),
329 };
330 let fn_name = format_ident!("{}", status_string);
331 quote! {
332 pub fn #fn_name(self, status: u16, #value_param) -> Self {
333 assert_eq!(status / 100u16, #status_type);
334 Self(self.0
335 .status(status)
336 #value_use
337 )
338 }
339 }
340 }
341 OperationResponseStatus::Default => quote! {
342 pub fn default_response(self, status: u16, #value_param) -> Self {
343 Self(self.0
344 .status(status)
345 #value_use
346 )
347 }
348 },
349 }
350 },
351 );
352
353 let then_impl = quote! {
354 impl #then {
355 pub fn new(inner: ::httpmock::Then) -> Self {
356 Self(inner)
357 }
358
359 pub fn into_inner(self) -> ::httpmock::Then {
360 self.0
361 }
362
363 #(#then_methods)*
364 }
365 };
366
367 MockOp {
368 when,
369 when_impl,
370 then,
371 then_impl,
372 }
373 }
374}