forked from iOliverNguyen/git-pr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_test.go
More file actions
542 lines (497 loc) · 16.2 KB
/
Copy pathgithub_test.go
File metadata and controls
542 lines (497 loc) · 16.2 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package main
import (
"errors"
"strconv"
"testing"
)
// TestDraftPRCreationLogic tests that the draft flag is correctly determined
// during PR creation based on config and commit title patterns.
func TestDraftPRCreationLogic(t *testing.T) {
// Save original config values to restore after tests
oldDraft := config.draft
oldDraftPatterns := config.draftPatterns
defer func() {
config.draft = oldDraft
config.draftPatterns = oldDraftPatterns
}()
// Set up draft patterns for testing
config.draftPatterns = []string{"wip:*", "draft:*", "*[wip]*", "*[draft]*"}
tests := []struct {
name string
configDraft bool
commitTitle string
wantDraft bool
description string
}{
{
name: "draft flag enabled with normal title",
configDraft: true,
commitTitle: "feat: add new feature",
wantDraft: true,
description: "When --draft flag is set, PR should be created as draft regardless of title",
},
{
name: "draft flag disabled with normal title",
configDraft: false,
commitTitle: "feat: add new feature",
wantDraft: false,
description: "Without --draft flag or draft pattern, PR should be ready for review",
},
{
name: "draft pattern in title with flag disabled",
configDraft: false,
commitTitle: "wip: add new feature",
wantDraft: true,
description: "Title with 'wip:' prefix should create draft PR even without --draft flag",
},
{
name: "draft pattern with brackets",
configDraft: false,
commitTitle: "[draft] add new feature",
wantDraft: true,
description: "Title with [draft] should create draft PR",
},
{
name: "draft pattern with wip in brackets",
configDraft: false,
commitTitle: "feat: [wip] add new feature",
wantDraft: true,
description: "Title with [wip] anywhere should create draft PR",
},
{
name: "both draft flag and pattern",
configDraft: true,
commitTitle: "wip: add new feature",
wantDraft: true,
description: "When both flag and pattern present, should definitely be draft",
},
{
name: "case insensitive pattern matching",
configDraft: false,
commitTitle: "WIP: add new feature",
wantDraft: true,
description: "Pattern matching should be case-insensitive",
},
{
name: "draft prefix pattern",
configDraft: false,
commitTitle: "draft: experimental feature",
wantDraft: true,
description: "Title with 'draft:' prefix should create draft PR",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Set config for this test
config.draft = tt.configDraft
// Simulate the draft detection logic from githubCreatePRForCommit
isDraft := config.draft || matchAnyPattern(config.draftPatterns, tt.commitTitle)
// Verify the result matches expectation
if isDraft != tt.wantDraft {
t.Errorf("%s\nGot isDraft=%v, want isDraft=%v\nTitle: %q, config.draft=%v",
tt.description, isDraft, tt.wantDraft, tt.commitTitle, tt.configDraft)
} else {
t.Logf("✓ %s", tt.description)
}
})
}
}
// TestPRNumberExtraction tests that PR numbers are correctly extracted
// from gh CLI output after PR creation.
func TestPRNumberExtraction(t *testing.T) {
tests := []struct {
name string
ghOutput string
expectedPRNum int
shouldExtract bool
description string
}{
{
name: "standard PR URL output",
ghOutput: "https://github.com/user/repo/pull/123\n",
expectedPRNum: 123,
shouldExtract: true,
description: "Should extract PR number from standard GitHub URL",
},
{
name: "PR URL with trailing newline",
ghOutput: "https://github.com/user/repo/pull/456",
expectedPRNum: 456,
shouldExtract: true,
description: "Should extract PR number even without trailing newline",
},
{
name: "large PR number",
ghOutput: "https://github.com/organization/repository/pull/99999\n",
expectedPRNum: 99999,
shouldExtract: true,
description: "Should handle large PR numbers correctly",
},
{
name: "output with extra text",
ghOutput: "Creating pull request...\nhttps://github.com/user/repo/pull/789\nSuccess!",
expectedPRNum: 789,
shouldExtract: true,
description: "Should extract PR number even with surrounding text",
},
{
name: "no PR number in output",
ghOutput: "Error: failed to create PR",
expectedPRNum: 0,
shouldExtract: false,
description: "Should handle cases where no PR number is present",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Simulate the PR number extraction logic
prNumStr := regexpNumber.FindString(tt.ghOutput)
if tt.shouldExtract {
if prNumStr == "" {
t.Errorf("%s\nFailed to extract PR number from output: %q",
tt.description, tt.ghOutput)
return
}
// Parse the extracted number
prNum := 0
if prNumStr != "" {
var err error
prNum, err = strconv.Atoi(prNumStr)
if err != nil {
t.Errorf("%s\nFailed to parse PR number: %v", tt.description, err)
return
}
}
if prNum != tt.expectedPRNum {
t.Errorf("%s\nGot PR number %d, want %d from output: %q",
tt.description, prNum, tt.expectedPRNum, tt.ghOutput)
} else {
t.Logf("✓ %s: extracted PR #%d", tt.description, prNum)
}
} else {
if prNumStr != "" {
t.Errorf("%s\nExpected no extraction, but got: %s",
tt.description, prNumStr)
} else {
t.Logf("✓ %s: correctly handled no PR number", tt.description)
}
}
})
}
}
func TestGithubRepoOwner(t *testing.T) {
oldRepo := config.git.repo
defer func() {
config.git.repo = oldRepo
}()
config.git.repo = "calendly/caf-switchboard"
if owner := githubRepoOwner(); owner != "calendly" {
t.Errorf("githubRepoOwner() = %q, want %q", owner, "calendly")
}
}
func TestSelectPRNumberForHeadRefPrefersOpenPR(t *testing.T) {
prs := []PR{
{
Number: 41,
State: "closed",
Head: struct {
Ref string `json:"ref"`
}{Ref: "dyt/split-profile-utils"},
},
{
Number: 42,
State: "open",
Head: struct {
Ref string `json:"ref"`
}{Ref: "dyt/split-profile-utils"},
},
}
prNumber := selectPRNumberForHeadRef(prs, "dyt/split-profile-utils")
if prNumber != 42 {
t.Errorf("selectPRNumberForHeadRef() = %d, want 42", prNumber)
}
}
func TestSelectPRNumberForHeadRefFallsBackToClosedPR(t *testing.T) {
prs := []PR{
{
Number: 41,
State: "closed",
Head: struct {
Ref string `json:"ref"`
}{Ref: "dyt/split-profile-utils"},
},
}
prNumber := selectPRNumberForHeadRef(prs, "dyt/split-profile-utils")
if prNumber != 41 {
t.Errorf("selectPRNumberForHeadRef() = %d, want 41", prNumber)
}
}
// TestCommitNewlyCreatedFlag tests that the NewlyCreated flag is properly
// managed to distinguish new PRs from existing ones.
func TestCommitNewlyCreatedFlag(t *testing.T) {
tests := []struct {
name string
initialState bool
afterCreation bool
description string
}{
{
name: "new commit starts as not newly created",
initialState: false,
afterCreation: true,
description: "Commit should start with NewlyCreated=false, then set to true after PR creation",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a test commit
commit := &Commit{
Hash: "abc12345",
Title: "test: add test commit",
NewlyCreated: tt.initialState,
}
// Verify initial state
if commit.NewlyCreated != tt.initialState {
t.Errorf("Initial state incorrect: got %v, want %v",
commit.NewlyCreated, tt.initialState)
}
// Simulate PR creation (this would be done in githubCreatePRForCommit)
commit.NewlyCreated = true
// Verify state after creation
if commit.NewlyCreated != tt.afterCreation {
t.Errorf("%s\nAfter creation: got NewlyCreated=%v, want %v",
tt.description, commit.NewlyCreated, tt.afterCreation)
} else {
t.Logf("✓ %s", tt.description)
}
})
}
}
// TestDraftStatusPreservation tests that draft status should NOT be modified
// during PR updates, only during creation.
func TestDraftStatusPreservation(t *testing.T) {
// This test documents the expected behavior: draft status should never
// be changed during PR updates. The update flow should only modify:
// - PR title
// - PR body
// - PR labels
// But NOT draft/ready status.
tests := []struct {
name string
scenario string
expectation string
}{
{
name: "existing draft PR stays draft",
scenario: "PR was created as draft, then user runs git-pr again",
expectation: "Draft status should remain unchanged - the update flow " +
"should not call 'gh pr ready' or 'gh pr ready --undo'",
},
{
name: "existing ready PR stays ready",
scenario: "PR was created as ready, then user runs git-pr again",
expectation: "Ready status should remain unchanged - the update flow " +
"should not call 'gh pr ready' or 'gh pr ready --undo'",
},
{
name: "manually marked ready stays ready",
scenario: "PR was created as draft, user manually marked it ready in GitHub UI, then runs git-pr",
expectation: "Should preserve the ready status chosen by user - the update flow " +
"should not call 'gh pr ready --undo' to revert it back to draft",
},
{
name: "manually marked draft stays draft",
scenario: "PR was created as ready, user manually marked it draft in GitHub UI, then runs git-pr",
expectation: "Should preserve the draft status chosen by user - the update flow " +
"should not call 'gh pr ready' to revert it back to ready",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Logf("Scenario: %s", tt.scenario)
t.Logf("Expected behavior: %s", tt.expectation)
// This test serves as documentation of the expected behavior.
// The actual implementation in main.go (lines 280-287) should:
// 1. Update PR title and body via PATCH request
// 2. Add labels if needed
// 3. NOT call 'gh pr ready' or 'gh pr ready --undo'
// The key insight is that the update logic has been simplified to:
// - httpRequest("PATCH", pullURL, {"title": ..., "body": ...})
// - gh("pr", "edit", prNumber, "--add-label", labels) [if needed]
// And specifically does NOT include any draft status management.
})
}
t.Log("\n✓ Draft status preservation is enforced by:")
t.Log(" 1. Only setting draft status during PR creation (githubCreatePRForCommit)")
t.Log(" 2. Never calling 'gh pr ready' or 'gh pr ready --undo' during updates")
t.Log(" 3. Update flow only modifies: title, body, and labels")
}
// TestDraftFlagPrecedence tests the precedence of draft determination:
// config.draft flag OR title pattern match should result in draft PR.
func TestDraftFlagPrecedence(t *testing.T) {
// Save and restore config
oldDraft := config.draft
oldDraftPatterns := config.draftPatterns
defer func() {
config.draft = oldDraft
config.draftPatterns = oldDraftPatterns
}()
config.draftPatterns = []string{"wip:*", "*[draft]*"}
tests := []struct {
name string
configDraft bool
titlePattern bool // whether title matches pattern
commitTitle string
wantDraft bool
rationale string
}{
{
name: "flag=false, pattern=false -> ready",
configDraft: false,
titlePattern: false,
commitTitle: "feat: normal commit",
wantDraft: false,
rationale: "Neither flag nor pattern present, should be ready for review",
},
{
name: "flag=true, pattern=false -> draft",
configDraft: true,
titlePattern: false,
commitTitle: "feat: normal commit",
wantDraft: true,
rationale: "Config flag alone is sufficient to create draft",
},
{
name: "flag=false, pattern=true -> draft",
configDraft: false,
titlePattern: true,
commitTitle: "wip: in progress",
wantDraft: true,
rationale: "Title pattern alone is sufficient to create draft",
},
{
name: "flag=true, pattern=true -> draft",
configDraft: true,
titlePattern: true,
commitTitle: "wip: in progress",
wantDraft: true,
rationale: "Both flag and pattern present, definitely draft",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config.draft = tt.configDraft
// Calculate draft status using OR logic (either condition triggers draft)
isDraft := config.draft || matchAnyPattern(config.draftPatterns, tt.commitTitle)
// Verify the precedence logic
if isDraft != tt.wantDraft {
t.Errorf("Draft precedence failed:\n"+
" Config flag: %v\n"+
" Title pattern: %v (title=%q)\n"+
" Expected draft: %v\n"+
" Got draft: %v\n"+
" Rationale: %s",
tt.configDraft, tt.titlePattern, tt.commitTitle,
tt.wantDraft, isDraft, tt.rationale)
} else {
t.Logf("✓ Correct precedence: %s", tt.rationale)
}
})
}
}
// TestDraftPRCreationVsUpdateBehavior documents the critical distinction
// between PR creation and update behavior.
func TestDraftPRCreationVsUpdateBehavior(t *testing.T) {
t.Log("=== PR Creation Behavior ===")
t.Log("When creating a NEW PR (githubCreatePRForCommit):")
t.Log(" 1. Check if draft needed: config.draft OR matchAnyPattern(title)")
t.Log(" 2. If draft needed: pass --draft flag to 'gh pr create'")
t.Log(" 3. Extract PR number from output")
t.Log(" 4. Set commit.NewlyCreated = true")
t.Log(" Result: PR is created in the correct state from the start")
t.Log("")
t.Log("=== PR Update Behavior ===")
t.Log("When updating an EXISTING PR (main.go update flow):")
t.Log(" 1. PATCH request to update title and body")
t.Log(" 2. Add labels if needed")
t.Log(" 3. Do NOT touch draft status at all")
t.Log(" Result: Draft/ready status is preserved as user intended")
t.Log("")
t.Log("=== Key Differences ===")
t.Log("Creation: Draft status IS determined by code")
t.Log("Update: Draft status is NEVER modified by code")
t.Log("")
t.Log("✓ This design ensures:")
t.Log(" - New PRs get correct initial status")
t.Log(" - User's manual status changes are preserved")
t.Log(" - No unexpected status flipping on updates")
}
func TestIsBaseChangeBlockedByStack(t *testing.T) {
cases := []struct {
name string
err error
want bool
}{
{"nil", nil, false},
{
"real gh error",
&execError{exitCode: 1, output: "GraphQL: Cannot change the base branch because the pull request is part of a stack. (updatePullRequest)"},
true,
},
{"plain wrapped", errors.New("something is part of a stack now"), true},
{"unrelated exec error", &execError{exitCode: 1, output: "GraphQL: Could not resolve to a PullRequest"}, false},
{"unrelated plain", errors.New("network timeout"), false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := isBaseChangeBlockedByStack(tc.err); got != tc.want {
t.Errorf("isBaseChangeBlockedByStack(%v) = %v, want %v", tc.err, got, tc.want)
}
})
}
}
func TestIsGhStackMissing(t *testing.T) {
cases := []struct {
name string
out string
err error
want bool
}{
{"nil", "", nil, false},
{"extension missing", `unknown command "stack" for "gh"`, &execError{exitCode: 1, output: `unknown command "stack" for "gh"`}, true},
{"unrelated error", "", &execError{exitCode: 1, output: "some other failure"}, false},
{"missing text but no error", `unknown command "stack" for "gh"`, nil, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := isGhStackMissing(tc.out, tc.err); got != tc.want {
t.Errorf("isGhStackMissing(%q, %v) = %v, want %v", tc.out, tc.err, got, tc.want)
}
})
}
}
func TestIsStackWouldRemove(t *testing.T) {
cases := []struct {
name string
out string
err error
want bool
}{
{"nil", "", nil, false},
{
"would remove",
"✗ Cannot update stack: this would remove #22054 from the stack",
&execError{exitCode: 5, output: "✗ Cannot update stack: this would remove #22054 from the stack"},
true,
},
{"unrelated error", "", &execError{exitCode: 1, output: "network timeout"}, false},
{"would-remove text but no error", "this would remove #1 from the stack", nil, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := isStackWouldRemove(tc.out, tc.err); got != tc.want {
t.Errorf("isStackWouldRemove(%q, %v) = %v, want %v", tc.out, tc.err, got, tc.want)
}
})
}
}