Skip to content

Commit 82333c2

Browse files
author
Stephan February
committed
Refactoring tests for clarity
1 parent 59e1dc2 commit 82333c2

File tree

3 files changed

+141
-136
lines changed

3 files changed

+141
-136
lines changed

test/script/interpreter_test.dart

Lines changed: 102 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:io';
33
import 'dart:typed_data';
44

55
import 'package:buffer/buffer.dart';
6+
import 'package:collection/collection.dart';
67
import 'package:dartsv/dartsv.dart';
78
import 'package:dartsv/src/encoding/utils.dart';
89
import 'package:dartsv/src/script/interpreter.dart';
@@ -209,54 +210,52 @@ void main() {
209210

210211
};
211212

212-
runScripTestFixtures(File fixtureFile) async {
213+
runScripTestFixtures(testData) {
214+
var testName = "";
215+
List.from(jsonDecode(testData)).forEachIndexed((index, vect) {
216+
if (vect.length == 1) {
217+
testName = vect[0];
218+
} else {
213219

214-
await fixtureFile
215-
.readAsString()
216-
.then((contents) => jsonDecode(contents))
217-
.then((jsonData) {
218-
List.from(jsonData).forEach((vect) {
219-
if (vect.length == 1) {
220-
return;
220+
if (vect.length == 5){
221+
testName = vect[4];
222+
}else{
223+
testName = "vector #${index}";
221224
}
222-
var extraData;
223-
if (vect[0] is List) {
225+
test("${testName}",() {
226+
var extraData;
227+
if (vect[0] is List) {
224228
extraData = (vect as List<dynamic>).removeAt(0);
225-
}
229+
}
226230

227-
String fullScriptString = "${vect[0]} ${vect[1]}";
228-
bool expected = vect[3] == 'OK';
229-
String comment = "";
230-
if (vect.length > 4) {
231+
String fullScriptString = "${vect[0]} ${vect[1]}";
232+
bool expected = vect[3] == 'OK';
233+
String comment = "";
234+
if (vect.length > 4) {
231235
comment = vect[4];
232-
}
236+
}
233237

234-
var txt = "should ${vect[3]} script_tests vector : ${fullScriptString}${comment}";
235-
print(txt);
238+
var txt = "should ${vect[3]} script_tests vector : ${fullScriptString}${comment}";
239+
print(txt);
236240

237-
testFixture(vect, expected, extraData);
238-
});
241+
testFixture(vect, expected, extraData);
242+
});
243+
}
239244
});
240245
}
241246

242-
test('bitcoin SV Node Test vectors', () async {
243-
await runScripTestFixtures(File("${Directory.current.path}/test/data/bitcoind/script_tests_svnode.json"));
244-
});
245247

246-
dataDrivenValidTransactions(File testFixtures) async {
248+
dataDrivenValidTransactions(testData){
247249
var testName = "";
248-
await testFixtures
249-
.readAsString()
250-
.then((contents) => jsonDecode(contents))
251-
.then((jsonData) {
252-
List.from(jsonData).forEach((vect) {
250+
List.from(jsonDecode(testData)).forEach((vect){
253251

254-
if (vect.length == 1) {
255-
testName = vect[0];
256-
print("Testing : ${testName}");
257-
}
252+
if(vect.length == 1){
253+
testName = vect[0];
254+
}
255+
256+
if (vect.length > 1) {
257+
test("$testName", (){
258258

259-
if (vect.length > 1) {
260259
Transaction spendingTx;
261260

262261
try {
@@ -283,7 +282,7 @@ void main() {
283282
input.prevTxnOutputIndex = -1;
284283
}
285284

286-
print("Spending INPUT : [${i}]");
285+
// print("Spending INPUT : [${i}]");
287286

288287
//reconstruct the key into our Map of Public Keys using the details from
289288
//the parsed transaction
@@ -307,94 +306,106 @@ void main() {
307306

308307
throw e;
309308
}
310-
}
311-
});
309+
310+
});
311+
}
312312
});
313313
}
314314

315-
dataDrivenInValidTransactions(File testFixtures) async {
315+
dataDrivenInValidTransactions(testData) async {
316+
316317
var testName = "";
317-
await testFixtures.readAsString().then((contents) => jsonDecode(contents)).then((jsonData) {
318-
List.from(jsonData).forEach((vect) {
318+
List.from(jsonDecode(testData)).forEach((vect){
319+
319320
if (vect.length == 1) {
320321
testName = vect[0];
321322
print("Testing : ${testName}");
322323
}
323324

324325
if (vect.length > 1) {
325-
Transaction spendingTx;
326-
bool valid = true;
327326

328-
try {
329-
var inputs = vect[0];
330-
var map = {};
331-
inputs.forEach((input) {
332-
var txid = input[0];
333-
var txoutnum = input[1];
334-
var scriptPubKeyStr = input[2];
335-
map[txid + ':' + txoutnum.toString()] = parseScriptString(scriptPubKeyStr);
336-
});
327+
test("$testName", ()
328+
{
329+
Transaction spendingTx;
330+
bool valid = true;
337331

338-
spendingTx = Transaction.fromHex(vect[1]);
339-
spendingTx.version = 1;
340332
try {
341-
spendingTx.verify();
342-
} on Exception catch (ex) {
343-
valid = false;
344-
}
333+
var inputs = vect[0];
334+
var map = {};
335+
inputs.forEach((input) {
336+
var txid = input[0];
337+
var txoutnum = input[1];
338+
var scriptPubKeyStr = input[2];
339+
map[txid + ':' + txoutnum.toString()] = parseScriptString(scriptPubKeyStr);
340+
});
341+
342+
spendingTx = Transaction.fromHex(vect[1]);
343+
spendingTx.version = 1;
344+
try {
345+
spendingTx.verify();
346+
} on Exception catch (ex) {
347+
valid = false;
348+
}
345349

346-
///all this ceremony to extract Verify Flags
347-
var verifyFlags = parseVerifyFlags(vect[2]);
350+
///all this ceremony to extract Verify Flags
351+
var verifyFlags = parseVerifyFlags(vect[2]);
348352

349-
for (int i = 0; i < spendingTx.inputs.length; i++) {
350-
TransactionInput input = spendingTx.inputs[i];
351-
if (input.prevTxnOutputIndex == 0xffffffff) {
352-
input.prevTxnOutputIndex = -1;
353-
}
353+
for (int i = 0; i < spendingTx.inputs.length; i++) {
354+
TransactionInput input = spendingTx.inputs[i];
355+
if (input.prevTxnOutputIndex == 0xffffffff) {
356+
input.prevTxnOutputIndex = -1;
357+
}
354358

355-
print("Spending INPUT : [${i}]");
359+
print("Spending INPUT : [${i}]");
356360

357-
//reconstruct the key into our Map of Public Keys using the details from
358-
//the parsed transaction
359-
// String txId = HEX.encode(input.prevTxnId);
360-
String keyName = "${input.prevTxnId}:${input.prevTxnOutputIndex}";
361+
//reconstruct the key into our Map of Public Keys using the details from
362+
//the parsed transaction
363+
// String txId = HEX.encode(input.prevTxnId);
364+
String keyName = "${input.prevTxnId}:${input.prevTxnOutputIndex}";
361365

362-
//assert that our parsed transaction has correctly extracted the provided
363-
//UTXO details
364-
// expect(scriptPubKeys.containsKey(keyName), true);
365-
var interp = Interpreter();
366-
interp.correctlySpends(input.script!, map[keyName], spendingTx, i, verifyFlags, Coin.ZERO);
366+
//assert that our parsed transaction has correctly extracted the provided
367+
//UTXO details
368+
// expect(scriptPubKeys.containsKey(keyName), true);
369+
var interp = Interpreter();
370+
interp.correctlySpends(input.script!, map[keyName], spendingTx, i, verifyFlags, Coin.ZERO);
367371

368-
//TODO: Would be better to assert expectation that no exception is thrown ?
369-
//Ans: The whole of the Script Interpreter uses Exception-Handling for error-handling. So no,
370-
// not without a deep refactor of the code.
372+
//TODO: Would be better to assert expectation that no exception is thrown ?
373+
//Ans: The whole of the Script Interpreter uses Exception-Handling for error-handling. So no,
374+
// not without a deep refactor of the code.
375+
}
376+
} on Exception catch (e) {
377+
valid = false;
371378
}
372-
} on Exception catch (e) {
373-
valid = false;
374-
}
375379

376-
if (valid) fail(testName);
380+
if (valid) fail(testName);
381+
});
377382
}
378383
});
379-
});
380384
}
381385

382-
383-
test('bitcoin SV Node valid transaction evaluation fixtures', () async {
384-
await dataDrivenValidTransactions(File("${Directory.current.path}/test/data/bitcoind/tx_valid_svnode.json"));
386+
group('bitcoin SV Node Test vectors', () {
387+
var testData = File("${Directory.current.path}/test/data/bitcoind/script_tests_svnode.json").readAsStringSync();
388+
runScripTestFixtures(testData);
385389
});
386390

391+
group('bitcoin SV Node valid transaction evaluation fixtures', () {
392+
var testData = File("${Directory.current.path}/test/data/bitcoind/tx_valid_svnode.json").readAsStringSync();
393+
dataDrivenValidTransactions(testData);
394+
});
387395

388-
test('bitcoin SV Node invalid transaction evaluation fixtures', () async {
389-
await dataDrivenInValidTransactions(File("${Directory.current.path}/test/data/bitcoind/tx_invalid_svnode.json"));
396+
group('bitcoin SV Node invalid transaction evaluation fixtures', () {
397+
var testData = File("${Directory.current.path}/test/data/bitcoind/tx_invalid_svnode.json").readAsStringSync();
398+
dataDrivenInValidTransactions(testData);
390399
});
391400

392-
test('bitcoind valid transaction evaluation fixtures', () async {
393-
await dataDrivenValidTransactions(File("${Directory.current.path}/test/data/bitcoind/tx_valid.json"));
401+
group('bitcoind valid transaction evaluation fixtures', () {
402+
var testData = File("${Directory.current.path}/test/data/bitcoind/tx_valid.json").readAsStringSync();
403+
dataDrivenValidTransactions(testData);
394404
});
395405

396-
test('bitcoind invalid transaction evaluation fixtures', () async {
397-
await dataDrivenInValidTransactions(File("${Directory.current.path}/test/data/bitcoind/tx_invalid.json"));
406+
group('bitcoind invalid transaction evaluation fixtures', () {
407+
var testData = File("${Directory.current.path}/test/data/bitcoind/tx_invalid.json").readAsStringSync();
408+
dataDrivenInValidTransactions(testData);
398409
});
399410

400411

test/script/script_builder_test.dart

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import 'dart:ffi';
21
import 'dart:typed_data';
32

43
import 'package:dartsv/dartsv.dart';

test/transaction/transaction_test.dart

Lines changed: 39 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:convert';
33
import 'dart:io';
44
import 'dart:typed_data';
55

6+
import 'package:collection/collection.dart';
67
import 'package:dartsv/dartsv.dart';
78
import 'package:test/test.dart';
89

@@ -220,13 +221,11 @@ main() {
220221
expect(transaction.serialize(), equals(tx1hex));
221222
});
222223

224+
group('transaction creation/serialization test vectors ', () {
225+
var bipFileContents = File("${Directory.current.path}/test/data/tx_creation.json").readAsStringSync();
226+
List.from(jsonDecode(bipFileContents)).forEachIndexed((index, item) {
223227

224-
test('transaction creation/serialization test vectors', () async {
225-
await File("${Directory.current.path}/test/data/tx_creation.json")
226-
.readAsString()
227-
.then((contents) => jsonDecode(contents))
228-
.then((jsonData) {
229-
List.from(jsonData).forEach((item) {
228+
test("Txn Vector #${index}", (){
230229
var privKey = SVPrivateKey.fromWIF(item['sign'][0]);
231230
Map<String, dynamic> utxoMap = item['from'][0][0];
232231

@@ -247,6 +246,7 @@ main() {
247246
signer.sign(transaction, TransactionOutput(satoshis, scriptPubKey), 0);
248247
expect(transaction.serialize(), equals(item['serialize']));
249248
});
249+
250250
});
251251
});
252252

@@ -691,52 +691,47 @@ main() {
691691
return sorted.map((value) => original.indexOf(value)).toList();
692692
};
693693

694-
test('input sorting ', () async {
695-
await File("${Directory.current.path}/test/data/bip69.json")
696-
.readAsString()
697-
.then((contents) => jsonDecode(contents))
698-
.then((jsonData) {
699-
HashMap.from(jsonData)["inputs"].forEach((vector) {
700-
var inputSet = vector["inputs"];
701-
var tx = new Transaction();
702-
var txInputs = inputSet.map((input) {
703-
return TransactionInput(
694+
var bipFileContents = File("${Directory.current.path}/test/data/bip69.json").readAsStringSync();
695+
HashMap.from(jsonDecode(bipFileContents))
696+
.forEach((key, value) {
697+
if (key == "outputs") {
698+
value.forEach((outputSet) =>{
699+
test("Input - ${outputSet['description']}", (){
700+
var tx = new Transaction();
701+
702+
var txOutputs = outputSet["outputs"].map((output) {
703+
var txOut = TransactionOutput(BigInt.from(output["value"]), P2PKHDataLockBuilder.fromAddress(fromAddress, utf8.encode(output["script"])).getScriptPubkey());
704+
return txOut;
705+
}).toList();
706+
707+
List<TransactionOutput> outputs = List<TransactionOutput>.from(txOutputs);
708+
tx.outputs.addAll(outputs);
709+
tx.sort();
710+
expect(getIndexOrder(outputs, tx.outputs), equals(outputSet["expected"]));
711+
})
712+
});
713+
}else if(key == "inputs"){
714+
value.forEach((inputSet) => {
715+
test("Output - ${inputSet['description']}", (){
716+
717+
var tx = new Transaction();
718+
var txInputs = inputSet["inputs"].map((input) {
719+
return TransactionInput(
704720
input["txId"],
705721
input["vout"],
706722
TransactionInput.MAX_SEQ_NUMBER,
707723
scriptBuilder: DefaultUnlockBuilder.fromScript(SVScript()));
708-
}).toList();
724+
}).toList();
709725

710-
List<TransactionInput> inputs = List<TransactionInput>.from(txInputs);
711-
tx.inputs.addAll(inputs);
712-
tx.sort();
713-
expect(getIndexOrder(inputs, tx.inputs), equals(vector["expected"]));
726+
List<TransactionInput> inputs = List<TransactionInput>.from(txInputs);
727+
tx.inputs.addAll(inputs);
728+
tx.sort();
729+
expect(getIndexOrder(inputs, tx.inputs), equals(inputSet["expected"]));
730+
})
714731
});
715-
});
732+
}
716733
});
717734

718-
719-
test('output sorting ', () async {
720-
await File("${Directory.current.path}/test/data/bip69.json")
721-
.readAsString()
722-
.then((contents) => jsonDecode(contents))
723-
.then((jsonData) {
724-
HashMap.from(jsonData)["outputs"].forEach((vector) {
725-
var outputSet = vector["outputs"];
726-
var tx = new Transaction();
727-
728-
var txOutputs = outputSet.map((output) {
729-
var txOut = TransactionOutput(BigInt.from(output["value"]), P2PKHDataLockBuilder.fromAddress(fromAddress, utf8.encode(output["script"])).getScriptPubkey());
730-
return txOut;
731-
}).toList();
732-
733-
List<TransactionOutput> outputs = List<TransactionOutput>.from(txOutputs);
734-
tx.outputs.addAll(outputs);
735-
tx.sort();
736-
expect(getIndexOrder(outputs, tx.outputs), equals(vector["expected"]));
737-
});
738-
});
739-
});
740735
});
741736

742737

0 commit comments

Comments
 (0)