未验证 提交 4b037d40 编写于 作者: LinuxSuRen's avatar LinuxSuRen 提交者: GitHub

Add test cases for open commands (#272)

* Add tests for open cmd

* Add test cases for open commands

* Add comment for the export type

* Fix the test error of GetCategories

* Fix the test error of open cmd

* Fix the error caused by conflicts

* Remove the focus test
上级 5381d913
...@@ -30,7 +30,7 @@ var cascApplyCmd = &cobra.Command{ ...@@ -30,7 +30,7 @@ var cascApplyCmd = &cobra.Command{
RoundTripper: cascApplyOption.RoundTripper, RoundTripper: cascApplyOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
return jClient.Apply() return jClient.Apply()
}, },
} }
...@@ -30,7 +30,7 @@ var cascExportCmd = &cobra.Command{ ...@@ -30,7 +30,7 @@ var cascExportCmd = &cobra.Command{
RoundTripper: cascExportOption.RoundTripper, RoundTripper: cascExportOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
var config string var config string
if config, err = jClient.Export(); err == nil { if config, err = jClient.Export(); err == nil {
......
...@@ -3,10 +3,17 @@ package cmd ...@@ -3,10 +3,17 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/jenkins-zh/jenkins-cli/app/i18n" "github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/jenkins-zh/jenkins-cli/util"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// CASCOpenOption is the option of casc open cmd
type CASCOpenOption struct {
ExecContext util.ExecContext
}
var cascOpenOption CASCOpenOption
func init() { func init() {
cascCmd.AddCommand(cascOpenCmd) cascCmd.AddCommand(cascOpenCmd)
} }
...@@ -17,6 +24,6 @@ var cascOpenCmd = &cobra.Command{ ...@@ -17,6 +24,6 @@ var cascOpenCmd = &cobra.Command{
Long: i18n.T("Open Configuration as Code page in browser"), Long: i18n.T("Open Configuration as Code page in browser"),
RunE: func(_ *cobra.Command, _ []string) error { RunE: func(_ *cobra.Command, _ []string) error {
jenkins := getCurrentJenkinsFromOptionsOrDie() jenkins := getCurrentJenkinsFromOptionsOrDie()
return open(fmt.Sprintf("%s/configuration-as-code", jenkins.URL)) return util.Open(fmt.Sprintf("%s/configuration-as-code", jenkins.URL), cascOpenOption.ExecContext)
}, },
} }
package cmd
import (
"github.com/jenkins-zh/jenkins-cli/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io/ioutil"
"os"
)
var _ = Describe("casc open test", func() {
var (
err error
)
BeforeEach(func() {
cascOpenOption.ExecContext = util.FakeExecCommandSuccess
data, err := generateSampleConfig()
Expect(err).To(BeNil())
rootOptions.ConfigFile = "test.yaml"
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
JustBeforeEach(func() {
rootCmd.SetArgs([]string{"casc", "open"})
_, err = rootCmd.ExecuteC()
})
AfterEach(func() {
os.Remove(rootOptions.ConfigFile)
})
It("should success", func() {
Expect(err).NotTo(HaveOccurred())
})
})
...@@ -30,7 +30,7 @@ var cascReloadCmd = &cobra.Command{ ...@@ -30,7 +30,7 @@ var cascReloadCmd = &cobra.Command{
RoundTripper: cascReloadOption.RoundTripper, RoundTripper: cascReloadOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
return jClient.Reload() return jClient.Reload()
}, },
} }
...@@ -30,7 +30,7 @@ var cascSchemaCmd = &cobra.Command{ ...@@ -30,7 +30,7 @@ var cascSchemaCmd = &cobra.Command{
RoundTripper: cascSchemaOption.RoundTripper, RoundTripper: cascSchemaOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
var config string var config string
if config, err = jClient.Schema(); err == nil { if config, err = jClient.Schema(); err == nil {
......
...@@ -46,7 +46,7 @@ func printUpdateCenter(jenkins *JenkinsServer, cmd *cobra.Command, roundTripper ...@@ -46,7 +46,7 @@ func printUpdateCenter(jenkins *JenkinsServer, cmd *cobra.Command, roundTripper
RoundTripper: roundTripper, RoundTripper: roundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
var centerStatus string var centerStatus string
if status, err = jclient.Status(); err == nil { if status, err = jclient.Status(); err == nil {
......
...@@ -37,7 +37,7 @@ var centerMirrorCmd = &cobra.Command{ ...@@ -37,7 +37,7 @@ var centerMirrorCmd = &cobra.Command{
RoundTripper: centerUpgradeOption.RoundTripper, RoundTripper: centerUpgradeOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
var siteURL string var siteURL string
if centerMirrorOption.Enable { if centerMirrorOption.Enable {
......
...@@ -2,14 +2,14 @@ package cmd ...@@ -2,14 +2,14 @@ package cmd
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"syscall"
"github.com/mitchellh/go-homedir"
"github.com/jenkins-zh/jenkins-cli/app/i18n" "github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/jenkins-zh/jenkins-cli/util"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
...@@ -38,7 +38,8 @@ type CenterStartOption struct { ...@@ -38,7 +38,8 @@ type CenterStartOption struct {
Download bool Download bool
Version string Version string
DryRun bool DryRun bool
SystemCallExec util.SystemCallExec
} }
var centerStartOption CenterStartOption var centerStartOption CenterStartOption
...@@ -133,9 +134,7 @@ var centerStartCmd = &cobra.Command{ ...@@ -133,9 +134,7 @@ var centerStartCmd = &cobra.Command{
fmt.Sprintf("--httpsPrivateKey=%s", centerStartOption.HTTPSPrivateKey)) fmt.Sprintf("--httpsPrivateKey=%s", centerStartOption.HTTPSPrivateKey))
} }
if !centerStartOption.DryRun { err = util.Exec(binary, jenkinsWarArgs, env, centerStartOption.SystemCallExec)
err = syscall.Exec(binary, jenkinsWarArgs, env)
}
} }
return return
}, },
......
package cmd package cmd
import ( import (
"github.com/jenkins-zh/jenkins-cli/util"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
var _ = Describe("center start command", func() { var _ = Describe("center start command", func() {
It("enable mirror site", func() { It("enable mirror site", func() {
centerStartOption.SystemCallExec = util.FakeSystemCallExecSuccess
rootCmd.SetArgs([]string{"center", "start", "--dry-run"}) rootCmd.SetArgs([]string{"center", "start", "--dry-run"})
_, err := rootCmd.ExecuteC() _, err := rootCmd.ExecuteC()
Expect(err).To(BeNil()) Expect(err).To(BeNil())
......
...@@ -3,7 +3,6 @@ package cmd ...@@ -3,7 +3,6 @@ package cmd
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2"
"github.com/jenkins-zh/jenkins-cli/app/i18n" "github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/jenkins-zh/jenkins-cli/client" "github.com/jenkins-zh/jenkins-cli/client"
...@@ -107,7 +106,7 @@ type HookOption struct { ...@@ -107,7 +106,7 @@ type HookOption struct {
SkipPostHook bool SkipPostHook bool
} }
func getCurrentJenkinsAndClient(jclient *client.JenkinsCore) (jenkins *JenkinsServer) { func getCurrentJenkinsAndClientOrDie(jclient *client.JenkinsCore) (jenkins *JenkinsServer) {
jenkins = getCurrentJenkinsFromOptionsOrDie() jenkins = getCurrentJenkinsFromOptionsOrDie()
jclient.URL = jenkins.URL jclient.URL = jenkins.URL
jclient.UserName = jenkins.UserName jclient.UserName = jenkins.UserName
...@@ -116,3 +115,14 @@ func getCurrentJenkinsAndClient(jclient *client.JenkinsCore) (jenkins *JenkinsSe ...@@ -116,3 +115,14 @@ func getCurrentJenkinsAndClient(jclient *client.JenkinsCore) (jenkins *JenkinsSe
jclient.ProxyAuth = jenkins.ProxyAuth jclient.ProxyAuth = jenkins.ProxyAuth
return return
} }
func getCurrentJenkinsAndClient(jClient *client.JenkinsCore) (jenkins *JenkinsServer) {
if jenkins = getCurrentJenkinsFromOptions(); jenkins != nil {
jClient.URL = jenkins.URL
jClient.UserName = jenkins.UserName
jClient.Token = jenkins.Token
jClient.Proxy = jenkins.Proxy
jClient.ProxyAuth = jenkins.ProxyAuth
}
return
}
...@@ -36,7 +36,7 @@ var computerListCmd = &cobra.Command{ ...@@ -36,7 +36,7 @@ var computerListCmd = &cobra.Command{
RoundTripper: computerListOption.RoundTripper, RoundTripper: computerListOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
var computers client.ComputerList var computers client.ComputerList
if computers, err = jClient.List(); err == nil { if computers, err = jClient.List(); err == nil {
......
...@@ -128,6 +128,10 @@ func getCurrentJenkins() (jenkinsServer *JenkinsServer) { ...@@ -128,6 +128,10 @@ func getCurrentJenkins() (jenkinsServer *JenkinsServer) {
} }
func findJenkinsByName(name string) (jenkinsServer *JenkinsServer) { func findJenkinsByName(name string) (jenkinsServer *JenkinsServer) {
if config == nil {
return
}
for _, cfg := range config.JenkinsServers { for _, cfg := range config.JenkinsServers {
if cfg.Name == name { if cfg.Name == name {
jenkinsServer = &cfg jenkinsServer = &cfg
......
...@@ -27,7 +27,7 @@ var crumbIssuerCmd = &cobra.Command{ ...@@ -27,7 +27,7 @@ var crumbIssuerCmd = &cobra.Command{
Long: `Print crumbIssuer of Jenkins`, Long: `Print crumbIssuer of Jenkins`,
Run: func(cmd *cobra.Command, _ []string) { Run: func(cmd *cobra.Command, _ []string) {
jenkinsCore := &client.JenkinsCore{RoundTripper: crumbIssuerOptions.RoundTripper} jenkinsCore := &client.JenkinsCore{RoundTripper: crumbIssuerOptions.RoundTripper}
getCurrentJenkinsAndClient(jenkinsCore) getCurrentJenkinsAndClientOrDie(jenkinsCore)
crumb, err := jenkinsCore.GetCrumb() crumb, err := jenkinsCore.GetCrumb()
if err == nil { if err == nil {
......
...@@ -55,7 +55,7 @@ var jobArtifactCmd = &cobra.Command{ ...@@ -55,7 +55,7 @@ var jobArtifactCmd = &cobra.Command{
RoundTripper: jobArtifactOption.RoundTripper, RoundTripper: jobArtifactOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
artifacts, err := jclient.List(jobName, buildID) artifacts, err := jclient.List(jobName, buildID)
if err == nil { if err == nil {
......
...@@ -59,7 +59,7 @@ var jobArtifactDownloadCmd = &cobra.Command{ ...@@ -59,7 +59,7 @@ var jobArtifactDownloadCmd = &cobra.Command{
RoundTripper: jobArtifactDownloadOption.RoundTripper, RoundTripper: jobArtifactDownloadOption.RoundTripper,
}, },
} }
jobArtifactDownloadOption.Jenkins = getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) jobArtifactDownloadOption.Jenkins = getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
artifacts, err := jclient.List(jobName, buildID) artifacts, err := jclient.List(jobName, buildID)
if err == nil { if err == nil {
......
...@@ -85,7 +85,7 @@ You need to give the parameters if your pipeline has them. Learn more about it f ...@@ -85,7 +85,7 @@ You need to give the parameters if your pipeline has them. Learn more about it f
RoundTripper: jobBuildOption.RoundTripper, RoundTripper: jobBuildOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
paramDefs := []client.ParameterDefinition{} paramDefs := []client.ParameterDefinition{}
hasParam := false hasParam := false
......
...@@ -38,7 +38,7 @@ var jobCreateCmd = &cobra.Command{ ...@@ -38,7 +38,7 @@ var jobCreateCmd = &cobra.Command{
RoundTripper: jobCreateOption.RoundTripper, RoundTripper: jobCreateOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
var createMode string var createMode string
if createMode, err = jobCreateOption.getCreateMode(jclient); err == nil { if createMode, err = jobCreateOption.getCreateMode(jclient); err == nil {
......
...@@ -41,7 +41,7 @@ var jobDeleteCmd = &cobra.Command{ ...@@ -41,7 +41,7 @@ var jobDeleteCmd = &cobra.Command{
RoundTripper: jobDeleteOption.RoundTripper, RoundTripper: jobDeleteOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
err := jclient.Delete(jobName) err := jclient.Delete(jobName)
helper.CheckErr(cmd, err) helper.CheckErr(cmd, err)
......
...@@ -45,7 +45,7 @@ var jobEditCmd = &cobra.Command{ ...@@ -45,7 +45,7 @@ var jobEditCmd = &cobra.Command{
RoundTripper: jobEditOption.RoundTripper, RoundTripper: jobEditOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
if content, err = jobEditOption.getPipeline(jclient, name); err == nil { if content, err = jobEditOption.getPipeline(jclient, name); err == nil {
err = jclient.UpdatePipeline(name, content) err = jclient.UpdatePipeline(name, content)
......
...@@ -37,7 +37,7 @@ var jobHistoryCmd = &cobra.Command{ ...@@ -37,7 +37,7 @@ var jobHistoryCmd = &cobra.Command{
RoundTripper: jobHistoryOption.RoundTripper, RoundTripper: jobHistoryOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
var builds []*client.JobBuild var builds []*client.JobBuild
builds, err = jClient.GetHistory(jobName) builds, err = jClient.GetHistory(jobName)
......
...@@ -54,7 +54,7 @@ var jobInputCmd = &cobra.Command{ ...@@ -54,7 +54,7 @@ var jobInputCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
if inputActions, err := jclient.GetJobInputActions(jobName, buildID); err != nil { if inputActions, err := jclient.GetJobInputActions(jobName, buildID); err != nil {
log.Fatal(err) log.Fatal(err)
......
...@@ -47,7 +47,7 @@ It'll print the log text of the last build if you don't give the build id.`), ...@@ -47,7 +47,7 @@ It'll print the log text of the last build if you don't give the build id.`),
RoundTripper: jobLogOption.RoundTripper, RoundTripper: jobLogOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
lastBuildID := -1 lastBuildID := -1
var jobBuild *client.JobBuild var jobBuild *client.JobBuild
......
...@@ -40,7 +40,7 @@ var jobParamCmd = &cobra.Command{ ...@@ -40,7 +40,7 @@ var jobParamCmd = &cobra.Command{
RoundTripper: jobParamOption.RoundTripper, RoundTripper: jobParamOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
job, err := jclient.GetJob(name) job, err := jclient.GetJob(name)
var data []byte var data []byte
......
...@@ -54,7 +54,7 @@ var jobSearchCmd = &cobra.Command{ ...@@ -54,7 +54,7 @@ var jobSearchCmd = &cobra.Command{
RoundTripper: jobSearchOption.RoundTripper, RoundTripper: jobSearchOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
status, err := jclient.Search(keyword, jobSearchOption.Max) status, err := jclient.Search(keyword, jobSearchOption.Max)
if err == nil { if err == nil {
......
...@@ -46,7 +46,7 @@ var jobStopCmd = &cobra.Command{ ...@@ -46,7 +46,7 @@ var jobStopCmd = &cobra.Command{
RoundTripper: jobStopOption.RoundTripper, RoundTripper: jobStopOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
return jclient.StopJob(jobName, buildNum) return jclient.StopJob(jobName, buildNum)
}, },
......
...@@ -37,7 +37,7 @@ var jobTypeCmd = &cobra.Command{ ...@@ -37,7 +37,7 @@ var jobTypeCmd = &cobra.Command{
RoundTripper: jobTypeOption.RoundTripper, RoundTripper: jobTypeOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
status, err := jclient.GetJobTypeCategories() status, err := jclient.GetJobTypeCategories()
if err == nil { if err == nil {
......
...@@ -55,7 +55,15 @@ var _ = Describe("job type command", func() { ...@@ -55,7 +55,15 @@ var _ = Describe("job type command", func() {
roundTripper.EXPECT(). roundTripper.EXPECT().
RoundTrip(request).Return(response, nil) RoundTrip(request).Return(response, nil)
//initConfig() config = &Config{
Current: "fake",
JenkinsServers: []JenkinsServer{JenkinsServer{
Name: "fake",
URL: "http://localhost:8080/jenkins",
UserName: "admin",
Token: "111e3a2f0231198855dceaff96f20540a9",
}},
}
jclient := &client.JobClient{ jclient := &client.JobClient{
JenkinsCore: client.JenkinsCore{ JenkinsCore: client.JenkinsCore{
RoundTripper: jobTypeOption.RoundTripper, RoundTripper: jobTypeOption.RoundTripper,
......
...@@ -2,12 +2,9 @@ package cmd ...@@ -2,12 +2,9 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"log"
"os/exec"
"runtime"
"github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/jenkins-zh/jenkins-cli/util"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
...@@ -17,6 +14,8 @@ type OpenOption struct { ...@@ -17,6 +14,8 @@ type OpenOption struct {
Name string Name string
Config bool Config bool
ExecContext util.ExecContext
} }
var openOption OpenOption var openOption OpenOption
...@@ -32,10 +31,10 @@ func init() { ...@@ -32,10 +31,10 @@ func init() {
var openCmd = &cobra.Command{ var openCmd = &cobra.Command{
Use: "open [config name]", Use: "open [config name]",
Short: i18n.T("Open your Jenkins with a browse"), Short: i18n.T("Open your Jenkins with a browser"),
Long: i18n.T(`Open your Jenkins with a browse`), Long: i18n.T(`Open your Jenkins with a browser`),
Example: `jcli open -n <config name>`, Example: `jcli open -n [config name]`,
Run: func(_ *cobra.Command, args []string) { RunE: func(_ *cobra.Command, args []string) (err error) {
var jenkins *JenkinsServer var jenkins *JenkinsServer
var configName string var configName string
...@@ -48,10 +47,12 @@ var openCmd = &cobra.Command{ ...@@ -48,10 +47,12 @@ var openCmd = &cobra.Command{
if configName == "" && openOption.Interactive { if configName == "" && openOption.Interactive {
jenkinsNames := getJenkinsNames() jenkinsNames := getJenkinsNames()
prompt := &survey.Select{ prompt := &survey.Select{
Message: "Choose a Jenkins that you want to open:", Message: i18n.T("Choose a Jenkins which you want to open:"),
Options: jenkinsNames, Options: jenkinsNames,
} }
survey.AskOne(prompt, &(configName)) if err = survey.AskOne(prompt, &(configName)); err != nil {
return
}
} }
if configName != "" { if configName != "" {
...@@ -65,26 +66,10 @@ var openCmd = &cobra.Command{ ...@@ -65,26 +66,10 @@ var openCmd = &cobra.Command{
if openOption.Config { if openOption.Config {
url = fmt.Sprintf("%s/configure", url) url = fmt.Sprintf("%s/configure", url)
} }
open(url) err = util.Open(url, openOption.ExecContext)
} else { } else {
log.Fatalf("No URL found with Jenkins %s", configName) err = fmt.Errorf("no URL found with Jenkins %s", configName)
} }
return
}, },
} }
func open(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"github.com/jenkins-zh/jenkins-cli/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("test open", func() {
var (
err error
jenkinsName string
)
BeforeEach(func() {
data, err := generateSampleConfig()
Expect(err).To(BeNil())
rootOptions.ConfigFile = "test.yaml"
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
openOption.ExecContext = util.FakeExecCommandSuccess
jenkinsName = "fake"
})
JustBeforeEach(func() {
buf := new(bytes.Buffer)
rootCmd.SetOut(buf)
rootCmd.SetArgs([]string{"open", jenkinsName})
_, err = rootCmd.ExecuteC()
})
It("open a not exists Jenkins", func() {
Expect(err).To(HaveOccurred())
Expect(fmt.Sprint(err)).To(ContainSubstring("no URL found with Jenkins " + jenkinsName))
})
Context("give a right config", func() {
BeforeEach(func() {
jenkinsName = "yourServer"
})
It("should success", func() {
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
os.Remove(rootOptions.ConfigFile)
})
})
})
...@@ -32,7 +32,7 @@ var pluginCheckCmd = &cobra.Command{ ...@@ -32,7 +32,7 @@ var pluginCheckCmd = &cobra.Command{
RoundTripper: pluginCheckoutOption.RoundTripper, RoundTripper: pluginCheckoutOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jClient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jClient.JenkinsCore))
err := jClient.CheckUpdate(func(response *http.Response) { err := jClient.CheckUpdate(func(response *http.Response) {
code := response.StatusCode code := response.StatusCode
......
...@@ -47,7 +47,7 @@ jcli plugin install localization-zh-cn@1.0.9 ...@@ -47,7 +47,7 @@ jcli plugin install localization-zh-cn@1.0.9
UseMirror: pluginInstallOption.UseMirror, UseMirror: pluginInstallOption.UseMirror,
MirrorURL: getDefaultMirror(), MirrorURL: getDefaultMirror(),
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
plugins := make([]string, len(args)) plugins := make([]string, len(args))
plugins = append(plugins, args...) plugins = append(plugins, args...)
......
...@@ -43,7 +43,7 @@ var pluginListCmd = &cobra.Command{ ...@@ -43,7 +43,7 @@ var pluginListCmd = &cobra.Command{
RoundTripper: pluginListOption.RoundTripper, RoundTripper: pluginListOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
var ( var (
filter bool filter bool
......
...@@ -2,11 +2,17 @@ package cmd ...@@ -2,11 +2,17 @@ package cmd
import ( import (
"fmt" "fmt"
"log" "github.com/jenkins-zh/jenkins-cli/util"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// PluginOpenOption is the option of plugin open cmd
type PluginOpenOption struct {
ExecContext util.ExecContext
}
var pluginOpenOption PluginOpenOption
func init() { func init() {
pluginCmd.AddCommand(pluginOpenCmd) pluginCmd.AddCommand(pluginOpenCmd)
} }
...@@ -15,13 +21,14 @@ var pluginOpenCmd = &cobra.Command{ ...@@ -15,13 +21,14 @@ var pluginOpenCmd = &cobra.Command{
Use: "open", Use: "open",
Short: "Open update center server in browser", Short: "Open update center server in browser",
Long: `Open update center server in browser`, Long: `Open update center server in browser`,
Run: func(_ *cobra.Command, _ []string) { RunE: func(_ *cobra.Command, _ []string) (err error) {
jenkins := getCurrentJenkinsFromOptionsOrDie() jenkins := getCurrentJenkinsFromOptionsOrDie()
if jenkins.URL != "" { if jenkins.URL != "" {
open(fmt.Sprintf("%s/pluginManager", jenkins.URL)) err = util.Open(fmt.Sprintf("%s/pluginManager", jenkins.URL), pluginOpenOption.ExecContext)
} else { } else {
log.Fatal(fmt.Sprintf("No URL fond from %s", jenkins.Name)) err = fmt.Errorf("no URL fond from %s", jenkins.Name)
} }
return
}, },
} }
package cmd
import (
"fmt"
"github.com/jenkins-zh/jenkins-cli/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
var _ = Describe("plugin open test", func() {
var (
err error
)
BeforeEach(func() {
pluginOpenOption.ExecContext = util.FakeExecCommandSuccess
data, err := generateSampleConfig()
Expect(err).To(BeNil())
rootOptions.ConfigFile = "test.yaml"
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
JustBeforeEach(func() {
rootCmd.SetArgs([]string{"plugin", "open"})
_, err = rootCmd.ExecuteC()
})
AfterEach(func() {
os.Remove(rootOptions.ConfigFile)
})
It("should success", func() {
Expect(err).NotTo(HaveOccurred())
})
Context("without url", func() {
BeforeEach(func() {
pluginOpenOption.ExecContext = util.FakeExecCommandSuccess
sampleConfig := getSampleConfig()
sampleConfig.JenkinsServers[0].URL = ""
data, err := yaml.Marshal(&sampleConfig)
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
It("should failure", func() {
Expect(err).To(HaveOccurred())
Expect(fmt.Sprint(err)).To(ContainSubstring("no URL fond from"))
})
})
})
...@@ -41,7 +41,7 @@ var pluginSearchCmd = &cobra.Command{ ...@@ -41,7 +41,7 @@ var pluginSearchCmd = &cobra.Command{
RoundTripper: pluginSearchOption.RoundTripper, RoundTripper: pluginSearchOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
plugins, err := jclient.GetAvailablePlugins() plugins, err := jclient.GetAvailablePlugins()
if err == nil { if err == nil {
...@@ -77,7 +77,7 @@ func matchPluginsData(plugins []client.AvailablePlugin, pluginJclient *client.Pl ...@@ -77,7 +77,7 @@ func matchPluginsData(plugins []client.AvailablePlugin, pluginJclient *client.Pl
RoundTripper: pluginSearchOption.RoundTripper, RoundTripper: pluginSearchOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
site, err := jclient.GetSite() site, err := jclient.GetSite()
noSite := (err != nil || site == nil) noSite := (err != nil || site == nil)
installedPlugins, err := pluginJclient.GetPlugins(1) installedPlugins, err := pluginJclient.GetPlugins(1)
......
...@@ -33,7 +33,7 @@ var pluginUninstallCmd = &cobra.Command{ ...@@ -33,7 +33,7 @@ var pluginUninstallCmd = &cobra.Command{
RoundTripper: pluginUninstallOption.RoundTripper, RoundTripper: pluginUninstallOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
err := jclient.UninstallPlugin(pluginName) err := jclient.UninstallPlugin(pluginName)
helper.CheckErr(cmd, err) helper.CheckErr(cmd, err)
......
...@@ -39,7 +39,7 @@ var pluginUpgradeCmd = &cobra.Command{ ...@@ -39,7 +39,7 @@ var pluginUpgradeCmd = &cobra.Command{
RoundTripper: pluginUpgradeOption.RoundTripper, RoundTripper: pluginUpgradeOption.RoundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
var err error var err error
targetPlugins := make([]string, 0) targetPlugins := make([]string, 0)
......
...@@ -67,7 +67,7 @@ var _ = Describe("plugin upgrade command", func() { ...@@ -67,7 +67,7 @@ var _ = Describe("plugin upgrade command", func() {
RoundTripper: roundTripper, RoundTripper: roundTripper,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
request, _ := client.PrepareForOneInstalledPlugin(roundTripper, "http://localhost:8080/jenkins") request, _ := client.PrepareForOneInstalledPlugin(roundTripper, "http://localhost:8080/jenkins")
request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9") request.SetBasicAuth("admin", "111e3a2f0231198855dceaff96f20540a9")
......
...@@ -119,7 +119,7 @@ jcli plugin upload sample.hpi --show-progress=false`, ...@@ -119,7 +119,7 @@ jcli plugin upload sample.hpi --show-progress=false`,
}, },
ShowProgress: pluginUploadOption.ShowProgress, ShowProgress: pluginUploadOption.ShowProgress,
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
jclient.Debug = rootOptions.Debug jclient.Debug = rootOptions.Debug
if pluginUploadOption.Remote != "" { if pluginUploadOption.Remote != "" {
......
...@@ -4,6 +4,8 @@ import ( ...@@ -4,6 +4,8 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"go.uber.org/zap" "go.uber.org/zap"
"github.com/jenkins-zh/jenkins-cli/client" "github.com/jenkins-zh/jenkins-cli/client"
...@@ -23,8 +25,8 @@ func init() { ...@@ -23,8 +25,8 @@ func init() {
var queueCancelCmd = &cobra.Command{ var queueCancelCmd = &cobra.Command{
Use: "cancel <id>", Use: "cancel <id>",
Short: "Cancel the queue of your Jenkins", Short: i18n.T("Cancel the queue items of your Jenkins"),
Long: `Cancel the queue of your Jenkins`, Long: i18n.T("Cancel the queue items of your Jenkins"),
Args: cobra.MinimumNArgs(1), Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) (err error) { RunE: func(cmd *cobra.Command, args []string) (err error) {
for _, arg := range args { for _, arg := range args {
...@@ -37,10 +39,7 @@ var queueCancelCmd = &cobra.Command{ ...@@ -37,10 +39,7 @@ var queueCancelCmd = &cobra.Command{
} }
func (c *QueueCancelOption) cancel(id string) (err error) { func (c *QueueCancelOption) cancel(id string) (err error) {
var ( var queueID int
queueID int
)
if queueID, err = strconv.Atoi(id); err != nil { if queueID, err = strconv.Atoi(id); err != nil {
return return
} }
......
...@@ -37,7 +37,7 @@ var queueListCmd = &cobra.Command{ ...@@ -37,7 +37,7 @@ var queueListCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
var err error var err error
var jobQueue *client.JobQueue var jobQueue *client.JobQueue
......
...@@ -49,7 +49,7 @@ var restartCmd = &cobra.Command{ ...@@ -49,7 +49,7 @@ var restartCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
if err := jclient.Restart(); err == nil { if err := jclient.Restart(); err == nil {
cmd.Println("Please wait while Jenkins is restarting") cmd.Println("Please wait while Jenkins is restarting")
......
...@@ -33,7 +33,7 @@ var userCmd = &cobra.Command{ ...@@ -33,7 +33,7 @@ var userCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
status, err := jclient.Get() status, err := jclient.Get()
if err == nil { if err == nil {
......
...@@ -37,7 +37,7 @@ var userCreateCmd = &cobra.Command{ ...@@ -37,7 +37,7 @@ var userCreateCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
if user, err := jclient.Create(username, password); err == nil { if user, err := jclient.Create(username, password); err == nil {
cmd.Println("create user success. Password is:", user.Password1) cmd.Println("create user success. Password is:", user.Password1)
......
...@@ -41,7 +41,7 @@ var userDeleteCmd = &cobra.Command{ ...@@ -41,7 +41,7 @@ var userDeleteCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
err := jclient.Delete(username) err := jclient.Delete(username)
helper.CheckErr(cmd, err) helper.CheckErr(cmd, err)
......
...@@ -41,7 +41,7 @@ var userTokenCmd = &cobra.Command{ ...@@ -41,7 +41,7 @@ var userTokenCmd = &cobra.Command{
Debug: rootOptions.Debug, Debug: rootOptions.Debug,
}, },
} }
getCurrentJenkinsAndClient(&(jclient.JenkinsCore)) getCurrentJenkinsAndClientOrDie(&(jclient.JenkinsCore))
tokenName := userTokenOption.Name tokenName := userTokenOption.Name
status, err := jclient.CreateToken(tokenName) status, err := jclient.CreateToken(tokenName)
......
...@@ -64,7 +64,7 @@ msgid "Build the job of your Jenkins.\n" ...@@ -64,7 +64,7 @@ msgid "Build the job of your Jenkins.\n"
msgstr "" msgstr ""
#: app/cmd/open.go:35 app/cmd/open.go:36 #: app/cmd/open.go:35 app/cmd/open.go:36
msgid "Open your Jenkins with a browse" msgid "Open your Jenkins with a browser"
msgstr "在浏览器里打开 Jenkins" msgstr "在浏览器里打开 Jenkins"
#: app/cmd/center_start.go:48 #: app/cmd/center_start.go:48
......
package util
import (
"os"
"os/exec"
"runtime"
"syscall"
)
// Open a URL in a browser
func Open(url string, cmdContext ExecContext) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "Open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-Open"
}
args = append(args, url)
if cmdContext == nil {
cmdContext = exec.Command
}
return cmdContext(cmd, args...).Start()
}
// Exec is the wrapper of syscall.Exec
func Exec(argv0 string, argv []string, envv []string, systemCallExec SystemCallExec) error {
if systemCallExec == nil {
systemCallExec = syscall.Exec
}
return systemCallExec(argv0, argv, envv)
}
// SystemCallExec is the context of syscall.Exec
type SystemCallExec = func(argv0 string, argv []string, envv []string) (err error)
// ExecContext is the context of system command caller
type ExecContext = func(name string, arg ...string) *exec.Cmd
// FakeExecCommandSuccess is a function that initialises a new exec.Cmd, one which will
// simply call TestShellProcessSuccess rather than the command it is provided. It will
// also pass through the command and its arguments as an argument to TestShellProcessSuccess
func FakeExecCommandSuccess(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestShellProcessSuccess", "--", command}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_TEST_PROCESS=1"}
return cmd
}
// FakeSystemCallExecSuccess is a fake function of syscall.Exec
func FakeSystemCallExecSuccess(argv0 string, argv []string, envv []string) (err error) {
return
}
package util
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Test open browser", func() {
It("should success", func() {
err := Open("fake://url", FakeExecCommandSuccess)
Expect(err).To(BeNil())
})
})
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册