init_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. "runtime"
  27. "sort"
  28. "strings"
  29. "testing"
  30. "github.com/ethereum/go-ethereum/params"
  31. )
  32. var (
  33. baseDir = filepath.Join(".", "testdata")
  34. blockTestDir = filepath.Join(baseDir, "BlockchainTests")
  35. stateTestDir = filepath.Join(baseDir, "GeneralStateTests")
  36. transactionTestDir = filepath.Join(baseDir, "TransactionTests")
  37. vmTestDir = filepath.Join(baseDir, "VMTests")
  38. rlpTestDir = filepath.Join(baseDir, "RLPTests")
  39. difficultyTestDir = filepath.Join(baseDir, "BasicTests")
  40. )
  41. func readJSON(reader io.Reader, value interface{}) error {
  42. data, err := ioutil.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. whitelistpat *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. func (tm *testMatcher) fails(pattern string, reason string) {
  106. if reason == "" {
  107. panic("empty fail reason")
  108. }
  109. tm.failpat = append(tm.failpat, testFailure{regexp.MustCompile(pattern), reason})
  110. }
  111. func (tm *testMatcher) whitelist(pattern string) {
  112. tm.whitelistpat = regexp.MustCompile(pattern)
  113. }
  114. // config defines chain config for tests matching the pattern.
  115. func (tm *testMatcher) config(pattern string, cfg params.ChainConfig) {
  116. tm.configpat = append(tm.configpat, testConfig{regexp.MustCompile(pattern), cfg})
  117. }
  118. // findSkip matches name against test skip patterns.
  119. func (tm *testMatcher) findSkip(name string) (reason string, skipload bool) {
  120. isWin32 := runtime.GOARCH == "386" && runtime.GOOS == "windows"
  121. for _, re := range tm.slowpat {
  122. if re.MatchString(name) {
  123. if testing.Short() {
  124. return "skipped in -short mode", false
  125. }
  126. if isWin32 {
  127. return "skipped on 32bit windows", false
  128. }
  129. }
  130. }
  131. for _, re := range tm.skiploadpat {
  132. if re.MatchString(name) {
  133. return "skipped by skipLoad", true
  134. }
  135. }
  136. return "", false
  137. }
  138. // findConfig returns the chain config matching defined patterns.
  139. func (tm *testMatcher) findConfig(name string) *params.ChainConfig {
  140. // TODO(fjl): name can be derived from testing.T when min Go version is 1.8
  141. for _, m := range tm.configpat {
  142. if m.p.MatchString(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, name string, err error) error {
  150. // TODO(fjl): name can be derived from t when min Go version is 1.8
  151. failReason := ""
  152. for _, m := range tm.failpat {
  153. if m.p.MatchString(name) {
  154. failReason = m.reason
  155. break
  156. }
  157. }
  158. if failReason != "" {
  159. t.Logf("expected failure: %s", failReason)
  160. if err != nil {
  161. t.Logf("error: %v", err)
  162. return nil
  163. }
  164. return fmt.Errorf("test succeeded unexpectedly")
  165. }
  166. return err
  167. }
  168. // walk invokes its runTest argument for all subtests in the given directory.
  169. //
  170. // runTest should be a function of type func(t *testing.T, name string, x <TestType>),
  171. // where TestType is the type of the test contained in test files.
  172. func (tm *testMatcher) walk(t *testing.T, dir string, runTest interface{}) {
  173. // Walk the directory.
  174. dirinfo, err := os.Stat(dir)
  175. if os.IsNotExist(err) || !dirinfo.IsDir() {
  176. fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the tests submodule?\n", dir)
  177. t.Skip("missing test files")
  178. }
  179. err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  180. name := filepath.ToSlash(strings.TrimPrefix(path, dir+string(filepath.Separator)))
  181. if info.IsDir() {
  182. if _, skipload := tm.findSkip(name + "/"); skipload {
  183. return filepath.SkipDir
  184. }
  185. return nil
  186. }
  187. if filepath.Ext(path) == ".json" {
  188. t.Run(name, func(t *testing.T) { tm.runTestFile(t, path, name, runTest) })
  189. }
  190. return nil
  191. })
  192. if err != nil {
  193. t.Fatal(err)
  194. }
  195. }
  196. func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest interface{}) {
  197. if r, _ := tm.findSkip(name); r != "" {
  198. t.Skip(r)
  199. }
  200. if tm.whitelistpat != nil {
  201. if !tm.whitelistpat.MatchString(name) {
  202. t.Skip("Skipped by whitelist")
  203. }
  204. }
  205. t.Parallel()
  206. // Load the file as map[string]<testType>.
  207. m := makeMapFromTestFunc(runTest)
  208. if err := readJSONFile(path, m.Addr().Interface()); err != nil {
  209. t.Fatal(err)
  210. }
  211. // Run all tests from the map. Don't wrap in a subtest if there is only one test in the file.
  212. keys := sortedMapKeys(m)
  213. if len(keys) == 1 {
  214. runTestFunc(runTest, t, name, m, keys[0])
  215. } else {
  216. for _, key := range keys {
  217. name := name + "/" + key
  218. t.Run(key, func(t *testing.T) {
  219. if r, _ := tm.findSkip(name); r != "" {
  220. t.Skip(r)
  221. }
  222. runTestFunc(runTest, t, name, m, key)
  223. })
  224. }
  225. }
  226. }
  227. func makeMapFromTestFunc(f interface{}) reflect.Value {
  228. stringT := reflect.TypeOf("")
  229. testingT := reflect.TypeOf((*testing.T)(nil))
  230. ftyp := reflect.TypeOf(f)
  231. if ftyp.Kind() != reflect.Func || ftyp.NumIn() != 3 || ftyp.NumOut() != 0 || ftyp.In(0) != testingT || ftyp.In(1) != stringT {
  232. panic(fmt.Sprintf("bad test function type: want func(*testing.T, string, <TestType>), have %s", ftyp))
  233. }
  234. testType := ftyp.In(2)
  235. mp := reflect.New(reflect.MapOf(stringT, testType))
  236. return mp.Elem()
  237. }
  238. func sortedMapKeys(m reflect.Value) []string {
  239. keys := make([]string, m.Len())
  240. for i, k := range m.MapKeys() {
  241. keys[i] = k.String()
  242. }
  243. sort.Strings(keys)
  244. return keys
  245. }
  246. func runTestFunc(runTest interface{}, t *testing.T, name string, m reflect.Value, key string) {
  247. reflect.ValueOf(runTest).Call([]reflect.Value{
  248. reflect.ValueOf(t),
  249. reflect.ValueOf(name),
  250. m.MapIndex(reflect.ValueOf(key)),
  251. })
  252. }