init_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. whitelistpat *regexp.Regexp
  86. }
  87. type testConfig struct {
  88. p *regexp.Regexp
  89. config params.ChainConfig
  90. }
  91. type testFailure struct {
  92. p *regexp.Regexp
  93. reason string
  94. }
  95. // skipShortMode skips tests matching when the -short flag is used.
  96. func (tm *testMatcher) skipShortMode(pattern string) {
  97. tm.skipshortpat = append(tm.skipshortpat, regexp.MustCompile(pattern))
  98. }
  99. // skipLoad skips JSON loading of tests matching the pattern.
  100. func (tm *testMatcher) skipLoad(pattern string) {
  101. tm.skiploadpat = append(tm.skiploadpat, regexp.MustCompile(pattern))
  102. }
  103. // fails adds an expected failure for tests matching the pattern.
  104. func (tm *testMatcher) fails(pattern string, reason string) {
  105. if reason == "" {
  106. panic("empty fail reason")
  107. }
  108. tm.failpat = append(tm.failpat, testFailure{regexp.MustCompile(pattern), reason})
  109. }
  110. func (tm *testMatcher) whitelist(pattern string) {
  111. tm.whitelistpat = regexp.MustCompile(pattern)
  112. }
  113. // config defines chain config for tests matching the pattern.
  114. func (tm *testMatcher) config(pattern string, cfg params.ChainConfig) {
  115. tm.configpat = append(tm.configpat, testConfig{regexp.MustCompile(pattern), cfg})
  116. }
  117. // findSkip matches name against test skip patterns.
  118. func (tm *testMatcher) findSkip(name string) (reason string, skipload bool) {
  119. if testing.Short() {
  120. for _, re := range tm.skipshortpat {
  121. if re.MatchString(name) {
  122. return "skipped in -short mode", false
  123. }
  124. }
  125. }
  126. for _, re := range tm.skiploadpat {
  127. if re.MatchString(name) {
  128. return "skipped by skipLoad", true
  129. }
  130. }
  131. return "", false
  132. }
  133. // findConfig returns the chain config matching defined patterns.
  134. func (tm *testMatcher) findConfig(name string) *params.ChainConfig {
  135. // TODO(fjl): name can be derived from testing.T when min Go version is 1.8
  136. for _, m := range tm.configpat {
  137. if m.p.MatchString(name) {
  138. return &m.config
  139. }
  140. }
  141. return new(params.ChainConfig)
  142. }
  143. // checkFailure checks whether a failure is expected.
  144. func (tm *testMatcher) checkFailure(t *testing.T, name string, err error) error {
  145. // TODO(fjl): name can be derived from t when min Go version is 1.8
  146. failReason := ""
  147. for _, m := range tm.failpat {
  148. if m.p.MatchString(name) {
  149. failReason = m.reason
  150. break
  151. }
  152. }
  153. if failReason != "" {
  154. t.Logf("expected failure: %s", failReason)
  155. if err != nil {
  156. t.Logf("error: %v", err)
  157. return nil
  158. }
  159. return fmt.Errorf("test succeeded unexpectedly")
  160. }
  161. return err
  162. }
  163. // walk invokes its runTest argument for all subtests in the given directory.
  164. //
  165. // runTest should be a function of type func(t *testing.T, name string, x <TestType>),
  166. // where TestType is the type of the test contained in test files.
  167. func (tm *testMatcher) walk(t *testing.T, dir string, runTest interface{}) {
  168. // Walk the directory.
  169. dirinfo, err := os.Stat(dir)
  170. if os.IsNotExist(err) || !dirinfo.IsDir() {
  171. fmt.Fprintf(os.Stderr, "can't find test files in %s, did you clone the tests submodule?\n", dir)
  172. t.Skip("missing test files")
  173. }
  174. err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  175. name := filepath.ToSlash(strings.TrimPrefix(path, dir+string(filepath.Separator)))
  176. if info.IsDir() {
  177. if _, skipload := tm.findSkip(name + "/"); skipload {
  178. return filepath.SkipDir
  179. }
  180. return nil
  181. }
  182. if filepath.Ext(path) == ".json" {
  183. t.Run(name, func(t *testing.T) { tm.runTestFile(t, path, name, runTest) })
  184. }
  185. return nil
  186. })
  187. if err != nil {
  188. t.Fatal(err)
  189. }
  190. }
  191. func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest interface{}) {
  192. if r, _ := tm.findSkip(name); r != "" {
  193. t.Skip(r)
  194. }
  195. if tm.whitelistpat != nil {
  196. if !tm.whitelistpat.MatchString(name) {
  197. t.Skip("Skipped by whitelist")
  198. }
  199. }
  200. t.Parallel()
  201. // Load the file as map[string]<testType>.
  202. m := makeMapFromTestFunc(runTest)
  203. if err := readJSONFile(path, m.Addr().Interface()); err != nil {
  204. t.Fatal(err)
  205. }
  206. // Run all tests from the map. Don't wrap in a subtest if there is only one test in the file.
  207. keys := sortedMapKeys(m)
  208. if len(keys) == 1 {
  209. runTestFunc(runTest, t, name, m, keys[0])
  210. } else {
  211. for _, key := range keys {
  212. name := name + "/" + key
  213. t.Run(key, func(t *testing.T) {
  214. if r, _ := tm.findSkip(name); r != "" {
  215. t.Skip(r)
  216. }
  217. runTestFunc(runTest, t, name, m, key)
  218. })
  219. }
  220. }
  221. }
  222. func makeMapFromTestFunc(f interface{}) reflect.Value {
  223. stringT := reflect.TypeOf("")
  224. testingT := reflect.TypeOf((*testing.T)(nil))
  225. ftyp := reflect.TypeOf(f)
  226. if ftyp.Kind() != reflect.Func || ftyp.NumIn() != 3 || ftyp.NumOut() != 0 || ftyp.In(0) != testingT || ftyp.In(1) != stringT {
  227. panic(fmt.Sprintf("bad test function type: want func(*testing.T, string, <TestType>), have %s", ftyp))
  228. }
  229. testType := ftyp.In(2)
  230. mp := reflect.New(reflect.MapOf(stringT, testType))
  231. return mp.Elem()
  232. }
  233. func sortedMapKeys(m reflect.Value) []string {
  234. keys := make([]string, m.Len())
  235. for i, k := range m.MapKeys() {
  236. keys[i] = k.String()
  237. }
  238. sort.Strings(keys)
  239. return keys
  240. }
  241. func runTestFunc(runTest interface{}, t *testing.T, name string, m reflect.Value, key string) {
  242. reflect.ValueOf(runTest).Call([]reflect.Value{
  243. reflect.ValueOf(t),
  244. reflect.ValueOf(name),
  245. m.MapIndex(reflect.ValueOf(key)),
  246. })
  247. }