github.com/theQRL/go-zond@v0.2.1/tests/init_test.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package tests
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"io"
    24  	"os"
    25  	"path/filepath"
    26  	"reflect"
    27  	"regexp"
    28  	"runtime"
    29  	"sort"
    30  	"strings"
    31  	"testing"
    32  
    33  	"github.com/theQRL/go-zond/params"
    34  )
    35  
    36  var (
    37  	baseDir            = filepath.Join(".", "testdata")
    38  	blockTestDir       = filepath.Join(baseDir, "BlockchainTests")
    39  	stateTestDir       = filepath.Join(baseDir, "GeneralStateTests")
    40  	legacyStateTestDir = filepath.Join(baseDir, "LegacyTests", "Constantinople", "GeneralStateTests")
    41  	transactionTestDir = filepath.Join(baseDir, "TransactionTests")
    42  	rlpTestDir         = filepath.Join(baseDir, "RLPTests")
    43  	executionSpecDir   = filepath.Join(".", "spec-tests", "fixtures")
    44  	benchmarksDir      = filepath.Join(".", "evm-benchmarks", "benchmarks")
    45  )
    46  
    47  func readJSON(reader io.Reader, value interface{}) error {
    48  	data, err := io.ReadAll(reader)
    49  	if err != nil {
    50  		return fmt.Errorf("error reading JSON file: %v", err)
    51  	}
    52  	if err = json.Unmarshal(data, &value); err != nil {
    53  		if syntaxerr, ok := err.(*json.SyntaxError); ok {
    54  			line := findLine(data, syntaxerr.Offset)
    55  			return fmt.Errorf("JSON syntax error at line %v: %v", line, err)
    56  		}
    57  		return err
    58  	}
    59  	return nil
    60  }
    61  
    62  func readJSONFile(fn string, value interface{}) error {
    63  	file, err := os.Open(fn)
    64  	if err != nil {
    65  		return err
    66  	}
    67  	defer file.Close()
    68  
    69  	err = readJSON(file, value)
    70  	if err != nil {
    71  		return fmt.Errorf("%s in file %s", err.Error(), fn)
    72  	}
    73  	return nil
    74  }
    75  
    76  // findLine returns the line number for the given offset into data.
    77  func findLine(data []byte, offset int64) (line int) {
    78  	line = 1
    79  	for i, r := range string(data) {
    80  		if int64(i) >= offset {
    81  			return
    82  		}
    83  		if r == '\n' {
    84  			line++
    85  		}
    86  	}
    87  	return
    88  }
    89  
    90  // testMatcher controls skipping and chain config assignment to tests.
    91  type testMatcher struct {
    92  	configpat      []testConfig
    93  	failpat        []testFailure
    94  	skiploadpat    []*regexp.Regexp
    95  	slowpat        []*regexp.Regexp
    96  	runonlylistpat *regexp.Regexp
    97  }
    98  
    99  type testConfig struct {
   100  	p      *regexp.Regexp
   101  	config params.ChainConfig
   102  }
   103  
   104  type testFailure struct {
   105  	p      *regexp.Regexp
   106  	reason string
   107  }
   108  
   109  // skipShortMode skips tests matching when the -short flag is used.
   110  func (tm *testMatcher) slow(pattern string) {
   111  	tm.slowpat = append(tm.slowpat, regexp.MustCompile(pattern))
   112  }
   113  
   114  // skipLoad skips JSON loading of tests matching the pattern.
   115  func (tm *testMatcher) skipLoad(pattern string) {
   116  	tm.skiploadpat = append(tm.skiploadpat, regexp.MustCompile(pattern))
   117  }
   118  
   119  // fails adds an expected failure for tests matching the pattern.
   120  //
   121  //nolint:unused
   122  func (tm *testMatcher) fails(pattern string, reason string) {
   123  	if reason == "" {
   124  		panic("empty fail reason")
   125  	}
   126  	tm.failpat = append(tm.failpat, testFailure{regexp.MustCompile(pattern), reason})
   127  }
   128  
   129  func (tm *testMatcher) runonly(pattern string) {
   130  	tm.runonlylistpat = regexp.MustCompile(pattern)
   131  }
   132  
   133  // config defines chain config for tests matching the pattern.
   134  func (tm *testMatcher) config(pattern string, cfg params.ChainConfig) {
   135  	tm.configpat = append(tm.configpat, testConfig{regexp.MustCompile(pattern), cfg})
   136  }
   137  
   138  // findSkip matches name against test skip patterns.
   139  func (tm *testMatcher) findSkip(name string) (reason string, skipload bool) {
   140  	isWin32 := runtime.GOARCH == "386" && runtime.GOOS == "windows"
   141  	for _, re := range tm.slowpat {
   142  		if re.MatchString(name) {
   143  			if testing.Short() {
   144  				return "skipped in -short mode", false
   145  			}
   146  			if isWin32 {
   147  				return "skipped on 32bit windows", false
   148  			}
   149  		}
   150  	}
   151  	for _, re := range tm.skiploadpat {
   152  		if re.MatchString(name) {
   153  			return "skipped by skipLoad", true
   154  		}
   155  	}
   156  	return "", false
   157  }
   158  
   159  // findConfig returns the chain config matching defined patterns.
   160  func (tm *testMatcher) findConfig(t *testing.T) *params.ChainConfig {
   161  	for _, m := range tm.configpat {
   162  		if m.p.MatchString(t.Name()) {
   163  			return &m.config
   164  		}
   165  	}
   166  	return new(params.ChainConfig)
   167  }
   168  
   169  // checkFailure checks whether a failure is expected.
   170  func (tm *testMatcher) checkFailure(t *testing.T, err error) error {
   171  	failReason := ""
   172  	for _, m := range tm.failpat {
   173  		if m.p.MatchString(t.Name()) {
   174  			failReason = m.reason
   175  			break
   176  		}
   177  	}
   178  	if failReason != "" {
   179  		t.Logf("expected failure: %s", failReason)
   180  		if err != nil {
   181  			t.Logf("error: %v", err)
   182  			return nil
   183  		}
   184  		return errors.New("test succeeded unexpectedly")
   185  	}
   186  	return err
   187  }
   188  
   189  // walk invokes its runTest argument for all subtests in the given directory.
   190  //
   191  // runTest should be a function of type func(t *testing.T, name string, x <TestType>),
   192  // where TestType is the type of the test contained in test files.
   193  func (tm *testMatcher) walk(t *testing.T, dir string, runTest interface{}) {
   194  	// Walk the directory.
   195  	dirinfo, err := os.Stat(dir)
   196  	if os.IsNotExist(err) || !dirinfo.IsDir() {
   197  		fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the tests submodule?\n", dir)
   198  		t.Skip("missing test files")
   199  	}
   200  	err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
   201  		name := filepath.ToSlash(strings.TrimPrefix(path, dir+string(filepath.Separator)))
   202  		if info.IsDir() {
   203  			if _, skipload := tm.findSkip(name + "/"); skipload {
   204  				return filepath.SkipDir
   205  			}
   206  			return nil
   207  		}
   208  		if filepath.Ext(path) == ".json" {
   209  			t.Run(name, func(t *testing.T) { tm.runTestFile(t, path, name, runTest) })
   210  		}
   211  		return nil
   212  	})
   213  	if err != nil {
   214  		t.Fatal(err)
   215  	}
   216  }
   217  
   218  func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest interface{}) {
   219  	if r, _ := tm.findSkip(name); r != "" {
   220  		t.Skip(r)
   221  	}
   222  	if tm.runonlylistpat != nil {
   223  		if !tm.runonlylistpat.MatchString(name) {
   224  			t.Skip("Skipped by runonly")
   225  		}
   226  	}
   227  	t.Parallel()
   228  
   229  	// Load the file as map[string]<testType>.
   230  	m := makeMapFromTestFunc(runTest)
   231  	if err := readJSONFile(path, m.Addr().Interface()); err != nil {
   232  		t.Fatal(err)
   233  	}
   234  
   235  	// Run all tests from the map. Don't wrap in a subtest if there is only one test in the file.
   236  	keys := sortedMapKeys(m)
   237  	if len(keys) == 1 {
   238  		runTestFunc(runTest, t, name, m, keys[0])
   239  	} else {
   240  		for _, key := range keys {
   241  			name := name + "/" + key
   242  			t.Run(key, func(t *testing.T) {
   243  				if r, _ := tm.findSkip(name); r != "" {
   244  					t.Skip(r)
   245  				}
   246  				runTestFunc(runTest, t, name, m, key)
   247  			})
   248  		}
   249  	}
   250  }
   251  
   252  func makeMapFromTestFunc(f interface{}) reflect.Value {
   253  	stringT := reflect.TypeOf("")
   254  	testingT := reflect.TypeOf((*testing.T)(nil))
   255  	ftyp := reflect.TypeOf(f)
   256  	if ftyp.Kind() != reflect.Func || ftyp.NumIn() != 3 || ftyp.NumOut() != 0 || ftyp.In(0) != testingT || ftyp.In(1) != stringT {
   257  		panic(fmt.Sprintf("bad test function type: want func(*testing.T, string, <TestType>), have %s", ftyp))
   258  	}
   259  	testType := ftyp.In(2)
   260  	mp := reflect.New(reflect.MapOf(stringT, testType))
   261  	return mp.Elem()
   262  }
   263  
   264  func sortedMapKeys(m reflect.Value) []string {
   265  	keys := make([]string, m.Len())
   266  	for i, k := range m.MapKeys() {
   267  		keys[i] = k.String()
   268  	}
   269  	sort.Strings(keys)
   270  	return keys
   271  }
   272  
   273  func runTestFunc(runTest interface{}, t *testing.T, name string, m reflect.Value, key string) {
   274  	reflect.ValueOf(runTest).Call([]reflect.Value{
   275  		reflect.ValueOf(t),
   276  		reflect.ValueOf(name),
   277  		m.MapIndex(reflect.ValueOf(key)),
   278  	})
   279  }
   280  
   281  func TestMatcherRunonlylist(t *testing.T) {
   282  	t.Parallel()
   283  	tm := new(testMatcher)
   284  	tm.runonly("invalid*")
   285  	tm.walk(t, rlpTestDir, func(t *testing.T, name string, test *RLPTest) {
   286  		if name[:len("invalidRLPTest.json")] != "invalidRLPTest.json" {
   287  			t.Fatalf("invalid test found: %s != invalidRLPTest.json", name)
   288  		}
   289  	})
   290  }