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