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

Show the changelog of jcli (#328)

* Show the changelog of jcli

* Add more test cases for version cmd

* Add comment for exported function

* Comment the useless code lines
上级 9266de06
package cmd
import (
"fmt"
"github.com/jenkins-zh/jenkins-cli/client"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
......@@ -27,7 +28,11 @@ var computerListCmd = &cobra.Command{
Short: i18n.T("List all Jenkins agents"),
Long: i18n.T("List all Jenkins agents"),
RunE: func(cmd *cobra.Command, _ []string) (err error) {
jClient, _ := GetComputerClient(computerListOption.CommonOption)
jClient, config := GetComputerClient(computerListOption.CommonOption)
if config == nil {
err = fmt.Errorf("cannot found the configuration")
return
}
var computers client.ComputerList
if computers, err = jClient.List(); err == nil {
......
......@@ -2,7 +2,6 @@ package cmd
import (
"bytes"
"io"
"io/ioutil"
"os"
......@@ -19,7 +18,7 @@ var _ = Describe("computer list command", func() {
var (
ctrl *gomock.Controller
roundTripper *mhttp.MockRoundTripper
buf io.Writer
buf *bytes.Buffer
)
BeforeEach(func() {
......@@ -61,5 +60,12 @@ var _ = Describe("computer list command", func() {
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
})
It("with a fake jenkins as option", func() {
rootCmd.SetArgs([]string{"computer", "list", "--jenkins", "fake"})
_, err := rootCmd.ExecuteC()
Expect(err).To(HaveOccurred())
Expect(buf.String()).To(ContainSubstring("cannot found the configuration"))
})
})
})
......@@ -2,15 +2,9 @@ package cmd
import (
"bytes"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/Netflix/go-expect"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"os"
"path"
"testing"
"time"
)
var _ = Describe("config generate command", func() {
......@@ -72,30 +66,30 @@ mirrors:
})
})
func TestConfigGenerate(t *testing.T) {
RunEditCommandTest(t, EditCommandTest{
ConfirmProcedure: func(c *expect.Console) {
c.ExpectString("Cannot found your config file, do you want to edit it?")
c.SendLine("y")
//c.ExpectEOF()
},
Procedure: func(c *expect.Console) {
c.ExpectString("Edit your config file")
c.SendLine("")
go c.ExpectEOF()
time.Sleep(time.Millisecond)
c.Send(`ifake-config`)
c.Send("\x1b")
c.SendLine(":wq!")
},
Test: func(stdio terminal.Stdio) (err error) {
configFile := path.Join(os.TempDir(), "fake.yaml")
defer os.Remove(configFile)
configGenerateOption.BatchOption.Stdio = stdio
configGenerateOption.CommonOption.Stdio = stdio
rootCmd.SetArgs([]string{"config", "generate", "--interactive", "--copy=false", "--configFile=" + configFile})
_, err = rootCmd.ExecuteC()
return
},
})
}
//func TestConfigGenerate(t *testing.T) {
// RunEditCommandTest(t, EditCommandTest{
// ConfirmProcedure: func(c *expect.Console) {
// c.ExpectString("Cannot found your config file, do you want to edit it?")
// c.SendLine("y")
// //c.ExpectEOF()
// },
// Procedure: func(c *expect.Console) {
// c.ExpectString("Edit your config file")
// c.SendLine("")
// go c.ExpectEOF()
// time.Sleep(time.Millisecond)
// c.Send(`ifake-config`)
// c.Send("\x1b")
// c.SendLine(":wq!")
// },
// Test: func(stdio terminal.Stdio) (err error) {
// configFile := path.Join(os.TempDir(), "fake.yaml")
// defer os.Remove(configFile)
// configGenerateOption.BatchOption.Stdio = stdio
// configGenerateOption.CommonOption.Stdio = stdio
// rootCmd.SetArgs([]string{"config", "generate", "--interactive", "--copy=false", "--configFile=" + configFile})
// _, err = rootCmd.ExecuteC()
// return
// },
// })
//}
......@@ -15,6 +15,7 @@ import (
var _ = Describe("config list command", func() {
var (
ctrl *gomock.Controller
err error
)
BeforeEach(func() {
......@@ -22,6 +23,12 @@ var _ = Describe("config list command", func() {
rootCmd.SetArgs([]string{})
rootOptions.Jenkins = ""
rootOptions.ConfigFile = "test.yaml"
var data []byte
data, err = generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
AfterEach(func() {
......@@ -34,11 +41,6 @@ var _ = Describe("config list command", func() {
Context("basic cases", func() {
It("should success", func() {
data, err := generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
buf := new(bytes.Buffer)
rootCmd.SetOutput(buf)
rootCmd.SetArgs([]string{"config", "list"})
......
......@@ -18,6 +18,13 @@ var _ = Describe("doc command test", func() {
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
config = nil
rootOptions.ConfigFile = "test.yaml"
data, err := generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
AfterEach(func() {
......
......@@ -17,6 +17,7 @@ var _ = Describe("job stop command", func() {
var (
ctrl *gomock.Controller
roundTripper *mhttp.MockRoundTripper
err error
)
BeforeEach(func() {
......@@ -26,6 +27,12 @@ var _ = Describe("job stop command", func() {
rootCmd.SetArgs([]string{})
rootOptions.Jenkins = ""
rootOptions.ConfigFile = "test.yaml"
var data []byte
data, err = generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
AfterEach(func() {
......@@ -37,10 +44,6 @@ var _ = Describe("job stop command", func() {
Context("basic cases", func() {
It("should success, with batch mode", func() {
data, err := generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
jobName := "fakeJob"
buildID := 1
......
......@@ -8,7 +8,6 @@ import (
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/spf13/cobra"
)
var _ = Describe("queue command", func() {
......@@ -38,16 +37,16 @@ var _ = Describe("queue command", func() {
Expect(err).To(BeNil())
rootCmd.SetArgs([]string{"queue"})
rootCmd.SetHelpFunc(func(cmd *cobra.Command, _ []string) {
cmd.Print("help")
})
//rootCmd.SetHelpFunc(func(cmd *cobra.Command, _ []string) {
// cmd.Print("help")
//})
buf := new(bytes.Buffer)
rootCmd.SetOutput(buf)
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
Expect(buf.String()).To(Equal("help"))
Expect(buf.String()).To(ContainSubstring("Manage the queue of your Jenkins"))
})
})
})
......@@ -16,7 +16,6 @@ import (
"github.com/jenkins-zh/jenkins-cli/client"
"github.com/jenkins-zh/jenkins-cli/app"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
......@@ -27,7 +26,6 @@ var logger *zap.Logger
type RootOptions struct {
ConfigFile string
Jenkins string
Version bool
Debug bool
URL string
......@@ -59,51 +57,50 @@ More information could found at https://jenkins-zh.cn`,
return
}
if rootOptions.ConfigFile == "" {
rootOptions.ConfigFile = os.Getenv("JCLI_CONFIG")
}
if needReadConfig(cmd) {
if rootOptions.ConfigFile == "" {
rootOptions.ConfigFile = os.Getenv("JCLI_CONFIG")
}
logger.Debug("read config file", zap.String("path", rootOptions.ConfigFile))
if rootOptions.Version && cmd.Flags().NFlag() == 1 {
return
logger.Debug("read config file", zap.String("path", rootOptions.ConfigFile))
if rootOptions.ConfigFile == "" {
if err = loadDefaultConfig(); err != nil {
configLoadErrorHandle(err)
}
} else {
if err = loadConfig(rootOptions.ConfigFile); err != nil {
configLoadErrorHandle(err)
}
}
}
if rootOptions.ConfigFile == "" {
if err := loadDefaultConfig(); err != nil {
configLoadErrorHandle(err)
if err == nil {
config = getConfig()
if config != nil {
// set Header Accept-Language
client.SetLanguage(config.Language)
}
} else {
if err := loadConfig(rootOptions.ConfigFile); err != nil {
configLoadErrorHandle(err)
}
}
config = getConfig()
if config != nil {
// set Header Accept-Language
client.SetLanguage(config.Language)
err = rootOptions.RunDiagnose(cmd)
}
err = rootOptions.RunDiagnose(cmd)
return
},
BashCompletionFunction: jcliBashCompletionFunc,
RunE: func(cmd *cobra.Command, args []string) (err error) {
cmd.Println(i18n.T("Jenkins CLI (jcli) manage your Jenkins"))
if rootOptions.Version {
cmd.Printf("Version: %s\n", app.GetVersion())
cmd.Printf("Commit: %s\n", app.GetCommit())
}
if rootOptions.Jenkins != "" {
current := getCurrentJenkinsFromOptions()
if current != nil {
cmd.Println("Current Jenkins is:", current.Name)
} else {
err = fmt.Errorf("cannot found the configuration: %s", rootOptions.Jenkins)
}
}
func needReadConfig(cmd *cobra.Command) bool {
ignoreConfigLoad := []string{
"config.generate",
"version",
}
configPath := getCmdPath(cmd)
for _, item := range ignoreConfigLoad {
if item == configPath {
return false
}
return
},
}
return true
}
// RunDiagnose run the diagnose for a specific command
......@@ -143,8 +140,6 @@ func init() {
"Logger level which could be: debug, info, warn, error")
rootCmd.PersistentFlags().BoolVarP(&rootOptions.Doctor, "doctor", "", false,
i18n.T("Run the diagnose for current command"))
rootCmd.Flags().BoolVarP(&rootOptions.Version, "version", "v", false,
i18n.T("Print the version of Jenkins CLI"))
rootCmd.PersistentFlags().StringVarP(&rootOptions.URL, "url", "", "",
i18n.T("The URL of Jenkins"))
......
......@@ -31,18 +31,6 @@ var _ = Describe("Root cmd test", func() {
ctrl.Finish()
})
Context("invalid logger level", func() {
It("cause errors", func() {
rootCmd.SetArgs([]string{"--logger-level", "fake"})
_, err := rootCmd.ExecuteC()
Expect(err).To(HaveOccurred())
rootCmd.SetArgs([]string{"--logger-level", "warn"})
_, err = rootCmd.ExecuteC()
Expect(err).NotTo(HaveOccurred())
})
})
Context("PreHook test", func() {
It("only with root cmd", func() {
path := getCmdPath(fakeRootCmd)
......@@ -276,20 +264,6 @@ var _ = Describe("Root cmd test", func() {
rootCmd.SetOut(buf)
})
It("should contain substring Version:", func() {
rootCmd.SetArgs([]string{"--version"})
_, err := rootCmd.ExecuteC()
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(ContainSubstring("Version:"))
})
It("with a fake jenkins as option", func() {
rootCmd.SetArgs([]string{"--jenkins", "fake"})
_, err := rootCmd.ExecuteC()
Expect(err).To(HaveOccurred())
Expect(buf.String()).To(ContainSubstring("cannot found the configuration:"))
})
It("with an exists jenkins as option", func() {
configFile, err := ioutil.TempFile("/tmp", ".yaml")
Expect(err).NotTo(HaveOccurred())
......@@ -304,7 +278,7 @@ var _ = Describe("Root cmd test", func() {
rootCmd.SetArgs([]string{"--jenkins", "yourServer", "--configFile", configFile.Name()})
_, err = rootCmd.ExecuteC()
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(ContainSubstring("Current Jenkins is:"))
Expect(buf.String()).To(ContainSubstring("jcli is Jenkins CLI which could help with your multiple Jenkins"))
})
})
......
......@@ -18,6 +18,7 @@ var _ = Describe("user token command", func() {
var (
ctrl *gomock.Controller
roundTripper *mhttp.MockRoundTripper
err error
)
BeforeEach(func() {
......@@ -27,6 +28,12 @@ var _ = Describe("user token command", func() {
rootCmd.SetArgs([]string{})
rootOptions.Jenkins = ""
rootOptions.ConfigFile = "test.yaml"
var data []byte
data, err = generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
AfterEach(func() {
......@@ -52,11 +59,6 @@ var _ = Describe("user token command", func() {
})
It("should success", func() {
data, err := generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
targetUser := "target-user"
tokenName := "fakename"
......@@ -74,11 +76,6 @@ var _ = Describe("user token command", func() {
})
It("with status code 500", func() {
data, err := generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
targetUser := "target-user"
tokenName := "fakename"
......
package cmd
import (
"fmt"
"github.com/google/go-github/v29/github"
"github.com/jenkins-zh/jenkins-cli/app"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/jenkins-zh/jenkins-cli/client"
"github.com/spf13/cobra"
"strings"
)
// VersionOption is the version option
type VersionOption struct {
Changelog bool
ShowLatest bool
GitHubClient *github.Client
}
var versionOption VersionOption
func init() {
rootCmd.AddCommand(versionCmd)
versionCmd.Flags().BoolVarP(&versionOption.Changelog, "changelog", "", false,
i18n.T("Output the changelog of current version"))
versionCmd.Flags().BoolVarP(&versionOption.ShowLatest, "show-latest", "", false,
i18n.T("Output the latest version"))
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the user of your Jenkins",
Long: `Print the user of your Jenkins`,
PreRun: func(cmd *cobra.Command, _ []string) {
if versionOption.GitHubClient == nil {
versionOption.GitHubClient = github.NewClient(nil)
}
},
RunE: func(cmd *cobra.Command, _ []string) (err error) {
cmd.Println(i18n.T("Jenkins CLI (jcli) manage your Jenkins"))
version := app.GetVersion()
cmd.Printf("Version: %s\n", version)
cmd.Printf("Commit: %s\n", app.GetCommit())
if rootOptions.Jenkins != "" {
current := getCurrentJenkinsFromOptions()
if current != nil {
cmd.Println("Current Jenkins is:", current.Name)
} else {
err = fmt.Errorf("cannot found the configuration: %s", rootOptions.Jenkins)
return
}
}
if strings.HasPrefix(version, "dev-") {
version = strings.ReplaceAll(version, "dev-", "")
}
ghClient := &client.GitHubReleaseClient{
Client: versionOption.GitHubClient,
}
var asset *client.ReleaseAsset
if versionOption.Changelog {
if asset, err = ghClient.GetJCLIAsset(version); err == nil && asset != nil {
cmd.Println()
cmd.Println(asset.Body)
}
} else if versionOption.ShowLatest {
if asset, err = ghClient.GetLatestJCLIAsset(); err == nil && asset != nil {
cmd.Println()
cmd.Println(asset.TagName)
cmd.Println(asset.Body)
}
}
return
},
Annotations: map[string]string{
since: "v0.0.26",
},
}
package cmd
import (
"bytes"
"github.com/jenkins-zh/jenkins-cli/app"
"github.com/jenkins-zh/jenkins-cli/client"
"io/ioutil"
"os"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("version command", func() {
var (
ctrl *gomock.Controller
buf *bytes.Buffer
err error
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
rootCmd.SetArgs([]string{})
rootOptions.Jenkins = ""
rootOptions.ConfigFile = "test.yaml"
buf = new(bytes.Buffer)
rootCmd.SetOutput(buf)
var data []byte
data, err = generateSampleConfig()
Expect(err).To(BeNil())
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
Expect(err).To(BeNil())
})
AfterEach(func() {
rootCmd.SetArgs([]string{})
os.Remove(rootOptions.ConfigFile)
rootOptions.ConfigFile = ""
ctrl.Finish()
})
Context("normal case", func() {
It("fake jenkins", func() {
rootCmd.SetArgs([]string{"version", "--jenkins", "fakeJenkins"})
_, err = rootCmd.ExecuteC()
Expect(err).To(HaveOccurred())
Expect(buf.String()).To(ContainSubstring("cannot found the configuration: fakeJenkins"))
})
It("should success", func() {
rootCmd.SetArgs([]string{"version", "--jenkins", "yourServer"})
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
Expect(buf.String()).To(ContainSubstring("Current Jenkins is:"))
Expect(buf.String()).To(ContainSubstring(`Version:
Commit:
`))
})
It("Output changelog", func() {
ghClient, teardown := client.PrepareForGetJCLIAsset("v0.0.1")
defer teardown()
app.SetVersion("dev-v0.0.1")
versionOption.GitHubClient = ghClient
rootCmd.SetArgs([]string{"version", "--changelog"})
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
Expect(buf.String()).To(ContainSubstring("body"))
})
It("Show the latest", func() {
ghClient, teardown := client.PrepareForGetLatestJCLIAsset()
defer teardown()
versionOption.GitHubClient = ghClient
rootCmd.SetArgs([]string{"version", "--changelog=false", "--show-latest"})
_, err = rootCmd.ExecuteC()
Expect(err).To(BeNil())
Expect(buf.String()).To(ContainSubstring(`tagName
body`))
})
})
})
......@@ -14,6 +14,11 @@ func GetVersion() string {
return version
}
// SetVersion is only for the test purpose
func SetVersion(ver string) {
version = ver
}
// GetCommit returns the commit id
func GetCommit() string {
return commit
......
package client
import (
"context"
"github.com/google/go-github/v29/github"
)
// GitHubReleaseClient is the client of jcli github
type GitHubReleaseClient struct {
Client *github.Client
}
// ReleaseAsset is the asset from GitHub release
type ReleaseAsset struct {
TagName string
Body string
}
// Init init the GitHub client
func (g *GitHubReleaseClient) Init() {
g.Client = github.NewClient(nil)
}
// GetLatestJCLIAsset returns the latest jcli asset
func (g *GitHubReleaseClient) GetLatestJCLIAsset() (*ReleaseAsset, error) {
return g.GetLatestReleaseAsset("jenkins-zh", "jenkins-cli")
}
// GetLatestReleaseAsset returns the latest release asset
func (g *GitHubReleaseClient) GetLatestReleaseAsset(owner, repo string) (ra *ReleaseAsset, err error) {
ctx := context.Background()
var release *github.RepositoryRelease
if release, _, err = g.Client.Repositories.GetLatestRelease(ctx, owner, repo); err == nil {
ra = &ReleaseAsset{
TagName: release.GetTagName(),
Body: release.GetBody(),
}
}
return
}
// GetJCLIAsset returns the asset from a tag name
func (g *GitHubReleaseClient) GetJCLIAsset(tagName string) (*ReleaseAsset, error) {
return g.GetReleaseAssetByTagName("jenkins-zh", "jenkins-cli", tagName)
}
// GetReleaseAssetByTagName returns the release asset by tag name
func (g *GitHubReleaseClient) GetReleaseAssetByTagName(owner, repo, tagName string) (ra *ReleaseAsset, err error) {
ctx := context.Background()
opt := &github.ListOptions{
PerPage: 99999,
}
var releaseList []*github.RepositoryRelease
if releaseList, _, err = g.Client.Repositories.ListReleases(ctx, owner, repo, opt); err == nil {
for _, item := range releaseList {
if item.GetTagName() == tagName {
ra = &ReleaseAsset{
TagName: item.GetTagName(),
Body: item.GetBody(),
}
break
}
}
}
return
}
package client_test
import (
jClient "github.com/jenkins-zh/jenkins-cli/client"
"github.com/stretchr/testify/assert"
"testing"
)
func TestInit(t *testing.T) {
ghClient := jClient.GitHubReleaseClient{}
assert.Nil(t, ghClient.Client)
ghClient.Init()
assert.NotNil(t, ghClient.Client)
}
func TestGetLatestReleaseAsset(t *testing.T) {
client, teardown := jClient.PrepareForGetLatestReleaseAsset() //setup()
defer teardown()
ghClient := jClient.GitHubReleaseClient{
Client: client,
}
asset, err := ghClient.GetLatestReleaseAsset("o", "r")
assert.Nil(t, err)
assert.NotNil(t, asset)
assert.Equal(t, "tagName", asset.TagName)
assert.Equal(t, "body", asset.Body)
}
func TestGetLatestJCLIAsset(t *testing.T) {
client, teardown := jClient.PrepareForGetLatestJCLIAsset() //setup()
defer teardown()
ghClient := jClient.GitHubReleaseClient{
Client: client,
}
asset, err := ghClient.GetLatestJCLIAsset()
assert.Nil(t, err)
assert.NotNil(t, asset)
assert.Equal(t, "tagName", asset.TagName)
assert.Equal(t, "body", asset.Body)
}
func TestGetJCLIAsset(t *testing.T) {
client, teardown := jClient.PrepareForGetJCLIAsset("tagName") //setup()
defer teardown()
ghClient := jClient.GitHubReleaseClient{
Client: client,
}
asset, err := ghClient.GetJCLIAsset("tagName")
assert.Nil(t, err)
assert.NotNil(t, asset)
assert.Equal(t, "tagName", asset.TagName)
assert.Equal(t, "body", asset.Body)
}
func TestGetReleaseAssetByTagName(t *testing.T) {
client, teardown := jClient.PrepareForGetReleaseAssetByTagName() //setup()
defer teardown()
ghClient := jClient.GitHubReleaseClient{
Client: client,
}
asset, err := ghClient.GetReleaseAssetByTagName("jenkins-zh", "jenkins-cli", "tagName")
assert.Nil(t, err)
assert.NotNil(t, asset)
assert.Equal(t, "tagName", asset.TagName)
assert.Equal(t, "body", asset.Body)
}
package client
import (
"fmt"
"github.com/google/go-github/v29/github"
"net/http"
"net/http/httptest"
"net/url"
)
// PrepareForGetJCLIAsset only for test
func PrepareForGetJCLIAsset(ver string) (client *github.Client, teardown func()) {
var mux *http.ServeMux
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/jenkins-zh/jenkins-cli/releases", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
fmt.Fprint(w, fmt.Sprintf(`[{"id":3, "body":"body", "tag_name":"%s"}]`, ver))
})
return
}
// PrepareForGetReleaseAssetByTagName only for test
func PrepareForGetReleaseAssetByTagName() (client *github.Client, teardown func()) {
var mux *http.ServeMux
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/jenkins-zh/jenkins-cli/releases", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
fmt.Fprint(w, `[{"id":3, "body":"body", "tag_name":"tagName"}]`)
})
return
}
// PrepareForGetLatestJCLIAsset only for test
func PrepareForGetLatestJCLIAsset() (client *github.Client, teardown func()) {
var mux *http.ServeMux
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/jenkins-zh/jenkins-cli/releases/latest", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":3, "body":"body", "tag_name":"tagName"}`)
})
return
}
// PrepareForGetLatestReleaseAsset only for test
func PrepareForGetLatestReleaseAsset() (client *github.Client, teardown func()) {
var mux *http.ServeMux
client, mux, _, teardown = setup()
mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) {
//testMethod(t, r, "GET")
fmt.Fprint(w, `{"id":3, "body":"body", "tag_name":"tagName"}`)
})
return
}
const (
// baseURLPath is a non-empty Client.BaseURL path to use during tests,
// to ensure relative URLs are used for all endpoints. See issue #752.
baseURLPath = "/api-v3"
)
// setup sets up a test HTTP server along with a github.Client that is
// configured to talk to that test server. Tests should register handlers on
// mux which provide mock responses for the API method being tested.
// this was copied from https://github.com/google/go-github
func setup() (client *github.Client, mux *http.ServeMux, serverURL string, teardown func()) {
// mux is the HTTP request multiplexer used with the test server.
mux = http.NewServeMux()
// We want to ensure that tests catch mistakes where the endpoint URL is
// specified as absolute rather than relative. It only makes a difference
// when there's a non-empty base URL path. So, use that. See issue #752.
apiHandler := http.NewServeMux()
apiHandler.Handle(baseURLPath+"/", http.StripPrefix(baseURLPath, mux))
// uncomment here once it gets useful
//apiHandler.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// fmt.Fprintln(os.Stderr, "FAIL: Client.BaseURL path prefix is not preserved in the request URL:")
// fmt.Fprintln(os.Stderr)
// fmt.Fprintln(os.Stderr, "\t"+req.URL.String())
// fmt.Fprintln(os.Stderr)
// fmt.Fprintln(os.Stderr, "\tDid you accidentally use an absolute endpoint URL rather than relative?")
// fmt.Fprintln(os.Stderr, "\tSee https://github.com/google/go-github/issues/752 for information.")
// http.Error(w, "Client.BaseURL path prefix is not preserved in the request URL.", http.StatusInternalServerError)
//})
// server is a test HTTP server used to provide mock API responses.
server := httptest.NewServer(apiHandler)
// client is the GitHub client being tested and is
// configured to use test server.
client = github.NewClient(nil)
url, _ := url.Parse(server.URL + baseURLPath + "/")
client.BaseURL = url
client.UploadURL = url
return client, mux, server.URL, server.Close
}
// this was copied from https://github.com/google/go-github
//func testMethod(t *testing.T, r *http.Request, want string) {
// t.Helper()
// if got := r.Method; got != want {
// t.Errorf("Request method: %v, want %v", got, want)
// }
//}
......@@ -36,6 +36,13 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-github/v29 v29.0.3 h1:IktKCTwU//aFHnpA+2SLIi7Oo9uhAzgsdZNbcAqhgdc=
github.com/google/go-github/v29 v29.0.3/go.mod h1:CHKiKKPHJ0REzfwc14QMklvtHwCveD0PxlMjLlzAM5E=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/gosuri/uilive v0.0.3 h1:kvo6aB3pez9Wbudij8srWo4iY6SFTTxTKOkb+uRCE8I=
github.com/gosuri/uilive v0.0.3/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8=
......@@ -134,6 +141,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2eP
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
......@@ -157,6 +165,7 @@ golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 h1:hKsoRgsbwY1NafxrwTs+k64
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册