提交 bf4d5173 编写于 作者: LinuxSuRen's avatar LinuxSuRen

Add test cases for job history

上级 553b3c82
package cmd package cmd
import ( import (
"bytes"
"fmt" "fmt"
"log" "github.com/jenkins-zh/jenkins-cli/app/helper"
"os"
"github.com/jenkins-zh/jenkins-cli/client" "github.com/jenkins-zh/jenkins-cli/client"
"github.com/jenkins-zh/jenkins-cli/util" "github.com/jenkins-zh/jenkins-cli/util"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"net/http"
) )
// JobHistoryOption is the job history option // JobHistoryOption is the job history option
type JobHistoryOption struct { type JobHistoryOption struct {
OutputOption OutputOption
RoundTripper http.RoundTripper
} }
var jobHistoryOption JobHistoryOption var jobHistoryOption JobHistoryOption
...@@ -30,41 +32,39 @@ var jobHistoryCmd = &cobra.Command{ ...@@ -30,41 +32,39 @@ var jobHistoryCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
jobName := args[0] jobName := args[0]
jenkins := getCurrentJenkinsFromOptionsOrDie() jClient := &client.JobClient{
jclient := &client.JobClient{} JenkinsCore: client.JenkinsCore{
jclient.URL = jenkins.URL RoundTripper: jobHistoryOption.RoundTripper,
jclient.UserName = jenkins.UserName },
jclient.Token = jenkins.Token }
jclient.Proxy = jenkins.Proxy getCurrentJenkinsAndClient(&(jClient.JenkinsCore))
jclient.ProxyAuth = jenkins.ProxyAuth
if builds, err := jclient.GetHistory(jobName); err == nil { builds, err := jClient.GetHistory(jobName)
if data, err := jobHistoryOption.Output(builds); err == nil { if err == nil {
if len(data) > 0 { var data []byte
fmt.Println(string(data)) data, err = jobHistoryOption.Output(builds)
} if err == nil && len(data) > 0 {
} else { cmd.Print(string(data))
log.Fatal(err)
} }
} else {
log.Fatal(err)
} }
helper.CheckErr(cmd, err)
}, },
} }
// Output print the output // Output print the output
func (o *JobHistoryOption) Output(obj interface{}) (data []byte, err error) { func (o *JobHistoryOption) Output(obj interface{}) (data []byte, err error) {
if data, err = o.OutputOption.Output(obj); err != nil { if data, err = o.OutputOption.Output(obj); err != nil {
buildList := obj.([]client.JobBuild) buildList := obj.([]*client.JobBuild)
table := util.CreateTable(os.Stdout) buf := new(bytes.Buffer)
table := util.CreateTable(buf)
table.AddRow("number", "displayname", "building", "result") table.AddRow("number", "displayname", "building", "result")
for i, build := range buildList { for i, build := range buildList {
table.AddRow(fmt.Sprintf("%d", i), build.DisplayName, table.AddRow(fmt.Sprintf("%d", i), build.DisplayName,
fmt.Sprintf("%v", build.Building), build.Result) fmt.Sprintf("%v", build.Building), build.Result)
} }
table.Render() table.Render()
data = buf.Bytes()
err = nil err = nil
data = []byte{}
} }
return return
} }
package cmd
import (
"bytes"
"github.com/jenkins-zh/jenkins-cli/client"
"io/ioutil"
"os"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/jenkins-zh/jenkins-cli/mock/mhttp"
)
var _ = Describe("job history command", func() {
var (
ctrl *gomock.Controller
roundTripper *mhttp.MockRoundTripper
err error
jenkinsRoot string
username string
token string
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
roundTripper = mhttp.NewMockRoundTripper(ctrl)
jobHistoryOption.RoundTripper = roundTripper
rootCmd.SetArgs([]string{})
rootOptions.Jenkins = ""
rootOptions.ConfigFile = "test.yaml"
jenkinsRoot = "http://localhost:8080/jenkins"
username = "admin"
token = "111e3a2f0231198855dceaff96f20540a9"
})
AfterEach(func() {
rootCmd.SetArgs([]string{})
err = os.Remove(rootOptions.ConfigFile)
rootOptions.ConfigFile = ""
ctrl.Finish()
})
Context("basic cases", func() {
It("should not error", func() {
Expect(err).NotTo(HaveOccurred())
})
It("should success", func() {
data, err := generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
jobName := "fakeJob"
client.PrepareForGetJob(roundTripper, jenkinsRoot, jobName, username, token)
client.PrepareForGetBuild(roundTripper, jenkinsRoot, jobName, 1, username, token)
client.PrepareForGetBuild(roundTripper, jenkinsRoot, jobName, 2, username, token)
rootCmd.SetArgs([]string{"job", "history", jobName})
buf := new(bytes.Buffer)
rootCmd.SetOutput(buf)
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
Expect(buf.String()).To(Equal(`number displayname building result
0 fake false
1 fake false
`))
})
})
})
...@@ -28,12 +28,8 @@ var jobParamCmd = &cobra.Command{ ...@@ -28,12 +28,8 @@ var jobParamCmd = &cobra.Command{
Use: "param <jobName>", Use: "param <jobName>",
Short: "Get param of the job of your Jenkins", Short: "Get param of the job of your Jenkins",
Long: `Get param of the job of your Jenkins`, Long: `Get param of the job of your Jenkins`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
return
}
name := args[0] name := args[0]
jenkins := getCurrentJenkinsFromOptionsOrDie() jenkins := getCurrentJenkinsFromOptionsOrDie()
jclient := &client.JobClient{} jclient := &client.JobClient{}
......
...@@ -2,6 +2,7 @@ package cmd ...@@ -2,6 +2,7 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/jenkins-zh/jenkins-cli/app/helper"
"net/http" "net/http"
"github.com/jenkins-zh/jenkins-cli/client" "github.com/jenkins-zh/jenkins-cli/client"
...@@ -42,8 +43,7 @@ var userDeleteCmd = &cobra.Command{ ...@@ -42,8 +43,7 @@ var userDeleteCmd = &cobra.Command{
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClient(&(jclient.JenkinsCore))
if err := jclient.Delete(username); err != nil { err := jclient.Delete(username)
cmd.PrintErrln(err) helper.CheckErr(cmd, err)
}
}, },
} }
...@@ -131,38 +131,18 @@ func (q *JobClient) UpdatePipeline(name, script string) (err error) { ...@@ -131,38 +131,18 @@ func (q *JobClient) UpdatePipeline(name, script string) (err error) {
} }
// GetHistory returns the build history of a job // GetHistory returns the build history of a job
func (q *JobClient) GetHistory(name string) (builds []JobBuild, err error) { func (q *JobClient) GetHistory(name string) (builds []*JobBuild, err error) {
var job *Job var job *Job
if job, err = q.GetJob(name); err == nil { if job, err = q.GetJob(name); err == nil {
builds = job.Builds buildList := job.Builds // only contains basic info
for i, build := range builds { var build *JobBuild
api := fmt.Sprintf("%sapi/json", build.URL) for _, buildItem := range buildList {
var ( build, err = q.GetBuild(name, buildItem.Number)
req *http.Request if err != nil {
response *http.Response break
)
req, err = http.NewRequest("GET", api, nil)
if err == nil {
q.AuthHandle(req)
} else {
return
}
client := q.GetClient()
if response, err = client.Do(req); err == nil {
code := response.StatusCode
var data []byte
data, err = ioutil.ReadAll(response.Body)
if code == 200 {
err = json.Unmarshal(data, &build)
builds[i] = build
} else {
log.Fatal(string(data))
}
} else {
log.Fatal(err)
} }
builds = append(builds, build)
} }
} }
return return
......
...@@ -158,18 +158,7 @@ var _ = Describe("job test", func() { ...@@ -158,18 +158,7 @@ var _ = Describe("job test", func() {
It("basic case with one build", func() { It("basic case with one build", func() {
jobName := "fake" jobName := "fake"
buildID := 2 buildID := 2
PrepareForGetBuild(roundTripper, jobClient.URL, jobName, 2, "", "")
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/job/%s/%d/api/json", jobClient.URL, jobName, buildID), nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
Request: request,
Body: ioutil.NopCloser(bytes.NewBufferString(`
{"displayName":"fake"}
`)),
}
roundTripper.EXPECT().
RoundTrip(request).Return(response, nil)
result, err := jobClient.GetBuild(jobName, buildID) result, err := jobClient.GetBuild(jobName, buildID)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
...@@ -365,4 +354,19 @@ var _ = Describe("job test", func() { ...@@ -365,4 +354,19 @@ var _ = Describe("job test", func() {
Expect(err).To(BeNil()) Expect(err).To(BeNil())
}) })
}) })
Context("GetHistory", func() {
It("simple case, should success", func() {
jobName := "fakeJob"
PrepareForGetJob(roundTripper, jobClient.URL, jobName, "", "")
PrepareForGetBuild(roundTripper, jobClient.URL, jobName, 1, "", "")
PrepareForGetBuild(roundTripper, jobClient.URL, jobName, 2, "", "")
builds, err := jobClient.GetHistory(jobName)
Expect(err).To(BeNil())
Expect(builds).NotTo(BeNil())
Expect(len(builds)).To(Equal(2))
})
})
}) })
...@@ -13,7 +13,7 @@ import ( ...@@ -13,7 +13,7 @@ import (
) )
// PrepareForGetJobInputActions only for test // PrepareForGetJobInputActions only for test
func PrepareForGetJobInputActions(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd, jobName string, buildID int) ( func PrepareForGetJobInputActions(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, jobName string, buildID int) (
request *http.Request, response *http.Response) { request *http.Request, response *http.Response) {
request, _ = http.NewRequest("GET", fmt.Sprintf("%s/job/%s/%d/wfapi/pendingInputActions", rootURL, jobName, buildID), nil) request, _ = http.NewRequest("GET", fmt.Sprintf("%s/job/%s/%d/wfapi/pendingInputActions", rootURL, jobName, buildID), nil)
response = &http.Response{ response = &http.Response{
...@@ -27,48 +27,93 @@ func PrepareForGetJobInputActions(roundTripper *mhttp.MockRoundTripper, rootURL, ...@@ -27,48 +27,93 @@ func PrepareForGetJobInputActions(roundTripper *mhttp.MockRoundTripper, rootURL,
roundTripper.EXPECT(). roundTripper.EXPECT().
RoundTrip(request).Return(response, nil) RoundTrip(request).Return(response, nil)
if user != "" && passwd != "" { if user != "" && password != "" {
request.SetBasicAuth(user, passwd) request.SetBasicAuth(user, password)
} }
return return
} }
// PrepareForSubmitInput only for test // PrepareForSubmitInput only for test
func PrepareForSubmitInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPath, user, passwd string) ( func PrepareForSubmitInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPath, user, password string) (
request *http.Request, response *http.Response) { request *http.Request, response *http.Response) {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s%s/%d/input/%s/abort?json={\"parameter\":[]}", rootURL, jobPath, 1, "Eff7d5dba32b4da32d9a67a519434d3f"), nil) request, _ = http.NewRequest("POST", fmt.Sprintf("%s%s/%d/input/%s/abort?json={\"parameter\":[]}", rootURL, jobPath, 1, "Eff7d5dba32b4da32d9a67a519434d3f"), nil)
PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL) PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return return
} }
// PrepareForSubmitProcessInput only for test // PrepareForSubmitProcessInput only for test
func PrepareForSubmitProcessInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPath, user, passwd string) ( func PrepareForSubmitProcessInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPath, user, password string) (
request *http.Request, response *http.Response) { request *http.Request, response *http.Response) {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s%s/%d/input/%s/proceed?json={\"parameter\":[]}", rootURL, jobPath, 1, "Eff7d5dba32b4da32d9a67a519434d3f"), nil) request, _ = http.NewRequest("POST", fmt.Sprintf("%s%s/%d/input/%s/proceed?json={\"parameter\":[]}", rootURL, jobPath, 1, "Eff7d5dba32b4da32d9a67a519434d3f"), nil)
PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL) PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return return
} }
// PrepareForBuildWithNoParams only for test // PrepareForBuildWithNoParams only for test
func PrepareForBuildWithNoParams(roundTripper *mhttp.MockRoundTripper, rootURL, jobName, user, passwd string) ( func PrepareForBuildWithNoParams(roundTripper *mhttp.MockRoundTripper, rootURL, jobName, user, password string) (
request *http.Request, response *http.Response) { request *http.Request, response *http.Response) {
formData := url.Values{"json": {`{"parameter": []}`}} formData := url.Values{"json": {`{"parameter": []}`}}
payload := strings.NewReader(formData.Encode()) payload := strings.NewReader(formData.Encode())
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload) request, _ = http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload)
request.Header.Add(util.ContentType, util.ApplicationForm) request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL) response = PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
response.StatusCode = 201 response.StatusCode = 201
return return
} }
// PrepareForBuildWithParams only for test // PrepareForBuildWithParams only for test
func PrepareForBuildWithParams(roundTripper *mhttp.MockRoundTripper, rootURL, jobName, user, passwd string) ( func PrepareForBuildWithParams(roundTripper *mhttp.MockRoundTripper, rootURL, jobName, user, password string) (
request *http.Request, response *http.Response) { request *http.Request, response *http.Response) {
formData := url.Values{"json": {`{"parameter": {"Description":"","name":"name","Type":"","value":"value","DefaultParameterValue":{"Description":"","Value":null}}}`}} formData := url.Values{"json": {`{"parameter": {"Description":"","name":"name","Type":"","value":"value","DefaultParameterValue":{"Description":"","Value":null}}}`}}
payload := strings.NewReader(formData.Encode()) payload := strings.NewReader(formData.Encode())
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload) request, _ = http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload)
request.Header.Add(util.ContentType, util.ApplicationForm) request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL) response = PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
response.StatusCode = 201 response.StatusCode = 201
return return
} }
// PrepareForGetJob only for test
func PrepareForGetJob(roundTripper *mhttp.MockRoundTripper, rootURL, jobName, user, password string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/job/%s/api/json", rootURL, jobName), nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
Request: request,
Body: ioutil.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{
"name" : "%s",
"builds" : [
{
"number" : 1,
"url" : "http://localhost:8080/job/we/1/"
},
{
"number" : 2,
"url" : "http://localhost:8080/job/we/2/"
}]
}`, jobName))),
}
roundTripper.EXPECT().
RoundTrip(request).Return(response, nil)
if user != "" && password != "" {
request.SetBasicAuth(user, password)
}
}
// PrepareForGetBuild only for test
func PrepareForGetBuild(roundTripper *mhttp.MockRoundTripper, rootURL, jobName string, buildID int, user, password string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/job/%s/%d/api/json", rootURL, jobName, buildID), nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
Request: request,
Body: ioutil.NopCloser(bytes.NewBufferString(`
{"displayName":"fake"}
`)),
}
roundTripper.EXPECT().
RoundTrip(request).Return(response, nil)
if user != "" && password != "" {
request.SetBasicAuth(user, password)
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册