-
Notifications
You must be signed in to change notification settings - Fork 33
/
test.go
256 lines (230 loc) · 5.79 KB
/
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package cmd
import (
"fmt"
"io"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/charmbracelet/log"
"github.com/spf13/cobra"
"github.com/j178/leetgo/config"
"github.com/j178/leetgo/lang"
"github.com/j178/leetgo/leetcode"
"github.com/j178/leetgo/utils"
)
var (
runLocally bool
runRemotely bool = true
runBoth bool
autoSubmit bool
targetCase string
forceSubmit bool
)
func init() {
testCmd.Flags().BoolVarP(
&runLocally,
"local",
"L",
false,
"run test locally",
)
testCmd.Flags().BoolVarP(
&runBoth,
"both",
"B",
false,
"run test both locally and remotely",
)
testCmd.Flags().BoolVarP(&autoSubmit, "submit", "s", false, "auto submit if all tests passed")
testCmd.Flags().BoolVarP(&forceSubmit, "force", "f", false, "force submit even if local test failed")
testCmd.Flags().StringVarP(&targetCase, "target", "t", "-", "only run the specified test case, e.g. 1, 1-3, -1, 1-")
}
var testCmd = &cobra.Command{
Use: "test qid",
Aliases: []string{"t"},
Args: cobra.ExactArgs(1),
ValidArgs: []string{"today", "last", "last/"},
Short: "Run question test cases",
Example: `leetgo test 244
leetgo test last
leetgo test w330/1
leetgo test w330/`,
RunE: func(cmd *cobra.Command, args []string) error {
if runLocally {
runRemotely = false
}
if runBoth {
runLocally = true
runRemotely = true
}
cfg := config.Get()
c := leetcode.NewClient(leetcode.ReadCredentials())
qs, err := leetcode.ParseQID(args[0], c)
if err != nil {
return err
}
gen, err := lang.GetGenerator(cfg.Code.Lang)
if err != nil {
return err
}
_, supportLocalTest := gen.(lang.LocalTestable)
if runLocally && !supportLocalTest {
return fmt.Errorf("local test not supported for %s", cfg.Code.Lang)
}
user, err := c.GetUserStatus()
if err != nil {
user = &leetcode.UserStatus{}
}
testLimiter := newLimiter(user)
submitLimiter := newLimiter(user)
var hasFailedCase bool
for _, q := range qs {
var (
localPassed = true
remotePassed = true
submitAccepted = true
)
if runLocally {
log.Info("running test locally", "question", q.TitleSlug)
localPassed, err = lang.RunLocalTest(q, targetCase)
if err != nil {
log.Error("failed to run test locally", "err", err)
}
}
if runRemotely {
log.Info("running test remotely", "question", q.TitleSlug)
result, err := runTestRemotely(cmd, q, c, gen, testLimiter)
if err != nil {
log.Error("failed to run test remotely", "err", err)
remotePassed = false
} else {
cmd.Print(result.Display(q))
remotePassed = result.CorrectAnswer
}
}
if autoSubmit && remotePassed && (localPassed || forceSubmit) {
log.Info("submitting solution", "user", user.Whoami(c))
result, err := submitSolution(cmd, q, c, gen, submitLimiter)
if err != nil {
submitAccepted = false
log.Error("failed to submit solution", "err", err)
} else {
cmd.Print(result.Display(q))
if !result.Accepted() {
submitAccepted = false
added, _ := appendToTestCases(q, result)
if added {
log.Info("added failed case to testcases.txt")
}
}
}
}
if !localPassed || !remotePassed || !submitAccepted {
hasFailedCase = true
}
}
if hasFailedCase {
return exitCode(1)
}
return nil
},
}
func runTestRemotely(
cmd *cobra.Command,
q *leetcode.QuestionData,
c leetcode.Client,
gen lang.Lang,
limiter *utils.RateLimiter,
) (
*leetcode.RunCheckResult,
error,
) {
solution, err := lang.GetSolutionCode(q)
if err != nil {
return nil, fmt.Errorf("failed to get solution code: %w", err)
}
err = q.Fulfill()
if err != nil {
return nil, fmt.Errorf("failed to fetch question: %s", err)
}
exampleCases := q.GetExampleTestCases()
casesStr := strings.Join(exampleCases, "\n")
var (
cases lang.TestCases
fromTestCasesFile bool
)
testCasesFile, err := lang.GetFileOutput(q, lang.TestCasesFile)
if err == nil {
cases, err = lang.ParseTestCases(q, testCasesFile)
if err == nil && len(cases.Cases) > 0 {
fromTestCasesFile = true
casesStr = cases.InputString()
}
}
spin := newSpinner(cmd.ErrOrStderr())
spin.Suffix = " Running tests..."
spin.Reverse()
spin.Start()
defer spin.Stop()
limiter.Take()
spin.Reverse()
interResult, err := c.RunCode(q, gen.Slug(), solution, casesStr)
if err != nil {
return nil, fmt.Errorf("failed to run test: %w", err)
}
spin.Lock()
spin.Suffix = " Waiting for result..."
spin.Unlock()
testResult, err := waitResult(c, interResult.InterpretId)
if err != nil {
return nil, fmt.Errorf("failed to wait test result: %w", err)
}
r := testResult.(*leetcode.RunCheckResult)
r.InputData = interResult.TestCase
if r.Accepted() && fromTestCasesFile {
updated, err := cases.UpdateOutputs(r.ExpectedCodeAnswer)
if err != nil {
log.Debug("failed to update test cases", "err", err)
} else if updated {
content := []byte(cases.String())
err = utils.WriteFile(testCasesFile.GetPath(), content)
if err != nil {
log.Debug("failed to update test cases", "err", err)
} else {
log.Info("testcases.txt updated")
}
}
}
return r, nil
}
func waitResult(c leetcode.Client, submissionId string) (
leetcode.CheckResult,
error,
) {
for {
result, err := c.CheckResult(submissionId)
if err != nil {
return nil, err
}
if result.GetState() == "SUCCESS" {
return result, nil
}
time.Sleep(1 * time.Second)
}
}
func newLimiter(user *leetcode.UserStatus) *utils.RateLimiter {
if user.IsPremium {
return utils.NewRateLimiter(1 * time.Second)
}
return utils.NewRateLimiter(10 * time.Second)
}
func newSpinner(w io.Writer) *spinner.Spinner {
spin := spinner.New(
spinner.CharSets[11],
125*time.Millisecond,
spinner.WithHiddenCursor(false),
spinner.WithWriter(w),
spinner.WithColor("fgHiCyan"),
)
return spin
}