init_test.go 8.0 KB

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