test: add tests to the remaining commands (#242)

* chore(ci): set up gitlab ci for tests

* fix: disable authentication on config

* test: add tests to the remaining commands

* Format code with gofmt

This commit fixes the style issues introduced in bb0d2eb according to the output
from gofmt.

Details: https://deepsource.io/gh/profclems/glab/transform/4b2c1a87-6034-43fd-9f87-45f176fd9c6d/

* 🔥 tests

* Format code with gofmt

This commit fixes the style issues introduced in 57a9ded according to the output
from gofmt.

Details: https://deepsource.io/gh/profclems/glab/transform/00b78f3f-212e-4bd7-b0a3-39e3f3b70463/

* add more tests

* fix test failing on PR
Since tests are failing on PRs, I created a valid account for glab with an access token for test authentication

* Format code with gofmt

This commit fixes the style issues introduced in f37993a according to the output
from gofmt.

Details: https://deepsource.io/gh/profclems/glab/transform/00ba1041-2293-49e2-8194-a4c8308c9211/

* fix mr autofill test failing

* fix mr autofill test failing

* fix mr autofill test failing

* fix note test

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
This commit is contained in:
Clement Sam 2020-10-02 17:10:58 +00:00 committed by GitHub
parent 82ed5e26d3
commit 37a6299a6b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 970 additions and 191 deletions

View File

@ -12,10 +12,6 @@ addons:
ssh_known_hosts:
- gitlab.com
env:
global:
secure: "LRYxxndzqJ1BV2JwpR9HBV7gdWNXwfLzR4JaKTltK/n+uMI6rD77GxAif1kKSaTE9jQBPFkIllJ+Vy7Xz15BFQaOmlGEwi/2Dv93gz/ENLrabytdzCj316QsjWEUmmj0OEH0bOvqFRwzyF7qDOKxd5tI0WVvZhGFTkFlbQwee46hs1gBgPW+ADPPUoiPgH1gkM/Rn7qwVZnB5go/Ph2yizYpWTerVJ/OdiwKD8Y21ib7cbChOV9wa5ey8hJOO4+tAtTt7VA7QXAntsWXPopqWp9BnNpu/umTQYPTR3tBL6zUcn+XRpizWCGSaxDopvrBIY8kw6/6IGbJ3+jJcTMpWgB53rLmGNn5CDpRJio66yCdhhXITZVVxO4nY8T+W1W6ybKzQgMiID0QOqRwm8rz1yoWJx5k8/OAAZTaxQ7Zgxt2yiK4Bzao9wqsKMXIASuLz2f/YKt4CuQHtuMWM4ESBAcUgVB6TltecDYqs06/OrCRmn4vHZcnm8s+MlPzZsOcOYT1pgKAlSanYOYuJvM8et6tEvrjfU3XJD89aJkm42WXyr4uToaOVoLSCniF9PuPr3m/OasbriwRDInNE3vF8HwKhX1kBezjVBfYImnNatwFhANO903kcSge6zpKNH7ge1JgYtmqwNHikUKD++yz1K0c23v1SqMzkxQLUGd1+xA="
before_install:
- echo -e "Host *\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
- go get -t -v ./...

View File

@ -0,0 +1,97 @@
package delete
import (
"fmt"
"strings"
"testing"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
)
// TODO: test by mocking the appropriate api function
func TestMain(m *testing.M) {
cmdtest.InitTest(m, "mr_delete_test")
}
func TestNewCmdDelete(t *testing.T) {
t.Parallel()
oldDeleteMR := api.DeleteMR
api.DeleteIssue = func(client *gitlab.Client, projectID interface{}, issueID int) error {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || issueID == 0 {
return fmt.Errorf("error expected")
}
return nil
}
tests := []struct {
name string
args []string
wantErr bool
errMsg string
assertFunc func(t *testing.T, out string)
}{
{
name: "delete",
args: []string{"0"},
wantErr: true,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "error expected")
},
},
{
name: "id exists",
args: []string{"1"},
wantErr: false,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "✓ Issue Deleted\n")
},
},
{
name: "delete on different repo",
args: []string{"1", "-R", "profclems/glab"},
wantErr: false,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "✓ Issue Deleted\n")
},
},
{
name: "delete no args",
wantErr: true,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "accepts 1 arg(s), received 0")
},
},
}
cmd := NewCmdDelete(cmdtest.StubFactory(""))
cmd.Flags().StringP("repo", "R", "", "")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cli := strings.Join(tt.args, " ")
t.Log(cli)
output, err := cmdtest.RunCommand(cmd, cli)
if !tt.wantErr {
assert.Nil(t, err)
} else {
assert.NotNil(t, err)
}
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
tt.assertFunc(t, out)
assert.Contains(t, outErr, tt.errMsg)
})
}
api.DeleteMR = oldDeleteMR
}

View File

@ -43,9 +43,10 @@ func NewCmdSubscribe(f *cmdutils.Factory) *cobra.Command {
fmt.Fprintln(out, "- Subscribing to Issue #"+i2)
issue, err := api.SubscribeToIssue(apiClient, repo.FullName(), utils.StringToInt(i2), nil)
if err != nil {
fmt.Fprintln(out, utils.GreenCheck(), "Subscribed to issue #"+i2)
fmt.Fprintln(out, issueutils.DisplayIssue(issue))
return err
}
fmt.Fprintln(out, utils.GreenCheck(), "Subscribed to issue #"+i2)
fmt.Fprintln(out, issueutils.DisplayIssue(issue))
}
return nil
},

View File

@ -0,0 +1,86 @@
package subscribe
import (
"fmt"
"testing"
"time"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xanzy/go-gitlab"
)
func TestNewCmdSubscribe(t *testing.T) {
t.Parallel()
oldSubscribeIssue := api.SubscribeToIssue
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.SubscribeToIssue = func(client *gitlab.Client, projectID interface{}, issueID int, opts gitlab.RequestOptionFunc) (*gitlab.Issue, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || issueID == 0 {
return nil, fmt.Errorf("error expected")
}
return &gitlab.Issue{
ID: issueID,
IID: issueID,
State: "closed",
Description: "Dummy description for issue " + string(rune(issueID)),
Author: &gitlab.IssueAuthor{
ID: 1,
Name: "John Dev Wick",
Username: "jdwick",
},
CreatedAt: &timer,
}, nil
}
testCases := []struct {
Name string
Issue string
ExpectedMsg []string
wantErr bool
}{
{
Name: "Issue Exists",
Issue: "1",
ExpectedMsg: []string{"- Subscribing to Issue #1", "✓ Subscribed to issue #1"},
},
{
Name: "Issue on another repo",
Issue: "1 -R profclems/glab",
ExpectedMsg: []string{"- Subscribing to Issue #1", "✓ Subscribed to issue #1"},
},
{
Name: "Issue Does Not Exist",
Issue: "0",
ExpectedMsg: []string{"- Subscribing to Issue #0", "error expected"},
wantErr: true,
},
}
cmd := NewCmdSubscribe(cmdtest.StubFactory("https://gitlab.com/glab-cli/test"))
cmd.Flags().StringP("repo", "R", "", "")
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
output, err := cmdtest.RunCommand(cmd, tc.Issue)
if tc.wantErr {
require.Error(t, err)
return
} else {
require.NoError(t, err)
}
out := stripansi.Strip(output.String())
for _, msg := range tc.ExpectedMsg {
assert.Contains(t, out, msg)
}
})
}
api.SubscribeToIssue = oldSubscribeIssue
}

View File

@ -40,12 +40,13 @@ func NewCmdUnsubscribe(f *cmdutils.Factory) *cobra.Command {
arrIds := strings.Split(strings.Trim(mergeID, "[] "), ",")
for _, i2 := range arrIds {
fmt.Println("Unsubscribing from Issue #" + i2)
fmt.Fprintln(out, "- Unsubscribing from Issue #"+i2)
issue, err := api.UnsubscribeFromIssue(apiClient, repo.FullName(), utils.StringToInt(i2), nil)
if err != nil {
fmt.Fprintln(out, utils.Red("✔"), "Unsubscribed from issue #"+i2)
fmt.Fprintln(out, issueutils.DisplayIssue(issue))
return err
}
fmt.Fprintln(out, utils.Red("✔"), "Unsubscribed from issue #"+i2)
fmt.Fprintln(out, issueutils.DisplayIssue(issue))
}
return nil
},

View File

@ -0,0 +1,85 @@
package unsubscribe
import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xanzy/go-gitlab"
"testing"
"time"
)
func TestNewCmdUnsubscribe(t *testing.T) {
t.Parallel()
oldUnsubscribeIssue := api.UnsubscribeFromIssue
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.UnsubscribeFromIssue = func(client *gitlab.Client, projectID interface{}, issueID int, opts gitlab.RequestOptionFunc) (*gitlab.Issue, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || issueID == 0 {
return nil, fmt.Errorf("error expected")
}
return &gitlab.Issue{
ID: issueID,
IID: issueID,
State: "closed",
Description: "Dummy description for issue " + string(rune(issueID)),
Author: &gitlab.IssueAuthor{
ID: 1,
Name: "John Dev Wick",
Username: "jdwick",
},
CreatedAt: &timer,
}, nil
}
testCases := []struct {
Name string
Issue string
ExpectedMsg []string
wantErr bool
}{
{
Name: "Issue Exists",
Issue: "1",
ExpectedMsg: []string{"- Unsubscribing from Issue #1", "✔ Unsubscribed from issue #1"},
},
{
Name: "Issue on another repo",
Issue: "1 -R profclems/glab",
ExpectedMsg: []string{"- Unsubscribing from Issue #1", "✔ Unsubscribed from issue #1"},
},
{
Name: "Issue Does Not Exist",
Issue: "0",
ExpectedMsg: []string{"- Unsubscribing from Issue #0", "error expected"},
wantErr: true,
},
}
cmd := NewCmdUnsubscribe(cmdtest.StubFactory("https://gitlab.com/glab-cli/test"))
cmd.Flags().StringP("repo", "R", "", "")
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
output, err := cmdtest.RunCommand(cmd, tc.Issue)
if tc.wantErr {
require.Error(t, err)
return
} else {
require.NoError(t, err)
}
out := stripansi.Strip(output.String())
for _, msg := range tc.ExpectedMsg {
assert.Contains(t, out, msg)
}
})
}
api.UnsubscribeFromIssue = oldUnsubscribeIssue
}

View File

@ -117,7 +117,7 @@ func NewCmdView(f *cmdutils.Factory) *cobra.Command {
fmt.Fprint(out, "") // Empty Space
if c, _ := cmd.Flags().GetBool("comments"); c {
showSystemLog, _ := cmd.Flags().GetBool("system-logs")
var commentsPrintDetails string
opts := &gitlab.ListIssueNotesOptions{}
@ -142,7 +142,7 @@ func NewCmdView(f *cmdutils.Factory) *cobra.Command {
`)
if len(notes) > 0 {
for _, note := range notes {
if note.System {
if note.System && !showSystemLog {
continue
}
//body, _ := utils.RenderMarkdown(note.Body)
@ -165,6 +165,7 @@ func NewCmdView(f *cmdutils.Factory) *cobra.Command {
}
issueViewCmd.Flags().BoolP("comments", "c", false, "Show issue comments and activities")
issueViewCmd.Flags().BoolP("system-logs", "s", false, "Show system activities / logs")
issueViewCmd.Flags().BoolP("web", "w", false, "Open issue in a browser. Uses default browser or browser specified in BROWSER variable")
issueViewCmd.Flags().IntP("page", "p", 1, "Page number")
issueViewCmd.Flags().IntP("per-page", "P", 20, "Number of items to list per page")

View File

@ -0,0 +1,159 @@
package view
import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/commands/cmdutils"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/internal/run"
"github.com/profclems/glab/pkg/api"
mainTest "github.com/profclems/glab/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xanzy/go-gitlab"
"os/exec"
"testing"
"time"
)
var (
stubFactory *cmdutils.Factory
)
type author struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Name string `json:"name"`
State string `json:"state"`
AvatarURL string `json:"avatar_url"`
WebURL string `json:"web_url"`
}
func TestMain(m *testing.M) {
defer config.StubConfig(`---
hosts:
gitlab.com:
username: monalisa
token: OTOKEN
`, "")()
stubFactory, _ = cmdtest.StubFactoryWithConfig("")
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.GetIssue = func(client *gitlab.Client, projectID interface{}, issueID int) (*gitlab.Issue, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" {
return nil, fmt.Errorf("error expected")
}
repo, err := stubFactory.BaseRepo()
if err != nil {
return nil, err
}
return &gitlab.Issue{
ID: issueID,
IID: issueID,
Title: "issueTitle",
Labels: gitlab.Labels{"test", "bug"},
State: "opened",
Description: "issueBody",
References: &gitlab.IssueReferences{
Full: fmt.Sprintf("%s#%d", repo.FullName(), issueID),
},
Author: &gitlab.IssueAuthor{
ID: issueID,
Name: "John Dev Wick",
Username: "jdwick",
},
WebURL: fmt.Sprintf("https://%s/%s/-/issues/%d", repo.RepoHost(), repo.FullName(), issueID),
CreatedAt: &timer,
}, nil
}
cmdtest.InitTest(m, "mr_view_test")
}
func TestNewCmdView_web_numberArg(t *testing.T) {
cmd := NewCmdView(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
var seenCmd *exec.Cmd
restoreCmd := run.SetPrepareCmd(func(cmd *exec.Cmd) run.Runnable {
seenCmd = cmd
return &mainTest.OutputStub{}
})
defer restoreCmd()
output, err := cmdtest.RunCommand(cmd, "225 -w -R glab-cli/test")
if err != nil {
t.Error(err)
return
}
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
assert.Contains(t, out, "Opening gitlab.com/glab-cli/test/-/issues/225 in your browser.")
assert.Equal(t, "", outErr)
if seenCmd == nil {
t.Log("expected a command to run")
}
}
func TestNewCmdView(t *testing.T) {
oldListIssueNotes := api.ListIssueNotes
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.ListIssueNotes = func(client *gitlab.Client, projectID interface{}, issueID int, opts *gitlab.ListIssueNotesOptions) ([]*gitlab.Note, error) {
if projectID == "PROJECT_MR_WITH_EMPTY_NOTE" {
return []*gitlab.Note{}, nil
}
return []*gitlab.Note{
{
ID: 1,
Body: "Note Body",
Title: "Note Title",
Author: author{
ID: 1,
Username: "johnwick",
Name: "John Wick",
},
System: false,
CreatedAt: &timer,
NoteableID: 0,
},
{
ID: 1,
Body: "Marked issue as stale",
Title: "",
Author: author{
ID: 1,
Username: "johnwick",
Name: "John Wick",
},
System: true,
CreatedAt: &timer,
NoteableID: 0,
},
}, nil
}
cmd := NewCmdView(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
t.Run("show", func(t *testing.T) {
output, err := cmdtest.RunCommand(cmd, "13 -c -s -R glab-cli/test")
if err != nil {
t.Error(err)
return
}
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
require.Contains(t, out, "issueTitle #13")
require.Contains(t, out, "issueBody")
require.Equal(t, outErr, "")
assert.Contains(t, out, "https://gitlab.com/glab-cli/test/-/issues/13")
assert.Contains(t, out, "johnwick:\tMarked issue as stale")
})
api.ListIssueNotes = oldListIssueNotes
}

View File

@ -62,7 +62,7 @@ func NewCmdCreate(f *cmdutils.Factory) *cobra.Command {
if t, _ := cmd.Flags().GetString("target-branch"); t != "" {
targetBranch = t
} else {
targetBranch, _ = git.GetDefaultBranch(repoRemote.Name)
targetBranch, _ = git.GetDefaultBranch(repoRemote.PushURL.String())
}
if source, _ := cmd.Flags().GetString("source-branch"); source != "" {
sourceBranch = strings.Trim(source, "[] ")

View File

@ -4,28 +4,33 @@ import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/commands/cmdutils"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/pkg/api"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"os/exec"
"strings"
"testing"
"time"
)
func TestMain(m *testing.M) {
cmdtest.InitTest(m, "")
}
var (
stubFactory *cmdutils.Factory
cmd *cobra.Command
)
func TestMrCmd(t *testing.T) {
func TestMain(m *testing.M) {
defer config.StubConfig(`---
git_protocol: https
hosts:
gitlab.com:
username: monalisa
token: OTOKEN
`, "")()
stubFactory, _ := cmdtest.StubFactoryWithConfig("")
oldCreateMR := api.CreateMR
stubFactory, _ = cmdtest.StubFactoryWithConfig("")
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.CreateMR = func(client *gitlab.Client, projectID interface{}, opts *gitlab.CreateMergeRequestOptions) (*gitlab.MergeRequest, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" {
@ -52,9 +57,14 @@ hosts:
}, nil
}
cmd := NewCmdCreate(stubFactory)
cmd = NewCmdCreate(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
cmdtest.InitTest(m, "mr_cmd_autofill")
}
func TestMrCmd(t *testing.T) {
cliStr := []string{"-t", "myMRtitle",
"-d", "myMRbody",
"-l", "test,bug",
@ -68,6 +78,7 @@ hosts:
output, err := cmdtest.RunCommand(cmd, cli)
if err != nil {
t.Error(err)
return
}
out := stripansi.Strip(output.String())
@ -76,6 +87,29 @@ hosts:
assert.Contains(t, cmdtest.FirstLine([]byte(out)), `!1 myMRtitle`)
cmdtest.Eq(t, outErr, "")
assert.Contains(t, out, "https://gitlab.com/glab-cli/test/-/merge_requests/1")
api.CreateMR = oldCreateMR
}
func TestNewCmdCreate_autofill(t *testing.T) {
t.Run("create_autofill", func(t *testing.T) {
git := exec.Command("git", "checkout", "test-cli")
b, err := git.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
output, err := cmdtest.RunCommand(cmd, "-f -b master")
if err != nil {
t.Error(err)
return
}
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
assert.Contains(t, cmdtest.FirstLine([]byte(out)), `!1 SOme changes happened'`)
cmdtest.Eq(t, outErr, "")
assert.Contains(t, out, "https://gitlab.com/glab-cli/test/-/merge_requests/1")
})
}

View File

@ -1,9 +1,13 @@
package delete
import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/assert"
"os/exec"
"github.com/xanzy/go-gitlab"
"strings"
"testing"
)
@ -14,20 +18,47 @@ func TestMain(m *testing.M) {
func Test_deleteMergeRequest(t *testing.T) {
t.Parallel()
repo := cmdtest.CopyTestRepo(t, "mr_delete_test")
var cmd *exec.Cmd
oldDeleteMR := api.DeleteMR
api.DeleteMR = func(client *gitlab.Client, projectID interface{}, mrID int) error {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || mrID == 0 {
return fmt.Errorf("error expected")
}
return nil
}
tests := []struct {
name string
args []string
wantErr bool
errMsg string
assertFunc func(t *testing.T, out string)
}{
{
name: "delete",
args: []string{"0"},
wantErr: true,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "404 Not Found")
assert.Contains(t, out, "error expected")
},
},
{
name: "id exists",
args: []string{"1"},
wantErr: false,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "- Deleting Merge Request !1\n")
assert.Contains(t, out, "✔ Merge request !1 deleted\n")
},
},
{
name: "delete on different repo",
args: []string{"1", "-R", "profclems/glab"},
wantErr: false,
assertFunc: func(t *testing.T, out string) {
assert.Contains(t, out, "- Deleting Merge Request !1\n")
assert.Contains(t, out, "✔ Merge request !1 deleted\n")
},
},
{
@ -38,17 +69,30 @@ func Test_deleteMergeRequest(t *testing.T) {
},
},
}
cmd := NewCmdDelete(cmdtest.StubFactory(""))
cmd.Flags().StringP("repo", "R", "", "")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd = exec.Command(cmdtest.GlabBinaryPath, tt.args...)
cmd.Dir = repo
b, err := cmd.CombinedOutput()
if err != nil && !tt.wantErr {
t.Log(string(b))
t.Error(err)
cli := strings.Join(tt.args, " ")
t.Log(cli)
output, err := cmdtest.RunCommand(cmd, cli)
if !tt.wantErr {
assert.Nil(t, err)
} else {
assert.NotNil(t, err)
}
out := string(b)
t.Log(out)
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
tt.assertFunc(t, out)
assert.Contains(t, outErr, tt.errMsg)
})
}
api.DeleteMR = oldDeleteMR
}

View File

@ -2,19 +2,11 @@ package mr
import (
"bytes"
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/stretchr/testify/require"
"io"
"math/rand"
"os"
"os/exec"
"regexp"
"strings"
"testing"
"time"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/commands/cmdutils"
"github.com/stretchr/testify/assert"
)
@ -47,118 +39,3 @@ func TestMrCmd_noARgs(t *testing.T) {
assert.Contains(t, out, "Use \"mr [command] --help\" for more information about a command.\n")
}
func TestMrCmd(t *testing.T) {
rand.Seed(time.Now().UnixNano())
repo := cmdtest.CopyTestRepo(t, "mr_cmd_test")
var mrID string
t.Run("create", func(t *testing.T) {
git := exec.Command("git", "checkout", "test-cli")
git.Dir = repo
b, err := git.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
cmd := exec.Command(cmdtest.GlabBinaryPath, "mr", "create",
"-t", fmt.Sprintf("MR Title %v", rand.Int()),
"-d", "This MR is created as a test",
"-l", "test,bug",
"--assignee", "profclems",
"--milestone", "1",
)
cmd.Dir = repo
b, _ = cmd.CombinedOutput()
out := string(b)
t.Log(out)
out = stripansi.Strip(out)
assert.Contains(t, out, "https://gitlab.com/glab-cli/test/-/merge_requests")
r := regexp.MustCompile(`!\S+`)
t.Log(out)
//i := strings.Index(out, "/diffs\n")
//mrID = strings.TrimPrefix(out[:i], "https://gitlab.com/glab-cli/test/-/merge_requests/")
mrID = strings.TrimPrefix(r.FindStringSubmatch(out)[0], "!")
t.Log(mrID)
})
t.Run("show", func(t *testing.T) {
if mrID == "" {
t.Skip("mrID is empty, create likely failed")
}
cmd := exec.Command(cmdtest.GlabBinaryPath, "mr", "show", mrID)
cmd.Dir = repo
b, err := cmd.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
out := string(b)
outStripped := stripansi.Strip(out) // To remove ansi chars added by glamour
require.Contains(t, outStripped, "This MR is created as a test")
assert.Contains(t, out, fmt.Sprintf("https://gitlab.com/glab-cli/test/-/merge_requests/%s", mrID))
})
t.Run("delete", func(t *testing.T) {
if mrID == "" {
t.Skip("mrID is empty, create likely failed")
}
cmd := exec.Command(cmdtest.GlabBinaryPath, "mr", "delete", mrID)
cmd.Dir = repo
b, err := cmd.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
out := stripansi.Strip(string(b))
require.Contains(t, out, fmt.Sprintf("- Deleting Merge Request !%s\n", mrID))
require.Contains(t, out, fmt.Sprintf("Merge request !%s deleted", mrID))
})
}
func Test_mrCmd_autofill(t *testing.T) {
repo := cmdtest.CopyTestRepo(t, "mr_cmd_autofill")
var mrID string
t.Run("create", func(t *testing.T) {
git := exec.Command("git", "checkout", "test-cli")
git.Dir = repo
b, err := git.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
cmd := exec.Command(cmdtest.GlabBinaryPath, "mr", "create", "-f")
cmd.Dir = repo
b, _ = cmd.CombinedOutput()
out := string(b)
t.Log(out)
out = stripansi.Strip(out)
require.Contains(t, out, "https://gitlab.com/glab-cli/test/-/merge_requests")
r := regexp.MustCompile(`!\S+`)
mrID = strings.TrimPrefix(r.FindStringSubmatch(out)[0], "!")
t.Log(mrID)
})
t.Run("delete", func(t *testing.T) {
if mrID == "" {
t.Skip("mrID is empty, create -F likely failed")
}
cmd := exec.Command(cmdtest.GlabBinaryPath, "mr", "delete", mrID)
cmd.Dir = repo
b, err := cmd.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
out := stripansi.Strip(string(b))
require.Contains(t, out, fmt.Sprintf("Deleting Merge Request !%s\n", mrID))
require.Contains(t, out, fmt.Sprintf("Merge request !%s deleted", mrID))
})
}

View File

@ -1,8 +1,13 @@
package note
import (
"os/exec"
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/pkg/api"
"github.com/xanzy/go-gitlab"
"testing"
"time"
"github.com/profclems/glab/commands/cmdtest"
"github.com/stretchr/testify/require"
@ -13,49 +18,113 @@ func TestMain(m *testing.M) {
cmdtest.InitTest(m, "mr_note_create_test")
}
type author struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Name string `json:"name"`
State string `json:"state"`
AvatarURL string `json:"avatar_url"`
WebURL string `json:"web_url"`
}
func Test_mrNoteCreate(t *testing.T) {
repo := cmdtest.CopyTestRepo(t, "mr_note_create_test")
var cmd *exec.Cmd
defer config.StubConfig(`---
hosts:
gitlab.com:
username: monalisa
token: OTOKEN
`, "")()
stubFactory, _ := cmdtest.StubFactoryWithConfig("")
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.CreateMRNote = func(client *gitlab.Client, projectID interface{}, mrID int, opts *gitlab.CreateMergeRequestNoteOptions) (*gitlab.Note, error) {
if projectID == "PROJECT_MR_WITH_EMPTY_NOTE" {
return &gitlab.Note{}, nil
}
return &gitlab.Note{
ID: 1,
Body: *opts.Body,
Title: *opts.Body,
Author: author{
ID: 1,
Username: "johnwick",
Name: "John Wick",
},
System: false,
CreatedAt: &timer,
NoteableID: 0,
}, nil
}
api.GetMR = func(client *gitlab.Client, projectID interface{}, mrID int, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" {
return nil, fmt.Errorf("error expected")
}
repo, err := stubFactory.BaseRepo()
if err != nil {
return nil, err
}
return &gitlab.MergeRequest{
ID: mrID,
IID: mrID,
Title: "mrTitle",
Labels: gitlab.Labels{"test", "bug"},
State: "opened",
Description: "mrBody",
Author: &gitlab.BasicUser{
ID: mrID,
Name: "John Dev Wick",
Username: "jdwick",
},
WebURL: fmt.Sprintf("https://%s/%s/-/merge_requests/%d", repo.RepoHost(), repo.FullName(), mrID),
CreatedAt: &timer,
}, nil
}
cmd := NewCmdNote(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
tests := []struct {
name string
args []string
args string
want bool
assertionFunc func(t *testing.T, out string)
assertionFunc func(*testing.T, string, string)
}{
{
name: "Has -m flag",
args: []string{"225", "-m", "Some test note"},
assertionFunc: func(t *testing.T, out string) {
require.Contains(t, out, "https://gitlab.com/glab-cli/test/merge_requests/1#note_")
args: "223 -m \"Some test note\"",
assertionFunc: func(t *testing.T, out, outErr string) {
require.Contains(t, out, "https://gitlab.com/glab-cli/test/-/merge_requests/223#note_1")
},
},
/*
{
name: "Has no flag",
args: []string{"225"},
assertionFunc: func(t *testing.T, out string) {
args: "11",
assertionFunc: func(t *testing.T, out, outErr string) {
require.Contains(t, out, "aborted... Note has an empty message")
},
},
*/
{
name: "With --repo flag",
args: []string{"225", "-m", "Some test note", "-R", "glab-cli/test"},
assertionFunc: func(t *testing.T, out string) {
require.Contains(t, out, "https://gitlab.com/glab-cli/test/merge_requests/1#note_")
args: "225 -m \"Some test note\" -R profclems/test",
assertionFunc: func(t *testing.T, out, outErr string) {
require.Contains(t, out, "https://gitlab.com/profclems/test/-/merge_requests/225#note_1")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
cmd = exec.Command(cmdtest.GlabBinaryPath, append([]string{"mr", "note"}, tt.args...)...)
cmd.Dir = repo
b, err := cmd.CombinedOutput()
output, err := cmdtest.RunCommand(cmd, tt.args)
if err != nil {
t.Log(string(b))
t.Fatal(err)
t.Error(err)
return
}
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
tt.assertionFunc(t, out, outErr)
})
}
}

View File

@ -41,7 +41,7 @@ func NewCmdSubscribe(f *cmdutils.Factory) *cobra.Command {
arrIds := strings.Split(strings.Trim(mergeID, "[] "), ",")
for _, i2 := range arrIds {
fmt.Fprintln(out, "- Subscribing to merge Request !"+i2)
fmt.Fprintln(out, "- Subscribing to merge request !"+i2)
mr, err := api.SubscribeToMR(apiClient, repo.FullName(), utils.StringToInt(i2), nil)
if err != nil {
return err

View File

@ -0,0 +1,107 @@
package subscribe
import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xanzy/go-gitlab"
"testing"
"time"
)
func TestMain(m *testing.M) {
cmdtest.InitTest(m, "")
}
func TestNewCmdSubscribe(t *testing.T) {
t.Parallel()
defer config.StubConfig(`---
hosts:
gitlab.com:
username: monalisa
token: OTOKEN
`, "")()
stubFactory, _ := cmdtest.StubFactoryWithConfig("")
oldSubscribeMR := api.SubscribeToMR
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.SubscribeToMR = func(client *gitlab.Client, projectID interface{}, mrID int, opts gitlab.RequestOptionFunc) (*gitlab.MergeRequest, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || mrID == 0 {
return nil, fmt.Errorf("error expected")
}
repo, err := stubFactory.BaseRepo()
if err != nil {
return nil, err
}
return &gitlab.MergeRequest{
ID: 1,
IID: 1,
Title: "mrtitile",
Labels: gitlab.Labels{"bug", "test"},
State: "opened",
Description: "mrbody",
Author: &gitlab.BasicUser{
ID: 1,
Name: "John Dev Wick",
Username: "jdwick",
},
WebURL: "https://" + repo.RepoHost() + "/" + repo.FullName() + "/-/merge_requests/1",
CreatedAt: &timer,
}, nil
}
testCases := []struct {
Name string
Issue string
ExpectedMsg []string
wantErr bool
}{
{
Name: "Issue Exists",
Issue: "1",
ExpectedMsg: []string{"- Subscribing to merge request !1", "✓ You have successfully subscribed to merge request !1"},
},
{
Name: "Issue on another repo",
Issue: "1 -R profclems/glab",
ExpectedMsg: []string{"- Subscribing to merge request !1",
"✓ You have successfully subscribed to merge request !1",
"https://gitlab.com/profclems/glab/-/merge_requests/1\n",
},
},
{
Name: "Issue Does Not Exist",
Issue: "0",
ExpectedMsg: []string{"- Subscribing to merge request !0", "error expected"},
wantErr: true,
},
}
cmd := NewCmdSubscribe(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
output, err := cmdtest.RunCommand(cmd, tc.Issue)
if tc.wantErr {
require.Error(t, err)
return
} else {
require.NoError(t, err)
}
out := stripansi.Strip(output.String())
for _, msg := range tc.ExpectedMsg {
assert.Contains(t, out, msg)
}
})
}
api.SubscribeToMR = oldSubscribeMR
}

View File

@ -40,7 +40,7 @@ func NewCmdUnsubscribe(f *cmdutils.Factory) *cobra.Command {
arrIds := strings.Split(strings.Trim(mergeID, "[] "), ",")
for _, i2 := range arrIds {
fmt.Fprintln(out, "Unsubscribing Merge Request !"+i2)
fmt.Fprintln(out, "- Unsubscribing from Merge Request !"+i2)
mr, err := api.UnsubscribeFromMR(apiClient, repo.FullName(), utils.StringToInt(i2), nil)
if err != nil {
return err

View File

@ -0,0 +1,104 @@
package unsubscribe
import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xanzy/go-gitlab"
"testing"
"time"
)
func TestMain(m *testing.M) {
cmdtest.InitTest(m, "")
}
func TestNewCmdUnsubscribe(t *testing.T) {
t.Parallel()
defer config.StubConfig(`---
hosts:
gitlab.com:
username: monalisa
token: OTOKEN
`, "")()
stubFactory, _ := cmdtest.StubFactoryWithConfig("")
oldUnsubscribeMR := api.UnsubscribeFromMR
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.UnsubscribeFromMR = func(client *gitlab.Client, projectID interface{}, mrID int, opts gitlab.RequestOptionFunc) (*gitlab.MergeRequest, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" || mrID == 0 {
return nil, fmt.Errorf("error expected")
}
repo, err := stubFactory.BaseRepo()
if err != nil {
return nil, err
}
return &gitlab.MergeRequest{
ID: 1,
IID: 1,
Title: "mrtitile",
Labels: gitlab.Labels{"bug", "test"},
State: "opened",
Description: "mrbody",
Author: &gitlab.BasicUser{
ID: 1,
Name: "John Dev Wick",
Username: "jdwick",
},
WebURL: "https://" + repo.RepoHost() + "/" + repo.FullName() + "/-/merge_requests/1",
CreatedAt: &timer,
}, nil
}
testCases := []struct {
Name string
Issue string
ExpectedMsg []string
wantErr bool
}{
{
Name: "Issue Exists",
Issue: "1",
ExpectedMsg: []string{"- Unsubscribing from Merge Request !1", "✓ You have successfully unsubscribed from merge request !1"},
},
{
Name: "Issue on another repo",
Issue: "1 -R profclems/glab",
ExpectedMsg: []string{"- Unsubscribing from Merge Request !1", "✓ You have successfully unsubscribed from merge request !1"},
},
{
Name: "Issue Does Not Exist",
Issue: "0",
ExpectedMsg: []string{"- Unsubscribing from Merge Request !0", "error expected"},
wantErr: true,
},
}
cmd := NewCmdUnsubscribe(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
output, err := cmdtest.RunCommand(cmd, tc.Issue)
if tc.wantErr {
require.Error(t, err)
return
} else {
require.NoError(t, err)
}
out := stripansi.Strip(output.String())
for _, msg := range tc.ExpectedMsg {
assert.Contains(t, out, msg)
}
})
}
api.UnsubscribeFromMR = oldUnsubscribeMR
}

View File

@ -1,8 +1,16 @@
package view
import (
"fmt"
"github.com/acarl005/stripansi"
"github.com/profclems/glab/commands/cmdutils"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/pkg/api"
"github.com/stretchr/testify/require"
"github.com/xanzy/go-gitlab"
"os/exec"
"testing"
"time"
"github.com/profclems/glab/commands/cmdtest"
"github.com/profclems/glab/internal/run"
@ -10,13 +18,62 @@ import (
"github.com/stretchr/testify/assert"
)
// TODO: test by mocking the appropriate api function
var (
stubFactory *cmdutils.Factory
)
type author struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Name string `json:"name"`
State string `json:"state"`
AvatarURL string `json:"avatar_url"`
WebURL string `json:"web_url"`
}
func TestMain(m *testing.M) {
defer config.StubConfig(`---
hosts:
gitlab.com:
username: monalisa
token: OTOKEN
`, "")()
stubFactory, _ = cmdtest.StubFactoryWithConfig("")
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.GetMR = func(client *gitlab.Client, projectID interface{}, mrID int, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
if projectID == "" || projectID == "WRONG_REPO" || projectID == "expected_err" {
return nil, fmt.Errorf("error expected")
}
repo, err := stubFactory.BaseRepo()
if err != nil {
return nil, err
}
return &gitlab.MergeRequest{
ID: mrID,
IID: mrID,
Title: "mrTitle",
Labels: gitlab.Labels{"test", "bug"},
State: "opened",
Description: "mrBody",
Author: &gitlab.BasicUser{
ID: mrID,
Name: "John Dev Wick",
Username: "jdwick",
},
WebURL: fmt.Sprintf("https://%s/%s/-/merge_requests/%d", repo.RepoHost(), repo.FullName(), mrID),
CreatedAt: &timer,
}, nil
}
cmdtest.InitTest(m, "mr_view_test")
}
func TestMRView_web_numberArg(t *testing.T) {
repo := cmdtest.CopyTestRepo(t, "mr_view_test")
cmd := NewCmdView(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
var seenCmd *exec.Cmd
restoreCmd := run.SetPrepareCmd(func(cmd *exec.Cmd) run.Runnable {
seenCmd = cmd
@ -24,18 +81,76 @@ func TestMRView_web_numberArg(t *testing.T) {
})
defer restoreCmd()
cmd := exec.Command(cmdtest.GlabBinaryPath, "mr", "view", "-w", "225")
cmd.Dir = repo
b, err := cmd.CombinedOutput()
output, err := cmdtest.RunCommand(cmd, "225 -w -R glab-cli/test")
if err != nil {
t.Log(string(b))
t.Errorf("error running command `mr view`: %v", err)
t.Error(err)
return
}
assert.Contains(t, string(b), "Opening gitlab.com/glab-cli/test/-/merge_requests/225 in your browser.")
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
assert.Contains(t, outErr, "Opening gitlab.com/glab-cli/test/-/merge_requests/225 in your browser.")
assert.Equal(t, out, "")
if seenCmd == nil {
t.Log("expected a command to run")
}
}
func TestMRView(t *testing.T) {
oldListMrNotes := api.ListMRNotes
timer, _ := time.Parse(time.RFC3339, "2014-11-12T11:45:26.371Z")
api.ListMRNotes = func(client *gitlab.Client, projectID interface{}, mrID int, opts *gitlab.ListMergeRequestNotesOptions) ([]*gitlab.Note, error) {
if projectID == "PROJECT_MR_WITH_EMPTY_NOTE" {
return []*gitlab.Note{}, nil
}
return []*gitlab.Note{
{
ID: 1,
Body: "Note Body",
Title: "Note Title",
Author: author{
ID: 1,
Username: "johnwick",
Name: "John Wick",
},
System: false,
CreatedAt: &timer,
NoteableID: 0,
},
{
ID: 1,
Body: "Marked PR as ready",
Title: "",
Author: author{
ID: 1,
Username: "johnwick",
Name: "John Wick",
},
System: true,
CreatedAt: &timer,
NoteableID: 0,
},
}, nil
}
cmd := NewCmdView(stubFactory)
cmd.Flags().StringP("repo", "R", "", "")
t.Run("show", func(t *testing.T) {
output, err := cmdtest.RunCommand(cmd, "13 -c -s -R glab-cli/test")
if err != nil {
t.Error(err)
return
}
out := stripansi.Strip(output.String())
outErr := stripansi.Strip(output.Stderr())
require.Contains(t, out, "mrTitle!13")
require.Equal(t, outErr, "")
assert.Contains(t, out, "https://gitlab.com/glab-cli/test/-/merge_requests/13")
assert.Contains(t, out, "johnwick:\tMarked PR as ready")
})
api.ListMRNotes = oldListMrNotes
}

2
go.mod
View File

@ -32,6 +32,6 @@ require (
github.com/tcnksm/go-gitconfig v0.1.2
github.com/wadey/gocovmerge v0.0.0-20160331181800-b5bfa59ec0ad // indirect
github.com/xanzy/go-gitlab v0.38.1
golang.org/x/tools v0.0.0-20200925191224-5d1fdd8fa346 // indirect
golang.org/x/tools v0.0.0-20201002141543-22683886a977 // indirect
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c
)

2
go.sum
View File

@ -335,6 +335,8 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200925191224-5d1fdd8fa346 h1:hzJjkvxUIF3bSt+v8N5tBQNx/605vszZJ+3XsIamzZo=
golang.org/x/tools v0.0.0-20200925191224-5d1fdd8fa346/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
golang.org/x/tools v0.0.0-20201002141543-22683886a977 h1:DHhk3I+S2b/npPIGINkUyTfTHOiEfEe9+mZz/mGI214=
golang.org/x/tools v0.0.0-20201002141543-22683886a977/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=

View File

@ -1 +1,2 @@
token: thisistotestconfigset
token: qRC87Xg9Wd46RhB8J8sp
git_protocol: ssh