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