Welcome to mirror list, hosted at ThFree Co, Russian Federation.

helpers_test.go « cache « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 761f6f6f0bec822964e742815d0d09e87317e7b6 (plain)
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package cache_test

import (
	"bytes"
	"context"
	"errors"
	"flag"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"testing"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/gitaly-proto/go/gitalypb"
	"gitlab.com/gitlab-org/gitaly/internal/cache"
	"gitlab.com/gitlab-org/gitaly/internal/config"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

const (
	helperProcess = "GO_WANT_HELPER_PROCESS"
	getOp         = "get"
	putOp         = "put"
)

// TestHelper allows us to create dedicated processes for testing
// our file locking strategy. The test process will accept command line args to
// determine the course of action. Depending on the operation, STDIN or STDOUT
// may be used. Upon error, exit status 1 will be returned along with error
// messages on STDERR.
// See original inspiration for this test pattern:
// https://npf.io/2015/06/testing-exec-command/
func TestHelper(_ *testing.T) {
	if os.Getenv(helperProcess) != "1" {
		// wan't invoked by function execTestHelper
		return
	}

	var (
		fset   = flag.NewFlagSet("helper", flag.ExitOnError)
		opFlag = fset.String("op", "", "get|put|invalidate")
		root   = fset.String("root", "", "root dir for stream DBs")
		repo   = fset.String("repo", "", "target repo")
		req    = fset.String("req", "", "request to cache")
		method = fset.String("method", "", "grpc method to inject into context")
	)

	for i, arg := range os.Args {
		if arg == "--" {
			err := fset.Parse(os.Args[i+1:])
			if err != nil {
				log.Fatal(err)
			}
			break
		}
	}

	db, err := cache.OpenStreamDB(*root, cache.NaiveKeyer{})
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	ctx = setMockMethodCtx(ctx, *method)

	switch *opFlag {
	case getOp:
		stream, err := db.GetStream(ctx, mustDecodeRepo(*repo), mustDecodeReq(*req))
		if err != nil {
			log.Fatal(err)
		}

		_, err = io.Copy(os.Stdout, stream)
		if err != nil {
			log.Fatal(err)
		}
	case putOp:
		err := db.PutStream(ctx, mustDecodeRepo(*repo), mustDecodeReq(*req), os.Stdin)
		if err != nil {
			log.Fatal(err)
		}
	default:
		log.Fatalf("invalid op: %s", *opFlag)
	}
}

func mustDecodeRepo(rawPB string) *gitalypb.Repository {
	repo := new(gitalypb.Repository)
	err := proto.Unmarshal([]byte(rawPB), repo)
	if err != nil {
		log.Fatal(err)
	}
	return repo
}

func mustDecodeReq(rawPB string) *gitalypb.InfoRefsRequest {
	req := new(gitalypb.InfoRefsRequest)
	err := proto.Unmarshal([]byte(rawPB), req)
	if err != nil {
		log.Fatal(err)
	}
	return req
}

func execTestHelper(t testing.TB, root, method, op string, stdin io.Reader, repo *gitalypb.Repository, req *gitalypb.InfoRefsRequest) (io.Reader, <-chan error) {
	args := []string{
		"-test.run=TestHelper",
		"--", // no more "go test" args, now our custom args
		"root=" + root,
		"op=" + op,
		"method=" + method,
	}

	switch op {
	case getOp:
		fallthrough
	case putOp:
		rawReq, err := proto.Marshal(repo)
		assert.NoError(t, err)

		rawRepo, err := proto.Marshal(repo)
		assert.NoError(t, err)

		args = append(args, "req="+string(rawReq), "repo="+string(rawRepo))
	default:
		assert.Fail(t, "🤠") // whoa cow poke, are you lost?
	}

	cmd := exec.Command(os.Args[0], args...)
	cmd.Env = []string{helperProcess + "=1"}
	cmd.Stdin = stdin

	pr, pw := io.Pipe()
	cmd.Stdout = pw

	stderrB := new(bytes.Buffer)
	cmd.Stderr = stderrB

	errQ := make(chan error)
	go func() {
		if err := cmd.Run(); err != nil {
			errQ <- errors.New(stderrB.String())
		}
	}()

	return pr, errQ
}

func tempDB(t testing.TB, ck cache.CacheKeyer) (*cache.StreamDB, func()) {
	root, err := ioutil.TempDir("", t.Name())
	assert.NoError(t, err)

	oldCfg := config.Config
	config.Config.Storages = []config.Storage{
		{
			Name: "default",
			Path: root,
		},
	}

	cleanup := func() {
		lsOutput, err := exec.Command("find", root).Output()
		require.NoError(t, err)
		log.Print(string(lsOutput))
		config.Config = oldCfg
		require.NoError(t, os.RemoveAll(root))
	}

	db, err := cache.OpenStreamDB(root, ck)
	assert.NoError(t, err)

	return db, cleanup
}

func setMockMethodCtx(ctx context.Context, method string) context.Context {
	return grpc.NewContextWithServerTransportStream(ctx, mockServerTransportStream{method})
}

type mockServerTransportStream struct {
	method string
}

func (msts mockServerTransportStream) Method() string             { return msts.method }
func (mockServerTransportStream) SetHeader(md metadata.MD) error  { return nil }
func (mockServerTransportStream) SendHeader(md metadata.MD) error { return nil }
func (mockServerTransportStream) SetTrailer(md metadata.MD) error { return nil }