1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use std::{collections::HashSet, fs, path::PathBuf, sync::Arc};
use forc_pkg as pkg;
use fuel_tx as tx;
use fuel_vm::{self as vm, prelude::Opcode};
use pkg::BuiltPackage;
use rand::{Rng, SeedableRng};
use sway_core::{language::ty::TyFunctionDeclaration, transform::AttributeKind};
use sway_types::{Span, Spanned};
#[derive(Debug)]
pub enum Tested {
Package(Box<TestedPackage>),
Workspace(Vec<TestedPackage>),
}
#[derive(Debug)]
pub struct TestedPackage {
pub built: Box<pkg::BuiltPackage>,
pub tests: Vec<TestResult>,
}
#[derive(Debug)]
pub struct TestDetails {
pub file_path: Arc<PathBuf>,
pub line_number: usize,
}
#[derive(Debug)]
pub struct TestResult {
pub name: String,
pub duration: std::time::Duration,
pub span: Span,
pub state: vm::state::ProgramState,
pub condition: TestPassCondition,
}
#[derive(Debug)]
pub enum TestPassCondition {
ShouldRevert,
ShouldNotRevert,
}
pub enum BuiltTests {
Package(Box<pkg::BuiltPackage>),
Workspace(Vec<pkg::BuiltPackage>),
}
#[derive(Default)]
pub struct Opts {
pub pkg: pkg::PkgOpts,
pub print: pkg::PrintOpts,
pub minify: pkg::MinifyOpts,
pub binary_outfile: Option<String>,
pub debug_outfile: Option<String>,
pub build_profile: Option<String>,
pub release: bool,
pub time_phases: bool,
}
impl Opts {
pub fn into_build_opts(self) -> pkg::BuildOpts {
pkg::BuildOpts {
pkg: self.pkg,
print: self.print,
minify: self.minify,
binary_outfile: self.binary_outfile,
debug_outfile: self.debug_outfile,
build_profile: self.build_profile,
release: self.release,
time_phases: self.time_phases,
tests: true,
}
}
}
impl TestResult {
pub fn passed(&self) -> bool {
match &self.condition {
TestPassCondition::ShouldRevert => {
matches!(self.state, vm::state::ProgramState::Revert(_))
}
TestPassCondition::ShouldNotRevert => {
!matches!(self.state, vm::state::ProgramState::Revert(_))
}
}
}
pub fn details(&self) -> anyhow::Result<TestDetails> {
let file_path = self
.span
.path()
.ok_or_else(|| anyhow::anyhow!("Missing span for test function"))?
.to_owned();
let span_start = self.span.start();
let file_str = fs::read_to_string(&*file_path)?;
let line_number = file_str[..span_start]
.chars()
.into_iter()
.filter(|&c| c == '\n')
.count();
Ok(TestDetails {
file_path,
line_number,
})
}
}
impl BuiltTests {
pub fn test_count(&self) -> usize {
let pkgs: Vec<&BuiltPackage> = match self {
BuiltTests::Package(pkg) => vec![pkg],
BuiltTests::Workspace(workspace) => workspace.iter().collect(),
};
pkgs.iter()
.map(|pkg| pkg.entries.iter().filter(|e| e.is_test()).count())
.sum()
}
pub fn run(self) -> anyhow::Result<Tested> {
run_tests(self)
}
}
pub fn build(opts: Opts) -> anyhow::Result<BuiltTests> {
let build_opts = opts.into_build_opts();
let built_tests = match pkg::build_with_options(build_opts)? {
pkg::Built::Package(pkg) => BuiltTests::Package(pkg),
pkg::Built::Workspace(workspace) => {
BuiltTests::Workspace(workspace.values().cloned().collect())
}
};
Ok(built_tests)
}
fn test_pass_condition(
test_function_decl: &TyFunctionDeclaration,
) -> anyhow::Result<TestPassCondition> {
let test_args: HashSet<String> = test_function_decl
.attributes
.get(&AttributeKind::Test)
.expect("test declaration is missing test attribute")
.iter()
.flat_map(|attr| attr.args.iter().map(|arg| arg.to_string()))
.collect();
let test_name = &test_function_decl.name;
if test_args.is_empty() {
Ok(TestPassCondition::ShouldNotRevert)
} else if test_args.get("should_revert").is_some() {
Ok(TestPassCondition::ShouldRevert)
} else {
anyhow::bail!("Invalid test argument(s) for test: {test_name}.")
}
}
fn run_tests(built: BuiltTests) -> anyhow::Result<Tested> {
match built {
BuiltTests::Package(pkg) => {
let tested_pkg = run_pkg_tests(*pkg)?;
Ok(Tested::Package(Box::new(tested_pkg)))
}
BuiltTests::Workspace(workspace) => {
let tested_pkgs = workspace
.into_iter()
.map(run_pkg_tests)
.collect::<anyhow::Result<Vec<TestedPackage>>>()?;
Ok(Tested::Workspace(tested_pkgs))
}
}
}
fn run_pkg_tests(built_pkg: BuiltPackage) -> anyhow::Result<TestedPackage> {
let tests = built_pkg
.entries
.iter()
.filter(|entry| entry.is_test())
.map(|entry| {
let offset = u32::try_from(entry.imm).expect("test instruction offset out of range");
let name = entry.fn_name.clone();
let (state, duration) = exec_test(&built_pkg.bytecode, offset);
let test_decl_id = entry
.test_decl_id
.clone()
.expect("test entry point is missing declaration id");
let span = test_decl_id.span();
let test_function_decl =
sway_core::declaration_engine::de_get_function(test_decl_id, &span)
.expect("declaration engine is missing function declaration for test");
let condition = test_pass_condition(&test_function_decl)?;
Ok(TestResult {
name,
duration,
span,
state,
condition,
})
})
.collect::<anyhow::Result<_>>()?;
let tested_pkg = TestedPackage {
built: Box::new(built_pkg),
tests,
};
Ok(tested_pkg)
}
fn patch_test_bytecode(bytecode: &[u8], test_offset: u32) -> std::borrow::Cow<[u8]> {
const PROGRAM_START_INST_OFFSET: u32 = 6;
const PROGRAM_START_BYTE_OFFSET: usize = PROGRAM_START_INST_OFFSET as usize * Opcode::LEN;
if test_offset == PROGRAM_START_INST_OFFSET {
return std::borrow::Cow::Borrowed(bytecode);
}
let ji = Opcode::JI(test_offset);
let ji_bytes = ji.to_bytes();
let start = PROGRAM_START_BYTE_OFFSET;
let end = start + ji_bytes.len();
let mut patched = bytecode.to_vec();
patched.splice(start..end, ji_bytes);
std::borrow::Cow::Owned(patched)
}
fn exec_test(bytecode: &[u8], test_offset: u32) -> (vm::state::ProgramState, std::time::Duration) {
let bytecode = patch_test_bytecode(bytecode, test_offset).into_owned();
let script_input_data = vec![];
let mut rng = rand::rngs::StdRng::seed_from_u64(0x7E57u64);
let maturity = 1;
let block_height = (u32::MAX >> 1) as u64;
let secret_key = rng.gen();
let utxo_id = rng.gen();
let amount = 1;
let asset_id = Default::default();
let tx_ptr = rng.gen();
let params = tx::ConsensusParameters::default();
let tx = tx::TransactionBuilder::script(bytecode, script_input_data)
.add_unsigned_coin_input(secret_key, utxo_id, amount, asset_id, tx_ptr, 0)
.gas_limit(tx::ConsensusParameters::DEFAULT.max_gas_per_tx)
.maturity(maturity)
.finalize_checked(block_height as tx::Word, ¶ms);
let storage = vm::storage::MemoryStorage::default();
let mut interpreter = vm::interpreter::Interpreter::with_storage(storage, params);
let start = std::time::Instant::now();
let transition = interpreter.transact(tx).unwrap();
let duration = start.elapsed();
let state = *transition.state();
(state, duration)
}