github.com/klaytn/klaytn@v1.10.2/tests/init_test.go (about)

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