{{!

  Copyright (c) Meta Platforms, Inc. and affiliates.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

}}// @{{!}}generated by Thrift for {{program:autogen_path}}
// This file is probably not the place you want to edit!

{{#program:include_docs}}
#![doc = include_str!("{{.}}")]
{{/program:include_docs}}
{{#program:services?}}
//! Mock definitions for `{{program:name}}`.
//!
//! Client mocks. For every service, a struct TheService that implements
//! client::TheService.
//!
//! As an example of the generated API, for the following thrift service in
//! example.thrift:
//!
//! ```thrift
//! service MyService {
//!     FunctionResponse myFunction(
//!         1: FunctionRequest request,
//!     ) throws {
//!         1: StorageException s,
//!         2: NotFoundException n,
//!     ),
//!
//!     // other functions
//! }
//! ```
//!
//! we would end up with this mock object in an `example_mocks` crate:
//!
//! ```
//! # const _: &str = stringify! {
//! impl example_clients::MyService for MyService<'mock> {...}
//!
//! pub struct MyService<'mock> {
//!     pub myFunction: myFunction<'mock>,
//!     // ...
//! }
//!
//! impl myFunction<'mock> {
//!     // directly return the given success response
//!     pub fn ret(&self, value: FunctionResponse);
//!
//!     // invoke closure to compute success response
//!     pub fn mock(
//!         &self,
//!         mock: impl FnMut(FunctionRequest) -> FunctionResponse + Send + Sync + 'mock,
//!     );
//!
//!     // invoke closure to compute response
//!     pub fn mock_result(
//!         &self,
//!         mock: impl FnMut(FunctionRequest) -> Result<FunctionResponse, example_services::errors::MyFunctionExn> + Send + Sync + 'mock,
//!     );
//!
//!     // return one of the function's declared exceptions
//!     pub fn throw<E>(&self, exception: E)
//!     where
//!         E: Clone + Into<example_services::errors::MyFunctionExn> + Send + Sync + 'mock;
//! }
//! # };
//! ```
//!
//! The intended usage from a test would be:
//!
//! ```
//! # const _: &str = stringify! {
//! use std::sync::Arc;
//! use example_clients::MyService;
//!
//! #[tokio::test]
//! async fn test_my_client() {
//!     let mock = Arc::new(example_mocks::new::<dyn MyService>());
//!
//!     // directly return a success response
//!     let resp = FunctionResponse {...};
//!     mock.myFunction.ret(resp);
//!
//!     // or give a closure to compute the success response
//!     mock.myFunction.mock(|request| FunctionResponse {...});
//!
//!     // or throw one of the function's exceptions
//!     mock.myFunction.throw(StorageException::ItFailed);
//!
//!     // or compute a Result (useful if your exceptions aren't Clone)
//!     mock.myFunction.mock_result(|request| Err(...));
//!
//!     let out = do_the_thing(mock).await.unwrap();
//!     assert!(out.what_i_expected());
//! }
//!
//! async fn do_the_thing(
//!     client: Arc<dyn MyService + Send + Sync + 'static>,
//! ) -> Out {...}
//! # };
//! ```

{{^program:multifile?}}
#![recursion_limit = "100000000"]
{{/program:multifile?}}
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals{{!
}}{{^program:multifile?}}, unused_crate_dependencies{{/program:multifile?}}{{!
}}, unused_imports, clippy::all)]

pub(crate) use {{program:types}} as types;
pub(crate) use {{program:clients}} as client;
pub(crate) use {{program:clients}}::errors;

{{^program:multifile?}}
pub fn new<'mock, Client>() -> Client::Mock<'mock>
where
    Client: ?::std::marker::Sized + DynClient,
{
    Client::mock()
}

pub trait DynClient {
    type Mock<'mock>;
    fn mock<'mock>() -> Self::Mock<'mock>;
}
{{/program:multifile?}}

{{#program:services}}
pub struct {{service:rust_name}}<'mock> {{>lib/block}}
    {{#service:extends}}
    pub parent: {{service:mock_package}}::{{service:rust_name}}<'mock>,
    {{/service:extends}}
    {{#service:rustFunctions}}
    {{^function:starts_interaction?}}{{^function:sink?}}
    pub {{function:rust_name}}: r#impl::{{service:snake}}::{{function:rust_name}}<'mock>,
    {{/function:sink?}}{{/function:starts_interaction?}}
    {{/service:rustFunctions}}
    _marker: ::std::marker::PhantomData<&'mock ()>,
}

impl crate::DynClient for dyn {{program:clients}}::{{service:rust_name}} {
    type Mock<'mock> = {{service:rust_name}}<'mock>;
    fn mock<'mock>() -> Self::Mock<'mock> {
        {{service:rust_name}} {
            {{#service:extends}}
            parent: {{service:mock_crate}}::new::<dyn {{service:client_package}}::{{service:rust_name}}>(),
            {{/service:extends}}
            {{#service:rustFunctions}}
            {{^function:starts_interaction?}}{{^function:sink?}}
            {{function:rust_name}}: {{!
                }}r#impl::{{service:snake}}::{{function:rust_name}}::unimplemented(),
            {{/function:sink?}}{{/function:starts_interaction?}}
            {{/service:rustFunctions}}
            _marker: ::std::marker::PhantomData,
        }
    }
}

impl<'mock> {{program:clients}}::{{service:rust_name}} for {{service:rust_name}}<'mock> {{>lib/block}}{{!
    }}{{#service:rustFunctions}}
    {{^function:starts_interaction?}}{{^function:sink?}}{{^function:creates_interaction?}}
    fn {{function:rust_name}}(
        &self,{{!
        }}{{#function:args}}
        arg_{{field:name}}: {{>lib/arg}},{{!
        }}{{/function:args}}
    ) -> {{>lib/client_return_type}} {
        let mut closure = self.{{function:rust_name}}.closure.lock().unwrap();
        let closure: &mut dyn ::std::ops::FnMut({{!
            }}{{#function:args}}{{!
            }}{{#field:type}}{{>lib/type}}{{/field:type}}{{!
            }}{{^last?}}, {{/last?}}{{!
            }}{{/function:args}}{{!
        }}) -> _ = &mut **closure;
        ::std::boxed::Box::pin(::futures::future::ready(closure({{!
            }}{{#function:args}}{{!
            }}arg_{{field:name}}{{#field:type}}{{!
                }}{{#type:string?}}.to_owned(){{/type:string?}}{{!
                }}{{#type:list?}}.to_owned(){{/type:list?}}{{!
                }}{{^type:string?}}{{^type:list?}}{{!
                    }}.clone(){{!
                }}{{/type:list?}}{{/type:string?}}{{!
            }}{{/field:type}}{{!
            }}{{^last?}}, {{/last?}}{{!
            }}{{/function:args}}{{!
        }})))
    }{{!
    }}{{/function:creates_interaction?}}{{#function:creates_interaction?}}
    fn {{function:rust_name}}(
        &self,{{!
        }}{{#function:args}}
        _arg_{{field:name}}: {{>lib/arg}},{{!
        }}{{/function:args}}
    ) -> {{>lib/client_return_type}} {
        unimplemented!("Mocking interactions is not yet implemented");
    }{{!
    }}{{/function:creates_interaction?}}{{/function:sink?}}{{/function:starts_interaction?}}{{#function:starts_interaction?}}
    fn {{function:rust_name}}(
        &self,
    ) -> ::std::result::Result<{{!
    }}{{service:client_package}}::{{function:interaction_name}}Client, {{!
    }}::anyhow::Error> {
        unimplemented!("Mocking interactions is not yet implemented");
    }{{!
    }}{{/function:starts_interaction?}}{{/service:rustFunctions}}
}

impl<'mock, T> {{program:clients}}::{{service:rust_name}}Ext<T> for {{service:rust_name}}<'mock>
where
    T: ::fbthrift::Transport,
{{>lib/block}}{{!
    }}{{#service:rustFunctions}}
    {{^function:starts_interaction?}}{{^function:sink?}}
    fn {{function:rust_name}}_with_rpc_opts(
        &self,{{!
        }}{{#function:args}}
        arg_{{field:name}}: {{>lib/arg}},{{!
        }}{{/function:args}}
        _rpc_options: T::RpcOptions,
    ) -> {{>lib/client_return_type}} {
        <Self as {{program:clients}}::{{service:rust_name}}>::{{function:rust_name}}(
            self,
            {{#function:args}}
            arg_{{field:name}},
            {{/function:args}}
        )
    }
    {{/function:sink?}}{{/function:starts_interaction?}}
    {{/service:rustFunctions}}
    {{^service:extendedClients}}

    fn transport(&self) -> &T {
        ::fbthrift::help::GetTransport::transport(self)
    }
    {{/service:extendedClients}}
}

impl<'mock, T> ::fbthrift::help::GetTransport<T> for {{service:rust_name}}<'mock>
where
    T: ::fbthrift::Transport,
{
    fn transport(&self) -> &T {
        unimplemented!("{{service:rust_name}}Ext::transport is not implemented for mock client")
    }
}

{{#service:extendedClients}}
#[allow(deprecated)]{{! `dependencies` modules are deprecated other than for packagePrefix to use }}
impl<'mock> {{!
    }}{{#extendedService:service}}{{!
    }}::std::convert::AsRef<dyn {{extendedService:packagePrefix}}::{{service:rust_name}} + 'mock> {{!
    }}{{/extendedService:service}}{{!
    }}for {{service:rust_name}}<'mock>
{
    {{#extendedService:service}}
    fn as_ref(&self) -> &(dyn {{extendedService:packagePrefix}}::{{service:rust_name}} + 'mock) {
        &self.parent
    }
    {{/extendedService:service}}
}

#[allow(deprecated)]{{! `dependencies` modules are deprecated other than for packagePrefix to use }}
impl<'mock, T> {{!
    }}{{#extendedService:service}}{{!
    }}::std::convert::AsRef<dyn {{extendedService:packagePrefix}}::{{service:rust_name}}Ext<T> + 'mock> {{!
    }}{{/extendedService:service}}{{!
    }}for {{service:rust_name}}<'mock>
where
    T: ::fbthrift::Transport,
{
    {{#extendedService:service}}
    fn as_ref(&self) -> &(dyn {{extendedService:packagePrefix}}::{{service:rust_name}}Ext<T> + 'mock) {
        &self.parent
    }
    {{/extendedService:service}}
}

{{/service:extendedClients}}{{!
}}{{/program:services}}
pub mod r#impl {{>lib/block}}{{!
}}{{#program:services}}
    pub mod {{service:snake}} {{>lib/block}}{{!

        }}{{#service:rustFunctions}}
        {{^function:starts_interaction?}}{{^function:sink?}}

        pub struct {{function:rust_name}}<'mock> {
            pub(crate) closure: ::std::sync::Mutex<::std::boxed::Box<
                dyn ::std::ops::FnMut({{!
                    }}{{#function:args}}{{!
                    }}{{#field:type}}{{>lib/type}}{{/field:type}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }}) -> ::std::result::Result<
                    {{#function:return_type}}{{>lib/return_type}}{{/function:return_type}},
                    {{program:clients}}::errors::{{service:snake}}::{{function:upcamel}}Error,
                > + ::std::marker::Send + ::std::marker::Sync + 'mock,
            >>,
        }

        #[allow(clippy::redundant_closure)]
        impl<'mock> {{function:rust_name}}<'mock> {
            pub(crate) fn unimplemented() -> Self {
                Self {
                    closure: ::std::sync::Mutex::new(::std::boxed::Box::new(|{{!
                        }}{{#function:args}}{{!
                        }}_: {{#field:type}}{{>lib/type}}{{/field:type}}{{!
                        }}{{^last?}}, {{/last?}}{{!
                        }}{{/function:args}}{{!
                    }}| panic!(
                        "{}::{} is not mocked",
                        "{{service:rust_name}}",
                        "{{function:name}}",
                    ))),
                }
            }

            pub fn ret({{!
                }}&self, {{!
                }}{{#function:stream?}}_{{/function:stream?}}value: {{#function:return_type}}{{>lib/return_type}}{{/function:return_type}}{{!
            }}) {
                {{#function:stream?}}
                unimplemented!("Mocking streams is not yet implemented, as value isn't cloneable")
                {{/function:stream?}}{{^function:stream?}}
                self.mock(move |{{!
                    }}{{#function:args}}{{!
                    }}_: {{#field:type}}{{>lib/type}}{{/field:type}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }}| value.clone());
                {{/function:stream?}}
            }

            pub fn mock(&self, mut mock: impl ::std::ops::FnMut({{!
                }}{{#function:args}}{{!
                }}{{#field:type}}{{>lib/type}}{{/field:type}}{{!
                }}{{^last?}}, {{/last?}}{{!
                }}{{/function:args}}{{!
            }}) -> {{#function:return_type}}{{>lib/return_type}}{{/function:return_type}}{{!
                }} + ::std::marker::Send + ::std::marker::Sync + 'mock) {{!
            }}{
                let mut closure = self.closure.lock().unwrap();
                *closure = ::std::boxed::Box::new(move |{{!
                    }}{{#function:args}}{{!
                    }}{{field:rust_name}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }}| ::std::result::Result::Ok(mock({{!
                    }}{{#function:args}}{{!
                    }}{{field:rust_name}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }})));
            }

            pub fn mock_result(&self, mut mock: impl ::std::ops::FnMut({{!
                }}{{#function:args}}{{!
                }}{{#field:type}}{{>lib/type}}{{/field:type}}{{!
                }}{{^last?}}, {{/last?}}{{!
                }}{{/function:args}}{{!
            }}) -> ::std::result::Result<{{!
                    }}{{#function:return_type}}{{>lib/return_type}}{{/function:return_type}}, {{!
                    }}{{program:clients}}::errors::{{service:snake}}::{{function:upcamel}}Error>{{!
                }} + ::std::marker::Send + ::std::marker::Sync + 'mock) {{!
            }}{
                let mut closure = self.closure.lock().unwrap();
                *closure = ::std::boxed::Box::new(move |{{!
                    }}{{#function:args}}{{!
                    }}{{field:rust_name}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }}| mock({{!
                    }}{{#function:args}}{{!
                    }}{{field:rust_name}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }}));
            }

            pub fn throw<E>(&self, exception: E)
            where
                E: ::std::convert::Into<{{program:clients}}::errors::{{service:snake}}::{{function:upcamel}}Error>,
                E: ::std::clone::Clone + ::std::marker::Send + ::std::marker::Sync + 'mock,
            {
                let mut closure = self.closure.lock().unwrap();
                *closure = ::std::boxed::Box::new(move |{{!
                    }}{{#function:args}}{{!
                    }}_: {{#field:type}}{{>lib/type}}{{/field:type}}{{!
                    }}{{^last?}}, {{/last?}}{{!
                    }}{{/function:args}}{{!
                }}| ::std::result::Result::Err(exception.clone().into()));
            }
        }{{!
        }}{{/function:sink?}}{{/function:starts_interaction?}}{{!
        }}{{/service:rustFunctions}}
    }{{!
}}{{/program:services}}
}
{{/program:services?}}
{{^program:services?}}
#![doc(hidden)]
#![allow({{!
}}{{^program:multifile?}}non_snake_case, unused_crate_dependencies, {{/program:multifile?}}{{!
}}unused_imports)]

pub(crate) use {{program:types}} as types;
{{/program:services?}}
{{#program:direct_dependencies?}}

#[doc(hidden)]
#[deprecated]
pub mod __dependencies {
    {{#program:direct_dependencies}}
    #[doc(hidden)]
    #[deprecated{{#dependency:label}} = "Please use `{{.}}-mocks` directly"{{/dependency:label}}]
    pub extern crate {{dependency:name_unmangled}}_mocks;
    {{/program:direct_dependencies}}
}
{{/program:direct_dependencies?}}
