github.com/ethereum/go-ethereum@v1.16.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/ethereum/go-ethereum/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  	difficultyTestDir               = filepath.Join(baseDir, "BasicTests")
    44  	executionSpecBlockchainTestDir  = filepath.Join(".", "spec-tests", "fixtures", "blockchain_tests")
    45  	executionSpecStateTestDir       = filepath.Join(".", "spec-tests", "fixtures", "state_tests")
    46  	executionSpecTransactionTestDir = filepath.Join(".", "spec-tests", "fixtures", "transaction_tests")
    47  	benchmarksDir                   = filepath.Join(".", "evm-benchmarks", "benchmarks")
    48  )
    49  
    50  func readJSON(reader io.Reader, value interface{}) error {
    51  	data, err := io.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  // slow adds expected slow tests matching the pattern.
   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  //
   124  //nolint:unused
   125  func (tm *testMatcher) fails(pattern string, reason string) {
   126  	if reason == "" {
   127  		panic("empty fail reason")
   128  	}
   129  	tm.failpat = append(tm.failpat, testFailure{regexp.MustCompile(pattern), reason})
   130  }
   131  
   132  func (tm *testMatcher) runonly(pattern string) {
   133  	tm.runonlylistpat = regexp.MustCompile(pattern)
   134  }
   135  
   136  // config defines chain config for tests matching the pattern.
   137  func (tm *testMatcher) config(pattern string, cfg params.ChainConfig) {
   138  	tm.configpat = append(tm.configpat, testConfig{regexp.MustCompile(pattern), cfg})
   139  }
   140  
   141  // findSkip matches name against test skip patterns.
   142  func (tm *testMatcher) findSkip(name string) (reason string, skipload bool) {
   143  	isWin32 := runtime.GOARCH == "386" && runtime.GOOS == "windows"
   144  	for _, re := range tm.slowpat {
   145  		if re.MatchString(name) {
   146  			if testing.Short() {
   147  				return "skipped in -short mode", false
   148  			}
   149  			if isWin32 {
   150  				return "skipped on 32bit windows", false
   151  			}
   152  		}
   153  	}
   154  	for _, re := range tm.skiploadpat {
   155  		if re.MatchString(name) {
   156  			return "skipped by skipLoad", true
   157  		}
   158  	}
   159  	return "", false
   160  }
   161  
   162  // findConfig returns the chain config matching defined patterns.
   163  func (tm *testMatcher) findConfig(t *testing.T) *params.ChainConfig {
   164  	for _, m := range tm.configpat {
   165  		if m.p.MatchString(t.Name()) {
   166  			return &m.config
   167  		}
   168  	}
   169  	return new(params.ChainConfig)
   170  }
   171  
   172  // checkFailure checks whether a failure is expected.
   173  func (tm *testMatcher) checkFailure(t *testing.T, err error) error {
   174  	failReason := ""
   175  	for _, m := range tm.failpat {
   176  		if m.p.MatchString(t.Name()) {
   177  			failReason = m.reason
   178  			break
   179  		}
   180  	}
   181  	if failReason != "" {
   182  		t.Logf("expected failure: %s", failReason)
   183  		if err != nil {
   184  			t.Logf("error: %v", err)
   185  			return nil
   186  		}
   187  		return errors.New("test succeeded unexpectedly")
   188  	}
   189  	return err
   190  }
   191  
   192  // walk invokes its runTest argument for all subtests in the given directory.
   193  //
   194  // runTest should be a function of type func(t *testing.T, name string, x <TestType>),
   195  // where TestType is the type of the test contained in test files.
   196  func (tm *testMatcher) walk(t *testing.T, dir string, runTest interface{}) {
   197  	// Walk the directory.
   198  	dirinfo, err := os.Stat(dir)
   199  	if os.IsNotExist(err) || !dirinfo.IsDir() {
   200  		fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the tests submodule?\n", dir)
   201  		t.Skip("missing test files")
   202  	}
   203  	err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
   204  		name := filepath.ToSlash(strings.TrimPrefix(path, dir+string(filepath.Separator)))
   205  		if info.IsDir() {
   206  			if _, skipload := tm.findSkip(name + "/"); skipload {
   207  				return filepath.SkipDir
   208  			}
   209  			return nil
   210  		}
   211  		if filepath.Ext(path) == ".json" {
   212  			t.Run(name, func(t *testing.T) { tm.runTestFile(t, path, name, runTest) })
   213  		}
   214  		return nil
   215  	})
   216  	if err != nil {
   217  		t.Fatal(err)
   218  	}
   219  }
   220  
   221  func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest interface{}) {
   222  	if r, _ := tm.findSkip(name); r != "" {
   223  		t.Skip(r)
   224  	}
   225  	if tm.runonlylistpat != nil {
   226  		if !tm.runonlylistpat.MatchString(name) {
   227  			t.Skip("Skipped by runonly")
   228  		}
   229  	}
   230  	t.Parallel()
   231  
   232  	// Load the file as map[string]<testType>.
   233  	m := makeMapFromTestFunc(runTest)
   234  	if err := readJSONFile(path, m.Addr().Interface()); err != nil {
   235  		t.Fatal(err)
   236  	}
   237  
   238  	// Run all tests from the map. Don't wrap in a subtest if there is only one test in the file.
   239  	keys := sortedMapKeys(m)
   240  	if len(keys) == 1 {
   241  		runTestFunc(runTest, t, name, m, keys[0])
   242  	} else {
   243  		for _, key := range keys {
   244  			name := name + "/" + key
   245  			t.Run(key, func(t *testing.T) {
   246  				if r, _ := tm.findSkip(name); r != "" {
   247  					t.Skip(r)
   248  				}
   249  				runTestFunc(runTest, t, name, m, key)
   250  			})
   251  		}
   252  	}
   253  }
   254  
   255  func makeMapFromTestFunc(f interface{}) reflect.Value {
   256  	stringT := reflect.TypeOf("")
   257  	testingT := reflect.TypeOf((*testing.T)(nil))
   258  	ftyp := reflect.TypeOf(f)
   259  	if ftyp.Kind() != reflect.Func || ftyp.NumIn() != 3 || ftyp.NumOut() != 0 || ftyp.In(0) != testingT || ftyp.In(1) != stringT {
   260  		panic(fmt.Sprintf("bad test function type: want func(*testing.T, string, <TestType>), have %s", ftyp))
   261  	}
   262  	testType := ftyp.In(2)
   263  	mp := reflect.New(reflect.MapOf(stringT, testType))
   264  	return mp.Elem()
   265  }
   266  
   267  func sortedMapKeys(m reflect.Value) []string {
   268  	keys := make([]string, m.Len())
   269  	for i, k := range m.MapKeys() {
   270  		keys[i] = k.String()
   271  	}
   272  	sort.Strings(keys)
   273  	return keys
   274  }
   275  
   276  func runTestFunc(runTest interface{}, t *testing.T, name string, m reflect.Value, key string) {
   277  	reflect.ValueOf(runTest).Call([]reflect.Value{
   278  		reflect.ValueOf(t),
   279  		reflect.ValueOf(name),
   280  		m.MapIndex(reflect.ValueOf(key)),
   281  	})
   282  }
   283  
   284  func TestMatcherRunonlylist(t *testing.T) {
   285  	t.Parallel()
   286  	tm := new(testMatcher)
   287  	tm.runonly("invalid*")
   288  	tm.walk(t, rlpTestDir, func(t *testing.T, name string, test *RLPTest) {
   289  		if name[:len("invalidRLPTest.json")] != "invalidRLPTest.json" {
   290  			t.Fatalf("invalid test found: %s != invalidRLPTest.json", name)
   291  		}
   292  	})
   293  }