Skip to content

Commit

Permalink
test: add more unit tests for the git comment (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen committed Sep 22, 2023
1 parent 04e31be commit 82e5d1c
Show file tree
Hide file tree
Showing 10 changed files with 250 additions and 36 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022 Rick
Copyright (c) 2022-2023 Rick

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
71 changes: 50 additions & 21 deletions cmd/pull_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"sync"

"text/template"

"github.com/jenkins-x/go-scm/scm"
"github.com/linuxsuren/gogit/pkg"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -80,34 +84,59 @@ func (o *pullRequestOption) runE(c *cobra.Command, args []string) (err error) {
go func(login string) {
defer wait.Done()
if token, ok := o.dingdingTokenMap[login]; ok {
api := fmt.Sprintf("https://oapi.dingtalk.com/robot/send?access_token=%s", token)
msg := strings.NewReader(`{"msgtype": "text", "text": {"content": "` + o.msg + `"}}`)

resp, err := http.Post(api, "application/json", msg)
if err != nil {
c.Println(err)
} else if resp.StatusCode != http.StatusOK {
c.Printf("send message to %q failed, received code %d instead of 200\n", login, resp.StatusCode)
} else {
body, _ := io.ReadAll(resp.Body)

dingdingResp := &DingDingResponse{}
if err := json.Unmarshal(body, dingdingResp); err != nil {
c.Printf("cannot unmarshal the response for %q: %v\n", login, err)
} else if dingdingResp.ErrCode != 0 {
c.Printf("receive error response for %q: %q\n", login, dingdingResp.ErrMsg)
} else {
c.Printf("send message to %q successfully\n", login)
}

}
sendToDingDing(login, token, o.msg, pr, c.OutOrStderr())
}
}(login)
}
wait.Wait()
return
}

func sendToDingDing(login, token, msg string, pr *scm.PullRequest, c io.Writer) (err error) {
formattedMsg, fmtErr := formatMessage(msg, pr)
if fmtErr != nil {
log.Printf("cannot format the message %q: %v\n", msg, fmtErr)
formattedMsg = msg
}

api := fmt.Sprintf("https://oapi.dingtalk.com/robot/send?access_token=%s", token)
payload := strings.NewReader(`{"msgtype": "text", "text": {"content": "` + formattedMsg + `"}}`)
fmt.Println(`{"msgtype": "text", "text": {"content": "`+formattedMsg+`"}}`, api)

var resp *http.Response
resp, err = http.Post(api, "application/json", payload)
if err != nil {
fmt.Fprintln(c, err)
} else if resp.StatusCode != http.StatusOK {
fmt.Fprintf(c, "send message to %q failed, received code %d instead of 200\n", login, resp.StatusCode)
} else {
body, _ := io.ReadAll(resp.Body)

dingdingResp := &DingDingResponse{}
if err := json.Unmarshal(body, dingdingResp); err != nil {
fmt.Fprintf(c, "cannot unmarshal the response for %q: %v\n", login, err)
} else if dingdingResp.ErrCode != 0 {
fmt.Fprintf(c, "receive error response for %q: %q\n", login, dingdingResp.ErrMsg)
} else {
fmt.Fprintf(c, "send message to %q successfully\n", login)
}
}
return
}

func formatMessage(msg string, pr *scm.PullRequest) (result string, err error) {
var tpl *template.Template
if tpl, err = template.New("message").Parse(msg); err == nil {
var b strings.Builder
if err = tpl.Execute(&b, pr); err == nil {
result = b.String()
}
err = pkg.WrapError(err, "cannot format the message %q: %v", msg)
return
}
return
}

type DingDingResponse struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
Expand Down
51 changes: 51 additions & 0 deletions cmd/pull_request_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,34 @@
/*
MIT License
Copyright (c) 2023 Rick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package cmd

import (
"io"
"testing"

"github.com/jenkins-x/go-scm/scm"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -38,3 +63,29 @@ func TestPullRequestCmd(t *testing.T) {
assert.Contains(t, err.Error(), "Unsupported")
})
}

func TestFormatMessage(t *testing.T) {
tests := []struct {
name string
msg string
pr *scm.PullRequest
expect string
}{{
name: "normal",
msg: "hello {{.Title}}",
pr: &scm.PullRequest{
Title: "world",
},
expect: "hello world",
}, {
name: "invalid template syntax",
msg: "hello {{.Title}",
expect: "",
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, _ := formatMessage(tt.msg, tt.pr)
assert.Equal(t, tt.expect, result)
})
}
}
1 change: 1 addition & 0 deletions cmd/testdata/dingding.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"msgtype": "text", "text": {"content": "hello world"}}
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/linuxsuren/gogit
go 1.18

require (
github.com/h2non/gock v1.2.0
github.com/jenkins-x/go-scm v1.11.19
github.com/spf13/cobra v1.6.1
github.com/stretchr/testify v1.8.1
Expand All @@ -16,6 +17,7 @@ require (
github.com/go-git/gcfg v1.5.0 // indirect
github.com/go-git/go-billy/v5 v5.3.1 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect
github.com/imdario/mergo v0.3.13 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
Expand All @@ -41,7 +43,7 @@ require (
github.com/shurcooL/githubv4 v0.0.0-20190718010115-4ba037080260 // indirect
github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/spf13/pflag v1.0.5
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // indirect
golang.org/x/net v0.3.1-0.20221206200815-1e63c2f08a10 // indirect
golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 // indirect
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@ github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE=
github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw=
github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
Expand Down Expand Up @@ -139,6 +142,8 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
Expand Down
42 changes: 42 additions & 0 deletions pkg/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
MIT License
Copyright (c) 2023 Rick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package pkg

import "fmt"

func WrapError(err error, msg string, args ...any) error {
if err != nil {
err = fmt.Errorf(msg, append(args, err)...)
}
return err
}

func IgnoreError(err error, msg string) error {
if err == nil || err.Error() == msg {
return nil
} else {
return err
}
}
61 changes: 61 additions & 0 deletions pkg/error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
MIT License
Copyright (c) 2023 Rick
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package pkg_test

import (
"errors"
"testing"

"github.com/linuxsuren/gogit/pkg"
"github.com/stretchr/testify/assert"
)

func TestWrapError(t *testing.T) {
tests := []struct {
err error
msg string
args []any
expect error
}{{
err: nil,
expect: nil,
}, {
err: defaultErr,
msg: "wrap %v",
expect: errors.New("wrap fake"),
}}
for _, tt := range tests {
err := pkg.WrapError(tt.err, tt.msg, tt.args...)
assert.Equal(t, tt.expect, err)
}
}

func TestIgnoreError(t *testing.T) {
assert.Equal(t, nil, pkg.IgnoreError(nil, "fake"))
assert.Equal(t, nil, pkg.IgnoreError(defaultErr, "fake"))
assert.Equal(t, defaultErr, pkg.IgnoreError(defaultErr, "other"))
}

var defaultErr = errors.New("fake")
24 changes: 11 additions & 13 deletions pkg/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,28 +130,24 @@ func (s *StatusMaker) CreateComment(ctx context.Context, message, endMarker stri
Page: 1,
Size: 100,
}); err != nil {
if err = ignoreError(err, "Not Found"); err != nil {
if err = IgnoreError(err, "Not Found"); err != nil {
err = fmt.Errorf("cannot any comments %v", err)
return
}
}

var commentIDs []int //:= -1
for _, comment := range comments {
if strings.HasSuffix(comment.Body, endMarker) {
commentIDs = append(commentIDs, comment.ID)
}
}

commentIDs := getCommentIDs(comments, endMarker)
commentInput := &scm.CommentInput{
Body: fmt.Sprintf("%s\n\n%s", message, endMarker),
}

if len(commentIDs) == 0 {
// not found existing comment, create a new one
_, _, err = scmClient.PullRequests.CreateComment(ctx, s.repo, s.pr, commentInput)
err = WrapError(err, "failed to create comment, repo is %q, pr is %d: %v", s.repo, s.pr)
} else {
_, _, err = scmClient.PullRequests.EditComment(ctx, s.repo, s.pr, commentIDs[0], commentInput)
err = WrapError(err, "failed to edit comment: %v")

// remove the duplicated comments
for i := 1; i < len(commentIDs); i++ {
Expand All @@ -161,12 +157,14 @@ func (s *StatusMaker) CreateComment(ctx context.Context, message, endMarker stri
return
}

func ignoreError(err error, msg string) error {
if err.Error() == msg {
return nil
} else {
return err
func getCommentIDs(comments []*scm.Comment, endMarker string) (commentIDs []int) {
for _, comment := range comments {
// comment := comments[i]
if strings.HasSuffix(comment.Body, endMarker) {
commentIDs = append(commentIDs, comment.ID)
}
}
return
}

// CreateStatus creates a generic status
Expand Down
Loading

0 comments on commit 82e5d1c

Please sign in to comment.