forked from onflow/cadence-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_runner.go
507 lines (414 loc) · 13.5 KB
/
test_runner.go
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright 2019-2022 Dapper Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test
import (
"fmt"
"strings"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/engine/execution/testutil"
"github.com/onflow/flow-go/fvm"
"github.com/onflow/flow-go/fvm/environment"
"github.com/onflow/cadence/runtime"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/interpreter"
"github.com/onflow/cadence/runtime/sema"
"github.com/onflow/cadence/runtime/stdlib"
)
// This Provides utility methods to easily run test-scripts.
// Example use-case:
// - To run all tests in a script:
// RunTests("source code")
// - To run a single test method in a script:
// RunTest("source code", "testMethodName")
//
// It is assumed that all test methods start with the 'test' prefix.
const testFunctionPrefix = "test"
const setupFunctionName = "setup"
const tearDownFunctionName = "tearDown"
var testScriptLocation = common.NewScriptLocation(nil, []byte("test"))
type Results []Result
type Result struct {
TestName string
Error error
}
// ImportResolver is used to resolve and get the source code for imports.
// Must be provided by the user of the TestRunner.
type ImportResolver func(location common.Location) (string, error)
// FileResolver is used to resolve and get local files.
// Returns the content of the file as a string.
// Must be provided by the user of the TestRunner.
type FileResolver func(path string) (string, error)
// TestRunner runs tests.
type TestRunner struct {
// importResolver is used to resolve imports of the *test script*.
// Note: This doesn't resolve the imports for the code that is being tested.
// i.e: the code that is submitted to the blockchain.
// Users need to use configurations to set the import mapping for the testing code.
importResolver ImportResolver
// fileResolver is used to resolve local files.
//
fileResolver FileResolver
testRuntime runtime.Runtime
coverageReport *runtime.CoverageReport
}
func NewTestRunner() *TestRunner {
return &TestRunner{
testRuntime: runtime.NewInterpreterRuntime(runtime.Config{}),
}
}
func (r *TestRunner) WithImportResolver(importResolver ImportResolver) *TestRunner {
r.importResolver = importResolver
return r
}
func (r *TestRunner) WithFileResolver(fileResolver FileResolver) *TestRunner {
r.fileResolver = fileResolver
return r
}
func (r *TestRunner) WithCoverageReport(coverageReport *runtime.CoverageReport) *TestRunner {
r.coverageReport = coverageReport
return r
}
// RunTest runs a single test in the provided test script.
func (r *TestRunner) RunTest(script string, funcName string) (result *Result, err error) {
defer func() {
recoverPanics(func(internalErr error) {
err = internalErr
})
}()
_, inter, err := r.parseCheckAndInterpret(script)
if err != nil {
return nil, err
}
// Run test `setup()` before running the test function.
err = r.runTestSetup(inter)
if err != nil {
return nil, err
}
_, testResult := inter.Invoke(funcName)
// Run test `tearDown()` once running all test functions are completed.
err = r.runTestTearDown(inter)
return &Result{
TestName: funcName,
Error: testResult,
}, err
}
// RunTests runs all the tests in the provided test script.
func (r *TestRunner) RunTests(script string) (results Results, err error) {
defer func() {
recoverPanics(func(internalErr error) {
err = internalErr
})
}()
program, inter, err := r.parseCheckAndInterpret(script)
if err != nil {
return nil, err
}
results = make(Results, 0)
// Run test `setup()` before test functions
err = r.runTestSetup(inter)
if err != nil {
return nil, err
}
for _, funcDecl := range program.Program.FunctionDeclarations() {
funcName := funcDecl.Identifier.Identifier
if !strings.HasPrefix(funcName, testFunctionPrefix) {
continue
}
err := r.invokeTestFunction(inter, funcName)
results = append(results, Result{
TestName: funcName,
Error: err,
})
}
// Run test `tearDown()` once running all test functions are completed.
err = r.runTestTearDown(inter)
return results, err
}
func (r *TestRunner) runTestSetup(inter *interpreter.Interpreter) error {
if !hasSetup(inter) {
return nil
}
return r.invokeTestFunction(inter, setupFunctionName)
}
func hasSetup(inter *interpreter.Interpreter) bool {
return inter.Globals.Contains(setupFunctionName)
}
func (r *TestRunner) runTestTearDown(inter *interpreter.Interpreter) error {
if !hasTearDown(inter) {
return nil
}
return r.invokeTestFunction(inter, tearDownFunctionName)
}
func hasTearDown(inter *interpreter.Interpreter) bool {
return inter.Globals.Contains(tearDownFunctionName)
}
func (r *TestRunner) invokeTestFunction(inter *interpreter.Interpreter, funcName string) (err error) {
// Individually fail each test-case for any internal error.
defer func() {
recoverPanics(func(internalErr error) {
err = internalErr
})
}()
_, err = inter.Invoke(funcName)
return err
}
func recoverPanics(onError func(error)) {
r := recover()
switch r := r.(type) {
case nil:
return
case error:
onError(r)
default:
onError(fmt.Errorf("%s", r))
}
}
func (r *TestRunner) parseCheckAndInterpret(script string) (*interpreter.Program, *interpreter.Interpreter, error) {
config := runtime.Config{
CoverageReportingEnabled: r.coverageReport != nil,
}
env := runtime.NewBaseInterpreterEnvironment(config)
ctx := runtime.Context{
Interface: newScriptEnvironment(),
Location: testScriptLocation,
Environment: env,
}
if r.coverageReport != nil {
r.coverageReport.ExcludeLocation(stdlib.CryptoCheckerLocation)
r.coverageReport.ExcludeLocation(stdlib.TestContractLocation)
r.coverageReport.ExcludeLocation(testScriptLocation)
ctx.CoverageReport = r.coverageReport
}
// Checker configs
env.CheckerConfig.ImportHandler = r.checkerImportHandler(ctx)
env.CheckerConfig.ContractValueHandler = contractValueHandler
// Interpreter configs
env.InterpreterConfig.ImportLocationHandler = r.interpreterImportHandler(ctx)
// It is safe to use the test-runner's environment as the standard library handler
// in the test framework, since it is only used for value conversions (i.e: values
// returned from blockchain to the test script)
env.InterpreterConfig.ContractValueHandler = r.interpreterContractValueHandler(env)
// TODO: The default injected fields handler only supports 'address' locations.
// However, during tests, it is possible to get non-address locations. e.g: file paths.
// Thus, need to properly handle them. Make this nil for now.
env.InterpreterConfig.InjectedCompositeFieldsHandler = nil
program, err := r.testRuntime.ParseAndCheckProgram([]byte(script), ctx)
if err != nil {
return nil, nil, err
}
// TODO: validate test function signature
// e.g: no return values, no arguments, etc.
// Set the storage after checking, because `ParseAndCheckProgram` clears the storage.
env.InterpreterConfig.Storage = runtime.NewStorage(ctx.Interface, nil)
_, inter, err := env.Interpret(
ctx.Location,
program,
nil,
)
if err != nil {
return nil, nil, err
}
return program, inter, nil
}
func (r *TestRunner) checkerImportHandler(ctx runtime.Context) sema.ImportHandlerFunc {
return func(
checker *sema.Checker,
importedLocation common.Location,
importRange ast.Range,
) (sema.Import, error) {
var elaboration *sema.Elaboration
switch importedLocation {
case stdlib.CryptoCheckerLocation:
cryptoChecker := stdlib.CryptoChecker()
elaboration = cryptoChecker.Elaboration
case stdlib.TestContractLocation:
elaboration = stdlib.TestContractChecker.Elaboration
default:
_, importedElaboration, err := r.parseAndCheckImport(importedLocation, ctx)
if err != nil {
return nil, err
}
elaboration = importedElaboration
}
return sema.ElaborationImport{
Elaboration: elaboration,
}, nil
}
}
func contractValueHandler(
checker *sema.Checker,
declaration *ast.CompositeDeclaration,
compositeType *sema.CompositeType,
) sema.ValueDeclaration {
constructorType, constructorArgumentLabels := sema.CompositeLikeConstructorType(
checker.Elaboration,
declaration,
compositeType,
)
return stdlib.StandardLibraryValue{
Name: declaration.Identifier.Identifier,
Type: constructorType,
DocString: declaration.DocString,
Kind: declaration.DeclarationKind(),
Position: &declaration.Identifier.Pos,
ArgumentLabels: constructorArgumentLabels,
}
}
func (r *TestRunner) interpreterContractValueHandler(
stdlibHandler stdlib.StandardLibraryHandler,
) interpreter.ContractValueHandlerFunc {
return func(
inter *interpreter.Interpreter,
compositeType *sema.CompositeType,
constructorGenerator func(common.Address) *interpreter.HostFunctionValue,
invocationRange ast.Range,
) interpreter.ContractValue {
switch compositeType.Location {
case stdlib.CryptoCheckerLocation:
contract, err := stdlib.NewCryptoContract(
inter,
constructorGenerator(common.Address{}),
invocationRange,
)
if err != nil {
panic(err)
}
return contract
case stdlib.TestContractLocation:
testFramework := NewEmulatorBackend(
r.fileResolver,
stdlibHandler,
r.coverageReport,
)
contract, err := stdlib.NewTestContract(
inter,
testFramework,
constructorGenerator(common.Address{}),
invocationRange,
)
if err != nil {
panic(err)
}
return contract
default:
// During tests, imported contracts can be constructed using the constructor,
// similar to structs. Therefore, generate a constructor function.
return constructorGenerator(common.Address{})
}
}
}
func (r *TestRunner) interpreterImportHandler(ctx runtime.Context) func(inter *interpreter.Interpreter, location common.Location) interpreter.Import {
return func(inter *interpreter.Interpreter, location common.Location) interpreter.Import {
switch location {
case stdlib.CryptoCheckerLocation:
cryptoChecker := stdlib.CryptoChecker()
program := interpreter.ProgramFromChecker(cryptoChecker)
subInterpreter, err := inter.NewSubInterpreter(program, location)
if err != nil {
panic(err)
}
return interpreter.InterpreterImport{
Interpreter: subInterpreter,
}
case stdlib.TestContractLocation:
program := interpreter.ProgramFromChecker(stdlib.TestContractChecker)
subInterpreter, err := inter.NewSubInterpreter(program, location)
if err != nil {
panic(err)
}
return interpreter.InterpreterImport{
Interpreter: subInterpreter,
}
default:
importedProgram, importedElaboration, err := r.parseAndCheckImport(location, ctx)
if err != nil {
panic(err)
}
program := &interpreter.Program{
Program: importedProgram,
Elaboration: importedElaboration,
}
subInterpreter, err := inter.NewSubInterpreter(program, location)
if err != nil {
panic(err)
}
return interpreter.InterpreterImport{
Interpreter: subInterpreter,
}
}
}
}
// newScriptEnvironment creates an environment for test scripts to run.
// Leverages the functionality of FVM.
func newScriptEnvironment() environment.Environment {
vm := fvm.NewVirtualMachine()
ctx := fvm.NewContext(fvm.WithLogger(zerolog.Nop()))
snapshotTree := testutil.RootBootstrappedLedger(vm, ctx)
return environment.NewScriptEnvironmentFromStorageSnapshot(
environment.DefaultEnvironmentParams(),
snapshotTree,
)
}
func (r *TestRunner) parseAndCheckImport(location common.Location, startCtx runtime.Context) (*ast.Program, *sema.Elaboration, error) {
if r.importResolver == nil {
return nil, nil, ImportResolverNotProvidedError{}
}
code, err := r.importResolver(location)
if err != nil {
return nil, nil, err
}
// Create a new (child) context, with new environment.
env := runtime.NewBaseInterpreterEnvironment(runtime.Config{})
ctx := runtime.Context{
Interface: startCtx.Interface,
Location: location,
Environment: env,
}
env.CheckerConfig.ImportHandler = func(
checker *sema.Checker,
importedLocation common.Location,
importRange ast.Range,
) (sema.Import, error) {
return nil, fmt.Errorf("nested imports are not supported")
}
env.CheckerConfig.ContractValueHandler = contractValueHandler
program, err := r.testRuntime.ParseAndCheckProgram([]byte(code), ctx)
if err != nil {
return nil, nil, err
}
return program.Program, program.Elaboration, nil
}
// PrettyPrintResults is a utility function to pretty print the test results.
func PrettyPrintResults(results Results, scriptPath string) string {
var sb strings.Builder
fmt.Fprintf(&sb, "Test results: %q\n", scriptPath)
for _, result := range results {
sb.WriteString(PrettyPrintResult(result.TestName, result.Error))
sb.WriteRune('\n')
}
return sb.String()
}
func PrettyPrintResult(funcName string, err error) string {
if err == nil {
return fmt.Sprintf("- PASS: %s", funcName)
}
// Indent the error messages
errString := strings.ReplaceAll(err.Error(), "\n", "\n\t\t\t")
return fmt.Sprintf("- FAIL: %s\n\t\t%s", funcName, errString)
}