-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathfixtures_test.go
183 lines (153 loc) · 4.45 KB
/
fixtures_test.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
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
package main
import (
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"syscall"
"testing"
"time"
"github.com/Yandex-Practicum/go-autotests/internal/fork"
"github.com/go-resty/resty/v2"
"github.com/rekby/fixenv"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
)
const (
startProcessTimeout = time.Second * 10
checkPortInterval = time.Millisecond * 10
)
type Env struct {
fixenv.EnvT
assert.Assertions
Ctx context.Context
Require require.Assertions
t testing.TB
}
func New(t testing.TB) *Env {
ctx, ctxCancel := context.WithCancel(context.Background())
t.Cleanup(ctxCancel)
res := Env{
EnvT: *fixenv.NewEnv(t),
Assertions: *assert.New(t),
Require: *require.New(t),
t: t,
Ctx: ctx,
}
return &res
}
func (e *Env) Fatalf(format string, args ...any) {
e.t.Helper()
e.T().Fatalf(format, args...)
}
func (e *Env) Logf(format string, args ...any) {
e.t.Helper()
e.t.Logf(format, args...)
}
func ExistPath(e *Env, filePath string) string {
return fixenv.Cache(&e.EnvT, filePath, &fixenv.FixtureOptions{
Scope: fixenv.ScopePackage,
}, func() (string, error) {
absFilePath, err := filepath.Abs(filePath)
if err != nil {
return "", err
}
e.Logf("Проверяю наличие файла: %q (%q)", absFilePath, filePath)
_, err = os.Stat(filePath)
if err != nil {
return "", err
}
return filePath, nil
})
}
func AgentPath(e *Env) string {
return ExistPath(e, flagAgentBinaryPath)
}
func ServerFilePath(e *Env) string {
return ExistPath(e, flagServerBinaryPath)
}
func ServerAddress(e *Env) string {
return fmt.Sprintf("http://%v:%v", ServerHost(e), ServerPort(e))
}
func ServerHost(e *Env) string {
return flagServerHost
}
func ServerPort(e *Env) int {
return fixenv.Cache(e, nil, nil, func() (int, error) {
return strconv.Atoi(flagServerPort)
})
}
func StartProcess(e *Env, name string, command string, args ...string) *fork.BackgroundProcess {
cacheKey := append([]string{name, command}, args...)
return fixenv.CacheWithCleanup(e, cacheKey, nil, func() (*fork.BackgroundProcess, fixenv.FixtureCleanupFunc, error) {
res := fork.NewBackgroundProcess(e.Ctx, command, fork.WithArgs(args...))
e.Logf("Запускаю %q: %q %#v", name, command, args)
err := res.Start(e.Ctx)
if err != nil {
return nil, nil, err
}
cleanup := func() {
e.Logf("Останавливаю %q: %q %#v", name, command, args)
exitCode, stopErr := res.Stop(syscall.SIGINT, syscall.SIGKILL)
stdOut := string(res.Stdout(context.Background()))
stdErr := string(res.Stderr(context.Background()))
e.Logf("stdout:\n%v", stdOut)
e.Logf("stderr:\n%v", stdErr)
if stopErr != nil {
e.Fatalf("Не получилось остановить процесс: %+v", stopErr)
}
if exitCode > 0 {
e.Logf("Ненулевой код возврата: %v", exitCode)
}
}
return res, cleanup, nil
})
}
func StartProcessWhichListenPort(e *Env, host string, port int, name string, command string, args ...string) *fork.BackgroundProcess {
cacheKey := append([]string{host, strconv.Itoa(port), name, command}, args...)
return fixenv.Cache[*fork.BackgroundProcess](e, cacheKey, nil, func() (*fork.BackgroundProcess, error) {
process := StartProcess(e, name, command, args...)
ctx, cancel := context.WithTimeout(e.Ctx, startProcessTimeout)
defer cancel()
address := fmt.Sprintf("%v:%v", host, port)
dialer := net.Dialer{}
e.Logf("Пробую подключиться на %q...", address)
for {
time.Sleep(checkPortInterval)
conn, err := dialer.DialContext(ctx, "tcp", address)
if err == nil {
e.Logf("Закрываю успешное подключение")
err = conn.Close()
return process, err
}
if ctx.Err() != nil {
e.Fatalf("Ошибка подлючения: %+v", err)
return nil, err
}
}
})
}
func RestyClient(e *Env, host string) *resty.Client {
return fixenv.Cache(e, host, nil, func() (*resty.Client, error) {
return resty.
New().
SetDebug(true).
SetBaseURL(host).
SetRedirectPolicy(resty.NoRedirectPolicy()).
SetLogger(restyLogger{e}), nil
})
}
type restyLogger struct {
e *Env
}
func (l restyLogger) Errorf(format string, v ...interface{}) {
l.e.Logf("RESTY ERROR: "+format, v...)
}
func (l restyLogger) Warnf(format string, v ...interface{}) {
l.e.Logf("resty warn: "+format, v...)
}
func (l restyLogger) Debugf(format string, v ...interface{}) {
l.e.Logf("resty: "+format, v...)
}