paritytech / ink

Compare 9fe9a42 ... +2 ... 802bb13

Coverage Reach
ink/ir/src/ir/item_impl/mod.rs ink/ir/src/ir/item_impl/callable.rs ink/ir/src/ir/item_impl/message.rs ink/ir/src/ir/item_impl/constructor.rs ink/ir/src/ir/item_impl/impl_item.rs ink/ir/src/ir/item_impl/iter.rs ink/ir/src/ir/item_impl/tests.rs ink/ir/src/ir/attrs.rs ink/ir/src/ir/trait_def/item/mod.rs ink/ir/src/ir/trait_def/item/trait_item.rs ink/ir/src/ir/trait_def/item/iter.rs ink/ir/src/ir/trait_def/config.rs ink/ir/src/ir/trait_def/mod.rs ink/ir/src/ir/trait_def/tests.rs ink/ir/src/ir/item/mod.rs ink/ir/src/ir/item/event.rs ink/ir/src/ir/item/storage.rs ink/ir/src/ir/item_mod.rs ink/ir/src/ir/chain_extension.rs ink/ir/src/ir/storage_item/mod.rs ink/ir/src/ir/storage_item/config.rs ink/ir/src/ir/utils.rs ink/ir/src/ir/selector.rs ink/ir/src/ir/e2e_config.rs ink/ir/src/ir/config.rs ink/ir/src/ir/blake2.rs ink/ir/src/ir/idents_lint.rs ink/ir/src/ir/contract.rs ink/ir/src/ir/ink_e2e_test.rs ink/ir/src/ir/ink_test.rs ink/ir/src/ast/attr_args.rs ink/ir/src/literal.rs ink/ir/src/error.rs ink/codegen/src/generator/trait_def/trait_registry.rs ink/codegen/src/generator/trait_def/call_forwarder.rs ink/codegen/src/generator/trait_def/call_builder.rs ink/codegen/src/generator/trait_def/definition.rs ink/codegen/src/generator/trait_def/mod.rs ink/codegen/src/generator/dispatch.rs ink/codegen/src/generator/as_dependency/contract_ref.rs ink/codegen/src/generator/as_dependency/call_builder.rs ink/codegen/src/generator/as_dependency/mod.rs ink/codegen/src/generator/metadata.rs ink/codegen/src/generator/item_impls.rs ink/codegen/src/generator/storage_item.rs ink/codegen/src/generator/events.rs ink/codegen/src/generator/ink_e2e_test.rs ink/codegen/src/generator/chain_extension.rs ink/codegen/src/generator/arg_list.rs ink/codegen/src/generator/storage.rs ink/codegen/src/generator/ink_test.rs ink/codegen/src/generator/contract.rs ink/codegen/src/generator/selector.rs ink/codegen/src/generator/blake2b.rs ink/codegen/src/generator/env.rs ink/codegen/src/generator/mod.rs ink/codegen/src/enforced_error.rs ink/codegen/src/traits.rs ink/codegen/src/lib.rs ink/tests/ui/contract/pass/example-erc721-works.rs ink/tests/ui/contract/pass/example-erc20-works.rs ink/tests/ui/contract/pass/dispatch-decoder-works.rs ink/tests/ui/contract/pass/event-topics.rs ink/tests/ui/contract/pass/event-anonymous.rs ink/tests/ui/contract/pass/event-many-definitions.rs ink/tests/ui/contract/pass/example-trait-incrementer-works.rs ink/tests/ui/contract/pass/message-selector.rs ink/tests/ui/contract/pass/message-many-outputs.rs ink/tests/ui/contract/pass/message-many-inputs.rs ink/tests/ui/contract/pass/env-access.rs ink/tests/ui/contract/pass/example-trait-flipper-works.rs ink/tests/ui/contract/pass/event-config-more-topics.rs ink/tests/ui/contract/pass/example-incrementer-works.rs ink/tests/ui/contract/pass/storage-many-fields.rs ink/tests/ui/contract/pass/constructor-many-inputs.rs ink/tests/ui/contract/pass/example-flipper-works.rs ink/tests/ui/contract/pass/traits-messages-same-name.rs ink/tests/ui/contract/pass/constructor-selector.rs ink/tests/ui/contract/pass/impl-block-using-env.rs ink/tests/ui/contract/pass/module-non-ink-items.rs ink/tests/ui/contract/pass/module-env-types.rs ink/tests/ui/contract/pass/trait-message-selector-guard.rs ink/tests/ui/contract/pass/trait-message-payable-guard.rs ink/tests/ui/contract/pass/message-payable.rs ink/tests/ui/contract/pass/storage-packed-fields.rs ink/tests/ui/contract/pass/constructor-payable-multiple.rs ink/tests/ui/contract/pass/constructor-non-payable-multiple.rs ink/tests/ui/contract/pass/message-wildcard-selector.rs ink/tests/ui/contract/pass/storage-single-field.rs ink/tests/ui/contract/pass/constructor-payable.rs ink/tests/ui/contract/pass/config-keep-attr.rs ink/tests/ui/contract/pass/event-single-definition.rs ink/tests/ui/contract/pass/storage-with-derives.rs ink/tests/ui/contract/pass/constructor-non-payable.rs ink/tests/ui/contract/pass/constructor-wildcard-selector.rs ink/tests/ui/contract/pass/impl-with-property.rs ink/tests/ui/contract/pass/impl-block-namespace.rs ink/tests/ui/contract/pass/no-implicit-prelude.rs ink/tests/ui/contract/pass/impl-alias-storage.rs ink/tests/ui/contract/pass/minimal-contract.rs ink/tests/ui/contract/pass/config-custom-env.rs ink/tests/ui/storage_item/pass/complex_non_packed_enum.rs ink/tests/ui/storage_item/pass/complex_non_packed_struct.rs ink/tests/ui/storage_item/pass/non_packed_tuple_struct.rs ink/tests/ui/storage_item/pass/argument_derive_false.rs ink/tests/ui/storage_item/pass/packed_tuple_struct.rs ink/tests/ui/storage_item/pass/complex_packed_enum.rs ink/tests/ui/storage_item/pass/complex_packed_struct.rs ink/tests/ui/storage_item/pass/default_storage_key_1.rs ink/tests/ui/storage_item/pass/default_storage_key_3.rs ink/tests/ui/storage_item/pass/default_storage_key_4.rs ink/tests/ui/storage_item/pass/default_storage_key_2.rs ink/tests/ui/chain_extension/E-01-simple.rs ink/tests/ui/trait_def/pass/payable_message.rs ink/tests/ui/trait_def/pass/valid_selectors_namespace.rs ink/tests/ui/trait_def/pass/valid_selectors.rs ink/tests/ui/trait_def/pass/avoid_overlap_with_namespace.rs ink/tests/ui/trait_def/pass/with_keep_attr.rs ink/tests/ui/trait_def/pass/many_outputs.rs ink/tests/ui/trait_def/pass/using-env-types.rs ink/tests/ui/trait_def/pass/no-implicit-prelude.rs ink/tests/ui/trait_def/pass/simple_definition.rs ink/tests/ui/trait_def/pass/with_namespace.rs ink/tests/ui/trait_def/pass/many_inputs.rs ink/tests/ui/selector_id/pass/string_input.rs ink/tests/ui/selector_id/pass/bytestring_input.rs ink/tests/ui/selector_id/pass/no_implicit_prelude.rs ink/tests/ui/blake2b/pass/bytestring_input.rs ink/tests/ui/blake2b/pass/string_input.rs ink/tests/ui/blake2b/pass/no_implicit_prelude.rs ink/tests/ui/selector_bytes/pass/bytestring_input.rs ink/tests/ui/selector_bytes/pass/string_input.rs ink/tests/ui/selector_bytes/pass/no_implicit_prelude.rs ink/tests/ui/pay_with_call/pass/multiple_args.rs ink/tests/unique_topics.rs ink/macro/src/storage/storage_layout.rs ink/macro/src/storage/storable.rs ink/macro/src/storage/storable_hint.rs ink/macro/src/storage/storage_key.rs ink/macro/src/storage/tests/mod.rs ink/macro/src/lib.rs ink/macro/src/selector.rs ink/macro/src/blake2b.rs ink/macro/src/storage_item.rs ink/macro/src/contract.rs ink/macro/src/chain_extension.rs ink/macro/src/trait_def.rs ink/macro/src/ink_e2e_test.rs ink/macro/src/ink_test.rs ink/src/env_access.rs ink/src/codegen/dispatch/execution.rs ink/src/reflect/dispatch.rs ink/src/result_info.rs env/src/engine/off_chain/impls.rs env/src/engine/off_chain/test_api.rs env/src/engine/off_chain/types.rs env/src/engine/off_chain/call_data.rs env/src/engine/off_chain/mod.rs env/src/engine/e2e/mod.rs env/src/engine/e2e/xts.rs env/src/call/call_builder.rs env/src/call/execution_input.rs env/src/call/create_builder.rs env/src/call/common.rs env/src/call/selector.rs env/src/api.rs env/src/chain_extension.rs env/src/backend.rs env/src/topics.rs env/src/arithmetic.rs env/src/types.rs metadata/src/specs.rs metadata/src/layout/mod.rs metadata/src/layout/tests.rs metadata/src/layout/validate.rs metadata/src/lib.rs metadata/src/utils.rs engine/src/ext.rs engine/src/test_api.rs engine/src/database.rs engine/src/chain_extension.rs engine/src/exec_context.rs engine/src/hashing.rs engine/src/types.rs engine/src/tests.rs allocator/src/bump.rs storage/src/lazy/mod.rs storage/src/lazy/mapping.rs storage/traits/src/layout/impls.rs storage/traits/src/storage.rs storage/traits/src/impls/mod.rs primitives/src/types.rs primitives/src/key.rs

No flags found

Use flags to group coverage reports by test type, project and/or folders.
Then setup custom commit statuses and notifications for each flag.

e.g., #unittest #integration

#production #enterprise

#frontend #backend

Learn more about Codecov Flags here.

Showing 9 of 30 files from the diff.

@@ -17,6 +17,7 @@
Loading
17 17
mod blake2b;
18 18
mod chain_extension;
19 19
mod contract;
20 +
mod ink_e2e_test;
20 21
mod ink_test;
21 22
mod selector;
22 23
mod storage;
@@ -835,6 +836,136 @@
Loading
835 836
    ink_test::generate(attr.into(), item.into()).into()
836 837
}
837 838
839 +
/// Defines an End-to-End test.
840 +
///
841 +
/// The system requirements are:
842 +
///
843 +
/// - A Substrate node with `pallet-contracts` running in the background.
844 +
///   You can e.g. use [`substrate-contracts-node`](https://github.com/paritytech/substrate-contracts-node)
845 +
///   and launch it with
846 +
///   `substrate-contracts-node -lerror,runtime::contracts=debug > /tmp/contracts-node.log 2>&1`.
847 +
/// - A `cargo-contract` installation that can build the contract.
848 +
///
849 +
/// Before the test function is invoked the contract will have been build. Any errors
850 +
/// that occur during the contract build will prevent the test function from being
851 +
/// invoked.
852 +
///
853 +
/// ## Header Arguments
854 +
///
855 +
/// The `#[ink::e2e_test]` macro can be provided with some additional comma-separated
856 +
/// header arguments:
857 +
///
858 +
/// - `ws_url: String`
859 +
///
860 +
///     The `ws_url` denotes the WebSocket URL where to connect to the RPC
861 +
///     endpoint of the node.
862 +
///
863 +
///     **Usage Example:**
864 +
///     ```no_compile
865 +
///     # // TODO(#xxx) Remove the `no_compile`.
866 +
///     type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
867 +
///     #[ink::e2e_test(ws_url = "ws://localhost:9944")]
868 +
///     async fn e2e_contract_must_transfer_value_to_sender(
869 +
///         mut client: ink::env::e2e::Client<C, E>,
870 +
///     ) -> E2EResult<()> {
871 +
///         Ok(())
872 +
///     }
873 +
///     ```
874 +
///
875 +
///     **Default value:** `"ws://localhost:9944"`.
876 +
///
877 +
/// - `node_log: String`
878 +
///
879 +
///     The `node_log` denotes the path under which to find the node's log.
880 +
///
881 +
///     **Usage Example:**
882 +
///     ```no_compile
883 +
///     # // TODO(#xxx) Remove the `no_compile`.
884 +
///     type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
885 +
///     #[ink::e2e_test(ws_url = "ws://localhost:9944")]
886 +
///     async fn e2e_contract_must_transfer_value_to_sender(
887 +
///         mut client: ink::env::e2e::Client<C, E>,
888 +
///     ) -> E2EResult<()> {
889 +
///         assert!(client.node_log_contains("requested value: 100000000000000\n"));
890 +
///         Ok(())
891 +
///     }
892 +
///     ```
893 +
///
894 +
///     **Default value:** `"/tmp/contracts-node.log"`.
895 +
///
896 +
/// - `skip_build: true`
897 +
///
898 +
///     Skips building the contract as part of the test. This is handy for debugging
899 +
///     test logic, when one wants to avoid the overhead of building the contract.
900 +
///
901 +
///     **Usage Example:**
902 +
///     ```no_compile
903 +
///     # // TODO(#xxx) Remove the `no_compile`.
904 +
///     type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
905 +
///     #[ink::e2e_test(skip_build = true)]
906 +
///     async fn e2e_contract_must_transfer_value_to_sender(
907 +
///         mut client: ink::env::e2e::Client<C, E>,
908 +
///     ) -> E2EResult<()> {
909 +
///         Ok(())
910 +
///     }
911 +
///     ```
912 +
///
913 +
///     **Default value:** `false`.
914 +
///
915 +
/// # Example
916 +
///
917 +
/// ```no_compile
918 +
/// # // TODO(#xxx) Remove the `no_compile`.
919 +
/// #[cfg(test)]
920 +
/// mod tests {
921 +
///     use ink::env::e2e::*;
922 +
///     type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
923 +
///
924 +
///     #[ink::e2e_test(skip_build = true)]
925 +
///     async fn e2e_test_2(mut client: ink::env::e2e::Client<C,E>) -> E2EResult<()> {
926 +
///         // given
927 +
///         let constructor = contract_transfer::constructors::new();
928 +
///         let contract_acc_id = client.instantiate(
929 +
///             &mut ink::env::e2e::alice(),
930 +
///             constructor,
931 +
///             1337,
932 +
///             None,
933 +
///         )
934 +
///         .await
935 +
///         .expect("instantiating contract failed")
936 +
///         .account_id;
937 +
///
938 +
///         // when
939 +
///         let transfer = contract_transfer::messages::give_me(120);
940 +
///         let call_res = client.call(
941 +
///             &mut ink::env::e2e::bob(),
942 +
///             contract_acc_id.clone(),
943 +
///             transfer.into(),
944 +
///             10,
945 +
///             None,
946 +
///         )
947 +
///         .await;
948 +
///
949 +
///         // then
950 +
///         assert!(call_res.is_ok());
951 +
///         Ok(())
952 +
///     }
953 +
/// }
954 +
/// ```
955 +
///
956 +
/// You can also use build the `Signer` type yourself, without going through
957 +
/// the pre-defined functions:
958 +
///
959 +
/// ```no_compile
960 +
/// let mut bob = ink::env::e2e::PairSigner::new(
961 +
///     ink::env::e2e::AccountKeyring::Bob.pair()
962 +
/// );
963 +
/// ```
964 +
#[proc_macro_attribute]
965 +
pub fn e2e_test(attr: TokenStream, item: TokenStream) -> TokenStream {
966 +
    ink_e2e_test::generate(attr.into(), item.into()).into()
967 +
}
968 +
838 969
/// Defines the interface for a chain extension.
839 970
///
840 971
/// # Structure

@@ -0,0 +1,188 @@
Loading
1 +
// Copyright 2018-2022 Parity Technologies (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 +
15 +
use crate::GenerateCode;
16 +
use core::cell::RefCell;
17 +
use derive_more::From;
18 +
use proc_macro2::TokenStream as TokenStream2;
19 +
use quote::quote;
20 +
use std::{
21 +
    path::PathBuf,
22 +
    sync::Once,
23 +
};
24 +
25 +
/// We use this to only build the contract once for all tests.
26 +
static BUILD_ONCE: Once = Once::new();
27 +
28 +
// We save the name of the currently executing test here.
29 +
thread_local! {
30 +
    pub static CONTRACT_PATH: RefCell<Option<PathBuf>> = RefCell::new(None);
31 +
}
32 +
33 +
/// Returns the path to the contract bundle of the contract for which a test
34 +
/// is currently executed.
35 +
pub fn contract_path() -> Option<PathBuf> {
36 +
    CONTRACT_PATH.with(|metadata_path| metadata_path.borrow().clone())
37 +
}
38 +
39 +
/// Generates code for the `[ink::e2e_test]` macro.
40 +
#[derive(From)]
41 +
pub struct InkE2ETest<'a> {
42 +
    /// The test function to generate code for.
43 +
    test: &'a ir::InkE2ETest,
44 +
}
45 +
46 +
impl GenerateCode for InkE2ETest<'_> {
47 +
    /// Generates the code for `#[ink:e2e_test]`.
48 +
    fn generate_code(&self) -> TokenStream2 {
49 +
        #[cfg(clippy)]
50 +
        if true {
51 +
            return quote! {}
52 +
        }
53 +
54 +
        let item_fn = &self.test.item_fn.item_fn;
55 +
        let fn_name = &item_fn.sig.ident;
56 +
        let block = &item_fn.block;
57 +
        let fn_return_type = &item_fn.sig.output;
58 +
        let vis = &item_fn.vis;
59 +
        let attrs = &item_fn.attrs;
60 +
        let ret = match fn_return_type {
61 +
            syn::ReturnType::Default => quote! {},
62 +
            syn::ReturnType::Type(rarrow, ret_type) => quote! { #rarrow #ret_type },
63 +
        };
64 +
65 +
        let ws_url = &self.test.config.ws_url();
66 +
        let node_log = &self.test.config.node_log();
67 +
        let skip_build = &self.test.config.skip_build();
68 +
69 +
        // This path will only be used in case `skip_build` is activated
70 +
        // and no path was specified for it.
71 +
        // TODO(#xxx) we should require specifying a path for `skip_build`.
72 +
        let mut path = PathBuf::from("./target/ink/metadata.json".to_string());
73 +
74 +
        // If a prior test did already build the contract and set the path
75 +
        // to the metadata file.
76 +
        if let Some(metadata_path) = contract_path() {
77 +
            path = metadata_path;
78 +
        }
79 +
80 +
        if !skip_build.value && contract_path().is_none() {
81 +
            BUILD_ONCE.call_once(|| {
82 +
                env_logger::init();
83 +
                use std::process::{
84 +
                    Command,
85 +
                    Stdio,
86 +
                };
87 +
                let output = Command::new("cargo")
88 +
                    // TODO(#xxx) Add possibility of configuring `skip_linting` in attributes.
89 +
                    .args(["+stable", "contract", "build", "--skip-linting", "--output-json"])
90 +
                    .env("RUST_LOG", "")
91 +
                    .stderr(Stdio::inherit())
92 +
                    .output()
93 +
                    .expect("failed to execute `cargo-contract` build process");
94 +
95 +
                log::info!("`cargo-contract` returned status: {}", output.status);
96 +
                eprintln!("`cargo-contract` returned status: {}", output.status);
97 +
                log::info!(
98 +
                    "`cargo-contract` stdout: {}",
99 +
                    String::from_utf8_lossy(&output.stdout)
100 +
                );
101 +
                eprintln!(
102 +
                    "`cargo-contract` stdout: {}",
103 +
                    String::from_utf8_lossy(&output.stdout)
104 +
                );
105 +
                if !output.status.success() {
106 +
                    log::info!(
107 +
                        "`cargo-contract` stderr: {}",
108 +
                        String::from_utf8_lossy(&output.stderr)
109 +
                    );
110 +
                    eprintln!(
111 +
                        "`cargo-contract` stderr: {}",
112 +
                        String::from_utf8_lossy(&output.stderr)
113 +
                    );
114 +
                }
115 +
116 +
                assert!(output.status.success());
117 +
118 +
                let json = String::from_utf8_lossy(&output.stdout);
119 +
                let metadata: serde_json::Value =
120 +
                    serde_json::from_str(&json).expect("cannot convert json to utf8");
121 +
                let mut dest_metadata =
122 +
                    metadata["metadata_result"]["dest_bundle"].to_string();
123 +
                dest_metadata = dest_metadata.trim_matches('"').to_string();
124 +
                path = PathBuf::from(dest_metadata);
125 +
                log::info!("extracted metadata path: {}", path.display());
126 +
127 +
                CONTRACT_PATH.with(|metadata_path| {
128 +
                    *metadata_path.borrow_mut() = Some(path.clone());
129 +
                });
130 +
            });
131 +
        } else {
132 +
            BUILD_ONCE.call_once(|| {
133 +
                env_logger::init();
134 +
            });
135 +
        }
136 +
137 +
        log::info!("using metadata path: {:?}", path);
138 +
139 +
        path.try_exists().unwrap_or_else(|err| {
140 +
            panic!("path {:?} does not exist: {:?}", path, err);
141 +
        });
142 +
        let os_path = path
143 +
            .as_os_str()
144 +
            .to_str()
145 +
            .expect("converting path to str failed");
146 +
        let path = syn::LitStr::new(os_path, proc_macro2::Span::call_site());
147 +
148 +
        quote! {
149 +
            #( #attrs )*
150 +
            #[ink::env::e2e::tokio::test]
151 +
            async #vis fn #fn_name () #ret {
152 +
                use ink::env::e2e::log_info;
153 +
                ink::env::e2e::LOG_PREFIX.with(|log_prefix| {
154 +
                    let str = format!("test: {}", stringify!(#fn_name));
155 +
                    *log_prefix.borrow_mut() = String::from(str);
156 +
                });
157 +
                log_info("setting up e2e test");
158 +
159 +
                ink::env::e2e::INIT.call_once(|| {
160 +
                    ink::env::e2e::env_logger::init();
161 +
                });
162 +
163 +
                log_info("extracting metadata");
164 +
                // TODO(#1421) `smart-bench_macro` needs to be forked.
165 +
                ink::env::e2e::smart_bench_macro::contract!(#path);
166 +
167 +
                log_info("creating new client");
168 +
169 +
                // TODO(#xxx) Make those two generic environments customizable.
170 +
                let mut client = ink::env::e2e::Client::<
171 +
                    ink::env::e2e::PolkadotConfig,
172 +
                    ink::env::DefaultEnvironment
173 +
                >::new(&#path, &#ws_url, &#node_log).await;
174 +
175 +
                let __ret = {
176 +
                    #block
177 +
                };
178 +
                __ret
179 +
            }
180 +
        }
181 +
    }
182 +
}
183 +
184 +
impl GenerateCode for ir::InkE2ETest {
185 +
    fn generate_code(&self) -> TokenStream2 {
186 +
        InkE2ETest::from(self).generate_code()
187 +
    }
188 +
}

@@ -0,0 +1,121 @@
Loading
1 +
// Copyright 2018-2022 Parity Technologies (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 +
15 +
//! Module for the logic behind ink!'s End-to-End testing framework.
16 +
17 +
mod client;
18 +
mod default_accounts;
19 +
mod xts;
20 +
21 +
pub use client::{
22 +
    Client,
23 +
    Error,
24 +
};
25 +
pub use default_accounts::*;
26 +
// TODO(#1421) `smart-bench_macro` needs to be forked.
27 +
use pallet_contracts_primitives::{
28 +
    ContractExecResult,
29 +
    ContractInstantiateResult,
30 +
};
31 +
pub use smart_bench_macro;
32 +
use xts::ContractsApi;
33 +
34 +
pub use env_logger;
35 +
pub use sp_keyring::AccountKeyring;
36 +
pub use subxt::tx::PairSigner;
37 +
pub use tokio;
38 +
39 +
use log;
40 +
use sp_core::sr25519;
41 +
use sp_runtime::traits::{
42 +
    IdentifyAccount,
43 +
    Verify,
44 +
};
45 +
use std::{
46 +
    cell::RefCell,
47 +
    sync::Once,
48 +
};
49 +
50 +
/// Default set of commonly used types by Substrate runtimes.
51 +
#[cfg(feature = "std")]
52 +
pub enum SubstrateConfig {}
53 +
54 +
#[cfg(feature = "std")]
55 +
impl subxt::Config for SubstrateConfig {
56 +
    type Index = u32;
57 +
    type BlockNumber = u32;
58 +
    type Hash = sp_core::H256;
59 +
    type Hashing = sp_runtime::traits::BlakeTwo256;
60 +
    type AccountId = sp_runtime::AccountId32;
61 +
    type Address = sp_runtime::MultiAddress<Self::AccountId, u32>;
62 +
    type Header =
63 +
        sp_runtime::generic::Header<Self::BlockNumber, sp_runtime::traits::BlakeTwo256>;
64 +
    type Signature = sp_runtime::MultiSignature;
65 +
    type Extrinsic = sp_runtime::OpaqueExtrinsic;
66 +
    type ExtrinsicParams = subxt::tx::SubstrateExtrinsicParams<Self>;
67 +
}
68 +
69 +
/// Default set of commonly used types by Polkadot nodes.
70 +
#[cfg(feature = "std")]
71 +
pub type PolkadotConfig = subxt::config::WithExtrinsicParams<
72 +
    SubstrateConfig,
73 +
    subxt::tx::PolkadotExtrinsicParams<SubstrateConfig>,
74 +
>;
75 +
76 +
/// Signer that is used throughout the E2E testing.
77 +
///
78 +
/// The E2E testing can only be used with nodes that support `sr25519`
79 +
/// cryptography.
80 +
pub type Signer<C> = PairSigner<C, sr25519::Pair>;
81 +
82 +
/// Trait for contract constructors.
83 +
// TODO(#1421) Merge this with `InkMessage` to be just `InkSelector`. Requires forking `smart-bench-macro`.
84 +
pub trait InkConstructor: scale::Encode {
85 +
    /// An ink! selector consists of four bytes.
86 +
    const SELECTOR: [u8; 4];
87 +
}
88 +
89 +
/// Trait for contract messages.
90 +
pub trait InkMessage: scale::Encode {
91 +
    /// An ink! selector consists of four bytes.
92 +
    const SELECTOR: [u8; 4];
93 +
}
94 +
95 +
/// We use this to only initialize `env_logger` once.
96 +
pub static INIT: Once = Once::new();
97 +
98 +
// We save the name of the currently executing test here as a mean
99 +
// of prefixing log entries to make it easier pinning them to tests.
100 +
thread_local! {
101 +
    /// This prefix will be used for log output. It is set by each
102 +
    /// `#[ink::e2e_test]` with the function name as String.
103 +
    /// This way it is possible to distinguish the lines in stdout
104 +
    /// and stderr, to still know which line belongs to which test.
105 +
    pub static LOG_PREFIX: RefCell<String> = RefCell::new(String::from("no prefix set"));
106 +
}
107 +
108 +
/// Returns the name of the test which is currently executed.
109 +
pub fn log_prefix() -> String {
110 +
    LOG_PREFIX.with(|log_prefix| log_prefix.borrow().clone())
111 +
}
112 +
113 +
/// Writes `msg` to stdout.
114 +
pub fn log_info(msg: &str) {
115 +
    log::info!("[{}] {}", log_prefix(), msg);
116 +
}
117 +
118 +
/// Writes `msg` to stderr.
119 +
pub fn log_error(msg: &str) {
120 +
    log::error!("[{}] {}", log_prefix(), msg);
121 +
}

@@ -34,6 +34,7 @@
Loading
34 34
mod dispatch;
35 35
mod env;
36 36
mod events;
37 +
mod ink_e2e_test;
37 38
mod ink_test;
38 39
mod item_impls;
39 40
mod metadata;
@@ -59,6 +60,7 @@
Loading
59 60
    dispatch::Dispatch,
60 61
    env::Env,
61 62
    events::Events,
63 +
    ink_e2e_test::InkE2ETest,
62 64
    ink_test::InkTest,
63 65
    item_impls::ItemImpls,
64 66
    metadata::Metadata,

@@ -0,0 +1,29 @@
Loading
1 +
// Copyright 2018-2022 Parity Technologies (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 +
15 +
use ink_codegen::generate_code;
16 +
use proc_macro2::TokenStream as TokenStream2;
17 +
use syn::Result;
18 +
19 +
pub fn generate(attr: TokenStream2, input: TokenStream2) -> TokenStream2 {
20 +
    match generate_or_err(attr, input) {
21 +
        Ok(tokens) => tokens,
22 +
        Err(err) => err.to_compile_error(),
23 +
    }
24 +
}
25 +
26 +
pub fn generate_or_err(attr: TokenStream2, input: TokenStream2) -> Result<TokenStream2> {
27 +
    let test_definition = ink_ir::InkE2ETest::new(attr, input)?;
28 +
    Ok(generate_code(&test_definition))
29 +
}

Click to load this diff.
Loading diff...

Click to load this diff.
Loading diff...

Click to load this diff.
Loading diff...

Click to load this diff.
Loading diff...

Learn more Showing 6 files with coverage changes found.

New file crates/ink/macro/src/ink_e2e_test.rs
New
Loading file...
New file crates/ink/codegen/src/generator/ink_e2e_test.rs
New
Loading file...
New file crates/env/src/engine/e2e/xts.rs
New
Loading file...
New file crates/ink/ir/src/ir/e2e_config.rs
New
Loading file...
New file crates/env/src/engine/e2e/mod.rs
New
Loading file...
New file crates/ink/ir/src/ir/ink_e2e_test.rs
New
Loading file...
Files Coverage
crates -1.20% 70.78%
Project Totals (193 files) 70.78%
Loading