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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
cfgpkg "github.com/mediocregopher/blog.mediocregopher.com/srv/cfg"
"github.com/mediocregopher/blog.mediocregopher.com/srv/post"
"github.com/mediocregopher/blog.mediocregopher.com/srv/post/asset"
"github.com/mediocregopher/mediocre-go-lib/v2/mctx"
"github.com/mediocregopher/mediocre-go-lib/v2/mlog"
"gopkg.in/yaml.v3"
)
type testData struct {
PublishedPosts []post.Post `yaml:"published_posts"`
Assets map[string]string
}
func loadTestData(path string) (testData, error) {
f, err := os.Open(path)
if err != nil {
return testData{}, fmt.Errorf("opening file: %w", err)
}
defer f.Close()
var res testData
if err := yaml.NewDecoder(f).Decode(&res); err != nil {
return testData{}, fmt.Errorf("decoding file contents: %w", err)
}
return res, nil
}
func main() {
ctx := context.Background()
cfg := cfgpkg.NewBlogCfg(cfgpkg.Params{})
var dataDir cfgpkg.DataDir
dataDir.SetupCfg(cfg)
defer dataDir.Close()
ctx = mctx.WithAnnotator(ctx, &dataDir)
testDataPath := cfg.String("test-data-path", "./test-data.yml", "File containing the data to be loaded in")
// initialization
err := cfg.Init(ctx)
logger := mlog.NewLogger(nil)
defer logger.Close()
logger.Info(ctx, "process started")
defer logger.Info(ctx, "process exiting")
if err != nil {
logger.Fatal(ctx, "initializing", err)
}
testDataDir := filepath.Dir(*testDataPath)
testData, err := loadTestData(*testDataPath)
if err != nil {
logger.Fatal(ctx, "loading test data", err)
}
postDB, err := post.NewSQLDB(dataDir)
if err != nil {
logger.Fatal(ctx, "initializing post sql db", err)
}
defer postDB.Close()
{
postStore := post.NewStore(postDB)
now := time.Now().Truncate(time.Hour)
for _, post := range testData.PublishedPosts {
ctx := mctx.Annotate(ctx,
"postID", post.ID,
"now", now)
if _, err := postStore.Set(post, now); err != nil {
logger.Fatal(ctx, "setting post", err)
}
logger.Info(ctx, "set post")
now = now.Add(-1 * time.Hour)
}
}
{
assetStore := asset.NewStore(postDB)
setAsset := func(assetID, assetPath string) error {
assetFullPath := filepath.Join(testDataDir, assetPath)
f, err := os.Open(assetFullPath)
if err != nil {
return fmt.Errorf("opening %q for reading: %w", assetFullPath, err)
}
defer f.Close()
return assetStore.Set(assetID, f)
}
for assetID, assetPath := range testData.Assets {
ctx := mctx.Annotate(ctx,
"assetID", assetID,
"assetPath", assetPath)
if err := setAsset(assetID, assetPath); err != nil {
logger.Fatal(ctx, "setting asset", err)
}
logger.Info(ctx, "set asset")
}
}
}
|