1use clap::Parser;
5use move_cli::base::{
6 self,
7 test::{self, UnitTestResult},
8};
9use move_package_alt_compilation::build_config::BuildConfig;
10use move_unit_test::{UnitTestingConfig, vm_test_setup::VMTestSetup};
11use move_vm_config::runtime::VMConfig;
12use move_vm_runtime::natives::extensions::NativeContextExtensions;
13use std::{
14 cell::RefCell,
15 collections::BTreeMap,
16 ops::{Deref, DerefMut},
17 path::Path,
18 rc::Rc,
19 sync::{Arc, LazyLock},
20};
21use sui_adapter::gas_meter::SuiGasMeter;
22use sui_move_build::decorate_warnings;
23use sui_move_natives::{
24 NativesCostTable, object_runtime::ObjectRuntime, test_scenario::InMemoryTestStore,
25 transaction_context::TransactionContext,
26};
27use sui_package_alt::find_environment;
28use sui_protocol_config::ProtocolConfig;
29use sui_sdk::wallet_context::WalletContext;
30use sui_types::{
31 base_types::{SuiAddress, TxContext},
32 digests::TransactionDigest,
33 gas::{SuiGasStatus, SuiGasStatusAPI},
34 gas_model::{tables::GasStatus, units_types::Gas},
35 in_memory_storage::InMemoryStorage,
36 metrics::ExecutionMetrics,
37};
38
39pub static MAX_UNIT_TEST_INSTRUCTIONS: LazyLock<u64> =
41 LazyLock::new(|| ProtocolConfig::get_for_max_version_UNSAFE().max_tx_gas());
42
43const TEST_GAS_PRICE: u64 = 500;
45
46#[derive(Parser)]
47#[group(id = "sui-move-test")]
48pub struct Test {
49 #[clap(flatten)]
50 pub test: test::Test,
51}
52
53impl Test {
54 pub async fn execute(
55 self,
56 path: Option<&Path>,
57 mut build_config: BuildConfig,
58 wallet: &WalletContext,
59 ) -> anyhow::Result<UnitTestResult> {
60 let compute_coverage = self.test.compute_coverage;
61 if !cfg!(feature = "tracing") && compute_coverage {
62 return Err(anyhow::anyhow!(
63 "The --coverage flag is currently supported only in builds built with the `tracing` feature enabled. \
64 Please build the Sui CLI from source with `--features tracing` to use this flag."
65 ));
66 }
67 let save_disassembly = self.test.trace.is_some();
69 if build_config.default_flavor.is_none() {
71 build_config.default_flavor = Some(move_compiler::editions::Flavor::Sui);
72 }
73
74 let rerooted_path = base::reroot_path(path)?;
76
77 let unit_test_config = self
81 .test
82 .unit_test_config(Some(*MAX_UNIT_TEST_INSTRUCTIONS));
83
84 let environment =
88 find_environment(&rerooted_path, build_config.environment, wallet, false).await?;
89 build_config.environment = Some(environment.name);
90
91 run_move_unit_tests(
92 &rerooted_path,
93 build_config,
94 Some(unit_test_config),
95 compute_coverage,
96 save_disassembly,
97 )
98 .await
99 }
100}
101
102pub async fn run_move_unit_tests(
105 path: &Path,
106 build_config: BuildConfig,
107 config: Option<UnitTestingConfig>,
108 compute_coverage: bool,
109 save_disassembly: bool,
110) -> anyhow::Result<UnitTestResult> {
111 let config = config.unwrap_or_else(|| {
112 UnitTestingConfig::default_with_bound(Some(*MAX_UNIT_TEST_INSTRUCTIONS))
113 });
114
115 let result = move_cli::base::test::run_move_unit_tests::<sui_package_alt::SuiFlavor, _, _>(
116 path,
117 build_config,
118 UnitTestingConfig {
119 report_stacktrace_on_abort: true,
120 ..config
121 },
122 sui_package_alt::SuiFlavor::new(),
123 SuiVMTestSetup::new(),
124 compute_coverage,
125 save_disassembly,
126 &mut std::io::stdout(),
127 )
128 .await;
129
130 result.map(|(test_result, warning_diags)| {
131 if test_result == UnitTestResult::Success
132 && let Some(diags) = warning_diags
133 {
134 decorate_warnings(diags, None);
135 }
136 test_result
137 })
138}
139
140pub struct SuiVMTestSetup {
141 gas_price: u64,
142 reference_gas_price: u64,
143 protocol_config: ProtocolConfig,
144 native_function_table: move_vm_runtime::natives::functions::NativeFunctionTable,
145}
146
147impl Default for SuiVMTestSetup {
148 fn default() -> Self {
149 Self::new()
150 }
151}
152
153impl SuiVMTestSetup {
154 pub fn new() -> Self {
155 let protocol_config = ProtocolConfig::get_for_max_version_UNSAFE();
156 let native_function_table =
157 sui_move_natives::all_natives(false, &protocol_config);
158 Self {
159 gas_price: TEST_GAS_PRICE,
160 reference_gas_price: TEST_GAS_PRICE,
161 protocol_config,
162 native_function_table,
163 }
164 }
165
166 pub fn max_gas_budget(&self) -> u64 {
167 self.protocol_config.max_tx_gas()
168 }
169}
170
171impl VMTestSetup for SuiVMTestSetup {
172 type Meter<'a> = SuiGasMeter<SuiGasStatusTestWrapper>;
173 type ExtensionsBuilder<'a> = InMemoryTestStore;
174
175 fn new_meter<'a>(&'a self, execution_bound: Option<u64>) -> Self::Meter<'a> {
176 SuiGasMeter(SuiGasStatusTestWrapper(
177 SuiGasStatus::new(
178 execution_bound.unwrap_or(*MAX_UNIT_TEST_INSTRUCTIONS),
179 self.gas_price,
180 self.reference_gas_price,
181 &self.protocol_config,
182 )
183 .unwrap(),
184 ))
185 }
186
187 fn used_gas<'a>(&'a self, execution_bound: u64, meter: Self::Meter<'a>) -> u64 {
188 let gas_status = &meter.0;
189 Gas::new(execution_bound)
190 .checked_sub(gas_status.remaining_gas())
191 .unwrap()
192 .into()
193 }
194
195 fn vm_config(&self) -> VMConfig {
196 sui_adapter::adapter::vm_config(&self.protocol_config)
197 }
198
199 fn native_function_table(&self) -> move_vm_runtime::natives::functions::NativeFunctionTable {
200 self.native_function_table.clone()
201 }
202
203 fn new_extensions_builder(&self) -> InMemoryTestStore {
204 InMemoryTestStore(RefCell::new(InMemoryStorage::default()))
205 }
206
207 fn new_native_context_extensions<'ext>(
208 &self,
209 store: &'ext InMemoryTestStore,
210 ) -> NativeContextExtensions<'ext> {
211 let mut ext = NativeContextExtensions::default();
212 let registry = prometheus::Registry::new();
214 let metrics = Arc::new(ExecutionMetrics::new(®istry));
215
216 ext.add(ObjectRuntime::new(
217 store,
218 BTreeMap::new(),
219 false,
220 Box::leak(Box::new(ProtocolConfig::get_for_max_version_UNSAFE())), metrics,
222 0, ));
224 ext.add(NativesCostTable::from_protocol_config(
225 &self.protocol_config,
226 ));
227 let tx_context = TxContext::new_from_components(
228 &SuiAddress::ZERO,
229 &TransactionDigest::default(),
230 &0,
231 0,
232 0,
233 0,
234 0,
235 None,
236 &self.protocol_config,
237 );
238 ext.add(TransactionContext::new_for_testing(Rc::new(RefCell::new(
239 tx_context,
240 ))));
241 ext.add(store);
242 ext
243 }
244}
245
246pub struct SuiGasStatusTestWrapper(SuiGasStatus);
248
249impl Deref for SuiGasStatusTestWrapper {
250 type Target = GasStatus;
251
252 fn deref(&self) -> &Self::Target {
253 self.0.move_gas_status()
254 }
255}
256
257impl DerefMut for SuiGasStatusTestWrapper {
258 fn deref_mut(&mut self) -> &mut Self::Target {
259 self.0.move_gas_status_mut()
260 }
261}