-
Notifications
You must be signed in to change notification settings - Fork 2
/
dataLoader.go
69 lines (65 loc) · 1.58 KB
/
dataLoader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package testdataloader
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
)
func GetBasePath() string {
dir, err := os.Getwd()
if err != nil {
panic(err)
}
for _, err := ioutil.ReadFile(filepath.Join(dir, "go.mod")); err != nil && len(dir) > 1; {
println(dir)
dir = filepath.Dir(dir)
_, err = ioutil.ReadFile(filepath.Join(dir, "go.mod"))
}
if len(dir) < 2 {
panic("No go.mod found")
}
return dir
}
// GetRandTestFile returns a random file matching the pattern parameter and panics on error.
// The pattern is relative to the "go.mod".
// Example: test files are json files in the "data" subdirectory:
//
// - go.mod
// - data
// - test1.json
// - test2.json
// Here you can provide pattern="data/test*.json"
func GetRandTestFile(pattern string) []byte {
absolutePattern := filepath.Join(GetBasePath(), pattern)
files, err := filepath.Glob(absolutePattern)
if err != nil {
panic(err)
}
if files == nil {
panic(fmt.Errorf("Pattern \"%s\" matches no files", absolutePattern))
}
filename := files[rand.Intn(len(files))]
file, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
return file
}
// GetTestFile loads a test file relative to the go.mod or panics on error.
// Example: test files are json files in the "data" subdirectory:
//
// - go.mod
// - data
// - test1.json
// - test2.json
// Now do
// test1:=GetTestFile("data/test1.json")
func GetTestFile(relativePath string) []byte {
absolutePath := filepath.Join(GetBasePath(), relativePath)
file, err := ioutil.ReadFile(absolutePath)
if err != nil {
panic(err)
}
return file
}