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::LimitsMetrics,
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).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 SuiVMTestSetup::new(),
123 compute_coverage,
124 save_disassembly,
125 &mut std::io::stdout(),
126 )
127 .await;
128
129 result.map(|(test_result, warning_diags)| {
130 if test_result == UnitTestResult::Success
131 && let Some(diags) = warning_diags
132 {
133 decorate_warnings(diags, None);
134 }
135 test_result
136 })
137}
138
139pub struct SuiVMTestSetup {
140 gas_price: u64,
141 reference_gas_price: u64,
142 protocol_config: ProtocolConfig,
143 native_function_table: move_vm_runtime::natives::functions::NativeFunctionTable,
144}
145
146impl Default for SuiVMTestSetup {
147 fn default() -> Self {
148 Self::new()
149 }
150}
151
152impl SuiVMTestSetup {
153 pub fn new() -> Self {
154 let protocol_config = ProtocolConfig::get_for_max_version_UNSAFE();
155 let native_function_table =
156 sui_move_natives::all_natives(false, &protocol_config);
157 Self {
158 gas_price: TEST_GAS_PRICE,
159 reference_gas_price: TEST_GAS_PRICE,
160 protocol_config,
161 native_function_table,
162 }
163 }
164
165 pub fn max_gas_budget(&self) -> u64 {
166 self.protocol_config.max_tx_gas()
167 }
168}
169
170impl VMTestSetup for SuiVMTestSetup {
171 type Meter<'a> = SuiGasMeter<SuiGasStatusTestWrapper>;
172 type ExtensionsBuilder<'a> = InMemoryTestStore;
173
174 fn new_meter<'a>(&'a self, execution_bound: Option<u64>) -> Self::Meter<'a> {
175 SuiGasMeter(SuiGasStatusTestWrapper(
176 SuiGasStatus::new(
177 execution_bound.unwrap_or(*MAX_UNIT_TEST_INSTRUCTIONS),
178 self.gas_price,
179 self.reference_gas_price,
180 &self.protocol_config,
181 )
182 .unwrap(),
183 ))
184 }
185
186 fn used_gas<'a>(&'a self, execution_bound: u64, meter: Self::Meter<'a>) -> u64 {
187 let gas_status = &meter.0;
188 Gas::new(execution_bound)
189 .checked_sub(gas_status.remaining_gas())
190 .unwrap()
191 .into()
192 }
193
194 fn vm_config(&self) -> VMConfig {
195 sui_adapter::adapter::vm_config(&self.protocol_config)
196 }
197
198 fn native_function_table(&self) -> move_vm_runtime::natives::functions::NativeFunctionTable {
199 self.native_function_table.clone()
200 }
201
202 fn new_extensions_builder(&self) -> InMemoryTestStore {
203 InMemoryTestStore(RefCell::new(InMemoryStorage::default()))
204 }
205
206 fn new_native_context_extensions<'ext>(
207 &self,
208 store: &'ext InMemoryTestStore,
209 ) -> NativeContextExtensions<'ext> {
210 let mut ext = NativeContextExtensions::default();
211 let registry = prometheus::Registry::new();
213 let metrics = Arc::new(LimitsMetrics::new(®istry));
214
215 ext.add(ObjectRuntime::new(
216 store,
217 BTreeMap::new(),
218 false,
219 Box::leak(Box::new(ProtocolConfig::get_for_max_version_UNSAFE())), metrics,
221 0, ));
223 ext.add(NativesCostTable::from_protocol_config(
224 &self.protocol_config,
225 ));
226 let tx_context = TxContext::new_from_components(
227 &SuiAddress::ZERO,
228 &TransactionDigest::default(),
229 &0,
230 0,
231 0,
232 0,
233 0,
234 None,
235 &self.protocol_config,
236 );
237 ext.add(TransactionContext::new_for_testing(Rc::new(RefCell::new(
238 tx_context,
239 ))));
240 ext.add(store);
241 ext
242 }
243}
244
245pub struct SuiGasStatusTestWrapper(SuiGasStatus);
247
248impl Deref for SuiGasStatusTestWrapper {
249 type Target = GasStatus;
250
251 fn deref(&self) -> &Self::Target {
252 self.0.move_gas_status()
253 }
254}
255
256impl DerefMut for SuiGasStatusTestWrapper {
257 fn deref_mut(&mut self) -> &mut Self::Target {
258 self.0.move_gas_status_mut()
259 }
260}