Skip to content

Commit

Permalink
Support to get all the labels of Jenkins (#50)
Browse files Browse the repository at this point in the history
* Add method to get labels

* Add a method for returning labels with string array

* Allow to mock any times
  • Loading branch information
LinuxSuRen authored Jul 25, 2022
1 parent 22f8c76 commit c930b66
Show file tree
Hide file tree
Showing 3 changed files with 146 additions and 0 deletions.
38 changes: 38 additions & 0 deletions pkg/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,44 @@ func (q *Client) ToJenkinsfile(data string) (result GenericResult, err error) {
return
}

// LabelsResponse represents the response from the labels request
type LabelsResponse struct {
Status string `json:"status"`
Data []AgentLabel `json:"data"`
}

// GetLabels returns the labels with string array format
func (l *LabelsResponse) GetLabels() (labels []string) {
for i := range l.Data {
labels = append(labels, l.Data[i].Label)
}
return
}

// AgentLabel represents a label object of the Jenkins agent
type AgentLabel struct {
CloudsCount int `json:"cloudsCount"`
Description string `json:"description"`
HasMoreThanOneJob bool `json:"hasMoreThanOneJob"`
JobsCount int `json:"jobsCount"`
JobsWithLabelDefaultValue []string `json:"jobsWithLabelDefaultValue"`
JobsWithLabelDefaultValueCount int `json:"jobsWithLabelDefaultValueCount"`
Label string `json:"label"`
LabelURL string `json:"labelURL"`
NodesCount int `json:"nodesCount"`
PluginActiveForLabel bool `json:"pluginActiveForLabel"`
TriggeredJobs []string `json:"triggeredJobs"`
TriggeredJobsCount int `json:"triggeredJobsCount"`
}

// GetLabels returns the labels of all the Jenkins agents
// Read details from https://github.com/jenkinsci/label-linked-jobs-plugin
func (q *Client) GetLabels() (labelsRes *LabelsResponse, err error) {
labelsRes = &LabelsResponse{}
err = q.RequestWithData(http.MethodGet, "/labelsdashboard/labelsData", nil, nil, http.StatusOK, labelsRes)
return
}

// PrepareShutdown Put Jenkins in a Quiet mode, in preparation for a restart. In that mode Jenkins don’t start any build
func (q *Client) PrepareShutdown(cancel bool) (err error) {
if cancel {
Expand Down
74 changes: 74 additions & 0 deletions pkg/core/core_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package core

import (
"reflect"
"testing"

"github.com/golang/mock/gomock"
"github.com/jenkins-zh/jenkins-client/pkg/mock/mhttp"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
Expand Down Expand Up @@ -159,4 +163,74 @@ var _ = Describe("core test", func() {
Expect(result.GetResult()).To(Equal("jenkinsfile"))
})
})

Context("GetLabels", func() {
var (
labels *LabelsResponse
err error
)
JustBeforeEach(func() {
PrepareForToGetLabels(roundTripper, coreClient.URL, username, password)
labels, err = coreClient.GetLabels()
})
It("normal", func() {
Expect(err).To(BeNil())
Expect(labels.GetLabels()).To(Equal([]string{"java"}))
Expect(labels).To(Equal(&LabelsResponse{
Status: "ok",
Data: []AgentLabel{{
CloudsCount: 0,
Description: "",
HasMoreThanOneJob: false,
JobsCount: 0,
JobsWithLabelDefaultValue: []string{},
JobsWithLabelDefaultValueCount: 0,
Label: "java",
LabelURL: "label/java/",
NodesCount: 1,
PluginActiveForLabel: false,
TriggeredJobs: []string{},
TriggeredJobsCount: 0,
}},
}))
})
})
})

func TestLabelsResponse_GetLabels(t *testing.T) {
type fields struct {
Status string
Data []AgentLabel
}
tests := []struct {
name string
fields fields
wantLabels []string
}{{
name: "normal case",
fields: fields{
Status: "",
Data: []AgentLabel{{
Label: "good",
}, {
Label: "bad",
}},
},
wantLabels: []string{"good", "bad"},
}, {
name: "no data field",
fields: fields{},
wantLabels: nil,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
l := &LabelsResponse{
Status: tt.fields.Status,
Data: tt.fields.Data,
}
if gotLabels := l.GetLabels(); !reflect.DeepEqual(gotLabels, tt.wantLabels) {
t.Errorf("GetLabels() = %v, want %v", gotLabels, tt.wantLabels)
}
})
}
}
34 changes: 34 additions & 0 deletions pkg/core/core_test_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,40 @@ func PrepareForToJenkinsfile(roundTripper *mhttp.MockRoundTripper, rootURL, user
PrepareCommonPost(request, `{"status":"ok","data":{"result":"success","jenkinsfile":"jenkinsfile"}}`, roundTripper, user, password, rootURL)
}

// PrepareForToGetLabels only for test
func PrepareForToGetLabels(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/labelsdashboard/labelsData", rootURL), nil)
if user != "" && password != "" {
request.SetBasicAuth(user, password)
}
response := &http.Response{
StatusCode: http.StatusOK,
Request: request,
Body: ioutil.NopCloser(bytes.NewBufferString(`{
"status": "ok",
"data": [
{
"cloudsCount": 0,
"description": "",
"hasMoreThanOneJob": false,
"jobs": [],
"jobsCount": 0,
"jobsWithLabelDefaultValue": [],
"jobsWithLabelDefaultValueCount": 0,
"label": "java",
"labelURL": "label/java/",
"nodesCount": 1,
"pluginActiveForLabel": false,
"triggeredJobs": [],
"triggeredJobsCount": 0
}
]
}`)),
}
roundTripper.EXPECT().
RoundTrip(NewVerboseRequestMatcher(request).WithBody().WithQuery()).Return(response, nil).AnyTimes()
}

// PrepareForGetIdentity only for test
func PrepareForGetIdentity(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/instance", rootURL), nil)
Expand Down

0 comments on commit c930b66

Please sign in to comment.