init_test.go 7.3 KB

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