未验证 提交 e253b3e7 编写于 作者: JenkinsInChina's avatar JenkinsInChina 提交者: GitHub

Fix cannot connect jnlp agent with http proxy (#420)

* Fix cannot connect jnlp agent with http proxy

* Add proxy credentials

* Add comments

* Fix the proxy protocoal

* Try to fix the unit test errors

* Fix the const export issues
上级 9e0ba17f
......@@ -60,7 +60,7 @@ var _ = Describe("center download command", func() {
})
It("download the lts Jenkins", func() {
request, _ := http.NewRequest("GET", "http://mirrors.jenkins.io/war-stable/latest/jenkins.war", nil)
request, _ := http.NewRequest(http.MethodGet, "http://mirrors.jenkins.io/war-stable/latest/jenkins.war", nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......@@ -82,7 +82,7 @@ var _ = Describe("center download command", func() {
})
It("download the weekly Jenkins", func() {
request, _ := http.NewRequest("GET", "http://mirrors.jenkins.io/war/latest/jenkins.war", nil)
request, _ := http.NewRequest(http.MethodGet, "http://mirrors.jenkins.io/war/latest/jenkins.war", nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......
......@@ -44,7 +44,7 @@ var _ = Describe("center command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......@@ -57,7 +57,7 @@ var _ = Describe("center command", func() {
roundTripper.EXPECT().
RoundTrip(client.NewRequestMatcher(requestCrumb)).Return(responseCrumb, nil)
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/updateCenter/api/json?pretty=false&depth=1", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/updateCenter/api/json?pretty=false&depth=1", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
StatusCode: 200,
......
......@@ -43,7 +43,7 @@ var _ = Describe("center upgrade command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......@@ -56,7 +56,7 @@ var _ = Describe("center upgrade command", func() {
roundTripper.EXPECT().
RoundTrip(client.NewRequestMatcher(requestCrumb)).Return(responseCrumb, nil)
request, _ := http.NewRequest("POST", "http://localhost:8080/jenkins/updateCenter/upgrade", nil)
request, _ := http.NewRequest(http.MethodPost, "http://localhost:8080/jenkins/updateCenter/upgrade", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
......
......@@ -46,7 +46,7 @@ var _ = Describe("center watch command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......
......@@ -4,15 +4,15 @@ import (
"fmt"
"github.com/jenkins-zh/jenkins-cli/app/cmd/common"
. "github.com/jenkins-zh/jenkins-cli/app/config"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/jenkins-zh/jenkins-cli/client"
"github.com/jenkins-zh/jenkins-cli/util"
"github.com/spf13/cobra"
"go.uber.org/zap"
"io/ioutil"
"net/url"
"os"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/spf13/cobra"
"strings"
)
// ComputerLaunchOption option for config list command
......@@ -28,14 +28,21 @@ type ComputerLaunchOption struct {
Output string
}
const (
// AgentJNLP is the agent type of jnlp
AgentJNLP = "jnlp"
)
var computerLaunchOption ComputerLaunchOption
func init() {
computerCmd.AddCommand(computerLaunchCmd)
computerLaunchCmd.Flags().StringVarP(&computerLaunchOption.Type, "type", "", "",
computerLaunchCmd.Flags().StringVarP(&computerLaunchOption.Type, "type", "", AgentJNLP,
i18n.T("The type of agent, include jnlp"))
computerLaunchCmd.Flags().BoolVarP(&computerLaunchOption.ShowProgress, "show-progress", "", true,
i18n.T("Show the progress of downloading agent.jar"))
healthCheckRegister.Register(getCmdPath(computerLaunchCmd), &computerLaunchOption)
}
var computerLaunchCmd = &cobra.Command{
......@@ -50,17 +57,24 @@ jcli agent launch agent-name --type jnlp`,
computerLaunchOption.ComputerClient, computerLaunchOption.CurrentJenkins =
GetComputerClient(computerLaunchOption.CommonOption)
if computerLaunchOption.Type != "jnlp" {
if computerLaunchOption.Type != AgentJNLP {
return
}
var f *os.File
if f, err = ioutil.TempFile("/tmp", "agent.jar"); err == nil {
computerLaunchOption.Output = f.Name()
agentURL := fmt.Sprintf("%s/jnlpJars/agent.jar", computerLaunchOption.ComputerClient.URL)
logger.Debug("start to download agent.jar", zap.String("url", agentURL))
logger.Debug("proxy setting", zap.String("sever", computerLaunchOption.CurrentJenkins.Proxy),
zap.String("auth", computerLaunchOption.CurrentJenkins.ProxyAuth))
downloader := util.HTTPDownloader{
RoundTripper: computerLaunchOption.RoundTripper,
TargetFilePath: computerLaunchOption.Output,
URL: fmt.Sprintf("%s/jnlpJars/agent.jar", computerLaunchOption.ComputerClient.URL),
URL: agentURL,
Proxy: computerLaunchOption.CurrentJenkins.Proxy,
ProxyAuth: computerLaunchOption.CurrentJenkins.ProxyAuth,
ShowProgress: computerLaunchOption.ShowProgress,
}
err = downloader.DownloadFile()
......@@ -69,11 +83,15 @@ jcli agent launch agent-name --type jnlp`,
},
RunE: func(_ *cobra.Command, args []string) (err error) {
name := args[0]
logger.Info("prepare to start agent", zap.String("name", name), zap.String("type", computerLaunchOption.Type))
switch computerLaunchOption.Type {
case "":
err = computerLaunchOption.Launch(name)
case "jnlp":
case AgentJNLP:
err = computerLaunchOption.LaunchJnlp(name)
default:
err = fmt.Errorf("unsupported agent type %s", computerLaunchOption.Type)
}
return
},
......@@ -89,6 +107,8 @@ func (o *ComputerLaunchOption) Launch(name string) (err error) {
func (o *ComputerLaunchOption) LaunchJnlp(name string) (err error) {
var secret string
if secret, err = o.ComputerClient.GetSecret(name); err == nil {
logger.Info("get agent secret", zap.String("value", secret))
var binary string
binary, err = util.LookPath("java", centerStartOption.LookPathContext)
if err == nil {
......@@ -97,10 +117,29 @@ func (o *ComputerLaunchOption) LaunchJnlp(name string) (err error) {
"-jnlpUrl", fmt.Sprintf("%s/computer/%s/slave-agent.jnlp", o.ComputerClient.URL, name),
"-secret", secret, "-workDir", "/tmp"}
logger.Debug("start a jnlp agent", zap.Any("command", agentArgs))
if o.CurrentJenkins.ProxyAuth != "" {
proxyURL, _ := url.Parse(o.CurrentJenkins.Proxy)
agentArgs = append(agentArgs, "-proxyCredentials", o.CurrentJenkins.ProxyAuth)
proxyAuth := strings.SplitN(o.CurrentJenkins.ProxyAuth, ":", 2)
if len(proxyAuth) == 2 {
env = append(env, fmt.Sprintf("http_proxy=http://%s:%s@%s", url.QueryEscape(proxyAuth[0]), url.QueryEscape(proxyAuth[1]), proxyURL.Host))
}
}
logger.Debug("start a jnlp agent", zap.Any("command", strings.Join(agentArgs, " ")))
err = util.Exec(binary, agentArgs, env, o.SystemCallExec)
}
}
return
}
// Check do the health check of casc cmd
func (o *ComputerLaunchOption) Check() (err error) {
opt := PluginOptions{
CommonOption: common.CommonOption{RoundTripper: o.RoundTripper},
}
_, err = opt.FindPlugin("pipeline-restful-api")
return
}
......@@ -73,7 +73,7 @@ var _ = Describe("computer launch command", func() {
computerLaunchOption.SystemCallExec = util.FakeSystemCallExecSuccess
computerLaunchOption.LookPathContext = util.FakeLookPath
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/jnlpJars/agent.jar", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/jnlpJars/agent.jar", nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......
......@@ -97,7 +97,7 @@ func TestGetLatest(t *testing.T) {
}
func prepareDownloadFileRequest(url, content string, roundTripper *mhttp.MockRoundTripper) {
request, _ := http.NewRequest("GET", url, nil)
request, _ := http.NewRequest(http.MethodGet, url, nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......@@ -108,7 +108,7 @@ func prepareDownloadFileRequest(url, content string, roundTripper *mhttp.MockRou
}
func prepareMavenMetadataRequest(roundTripper *mhttp.MockRoundTripper) {
request, _ := http.NewRequest("GET", "http://localhost/maven-metadata.xml", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost/maven-metadata.xml", nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......
......@@ -66,7 +66,7 @@ var _ = Describe("job artifact download command", func() {
client.PrepareGetArtifacts(roundTripper, "http://localhost:8080/jenkins", "admin", "111e3a2f0231198855dceaff96f20540a9", jobName, buildID)
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/job/pipeline/1/artifact/a.log", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/job/pipeline/1/artifact/a.log", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
StatusCode: 200,
......
......@@ -66,7 +66,7 @@ You need to give the parameters if your pipeline has them. Learn more about it f
paramDefs = append(paramDefs, client.ParameterDefinition{
Name: entryArray[0],
Value: entryArray[1],
Type: "StringParameterDefinition",
Type: client.StringParameterDefinition,
})
}
}
......
......@@ -53,7 +53,7 @@ var _ = Describe("job build command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
request, _ := http.NewRequest("POST", fmt.Sprintf("http://localhost:8080/jenkins/job/%s/build", jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/jenkins/job/%s/build", jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
......@@ -65,7 +65,7 @@ var _ = Describe("job build command", func() {
roundTripper.EXPECT().
RoundTrip(client.NewRequestMatcher(request)).Return(response, nil)
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......@@ -156,7 +156,7 @@ var _ = Describe("job build command", func() {
// token = "111e3a2f0231198855dceaff96f20540a9"
// )
//
// request, _ := http.NewRequest("GET", fmt.Sprintf("%s/job/%s/api/json",
// request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/job/%s/api/json",
// url, jobName), nil)
// request.SetBasicAuth(user, token)
// response := &http.Response{
......
......@@ -57,7 +57,7 @@ var _ = Describe("job delete command", func() {
Expect(err).To(BeNil())
jobName := "fakeJob"
request, _ := http.NewRequest("POST", fmt.Sprintf("http://localhost:8080/jenkins/job/%s/doDelete", jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/jenkins/job/%s/doDelete", jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
request.Header.Add(util.ContentType, util.ApplicationForm)
......@@ -70,7 +70,7 @@ var _ = Describe("job delete command", func() {
roundTripper.EXPECT().
RoundTrip(client.NewRequestMatcher(request)).Return(response, nil)
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......
......@@ -100,7 +100,7 @@ var _ = Describe("job edit command", func() {
client.PrepareForUpdatePipelineJob(roundTripper, jenkinsRoot, "sample", username, token)
remoteJenkinsfileURL := "http://test"
remoteJenkinsfileReq, _ := http.NewRequest("GET", remoteJenkinsfileURL, nil)
remoteJenkinsfileReq, _ := http.NewRequest(http.MethodGet, remoteJenkinsfileURL, nil)
remoteJenkinsfileResponse := &http.Response{
StatusCode: 200,
Request: remoteJenkinsfileReq,
......
......@@ -48,7 +48,7 @@ var _ = Describe("job stop command", func() {
jobName := "fakeJob"
buildID := 1
request, _ := http.NewRequest("POST", fmt.Sprintf("http://localhost:8080/jenkins/job/%s/%d/stop", jobName, buildID), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/jenkins/job/%s/%d/stop", jobName, buildID), nil)
request.Header.Add("CrumbRequestField", "Crumb")
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
......@@ -60,7 +60,7 @@ var _ = Describe("job stop command", func() {
roundTripper.EXPECT().
RoundTrip(client.NewRequestMatcher(request)).Return(response, nil)
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......@@ -90,7 +90,7 @@ var _ = Describe("job stop command", func() {
Expect(err).To(BeNil())
jobName := "fakeJob"
request, _ := http.NewRequest("POST", fmt.Sprintf("http://localhost:8080/jenkins/job/%s/lastBuild/stop", jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/jenkins/job/%s/lastBuild/stop", jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
......@@ -102,7 +102,7 @@ var _ = Describe("job stop command", func() {
roundTripper.EXPECT().
RoundTrip(client.NewRequestMatcher(request)).Return(response, nil)
requestCrumb, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/crumbIssuer/api/json", nil)
requestCrumb.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
responseCrumb := &http.Response{
StatusCode: 200,
......
......@@ -45,7 +45,7 @@ var _ = Describe("job type command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
StatusCode: 200,
......@@ -84,7 +84,7 @@ var _ = Describe("job type command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
StatusCode: 200,
......@@ -111,7 +111,7 @@ var _ = Describe("job type command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
StatusCode: 200,
......@@ -138,7 +138,7 @@ var _ = Describe("job type command", func() {
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
request, _ := http.NewRequest("GET", "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/jenkins/view/all/itemCategories?depth=3", nil)
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
response := &http.Response{
StatusCode: 200,
......
......@@ -2,6 +2,7 @@ package client
import (
"fmt"
"net/http"
)
// Artifact represents the artifacts from Jenkins build
......@@ -27,6 +28,6 @@ func (q *ArtifactClient) List(jobName string, buildID int) (artifacts []Artifact
} else {
api = fmt.Sprintf("%s/%d/wfapi/artifacts", path, buildID)
}
err = q.RequestWithData("GET", api, nil, nil, 200, &artifacts)
err = q.RequestWithData(http.MethodGet, api, nil, nil, 200, &artifacts)
return
}
......@@ -19,7 +19,7 @@ func PrepareGetArtifacts(roundTripper *mhttp.MockRoundTripper, rootURL, user, pa
} else {
api = fmt.Sprintf("%s/%d/wfapi/artifacts", path, buildID)
}
request, _ := http.NewRequest("GET", fmt.Sprintf("%s%s", rootURL, api), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", rootURL, api), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......
package client
import "net/http"
// CASCManager is the client of configuration as code
type CASCManager struct {
JenkinsCore
......@@ -12,7 +14,7 @@ func (c *CASCManager) Export() (config string, err error) {
statusCode int
)
if statusCode, data, err = c.Request("POST", "/configuration-as-code/export",
if statusCode, data, err = c.Request(http.MethodPost, "/configuration-as-code/export",
nil, nil); err == nil &&
statusCode != 200 {
err = c.ErrorHandle(statusCode, data)
......@@ -28,7 +30,7 @@ func (c *CASCManager) Schema() (schema string, err error) {
statusCode int
)
if statusCode, data, err = c.Request("POST", "/configuration-as-code/schema",
if statusCode, data, err = c.Request(http.MethodPost, "/configuration-as-code/schema",
nil, nil); err == nil &&
statusCode != 200 {
err = c.ErrorHandle(statusCode, data)
......@@ -39,14 +41,14 @@ func (c *CASCManager) Schema() (schema string, err error) {
// Reload reload the config of configuration-as-code
func (c *CASCManager) Reload() (err error) {
_, err = c.RequestWithoutData("POST", "/configuration-as-code/reload",
_, err = c.RequestWithoutData(http.MethodPost, "/configuration-as-code/reload",
nil, nil, 200)
return
}
// Apply apply the config of configuration-as-code
func (c *CASCManager) Apply() (err error) {
_, err = c.RequestWithoutData("POST", "/configuration-as-code/apply",
_, err = c.RequestWithoutData(http.MethodPost, "/configuration-as-code/apply",
nil, nil, 200)
return
}
......@@ -8,14 +8,14 @@ import (
// PrepareForSASCReload only for test
func PrepareForSASCReload(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest("POST",
request, _ := http.NewRequest(http.MethodPost,
fmt.Sprintf("%s/configuration-as-code/reload", rootURL), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
// PrepareForSASCApply only for test
func PrepareForSASCApply(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest("POST",
request, _ := http.NewRequest(http.MethodPost,
fmt.Sprintf("%s/configuration-as-code/apply", rootURL), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......@@ -23,7 +23,7 @@ func PrepareForSASCApply(roundTripper *mhttp.MockRoundTripper, rootURL, user, pa
// PrepareForSASCExport only for test
func PrepareForSASCExport(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) (
response *http.Response) {
request, _ := http.NewRequest("POST",
request, _ := http.NewRequest(http.MethodPost,
fmt.Sprintf("%s/configuration-as-code/export", rootURL), nil)
response = PrepareCommonPost(request, "sample", roundTripper, user, password, rootURL)
return
......@@ -38,7 +38,7 @@ func PrepareForSASCExportWithCode(roundTripper *mhttp.MockRoundTripper, rootURL,
// PrepareForSASCSchema only for test
func PrepareForSASCSchema(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) (
response *http.Response) {
request, _ := http.NewRequest("POST",
request, _ := http.NewRequest(http.MethodPost,
fmt.Sprintf("%s/configuration-as-code/schema", rootURL), nil)
response = PrepareCommonPost(request, "sample", roundTripper, user, password, rootURL)
return
......
......@@ -97,7 +97,7 @@ func (j *JenkinsCore) AuthHandle(request *http.Request) (err error) {
j.ProxyHandle(request)
// all post request to Jenkins must be has the crumb
if request.Method == "POST" {
if request.Method == http.MethodPost {
err = j.CrumbHandle(request)
}
return
......@@ -124,7 +124,7 @@ func (j *JenkinsCore) GetCrumb() (crumbIssuer *JenkinsCrumb, err error) {
data []byte
)
if statusCode, data, err = j.Request("GET", "/crumbIssuer/api/json", nil, nil); err == nil {
if statusCode, data, err = j.Request(http.MethodGet, "/crumbIssuer/api/json", nil, nil); err == nil {
if statusCode == 200 {
err = json.Unmarshal(data, &crumbIssuer)
} else if statusCode == 404 {
......
......@@ -41,7 +41,7 @@ var _ = Describe("common test", func() {
)
BeforeEach(func() {
method = "GET"
method = http.MethodGet
api = "/fake"
})
......@@ -64,7 +64,7 @@ var _ = Describe("common test", func() {
})
It("normal case for post request", func() {
method = "POST"
method = http.MethodPost
request, _ := http.NewRequest(method, fmt.Sprintf("%s%s", jenkinsCore.URL, api), payload)
request.Header.Add("CrumbRequestField", "Crumb")
request.Header.Add("Fake", "fake")
......@@ -77,7 +77,7 @@ var _ = Describe("common test", func() {
roundTripper.EXPECT().
RoundTrip(NewRequestMatcher(request)).Return(response, nil)
requestCrumb, _ := http.NewRequest("GET", fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), payload)
requestCrumb, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), payload)
responseCrumb := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -100,7 +100,7 @@ var _ = Describe("common test", func() {
Context("GetCrumb", func() {
It("without crumb setting", func() {
requestCrumb, _ := http.NewRequest("GET", fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), nil)
responseCrumb := &http.Response{
StatusCode: 404,
Proto: "HTTP/1.1",
......@@ -125,7 +125,7 @@ var _ = Describe("common test", func() {
})
It("with error from server", func() {
//requestCrumb, _ := http.NewRequest("GET", fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), nil)
//requestCrumb, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), nil)
//responseCrumb := &http.Response{
// StatusCode: 500,
// Proto: "HTTP/1.1",
......@@ -141,7 +141,7 @@ var _ = Describe("common test", func() {
})
It("with Language", func() {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s%s", jenkinsCore.URL, "/view/all/itemCategories?depth=3"), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", jenkinsCore.URL, "/view/all/itemCategories?depth=3"), nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -162,7 +162,7 @@ var _ = Describe("common test", func() {
RoundTrip(NewRequestMatcher(request)).Return(response, nil)
SetLanguage("zh-CN")
statusCode, data, err := jenkinsCore.Request("GET", "/view/all/itemCategories?depth=3", nil, nil)
statusCode, data, err := jenkinsCore.Request(http.MethodGet, "/view/all/itemCategories?depth=3", nil, nil)
SetLanguage("")
Expect(err).To(BeNil())
Expect(statusCode).To(Equal(200))
......@@ -191,7 +191,7 @@ var _ = Describe("common test", func() {
})
It("with CrumbHandle error from server", func() {
requestCrumb, _ := http.NewRequest("GET", fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", jenkinsCore.URL, "/crumbIssuer/api/json"), nil)
responseCrumb := &http.Response{
StatusCode: 500,
Proto: "HTTP/1.1",
......
......@@ -12,7 +12,7 @@ import (
// PrepareForGetIssuer only for test
func PrepareForGetIssuer(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) (
request *http.Request, response *http.Response) {
request, _ = http.NewRequest("GET", fmt.Sprintf("%s%s", rootURL, "/crumbIssuer/api/json"), nil)
request, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", rootURL, "/crumbIssuer/api/json"), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......
......@@ -16,7 +16,7 @@ type ComputerClient struct {
// List get the computer list
func (c *ComputerClient) List() (computers ComputerList, err error) {
err = c.RequestWithData("GET", "/computer/api/json",
err = c.RequestWithData(http.MethodGet, "/computer/api/json",
nil, nil, 200, &computers)
return
}
......@@ -24,14 +24,14 @@ func (c *ComputerClient) List() (computers ComputerList, err error) {
// Launch starts up a agent
func (c *ComputerClient) Launch(name string) (err error) {
api := fmt.Sprintf("/computer/%s/launchSlaveAgent", name)
_, err = c.RequestWithoutData("POST", api, nil, nil, 200)
_, err = c.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
// Delete removes a agent from Jenkins
func (c *ComputerClient) Delete(name string) (err error) {
api := fmt.Sprintf("/computer/%s/doDelete", name)
_, err = c.RequestWithoutData("POST", api, nil, nil, 200)
_, err = c.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......@@ -39,7 +39,7 @@ func (c *ComputerClient) Delete(name string) (err error) {
func (c *ComputerClient) GetSecret(name string) (secret string, err error) {
api := fmt.Sprintf("/instance/agentSecret?name=%s", name)
var response *http.Response
if response, err = c.RequestWithResponse("POST", api, nil, nil); err == nil {
if response, err = c.RequestWithResponse(http.MethodPost, api, nil, nil); err == nil {
var data []byte
if data, err = ioutil.ReadAll(response.Body); err == nil {
secret = string(data)
......@@ -52,7 +52,7 @@ func (c *ComputerClient) GetSecret(name string) (secret string, err error) {
func (c *ComputerClient) GetLog(name string) (log string, err error) {
var response *http.Response
api := fmt.Sprintf("/computer/%s/logText/progressiveText", name)
if response, err = c.RequestWithResponse("GET", api, nil, nil); err == nil {
if response, err = c.RequestWithResponse(http.MethodGet, api, nil, nil); err == nil {
statusCode := response.StatusCode
if statusCode != 200 {
err = fmt.Errorf("unexpected status code %d", statusCode)
......@@ -74,10 +74,10 @@ func (c *ComputerClient) Create(name string) (err error) {
"mode": {"hudson.slaves.DumbSlave"},
}
payload := strings.NewReader(formData.Encode())
if _, err = c.RequestWithoutData("POST", "/computer/createItem",
if _, err = c.RequestWithoutData(http.MethodPost, "/computer/createItem",
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200); err == nil {
payload = GetPayloadForCreateAgent(name)
_, err = c.RequestWithoutData("POST", "/computer/doCreateItem",
_, err = c.RequestWithoutData(http.MethodPost, "/computer/doCreateItem",
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
}
return
......
......@@ -14,7 +14,7 @@ import (
// PrepareForComputerListRequest only for test
func PrepareForComputerListRequest(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/computer/api/json", rootURL), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/computer/api/json", rootURL), nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......@@ -29,7 +29,7 @@ func PrepareForComputerListRequest(roundTripper *mhttp.MockRoundTripper, rootURL
// PrepareForLaunchComputer only for test
func PrepareForLaunchComputer(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, name string) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/computer/%s/launchSlaveAgent", rootURL, name), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/computer/%s/launchSlaveAgent", rootURL, name), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......@@ -41,7 +41,7 @@ func PrepareForComputerLogRequest(roundTripper *mhttp.MockRoundTripper, rootURL,
// PrepareForComputerLogRequestWithCode only for test
func PrepareForComputerLogRequestWithCode(roundTripper *mhttp.MockRoundTripper, rootURL, user, password,
name string, statusCode int) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/computer/%s/logText/progressiveText", rootURL, name), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/computer/%s/logText/progressiveText", rootURL, name), nil)
response := &http.Response{
StatusCode: statusCode,
Request: request,
......@@ -56,13 +56,13 @@ func PrepareForComputerLogRequestWithCode(roundTripper *mhttp.MockRoundTripper,
// PrepareForComputerDeleteRequest only for test
func PrepareForComputerDeleteRequest(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, name string) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/computer/%s/doDelete", rootURL, name), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/computer/%s/doDelete", rootURL, name), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
// PrepareForComputerAgentSecretRequest only for test
func PrepareForComputerAgentSecretRequest(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, name, secret string) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/instance/agentSecret?name=%s", rootURL, name), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/instance/agentSecret?name=%s", rootURL, name), nil)
PrepareCommonPost(request, secret, roundTripper, user, password, rootURL)
}
......@@ -73,12 +73,12 @@ func PrepareForComputerCreateRequest(roundTripper *mhttp.MockRoundTripper, rootU
"mode": {"hudson.slaves.DumbSlave"},
}
payload := strings.NewReader(formData.Encode())
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/computer/createItem", rootURL), payload)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/computer/createItem", rootURL), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
payload = GetPayloadForCreateAgent(name)
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/computer/doCreateItem", rootURL), payload)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/computer/doCreateItem", rootURL), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......
......@@ -3,6 +3,7 @@ package client
import (
"github.com/jenkins-zh/jenkins-cli/util"
"go.uber.org/zap"
"net/http"
)
var logger *zap.Logger
......@@ -28,22 +29,22 @@ type CoreClient struct {
// Restart will send the restart request
func (q *CoreClient) Restart() (err error) {
_, err = q.RequestWithoutData("POST", "/safeRestart", nil, nil, 503)
_, err = q.RequestWithoutData(http.MethodPost, "/safeRestart", nil, nil, 503)
return
}
// RestartDirectly restart Jenkins directly
func (q *CoreClient) RestartDirectly() (err error) {
_, err = q.RequestWithoutData("POST", "/restart", nil, nil, 503)
_, err = q.RequestWithoutData(http.MethodPost, "/restart", nil, nil, 503)
return
}
// Shutdown puts Jenkins into the quiet mode, wait for existing builds to be completed, and then shut down Jenkins
func (q *CoreClient) Shutdown(safe bool) (err error) {
if safe {
_, err = q.RequestWithoutData("POST", "/safeExit", nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, "/safeExit", nil, nil, 200)
} else {
_, err = q.RequestWithoutData("POST", "/exit", nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, "/exit", nil, nil, 200)
}
return
}
......@@ -51,9 +52,9 @@ func (q *CoreClient) Shutdown(safe bool) (err error) {
// PrepareShutdown Put Jenkins in a Quiet mode, in preparation for a restart. In that mode Jenkins don’t start any build
func (q *CoreClient) PrepareShutdown(cancel bool) (err error) {
if cancel {
_, err = q.RequestWithoutData("POST", "/cancelQuietDown", nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, "/cancelQuietDown", nil, nil, 200)
} else {
_, err = q.RequestWithoutData("POST", "/quietDown", nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, "/quietDown", nil, nil, 200)
}
return
}
......@@ -67,6 +68,6 @@ type JenkinsIdentity struct {
// GetIdentity returns the identity of a Jenkins
func (q *CoreClient) GetIdentity() (identity JenkinsIdentity, err error) {
err = q.RequestWithData("GET", "/instance", nil, nil, 200, &identity)
err = q.RequestWithData(http.MethodGet, "/instance", nil, nil, 200, &identity)
return
}
......@@ -35,7 +35,7 @@ var _ = Describe("core test", func() {
ctrl.Finish()
})
Context("Get", func() {
Context("Get data", func() {
It("should success", func() {
PrepareRestart(roundTripper, coreClient.URL, username, password, 503)
......
......@@ -10,7 +10,7 @@ import (
// PrepareRestart only for test
func PrepareRestart(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string, statusCode int) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/safeRestart", rootURL), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/safeRestart", rootURL), nil)
response := PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
response.StatusCode = statusCode
return
......@@ -18,7 +18,7 @@ func PrepareRestart(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwor
// PrepareRestartDirectly only for test
func PrepareRestartDirectly(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string, statusCode int) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/restart", rootURL), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/restart", rootURL), nil)
response := PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
response.StatusCode = statusCode
return
......@@ -28,9 +28,9 @@ func PrepareRestartDirectly(roundTripper *mhttp.MockRoundTripper, rootURL, user,
func PrepareForShutdown(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string, safe bool) {
var request *http.Request
if safe {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/safeExit", rootURL), nil)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/safeExit", rootURL), nil)
} else {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/exit", rootURL), nil)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/exit", rootURL), nil)
}
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return
......@@ -40,9 +40,9 @@ func PrepareForShutdown(roundTripper *mhttp.MockRoundTripper, rootURL, user, pas
func PrepareForCancelShutdown(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string, cancel bool) {
var request *http.Request
if cancel {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/cancelQuietDown", rootURL), nil)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/cancelQuietDown", rootURL), nil)
} else {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/quietDown", rootURL), nil)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/quietDown", rootURL), nil)
}
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return
......@@ -50,7 +50,7 @@ func PrepareForCancelShutdown(roundTripper *mhttp.MockRoundTripper, rootURL, use
// PrepareForGetIdentity only for test
func PrepareForGetIdentity(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/instance", rootURL), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/instance", rootURL), nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......
......@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"go.uber.org/zap"
"net/http"
"net/url"
"strings"
......@@ -18,14 +19,14 @@ type CredentialsManager struct {
// GetList returns the credential list
func (c *CredentialsManager) GetList(store string) (credentialList CredentialList, err error) {
api := fmt.Sprintf("/credentials/store/%s/domain/_/api/json?pretty=true&depth=1", store)
err = c.RequestWithData("GET", api, nil, nil, 200, &credentialList)
err = c.RequestWithData(http.MethodGet, api, nil, nil, 200, &credentialList)
return
}
// Delete removes a credential by id from a store
func (c *CredentialsManager) Delete(store, id string) (err error) {
api := fmt.Sprintf("/credentials/store/%s/domain/_/credential/%s/doDelete", store, id)
_, err = c.RequestWithoutData("POST", api, nil, nil, 200)
_, err = c.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......@@ -39,7 +40,7 @@ func (c *CredentialsManager) Create(store, credential string) (err error) {
formData.Add("json", fmt.Sprintf(`{"credentials": %s}`, credential))
payload := strings.NewReader(formData.Encode())
_, err = c.RequestWithoutData("POST", api,
_, err = c.RequestWithoutData(http.MethodPost, api,
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
return
}
......
......@@ -16,7 +16,7 @@ import (
// PrepareForGetCredentialList only for test
func PrepareForGetCredentialList(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, store string) {
api := fmt.Sprintf("%s/credentials/store/%s/domain/_/api/json?pretty=true&depth=1", rootURL, store)
request, _ := http.NewRequest("GET", api, nil)
request, _ := http.NewRequest(http.MethodGet, api, nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......@@ -32,7 +32,7 @@ func PrepareForGetCredentialList(roundTripper *mhttp.MockRoundTripper, rootURL,
// PrepareForDeleteCredential only for test
func PrepareForDeleteCredential(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, store, id string) {
api := fmt.Sprintf("%s/credentials/store/%s/domain/_/credential/%s/doDelete", rootURL, store, id)
request, _ := http.NewRequest("POST", api, nil)
request, _ := http.NewRequest(http.MethodPost, api, nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......@@ -44,7 +44,7 @@ func PrepareForCreateCredential(roundTripper *mhttp.MockRoundTripper, rootURL, u
formData.Add("json", fmt.Sprintf(`{"credentials": %s}`, credential))
payload := strings.NewReader(formData.Encode())
request, _ := http.NewRequest("POST", api, payload)
request, _ := http.NewRequest(http.MethodPost, api, payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......
......@@ -20,8 +20,12 @@ import (
"github.com/jenkins-zh/jenkins-cli/util"
)
// FileParameterDefinition is the definition for file parameter
const FileParameterDefinition = "FileParameterDefinition"
const (
// StringParameterDefinition is the definition for string parameter
StringParameterDefinition = "StringParameterDefinition"
// FileParameterDefinition is the definition for file parameter
FileParameterDefinition = "FileParameterDefinition"
)
// JobClient is client for operate jobs
type JobClient struct {
......@@ -32,7 +36,7 @@ type JobClient struct {
// Search find a set of jobs by name
func (q *JobClient) Search(name, kind string, start, limit int) (items []JenkinsItem, err error) {
err = q.RequestWithData("GET", fmt.Sprintf("/items/list?name=%s&type=%s&start=%d&limit=%d&parent=%s",
err = q.RequestWithData(http.MethodGet, fmt.Sprintf("/items/list?name=%s&type=%s&start=%d&limit=%d&parent=%s",
name, kind, start, limit, q.Parent),
nil, nil, 200, &items)
return
......@@ -41,7 +45,7 @@ func (q *JobClient) Search(name, kind string, start, limit int) (items []Jenkins
// Build trigger a job
func (q *JobClient) Build(jobName string) (err error) {
path := ParseJobPath(jobName)
_, err = q.RequestWithoutData("POST", fmt.Sprintf("%s/build", path), nil, nil, 201)
_, err = q.RequestWithoutData(http.MethodPost, fmt.Sprintf("%s/build", path), nil, nil, 201)
return
}
......@@ -64,55 +68,61 @@ func (q *JobClient) BuildWithParams(jobName string, parameters []ParameterDefini
path := ParseJobPath(jobName)
api := fmt.Sprintf("%s/build", path)
fileParameters := make([]ParameterDefinition, 0, len(parameters))
for _, parameter := range parameters {
if parameter.Type == FileParameterDefinition {
fileParameters = append(fileParameters, parameter)
}
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
defer writer.Close()
// upload file
for _, parameter := range fileParameters {
var file *os.File
file, err = os.Open(parameter.Filepath)
if err != nil {
return err
}
defer file.Close()
hasFileParam := false
stringParameters := make([]ParameterDefinition, 0, len(parameters))
for _, parameter := range parameters {
if parameter.Type == FileParameterDefinition {
hasFileParam = true
var file *os.File
file, err = os.Open(parameter.Filepath)
if err != nil {
return err
}
defer file.Close()
var fWriter io.Writer
fWriter, err = writer.CreateFormFile(parameter.Filepath, filepath.Base(parameter.Filepath))
if err != nil {
return err
var fWriter io.Writer
fWriter, err = writer.CreateFormFile(parameter.Filepath, filepath.Base(parameter.Filepath))
if err != nil {
return err
}
_, err = io.Copy(fWriter, file)
} else {
stringParameters = append(stringParameters, parameter)
}
_, err = io.Copy(fWriter, file)
}
var paramJSON []byte
if len(parameters) == 1 {
paramJSON, err = json.Marshal(parameters[0])
if len(stringParameters) == 1 {
paramJSON, err = json.Marshal(stringParameters[0])
} else {
paramJSON, err = json.Marshal(parameters)
paramJSON, err = json.Marshal(stringParameters)
}
if err != nil {
return err
return
}
if err = writer.WriteField("json", fmt.Sprintf("{\"parameter\": %s}", string(paramJSON))); err != nil {
return err
}
if hasFileParam {
if err = writer.WriteField("json", fmt.Sprintf("{\"parameter\": %s}", string(paramJSON))); err != nil {
return
}
if err = writer.Close(); err != nil {
return err
}
if err = writer.Close(); err != nil {
return
}
_, err = q.RequestWithoutData("POST", api,
map[string]string{util.ContentType: writer.FormDataContentType()}, body, 201)
_, err = q.RequestWithoutData(http.MethodPost, api,
map[string]string{util.ContentType: writer.FormDataContentType()}, body, 201)
} else {
formData := url.Values{"json": {fmt.Sprintf("{\"parameter\": %s}", string(paramJSON))}}
payload := strings.NewReader(formData.Encode())
_, err = q.RequestWithoutData(http.MethodPost, api,
map[string]string{util.ContentType: util.ApplicationForm}, payload, 201)
}
return
}
......@@ -121,7 +131,7 @@ func (q *JobClient) DisableJob(jobName string) (err error) {
path := ParseJobPath(jobName)
api := fmt.Sprintf("%s/disable", path)
_, err = q.RequestWithoutData("POST", api, nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......@@ -130,7 +140,7 @@ func (q *JobClient) EnableJob(jobName string) (err error) {
path := ParseJobPath(jobName)
api := fmt.Sprintf("%s/enable", path)
_, err = q.RequestWithoutData("POST", api, nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......@@ -145,7 +155,7 @@ func (q *JobClient) StopJob(jobName string, num int) (err error) {
api = fmt.Sprintf("%s/%d/stop", path, num)
}
_, err = q.RequestWithoutData("POST", api, nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......@@ -196,7 +206,7 @@ func (q *JobClient) UpdatePipeline(name, script string) (err error) {
path := ParseJobPath(name)
api := fmt.Sprintf("%s/restFul/update?%s", path, formData.Encode())
_, err = q.RequestWithoutData("POST", api, nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......@@ -286,7 +296,7 @@ func (q *JobClient) Create(jobPayload CreateJobPayload) (err error) {
payload := strings.NewReader(formData.Encode())
var code int
code, err = q.RequestWithoutData("POST", "/view/all/createItem",
code, err = q.RequestWithoutData(http.MethodPost, "/view/all/createItem",
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
if code == 302 {
err = nil
......@@ -306,7 +316,7 @@ func (q *JobClient) Delete(jobName string) (err error) {
util.ContentType: util.ApplicationForm,
}
if statusCode, _, err = q.Request("POST", api, header, nil); err == nil {
if statusCode, _, err = q.Request(http.MethodPost, api, header, nil); err == nil {
if statusCode != 200 && statusCode != 302 {
err = fmt.Errorf("unexpected status code: %d", statusCode)
}
......@@ -350,7 +360,7 @@ func (q *JobClient) JobInputSubmit(jobName, inputID string, buildID int, abort b
paramData, _ := json.Marshal(request)
api = fmt.Sprintf("%s?json=%s", api, string(paramData))
_, err = q.RequestWithoutData("POST", api, nil, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, api, nil, nil, 200)
return
}
......
......@@ -62,7 +62,7 @@ var _ = Describe("job test", func() {
Context("Build", func() {
It("trigger a simple job without a folder", func() {
jobName := "fakeJob"
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", jobClient.URL, jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/build", jobClient.URL, jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
StatusCode: 201,
......@@ -91,7 +91,7 @@ var _ = Describe("job test", func() {
It("trigger a simple job with an error", func() {
jobName := "fakeJob"
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", jobClient.URL, jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/build", jobClient.URL, jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
StatusCode: 500,
......@@ -162,7 +162,7 @@ var _ = Describe("job test", func() {
Expect(err).To(BeNil())
})
It("with params", func() {
FIt("with params", func() {
jobName := "fake"
PrepareForBuildWithParams(roundTripper, jobClient.URL, jobName, "", "")
......@@ -170,7 +170,7 @@ var _ = Describe("job test", func() {
err := jobClient.BuildWithParams(jobName, []ParameterDefinition{{
Name: "name",
Value: "value",
Type: "StringParameterDefinition",
Type: StringParameterDefinition,
}})
Expect(err).To(BeNil())
})
......@@ -180,7 +180,7 @@ var _ = Describe("job test", func() {
It("stop a job build without a folder", func() {
jobName := "fakeJob"
buildID := 1
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/%d/stop", jobClient.URL, jobName, buildID), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/%d/stop", jobClient.URL, jobName, buildID), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
StatusCode: 200,
......@@ -210,7 +210,7 @@ var _ = Describe("job test", func() {
It("stop the last job build without a folder", func() {
jobName := "fakeJob"
buildID := -1
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/lastBuild/stop", jobClient.URL, jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/lastBuild/stop", jobClient.URL, jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
StatusCode: 200,
......@@ -325,7 +325,7 @@ var _ = Describe("job test", func() {
Context("Delete", func() {
It("delete a job", func() {
jobName := "fakeJob"
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/doDelete", jobClient.URL, jobName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/doDelete", jobClient.URL, jobName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
request.Header.Add(util.ContentType, util.ApplicationForm)
response := &http.Response{
......
......@@ -15,7 +15,7 @@ import (
// PrepareForGetJobInputActions only for test
func PrepareForGetJobInputActions(roundTripper *mhttp.MockRoundTripper, rootURL, user, password, jobName string, buildID int) (
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(http.MethodGet, fmt.Sprintf("%s/job/%s/%d/wfapi/pendingInputActions", rootURL, jobName, buildID), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......@@ -36,7 +36,7 @@ func PrepareForGetJobInputActions(roundTripper *mhttp.MockRoundTripper, rootURL,
// PrepareForSubmitInput only for test
func PrepareForSubmitInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPath, user, password string) (
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(http.MethodPost, fmt.Sprintf("%s%s/%d/input/%s/abort?json={\"parameter\":[]}", rootURL, jobPath, 1, "Eff7d5dba32b4da32d9a67a519434d3f"), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return
}
......@@ -44,7 +44,7 @@ func PrepareForSubmitInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPat
// PrepareForSubmitProcessInput only for test
func PrepareForSubmitProcessInput(roundTripper *mhttp.MockRoundTripper, rootURL, jobPath, user, password string) (
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(http.MethodPost, fmt.Sprintf("%s%s/%d/input/%s/proceed?json={\"parameter\":[]}", rootURL, jobPath, 1, "Eff7d5dba32b4da32d9a67a519434d3f"), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return
}
......@@ -54,7 +54,7 @@ func PrepareForBuildWithNoParams(roundTripper *mhttp.MockRoundTripper, rootURL,
request *http.Request, response *http.Response) {
formData := url.Values{"json": {`{"parameter": []}`}}
payload := strings.NewReader(formData.Encode())
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
response.StatusCode = 201
......@@ -66,7 +66,7 @@ func PrepareForBuildWithParams(roundTripper *mhttp.MockRoundTripper, rootURL, jo
request *http.Request, response *http.Response) {
formData := url.Values{"json": {`{"parameter": {"Description":"","name":"name","Type":"StringParameterDefinition","value":"value","DefaultParameterValue":{"Description":"","Value":null}}}`}}
payload := strings.NewReader(formData.Encode())
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/build", rootURL, jobName), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
response.StatusCode = 201
......@@ -76,7 +76,7 @@ func PrepareForBuildWithParams(roundTripper *mhttp.MockRoundTripper, rootURL, jo
// PrepareForGetJob only for test
func PrepareForGetJob(roundTripper *mhttp.MockRoundTripper, rootURL, jobName, user, password string) (
response *http.Response) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/job/%s/api/json", rootURL, jobName), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/job/%s/api/json", rootURL, jobName), nil)
response = &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -145,7 +145,7 @@ func PrepareForGetBuild(roundTripper *mhttp.MockRoundTripper, rootURL, jobName s
} else {
api = fmt.Sprintf("%s/job/%s/%d/api/json", rootURL, jobName, buildID)
}
request, _ := http.NewRequest("GET", api, nil)
request, _ := http.NewRequest(http.MethodGet, api, nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -169,7 +169,7 @@ func PrepareForJobLog(roundTripper *mhttp.MockRoundTripper, rootURL, jobName str
} else {
api = fmt.Sprintf("%s/job/%s/%d/logText/progressiveText?start=%d", rootURL, jobName, buildID, 0)
}
request, _ := http.NewRequest("GET", api, nil)
request, _ := http.NewRequest(http.MethodGet, api, nil)
response := &http.Response{
StatusCode: 200,
Request: request,
......@@ -188,7 +188,7 @@ func PrepareForJobLog(roundTripper *mhttp.MockRoundTripper, rootURL, jobName str
// PrepareOneItem only for test
func PrepareOneItem(roundTripper *mhttp.MockRoundTripper, rootURL, name, kind, user, token string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/items/list?name=%s&type=%s&start=%d&limit=%d&parent=",
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/items/list?name=%s&type=%s&start=%d&limit=%d&parent=",
rootURL, name, kind, 0, 50), nil)
response := &http.Response{
StatusCode: 200,
......@@ -204,7 +204,7 @@ func PrepareOneItem(roundTripper *mhttp.MockRoundTripper, rootURL, name, kind, u
// PrepareEmptyItems only for test
func PrepareEmptyItems(roundTripper *mhttp.MockRoundTripper, rootURL, name, kind, user, token string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/items/list?name=%s&type=%s&start=%d&limit=%d&parent=",
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/items/list?name=%s&type=%s&start=%d&limit=%d&parent=",
rootURL, name, kind, 0, 50), nil)
response := &http.Response{
StatusCode: 200,
......@@ -220,7 +220,7 @@ func PrepareEmptyItems(roundTripper *mhttp.MockRoundTripper, rootURL, name, kind
// PrepareForDisableJob only for test
func PrepareForDisableJob(roundTripper *mhttp.MockRoundTripper, rootURL, name, user, token string) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/disable", rootURL, name), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/disable", rootURL, name), nil)
PrepareCommonPost(request, "", roundTripper, user, token, rootURL)
//response := &http.Response{
// StatusCode: 200,
......@@ -236,7 +236,7 @@ func PrepareForDisableJob(roundTripper *mhttp.MockRoundTripper, rootURL, name, u
// PrepareForEnableJob only for test
func PrepareForEnableJob(roundTripper *mhttp.MockRoundTripper, rootURL, name, user, token string) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/%s/enable", rootURL, name), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/%s/enable", rootURL, name), nil)
PrepareCommonPost(request, "", roundTripper, user, token, rootURL)
//response := &http.Response{
// StatusCode: 200,
......
......@@ -12,7 +12,7 @@ import (
// PrepareShowTrend only for test
func PrepareShowTrend(roundTripper *mhttp.MockRoundTripper, keyword string) (
response *http.Response) {
request, _ := http.NewRequest("GET", fmt.Sprintf("https://plugins.jenkins.io/api/plugin/%s", keyword), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("https://plugins.jenkins.io/api/plugin/%s", keyword), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......@@ -56,7 +56,7 @@ func PrepareOnePluginWithOptionalDep(roundTripper *mhttp.MockRoundTripper, plugi
// PrepareDownloadPlugin only for test
func PrepareDownloadPlugin(roundTripper *mhttp.MockRoundTripper) (response *http.Response) {
request, _ := http.NewRequest("GET",
request, _ := http.NewRequest(http.MethodGet,
"http://updates.jenkins-ci.org/download/plugins/hugo/0.1.8/hugo.hpi", nil)
response = &http.Response{
StatusCode: 200,
......@@ -71,14 +71,14 @@ func PrepareDownloadPlugin(roundTripper *mhttp.MockRoundTripper) (response *http
// PrepareCheckUpdate only for test
func PrepareCheckUpdate(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
api := fmt.Sprintf("%s/pluginManager/checkUpdatesServer", rootURL)
request, _ := http.NewRequest("POST", api, nil)
request, _ := http.NewRequest(http.MethodPost, api, nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
// PrepareShowPlugins only for test
func PrepareShowPlugins(roundTripper *mhttp.MockRoundTripper, keyword string) (
response *http.Response) {
request, _ := http.NewRequest("GET", fmt.Sprintf("https://plugins.jenkins.io/api/plugins/?q=%s&page=1&limit=1000", keyword), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("https://plugins.jenkins.io/api/plugins/?q=%s&page=1&limit=1000", keyword), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......
......@@ -82,7 +82,7 @@ var _ = Describe("PluginManager test", func() {
})
It("response with 500", func() {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/pluginManager/plugins", pluginMgr.URL), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/pluginManager/plugins", pluginMgr.URL), nil)
response := &http.Response{
StatusCode: 500,
Proto: "HTTP/1.1",
......
......@@ -78,7 +78,7 @@ var debugLogFile = "debug.html"
func (p *PluginManager) CheckUpdate(handle func(*http.Response)) (err error) {
api := "/pluginManager/checkUpdatesServer"
var response *http.Response
response, err = p.RequestWithResponseHeader("POST", api, nil, nil, nil)
response, err = p.RequestWithResponseHeader(http.MethodPost, api, nil, nil, nil)
if err == nil {
p.handleCheck(handle)(response)
}
......@@ -87,16 +87,16 @@ func (p *PluginManager) CheckUpdate(handle func(*http.Response)) (err error) {
// GetAvailablePlugins get the aviable plugins from Jenkins
func (p *PluginManager) GetAvailablePlugins() (pluginList *AvailablePluginList, err error) {
err = p.RequestWithData("GET", "/pluginManager/plugins", nil, nil, 200, &pluginList)
err = p.RequestWithData(http.MethodGet, "/pluginManager/plugins", nil, nil, 200, &pluginList)
return
}
// GetPlugins get installed plugins
func (p *PluginManager) GetPlugins(depth int) (pluginList *InstalledPluginList, err error) {
if depth > 1 {
err = p.RequestWithData("GET", fmt.Sprintf("/pluginManager/api/json?depth=%d", depth), nil, nil, 200, &pluginList)
err = p.RequestWithData(http.MethodGet, fmt.Sprintf("/pluginManager/api/json?depth=%d", depth), nil, nil, 200, &pluginList)
} else {
err = p.RequestWithData("GET", "/pluginManager/api/json?depth=1", nil, nil, 200, &pluginList)
err = p.RequestWithData(http.MethodGet, "/pluginManager/api/json?depth=1", nil, nil, 200, &pluginList)
}
return
}
......@@ -158,7 +158,7 @@ func (p *PluginManager) InstallPlugin(names []string) (err error) {
func (p *PluginManager) installPluginsWithoutVersion(plugins string) (err error) {
api := fmt.Sprintf("/pluginManager/install?%s", plugins)
var response *http.Response
response, err = p.RequestWithResponse("POST", api, nil, nil)
response, err = p.RequestWithResponse(http.MethodPost, api, nil, nil)
if response != nil && response.StatusCode == 400 {
if errMsg, ok := response.Header["X-Error"]; ok {
for _, msg := range errMsg {
......@@ -210,7 +210,7 @@ func (p *PluginManager) UninstallPlugin(name string) (err error) {
data []byte
)
if statusCode, data, err = p.Request("POST", api, nil, nil); err == nil {
if statusCode, data, err = p.Request(http.MethodPost, api, nil, nil); err == nil {
if statusCode != 200 {
err = fmt.Errorf("unexpected status code: %d", statusCode)
if p.Debug {
......@@ -296,9 +296,9 @@ func (p *PluginManager) newfileUploadRequest(uri string, params map[string]strin
Title: "Uploading",
}
progressWriter.Init()
req, err = http.NewRequest("POST", uri, progressWriter)
req, err = http.NewRequest(http.MethodPost, uri, progressWriter)
} else {
req, err = http.NewRequest("POST", uri, bytesBuffer)
req, err = http.NewRequest(http.MethodPost, uri, bytesBuffer)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
......
......@@ -2,6 +2,7 @@ package client
import (
"fmt"
"net/http"
)
// QueueClient is the client of queue
......@@ -11,7 +12,7 @@ type QueueClient struct {
// Get returns the job queue
func (q *QueueClient) Get() (status *JobQueue, err error) {
err = q.RequestWithData("GET", "/queue/api/json", nil, nil, 200, &status)
err = q.RequestWithData(http.MethodGet, "/queue/api/json", nil, nil, 200, &status)
return
}
......@@ -19,7 +20,7 @@ func (q *QueueClient) Get() (status *JobQueue, err error) {
func (q *QueueClient) Cancel(id int) (err error) {
api := fmt.Sprintf("/queue/cancelItem?id=%d", id)
var statusCode int
if statusCode, err = q.RequestWithoutData("POST", api, nil, nil, 302); err != nil &&
if statusCode, err = q.RequestWithoutData(http.MethodPost, api, nil, nil, 302); err != nil &&
(statusCode == 200 ||
statusCode == 404) { // 404 should be an error, but no idea why it can be triggered successful
err = nil
......
......@@ -15,7 +15,7 @@ func PrepareForGetJCLIAsset(ver string) (client *github.Client, teardown func())
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/jenkins-zh/jenkins-cli/releases", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
//testMethod(t, r, http.MethodGet)
fmt.Fprint(w, fmt.Sprintf(`[{"id":3, "body":"body", "tag_name":"%s"}]`, ver))
})
return
......@@ -28,7 +28,7 @@ func PrepareForGetReleaseAssetByTagName() (client *github.Client, teardown func(
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/jenkins-zh/jenkins-cli/releases", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
//testMethod(t, r, http.MethodGet)
fmt.Fprint(w, `[{"id":3, "body":"body", "tag_name":"tagName"}]`)
})
return
......@@ -41,7 +41,7 @@ func PrepareForGetLatestJCLIAsset() (client *github.Client, teardown func()) {
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/jenkins-zh/jenkins-cli/releases/latest", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
//testMethod(t, r, http.MethodGet)
fmt.Fprint(w, `{"id":3, "body":"body", "tag_name":"tagName"}`)
})
return
......@@ -54,7 +54,7 @@ func PrepareForGetLatestReleaseAsset() (client *github.Client, teardown func())
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
//testMethod(t, r, http.MethodGet)
fmt.Fprint(w, `{"id":3, "body":"body", "tag_name":"tagName"}`)
})
return
......
......@@ -42,7 +42,7 @@ type JenkinsStatusClient struct {
func (q *JenkinsStatusClient) Get() (status *JenkinsStatus, err error) {
status = &JenkinsStatus{}
var response *http.Response
response, err = q.RequestWithResponseHeader("GET", "/api/json", nil, nil, status)
response, err = q.RequestWithResponseHeader(http.MethodGet, "/api/json", nil, nil, status)
if err == nil {
if ver, ok := response.Header["X-Jenkins"]; ok && len(ver) > 0 {
status.Version = ver[0]
......
......@@ -32,7 +32,7 @@ var _ = Describe("status test", func() {
ctrl.Finish()
})
Context("Get", func() {
Context("Get status", func() {
It("should success", func() {
statusClient.UserName = username
statusClient.Token = password
......
......@@ -10,7 +10,7 @@ import (
//PrepareGetStatus only for test
func PrepareGetStatus(roundTripper *mhttp.MockRoundTripper, rootURL, user, password string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/api/json", rootURL), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/json", rootURL), nil)
response := &http.Response{
StatusCode: 200,
Header: http.Header{},
......
......@@ -19,7 +19,7 @@ import (
// PrepareForEmptyAvaiablePluginList only for test
func PrepareForEmptyAvaiablePluginList(roundTripper *mhttp.MockRoundTripper, rootURL string) (
request *http.Request, response *http.Response) {
request, _ = http.NewRequest("GET", fmt.Sprintf("%s/pluginManager/plugins", rootURL), nil)
request, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/pluginManager/plugins", rootURL), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......@@ -87,9 +87,9 @@ func PrepareForManyAvaiablePlugin(roundTripper *mhttp.MockRoundTripper, rootURL
func PrepareForEmptyInstalledPluginList(roundTripper *mhttp.MockRoundTripper, rootURL string, depth int) (
request *http.Request, response *http.Response) {
if depth > 1 {
request, _ = http.NewRequest("GET", fmt.Sprintf("%s/pluginManager/api/json?depth=%d", rootURL, depth), nil)
request, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/pluginManager/api/json?depth=%d", rootURL, depth), nil)
} else {
request, _ = http.NewRequest("GET", fmt.Sprintf("%s/pluginManager/api/json?depth=1", rootURL), nil)
request, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/pluginManager/api/json?depth=1", rootURL), nil)
}
response = &http.Response{
StatusCode: 200,
......@@ -181,7 +181,7 @@ func PrepareForUploadPlugin(roundTripper *mhttp.MockRoundTripper, rootURL string
io.Copy(part, tmpfile)
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/pluginManager/uploadPlugin", rootURL), nil)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/pluginManager/uploadPlugin", rootURL), nil)
request.Header.Add("CrumbRequestField", "Crumb")
request.Header.Set("Content-Type", writer.FormDataContentType())
response = &http.Response{
......@@ -200,7 +200,7 @@ func PrepareForUploadPlugin(roundTripper *mhttp.MockRoundTripper, rootURL string
// PrepareForUninstallPlugin only for test
func PrepareForUninstallPlugin(roundTripper *mhttp.MockRoundTripper, rootURL, pluginName string) (
request *http.Request, response *http.Response, requestCrumb *http.Request, responseCrumb *http.Response) {
request, _ = http.NewRequest("POST", fmt.Sprintf("%s/pluginManager/plugin/%s/doUninstall", rootURL, pluginName), nil)
request, _ = http.NewRequest(http.MethodPost, fmt.Sprintf("%s/pluginManager/plugin/%s/doUninstall", rootURL, pluginName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response = &http.Response{
StatusCode: 200,
......@@ -225,7 +225,7 @@ func PrepareForUninstallPluginWith500(roundTripper *mhttp.MockRoundTripper, root
// PrepareCancelQueue only for test
func PrepareCancelQueue(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd string) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/queue/cancelItem?id=1", rootURL), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/queue/cancelItem?id=1", rootURL), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
StatusCode: 200,
......@@ -244,7 +244,7 @@ func PrepareCancelQueue(roundTripper *mhttp.MockRoundTripper, rootURL, user, pas
// PrepareGetQueue only for test
func PrepareGetQueue(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd string) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/queue/api/json", rootURL), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/queue/api/json", rootURL), nil)
response := &http.Response{
StatusCode: 200,
Header: map[string][]string{},
......@@ -284,7 +284,7 @@ func PrepareGetQueue(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd
// PrepareForRequestUpdateCenter only for the test case
func PrepareForRequestUpdateCenter(roundTripper *mhttp.MockRoundTripper, rootURL string) (
requestCenter *http.Request, responseCenter *http.Response) {
requestCenter, _ = http.NewRequest("GET", fmt.Sprintf("%s/updateCenter/site/default/api/json?pretty=true&depth=2", rootURL), nil)
requestCenter, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/updateCenter/site/default/api/json?pretty=true&depth=2", rootURL), nil)
responseCenter = &http.Response{
StatusCode: 200,
Request: requestCenter,
......@@ -362,7 +362,7 @@ func PrepareForRequestUpdateCenter(roundTripper *mhttp.MockRoundTripper, rootURL
// PrepareForNoAvailablePlugins only for the test case
func PrepareForNoAvailablePlugins(roundTripper *mhttp.MockRoundTripper, rootURL string) (
requestCenter *http.Request, responseCenter *http.Response) {
requestCenter, _ = http.NewRequest("GET", fmt.Sprintf("%s/updateCenter/site/default/api/json?pretty=true&depth=2", rootURL), nil)
requestCenter, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/updateCenter/site/default/api/json?pretty=true&depth=2", rootURL), nil)
responseCenter = &http.Response{
StatusCode: 200,
Request: requestCenter,
......@@ -406,7 +406,7 @@ func PrepareForInstallPluginWithVersion(roundTripper *mhttp.MockRoundTripper, ro
// PrepareForInstallPluginWithCode only for test
func PrepareForInstallPluginWithCode(roundTripper *mhttp.MockRoundTripper,
statusCode int, rootURL, pluginName, user, passwd string) (response *http.Response) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/pluginManager/install?plugin.%s=", rootURL, pluginName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/pluginManager/install?plugin.%s=", rootURL, pluginName), nil)
request.Header.Add("CrumbRequestField", "Crumb")
response = &http.Response{
StatusCode: statusCode,
......@@ -429,7 +429,7 @@ func PrepareForInstallPluginWithCode(roundTripper *mhttp.MockRoundTripper,
// PrepareForPipelineJob only for test
func PrepareForPipelineJob(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd string) (
request *http.Request, response *http.Response) {
request, _ = http.NewRequest("GET", fmt.Sprintf("%s/job/test/restFul", rootURL), nil)
request, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/job/test/restFul", rootURL), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......@@ -448,7 +448,7 @@ func PrepareForPipelineJob(roundTripper *mhttp.MockRoundTripper, rootURL, user,
func PrepareForUpdatePipelineJob(roundTripper *mhttp.MockRoundTripper, rootURL, script, user, password string) {
formData := url.Values{}
formData.Add("script", script)
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/job/test/restFul/update?%s", rootURL, formData.Encode()), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/job/test/restFul/update?%s", rootURL, formData.Encode()), nil)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return
}
......@@ -464,7 +464,7 @@ func PrepareForCreatePipelineJob(roundTripper *mhttp.MockRoundTripper, rootURL,
}
payload := strings.NewReader(formData.Encode())
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/view/all/createItem", rootURL), payload)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/view/all/createItem", rootURL), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
return
......
......@@ -2,6 +2,7 @@ package client
import (
"fmt"
"net/http"
"net/url"
"strings"
......@@ -101,13 +102,13 @@ type CenterPlugin struct {
// Status returns the status of Jenkins
func (u *UpdateCenterManager) Status() (status *UpdateCenter, err error) {
err = u.RequestWithData("GET", "/updateCenter/api/json?pretty=false&depth=1", nil, nil, 200, &status)
err = u.RequestWithData(http.MethodGet, "/updateCenter/api/json?pretty=false&depth=1", nil, nil, 200, &status)
return
}
// Upgrade the Jenkins core
func (u *UpdateCenterManager) Upgrade() (err error) {
_, err = u.RequestWithoutData("POST", "/updateCenter/upgrade",
_, err = u.RequestWithoutData(http.MethodPost, "/updateCenter/upgrade",
nil, nil, 200)
return
}
......@@ -146,7 +147,7 @@ func (u *UpdateCenterManager) GetJenkinsWarURL() (warURL string) {
// GetSite is get Available Plugins and Updated Plugins from UpdateCenter
func (u *UpdateCenterManager) GetSite() (site *CenterSite, err error) {
err = u.RequestWithData("GET", "/updateCenter/site/default/api/json?pretty=true&depth=2", nil, nil, 200, &site)
err = u.RequestWithData(http.MethodGet, "/updateCenter/site/default/api/json?pretty=true&depth=2", nil, nil, 200, &site)
return
}
......@@ -157,7 +158,7 @@ func (u *UpdateCenterManager) ChangeUpdateCenterSite(name, updateCenterURL strin
payload := strings.NewReader(formData.Encode())
api := "/pluginManager/siteConfigure"
_, err = u.RequestWithoutData("POST", api,
_, err = u.RequestWithoutData(http.MethodPost, api,
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
return
}
......@@ -169,7 +170,7 @@ func (u *UpdateCenterManager) SetMirrorCertificate(enable bool) (err error) {
api = "/update-center-mirror/remove"
}
_, err = u.RequestWithoutData("POST", api,
_, err = u.RequestWithoutData(http.MethodPost, api,
map[string]string{util.ContentType: util.ApplicationForm}, nil, 200)
return
}
......@@ -42,7 +42,7 @@ var _ = Describe("update center test", func() {
manager.ShowProgress = false
manager.Output = donwloadFile
request, _ := http.NewRequest("GET", "http://mirrors.jenkins.io/war/latest/jenkins.war", nil)
request, _ := http.NewRequest(http.MethodGet, "http://mirrors.jenkins.io/war/latest/jenkins.war", nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -69,7 +69,7 @@ var _ = Describe("update center test", func() {
manager.RoundTripper = roundTripper
manager.URL = ""
requestCrumb, _ := http.NewRequest("GET", fmt.Sprintf("%s/crumbIssuer/api/json", ""), nil)
requestCrumb, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/crumbIssuer/api/json", ""), nil)
responseCrumb := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -81,7 +81,7 @@ var _ = Describe("update center test", func() {
roundTripper.EXPECT().
RoundTrip(NewRequestMatcher(requestCrumb)).Return(responseCrumb, nil)
request, _ := http.NewRequest("POST", "/updateCenter/upgrade", nil)
request, _ := http.NewRequest(http.MethodPost, "/updateCenter/upgrade", nil)
request.Header.Add("CrumbRequestField", "Crumb")
response := &http.Response{
StatusCode: 200,
......@@ -102,7 +102,7 @@ var _ = Describe("update center test", func() {
manager.RoundTripper = roundTripper
manager.URL = ""
request, _ := http.NewRequest("GET", "/updateCenter/api/json?pretty=false&depth=1", nil)
request, _ := http.NewRequest(http.MethodGet, "/updateCenter/api/json?pretty=false&depth=1", nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -126,7 +126,7 @@ var _ = Describe("update center test", func() {
manager.RoundTripper = roundTripper
manager.URL = ""
requestCenter, _ := http.NewRequest("GET", "/updateCenter/site/default/api/json?pretty=true&depth=2", nil)
requestCenter, _ := http.NewRequest(http.MethodGet, "/updateCenter/site/default/api/json?pretty=true&depth=2", nil)
responseCenter := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......
......@@ -16,7 +16,7 @@ func PrepareForSetMirrorCertificate(roundTripper *mhttp.MockRoundTripper, rootUR
api = "/update-center-mirror/remove"
}
request, _ := http.NewRequest("POST", fmt.Sprintf("%s%s", rootURL, api), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s", rootURL, api), nil)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......@@ -27,7 +27,7 @@ func PrepareForChangeUpdateCenterSite(roundTripper *mhttp.MockRoundTripper, root
formData.Add("site", updateCenterURL)
payload := strings.NewReader(formData.Encode())
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/pluginManager/siteConfigure", rootURL), payload)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/pluginManager/siteConfigure", rootURL), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, password, rootURL)
}
......@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
......@@ -32,7 +33,7 @@ type TokenData struct {
// Get returns a user's detail
func (q *UserClient) Get() (status *User, err error) {
api := fmt.Sprintf("/user/%s/api/json", q.UserName)
err = q.RequestWithData("GET", api, nil, nil, 200, &status)
err = q.RequestWithData(http.MethodGet, api, nil, nil, 200, &status)
return
}
......@@ -41,13 +42,13 @@ func (q *UserClient) EditDesc(description string) (err error) {
formData := url.Values{}
formData.Add("description", description)
payload := strings.NewReader(formData.Encode())
_, err = q.RequestWithoutData("POST", fmt.Sprintf("/user/%s/submitDescription", q.UserName), map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
_, err = q.RequestWithoutData(http.MethodPost, fmt.Sprintf("/user/%s/submitDescription", q.UserName), map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
return
}
// Delete will remove a user from Jenkins
func (q *UserClient) Delete(username string) (err error) {
_, err = q.RequestWithoutData("POST", fmt.Sprintf("/securityRealm/user/%s/doDelete", username), map[string]string{util.ContentType: util.ApplicationForm}, nil, 200)
_, err = q.RequestWithoutData(http.MethodPost, fmt.Sprintf("/securityRealm/user/%s/doDelete", username), map[string]string{util.ContentType: util.ApplicationForm}, nil, 200)
return
}
......@@ -85,7 +86,7 @@ func (q *UserClient) Create(username, password string) (user *UserForCreate, err
}
payload, user = genSimpleUserAsPayload(username, password)
code, err = q.RequestWithoutData("POST", "/securityRealm/createAccountByAdmin",
code, err = q.RequestWithoutData(http.MethodPost, "/securityRealm/createAccountByAdmin",
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200)
if code == 302 {
err = nil
......@@ -109,7 +110,7 @@ func (q *UserClient) CreateToken(targetUser, newTokenName string) (status *Token
formData.Add("newTokenName", newTokenName)
payload := strings.NewReader(formData.Encode())
err = q.RequestWithData("POST", api,
err = q.RequestWithData(http.MethodPost, api,
map[string]string{util.ContentType: util.ApplicationForm}, payload, 200, &status)
return
}
......
......@@ -32,7 +32,7 @@ var _ = Describe("user test", func() {
ctrl.Finish()
})
Context("Get", func() {
Context("Get users", func() {
It("should success", func() {
userClient.UserName = username
userClient.Token = password
......
......@@ -14,7 +14,7 @@ import (
// PrepareGetUser only for test
func PrepareGetUser(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd string) (
response *http.Response) {
request, _ := http.NewRequest("GET", fmt.Sprintf("%s/user/%s/api/json", rootURL, user), nil)
request, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/user/%s/api/json", rootURL, user), nil)
response = &http.Response{
StatusCode: 200,
Request: request,
......@@ -33,7 +33,7 @@ func PrepareGetUser(roundTripper *mhttp.MockRoundTripper, rootURL, user, passwd
func PrepareCreateUser(roundTripper *mhttp.MockRoundTripper, rootURL,
user, passwd, targetUserName string) (response *http.Response) {
payload, _ := genSimpleUserAsPayload(targetUserName, "fakePass")
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/securityRealm/createAccountByAdmin", rootURL), payload)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/securityRealm/createAccountByAdmin", rootURL), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL)
return
......@@ -46,7 +46,7 @@ func PrepareCreateToken(roundTripper *mhttp.MockRoundTripper, rootURL,
formData.Add("newTokenName", newTokenName)
payload := strings.NewReader(formData.Encode())
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/user/%s/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken", rootURL, targetUser), payload)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/user/%s/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken", rootURL, targetUser), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, `{"status":"ok"}`, roundTripper, user, passwd, rootURL)
return
......@@ -58,7 +58,7 @@ func PrepareForEditUserDesc(roundTripper *mhttp.MockRoundTripper, rootURL, userN
formData.Add("description", description)
payload := strings.NewReader(formData.Encode())
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/user/%s/submitDescription", rootURL, userName), payload)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/user/%s/submitDescription", rootURL, userName), payload)
request.Header.Add(util.ContentType, util.ApplicationForm)
PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL)
return
......@@ -67,7 +67,7 @@ func PrepareForEditUserDesc(roundTripper *mhttp.MockRoundTripper, rootURL, userN
// PrepareForDeleteUser only for test
func PrepareForDeleteUser(roundTripper *mhttp.MockRoundTripper, rootURL, userName, user, passwd string) (
response *http.Response) {
request, _ := http.NewRequest("POST", fmt.Sprintf("%s/securityRealm/user/%s/doDelete", rootURL, userName), nil)
request, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/securityRealm/user/%s/doDelete", rootURL, userName), nil)
request.Header.Add(util.ContentType, util.ApplicationForm)
response = PrepareCommonPost(request, "", roundTripper, user, passwd, rootURL)
return
......
......@@ -64,7 +64,7 @@ func SetProxy(proxy, proxyAuth string, tr *http.Transport) (err error) {
func (h *HTTPDownloader) DownloadFile() error {
filepath, downloadURL, showProgress := h.TargetFilePath, h.URL, h.ShowProgress
// Get the data
req, err := http.NewRequest("GET", downloadURL, nil)
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
if err != nil {
return err
}
......@@ -79,14 +79,20 @@ func (h *HTTPDownloader) DownloadFile() error {
trp := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: h.InsecureSkipVerify},
}
tr = trp
if err = SetProxy(h.Proxy, h.ProxyAuth, trp); err != nil {
return err
}
if h.Proxy != "" {
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(h.ProxyAuth))
req.Header.Add("Proxy-Authorization", basicAuth)
}
tr = trp
}
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
var resp *http.Response
if resp, err = client.Do(req); err != nil {
return err
}
......
......@@ -57,7 +57,7 @@ var _ = Describe("http test", func() {
Context("DownloadFile", func() {
It("no progress indication", func() {
request, _ := http.NewRequest("GET", "", nil)
request, _ := http.NewRequest(http.MethodGet, "", nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......@@ -87,7 +87,7 @@ var _ = Describe("http test", func() {
Password: "Password",
}
request, _ := http.NewRequest("GET", "", nil)
request, _ := http.NewRequest(http.MethodGet, "", nil)
request.SetBasicAuth(downloader.UserName, downloader.Password)
response := &http.Response{
StatusCode: 200,
......@@ -123,7 +123,7 @@ var _ = Describe("http test", func() {
RoundTripper: roundTripper,
}
request, _ := http.NewRequest("GET", "", nil)
request, _ := http.NewRequest(http.MethodGet, "", nil)
response := &http.Response{}
roundTripper.EXPECT().
RoundTrip((request)).Return(response, fmt.Errorf("fake error"))
......@@ -137,7 +137,7 @@ var _ = Describe("http test", func() {
Debug: true,
}
request, _ := http.NewRequest("GET", "", nil)
request, _ := http.NewRequest(http.MethodGet, "", nil)
response := &http.Response{
StatusCode: 400,
Proto: "HTTP/1.1",
......@@ -168,7 +168,7 @@ var _ = Describe("http test", func() {
TargetFilePath: targetFilePath,
}
request, _ := http.NewRequest("GET", "", nil)
request, _ := http.NewRequest(http.MethodGet, "", nil)
response := &http.Response{
StatusCode: 200,
Proto: "HTTP/1.1",
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册