ink_codegen/generator/ink_test.rs
1// Copyright (C) Use Ink (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::GenerateCode;
16use derive_more::From;
17use proc_macro2::TokenStream as TokenStream2;
18use quote::quote;
19
20/// Generates code for the `[ink::test]` macro.
21#[derive(From)]
22pub struct InkTest<'a> {
23 /// The test function to generate code for.
24 test: &'a ir::InkTest,
25}
26
27impl GenerateCode for InkTest<'_> {
28 /// Generates the code for `#[ink:test]`.
29 fn generate_code(&self) -> TokenStream2 {
30 let item_fn = &self.test.item_fn;
31 let attrs = &item_fn.attrs;
32 let sig = &item_fn.sig;
33 let fn_name = &sig.ident;
34 let fn_return_type = &sig.output;
35 let fn_block = &item_fn.block;
36 let vis = &item_fn.vis;
37 let fn_args = &sig.inputs;
38 let expect_msg = format!(
39 "{}: the off-chain testing environment returned an error",
40 stringify!(#fn_name)
41 );
42 match fn_return_type {
43 syn::ReturnType::Default => {
44 quote! {
45 #( #attrs )*
46 #[test]
47 #vis fn #fn_name( #fn_args ) {
48 ::ink::env::test::run_test::<::ink::env::DefaultEnvironment, _>(|_| {
49 {
50 {
51 #fn_block
52 };
53 ::core::result::Result::Ok(())
54 }
55 })
56 .unwrap_or_else(|error| ::core::panic!("{}: {:?}", #expect_msg, error));
57 }
58 }
59 }
60 syn::ReturnType::Type(rarrow, ret_type) => {
61 quote! {
62 #( #attrs )*
63 #[test]
64 #vis fn #fn_name( #fn_args ) #rarrow #ret_type {
65 ::ink::env::test::run_test::<::ink::env::DefaultEnvironment, _>(|_| {
66 #fn_block
67 })
68 }
69 }
70 }
71 }
72 }
73}
74
75impl GenerateCode for ir::InkTest {
76 fn generate_code(&self) -> TokenStream2 {
77 InkTest::from(self).generate_code()
78 }
79}