testable.rs 4.82 KB
Newer Older
1 2
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
3 4 5
// 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
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9 10 11 12 13
// 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.
14

Hero Bird's avatar
Hero Bird committed
15 16 17 18 19 20 21
use derive_more::From;
use proc_macro2::TokenStream as TokenStream2;
use quote::{
    quote,
    quote_spanned,
};

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
use crate::{
    codegen::{
        GenerateCode,
        GenerateCodeUsing,
    },
    ir,
    ir::utils,
};

#[derive(From)]
pub struct TestWrapper<'a> {
    contract: &'a ir::Contract,
}

impl GenerateCodeUsing for TestWrapper<'_> {
    fn contract(&self) -> &ir::Contract {
        &self.contract
    }
}

impl GenerateCode for TestWrapper<'_> {
    fn generate_code(&self) -> TokenStream2 {
        let wrapped_constructors = self.generate_constructors();
        let testable_storage_and_env = self.generate_testable_storage_and_env();

        quote! {
            #[cfg(all(test, feature = "test-env"))]
49
            pub use self::__ink_testable::TestableStorage;
50 51 52 53 54

            #[cfg(all(test, feature = "test-env"))]
            mod __ink_testable {
                use super::*;

55 56
                impl ink_lang::InstantiateTestable for Storage {
                    type Wrapped = TestableStorage;
57 58

                    fn instantiate() -> Self::Wrapped {
59 60
                        ink_core::env::test::initialize_as_default::<ink_core::env::DefaultEnvTypes>()
                            .expect("encountered already initialized off-chain environment");
61 62 63
                        let mut contract: Self = unsafe {
                            let mut alloc =
                                ink_core::storage::alloc::BumpAlloc::from_raw_parts(
64
                                    ink_primitives::Key([0x00; 32]),
65 66 67 68 69 70 71 72 73 74 75 76
                                );
                            ink_core::storage::alloc::AllocateUsing::allocate_using(
                                &mut alloc,
                            )
                        };
                        ink_core::storage::alloc::Initialize::try_default_initialize(
                            &mut contract,
                        );
                        contract.into()
                    }
                }

77
                pub use self::__ink_private::TestableStorage;
78 79 80 81 82 83
                mod __ink_private {
                    use super::*;

                    #testable_storage_and_env
                }

84
                impl TestableStorage {
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
                    #(
                        #wrapped_constructors
                    )*
                }
            }
        }
    }
}

impl TestWrapper<'_> {
    fn generate_constructors<'a>(&'a self) -> impl Iterator<Item = TokenStream2> + 'a {
        self.contract.functions.iter().filter_map(|function| {
            function
                .filter_constructor()
                .map(|kind| (function, kind))
        }).map(|(function, _kind)| {
            let span = function.span();
            let ident = &function.sig.ident;
            let fn_args = function.sig.inputs();
            let arg_idents = function.sig.inputs().map(move |fn_arg| &fn_arg.ident);

            quote_spanned!(span=>
                pub fn #ident(
                    #(#fn_args),*
109 110
                ) -> <Storage as ink_lang::InstantiateTestable>::Wrapped {
                    let mut contract = <Storage as ink_lang::InstantiateTestable>::instantiate();
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
                    contract.#ident(
                        #(
                            #arg_idents
                        ),*
                    );
                    contract
                }
            )
        })
    }

    fn generate_testable_storage_and_env(&self) -> TokenStream2 {
        let attrs = utils::filter_non_ink_attributes(&self.contract.storage.attrs);

        quote! {
            #( #attrs )*
            #[derive(Debug)]
128 129
            pub struct TestableStorage {
                contract: Storage,
130 131
            }

132 133
            impl From<Storage> for TestableStorage {
                fn from(contract: Storage) -> Self {
134 135 136 137
                    Self { contract }
                }
            }

138 139
            impl core::ops::Deref for TestableStorage {
                type Target = Storage;
140 141 142 143 144 145

                fn deref(&self) -> &Self::Target {
                    &self.contract
                }
            }

146
            impl core::ops::DerefMut for TestableStorage {
147 148 149 150 151 152 153
                fn deref_mut(&mut self) -> &mut Self::Target {
                    &mut self.contract
                }
            }
        }
    }
}