format with gofumpt (#18184)

* gofumpt -w -l .

* gofumpt -w -l -extra .

* Add linter

* manual fix

* change make fmt
This commit is contained in:
6543
2022-01-20 18:46:10 +01:00
committed by GitHub
parent 1d98d205f5
commit 54e9ee37a7
423 changed files with 1585 additions and 1758 deletions

View File

@ -17,6 +17,7 @@ linters:
- bidichk
- ineffassign
- revive
- gofumpt
enable-all: false
disable-all: true
fast: false
@ -57,6 +58,9 @@ linters-settings:
- name: errorf
- name: duplicated-imports
- name: modifies-value-receiver
gofumpt:
extra-rules: true
lang-version: 1.16
issues:
exclude-rules:

View File

@ -231,8 +231,10 @@ clean:
.PHONY: fmt
fmt:
@echo "Running gitea-fmt(with gofmt)..."
@$(GO) run build/code-batch-process.go gitea-fmt -s -w '{file-list}'
@hash xgogofumpt > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
$(GO) install mvdan.cc/gofumpt@latest; \
fi
gofumpt -w -l -extra -lang 1.16 .
.PHONY: vet
vet:

View File

@ -136,7 +136,7 @@ func (fc *fileCollector) collectFiles() (res [][]string, err error) {
}
// substArgFiles expands the {file-list} to a real file list for commands
func substArgFiles(args []string, files []string) []string {
func substArgFiles(args, files []string) []string {
for i, s := range args {
if s == "{file-list}" {
newArgs := append(args[:i], files...)

View File

@ -20,8 +20,10 @@ var importPackageGroupOrders = map[string]int{
var errInvalidCommentBetweenImports = errors.New("comments between imported packages are invalid, please move comments to the end of the package line")
var importBlockBegin = []byte("\nimport (\n")
var importBlockEnd = []byte("\n)")
var (
importBlockBegin = []byte("\nimport (\n")
importBlockEnd = []byte("\n)")
)
type importLineParsed struct {
group string
@ -59,8 +61,10 @@ func parseImportLine(line string) (*importLineParsed, error) {
return il, nil
}
type importLineGroup []*importLineParsed
type importLineGroupMap map[string]importLineGroup
type (
importLineGroup []*importLineParsed
importLineGroupMap map[string]importLineGroup
)
func formatGoImports(contentBytes []byte) ([]byte, error) {
p1 := bytes.Index(contentBytes, importBlockBegin)
@ -153,7 +157,7 @@ func formatGoImports(contentBytes []byte) ([]byte, error) {
return formattedBytes, nil
}
//FormatGoImports format the imports by our rules (see unit tests)
// FormatGoImports format the imports by our rules (see unit tests)
func FormatGoImports(file string) error {
f, err := os.Open(file)
if err != nil {
@ -177,7 +181,7 @@ func FormatGoImports(file string) error {
if bytes.Equal(contentBytes, formattedBytes) {
return nil
}
f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0644)
f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0o644)
if err != nil {
return err
}

View File

@ -20,7 +20,7 @@ import (
"github.com/shurcooL/vfsgen"
)
func needsUpdate(dir string, filename string) (bool, []byte) {
func needsUpdate(dir, filename string) (bool, []byte) {
needRegen := false
_, err := os.Stat(filename)
if err != nil {
@ -50,7 +50,6 @@ func needsUpdate(dir string, filename string) (bool, []byte) {
newHash := hasher.Sum([]byte{})
if bytes.Compare(oldHash, newHash) != 0 {
return true, newHash
}
@ -87,5 +86,5 @@ func main() {
if err != nil {
log.Fatalf("%v\n", err)
}
_ = os.WriteFile(filename+".hash", newHash, 0666)
_ = os.WriteFile(filename+".hash", newHash, 0o666)
}

View File

@ -30,9 +30,7 @@ const (
maxUnicodeVersion = 12
)
var (
flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
)
var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
// Gemoji is a set of emoji data.
type Gemoji []Emoji
@ -68,7 +66,7 @@ func main() {
}
// write
err = os.WriteFile(*flagOut, buf, 0644)
err = os.WriteFile(*flagOut, buf, 0o644)
if err != nil {
log.Fatal(err)
}
@ -109,7 +107,7 @@ func generate() ([]byte, error) {
return nil, err
}
var skinTones = make(map[string]string)
skinTones := make(map[string]string)
skinTones["\U0001f3fb"] = "Light Skin Tone"
skinTones["\U0001f3fc"] = "Medium-Light Skin Tone"
@ -119,7 +117,7 @@ func generate() ([]byte, error) {
var tmp Gemoji
//filter out emoji that require greater than max unicode version
// filter out emoji that require greater than max unicode version
for i := range data {
val, _ := strconv.ParseFloat(data[i].UnicodeVersion, 64)
if int(val) <= maxUnicodeVersion {
@ -158,7 +156,7 @@ func generate() ([]byte, error) {
// write a JSON file to use with tribute (write before adding skin tones since we can't support them there yet)
file, _ := json.Marshal(data)
_ = os.WriteFile("assets/emoji.json", file, 0644)
_ = os.WriteFile("assets/emoji.json", file, 0o644)
// Add skin tones to emoji that support it
var (

View File

@ -34,7 +34,6 @@ func main() {
flag.Parse()
file, err := os.CreateTemp(os.TempDir(), prefix)
if err != nil {
log.Fatalf("Failed to create temp file. %s", err)
}
@ -65,7 +64,6 @@ func main() {
}
gz, err := gzip.NewReader(file)
if err != nil {
log.Fatalf("Failed to gunzip the archive. %s", err)
}
@ -96,7 +94,6 @@ func main() {
}
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")))
if err != nil {
log.Fatalf("Failed to create new file. %s", err)
}
@ -119,7 +116,7 @@ func main() {
}
// Write data to dst
dst = path.Join(destination, dst)
err = os.WriteFile(dst, data, 0644)
err = os.WriteFile(dst, data, 0o644)
if err != nil {
log.Fatalf("Failed to write new file. %s", err)
}

View File

@ -34,7 +34,6 @@ func main() {
flag.Parse()
file, err := os.CreateTemp(os.TempDir(), prefix)
if err != nil {
log.Fatalf("Failed to create temp file. %s", err)
}
@ -66,7 +65,6 @@ func main() {
}
gz, err := gzip.NewReader(file)
if err != nil {
log.Fatalf("Failed to gunzip the archive. %s", err)
}
@ -100,7 +98,6 @@ func main() {
continue
}
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".txt")))
if err != nil {
log.Fatalf("Failed to create new file. %s", err)
}

View File

@ -22,7 +22,7 @@ import (
"golang.org/x/tools/cover"
)
func mergeProfiles(p *cover.Profile, merge *cover.Profile) {
func mergeProfiles(p, merge *cover.Profile) {
if p.Mode != merge.Mode {
log.Fatalf("cannot merge profiles with different modes")
}

View File

@ -525,7 +525,7 @@ func runCreateUser(c *cli.Context) error {
}
// always default to true
var changePassword = true
changePassword := true
// If this is the first user being created.
// Take it as the admin and don't force a password update.
@ -577,7 +577,6 @@ func runListUsers(c *cli.Context) error {
}
users, err := user_model.GetAllUsers()
if err != nil {
return err
}
@ -601,7 +600,6 @@ func runListUsers(c *cli.Context) error {
w.Flush()
return nil
}
func runDeleteUser(c *cli.Context) error {
@ -826,7 +824,6 @@ func runUpdateOauth(c *cli.Context) error {
if c.IsSet("required-claim-name") {
oAuth2Config.RequiredClaimName = c.String("required-claim-name")
}
if c.IsSet("required-claim-value") {
oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
@ -843,7 +840,7 @@ func runUpdateOauth(c *cli.Context) error {
}
// update custom URL mapping
var customURLMapping = &oauth2.CustomURLMapping{}
customURLMapping := &oauth2.CustomURLMapping{}
if oAuth2Config.CustomURLMapping != nil {
customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
@ -926,7 +923,7 @@ func runAddSMTP(c *cli.Context) error {
if !c.IsSet("port") {
return errors.New("port must be set")
}
var active = true
active := true
if c.IsSet("active") {
active = c.BoolT("active")
}
@ -994,7 +991,6 @@ func runListAuth(c *cli.Context) error {
}
authSources, err := auth.Sources()
if err != nil {
return err
}

View File

@ -17,12 +17,12 @@ import (
func TestAddLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
source *auth.Source
errMsg string
@ -243,12 +243,12 @@ func TestAddLdapBindDn(t *testing.T) {
func TestAddLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
authSource *auth.Source
errMsg string
@ -474,12 +474,12 @@ func TestAddLdapSimpleAuth(t *testing.T) {
func TestUpdateLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
id int64
existingAuthSource *auth.Source
@ -907,12 +907,12 @@ func TestUpdateLdapBindDn(t *testing.T) {
func TestUpdateLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
id int64
existingAuthSource *auth.Source
@ -1161,7 +1161,6 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
authSource: &auth.Source{
Type: auth.DLDAP,
Cfg: &ldap.Source{
AttributeMail: "mail",
},
},

View File

@ -180,7 +180,7 @@ func runCert(c *cli.Context) error {
}
log.Println("Written cert.pem")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
log.Fatalf("Failed to open key.pem for writing: %v", err)
}

View File

@ -121,7 +121,6 @@ func runRecreateTable(ctx *cli.Context) error {
}
return recreateTables(x)
})
}
func runDoctor(ctx *cli.Context) error {

View File

@ -370,7 +370,7 @@ func runDump(ctx *cli.Context) error {
fatal("Failed to save %s: %v", fileName, err)
}
if err := os.Chmod(fileName, 0600); err != nil {
if err := os.Chmod(fileName, 0o600); err != nil {
log.Info("Can't change file access permissions mask to 0600: %v", err)
}
}

View File

@ -107,7 +107,7 @@ func runDumpRepository(ctx *cli.Context) error {
}
serviceType = convert.ToGitServiceType(serviceStr)
var opts = base.MigrateOptions{
opts := base.MigrateOptions{
GitServiceType: serviceType,
CloneAddr: cloneAddr,
AuthUsername: ctx.String("auth_username"),

View File

@ -109,7 +109,6 @@ type asset struct {
}
func initEmbeddedExtractor(c *cli.Context) error {
// Silence the console logger
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)
@ -260,7 +259,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error {
return fmt.Errorf("%s: %v", dir, err)
}
perms := os.ModePerm & 0666
perms := os.ModePerm & 0o666
fi, err := os.Lstat(dest)
if err != nil {
@ -296,7 +295,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error {
}
func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
var results = make([]asset, 0, 64)
results := make([]asset, 0, 64)
for _, name := range sec.Names() {
if isdir, err := sec.IsDir(name); !isdir && err == nil {
if sec.Path == "public" &&
@ -307,9 +306,11 @@ func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
matchName := sec.Path + "/" + name
for _, g := range globs {
if g.Match(matchName) {
results = append(results, asset{Section: sec,
Name: name,
Path: sec.Path + "/" + name})
results = append(results, asset{
Section: sec,
Name: name,
Path: sec.Path + "/" + name,
})
break
}
}

View File

@ -58,7 +58,8 @@ var (
Name: "timeout",
Value: 60 * time.Second,
Usage: "Timeout for the flushing process",
}, cli.BoolFlag{
},
cli.BoolFlag{
Name: "non-blocking",
Usage: "Set to true to not wait for flush to complete before returning",
},

View File

@ -247,7 +247,7 @@ func runServ(c *cli.Context) error {
os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID))
os.Setenv(models.EnvAppURL, setting.AppURL)
//LFS token authentication
// LFS token authentication
if verb == lfsAuthenticateVerb {
url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))

View File

@ -71,8 +71,7 @@ func runHTTPRedirector() {
http.Redirect(w, r, target, http.StatusTemporaryRedirect)
})
var err = runHTTP("tcp", source, "HTTP Redirector", handler)
err := runHTTP("tcp", source, "HTTP Redirector", handler)
if err != nil {
log.Fatal("Failed to start port redirection: %v", err)
}

View File

@ -17,7 +17,6 @@ import (
)
func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error {
// If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443.
// Due to docker port mapping this can't be checked programmatically
// TODO: these are placeholders until we add options for each in settings with appropriate warning
@ -77,7 +76,7 @@ func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler)
go func() {
log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect)
// all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here)
var err = runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler)))
err := runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler)))
if err != nil {
log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
}

View File

@ -66,7 +66,7 @@ func generate(name string) error {
return err
}
path := filepath.Join(fixturesDir, name+".yml")
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
return fmt.Errorf("%s: %+v", path, err)
}
fmt.Printf("%s created.\n", path)

View File

@ -93,13 +93,13 @@ func runPR() {
routers.InitGitServices()
setting.Database.LogSQL = true
//x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
// x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
db.InitEngineWithMigration(context.Background(), func(_ *xorm.Engine) error {
return nil
})
db.HasEngine = true
//x.ShowSQL(true)
// x.ShowSQL(true)
err = unittest.InitFixtures(
unittest.FixturesOptions{
Dir: path.Join(curDir, "models/fixtures/"),
@ -115,7 +115,7 @@ func runPR() {
util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
log.Printf("[PR] Setting up router\n")
//routers.GlobalInit()
// routers.GlobalInit()
external.RegisterRenderers()
markup.Init()
c := routers.NormalRoutes()
@ -137,7 +137,7 @@ func runPR() {
}
*/
//Start the server
// Start the server
http.ListenAndServe(":8080", c)
log.Printf("[PR] Cleaning up ...\n")
@ -160,7 +160,7 @@ func runPR() {
}
func main() {
var runPRFlag = flag.Bool("run", false, "Run the PR code")
runPRFlag := flag.Bool("run", false, "Run the PR code")
flag.Parse()
if *runPRFlag {
runPR()
@ -173,15 +173,15 @@ func main() {
force = false
}
//Otherwise checkout PR
// Otherwise checkout PR
if len(os.Args) != 2 {
log.Fatal("Need only one arg: the PR number")
}
pr := os.Args[1]
codeFilePath = filepath.FromSlash(codeFilePath) //Convert to running OS
codeFilePath = filepath.FromSlash(codeFilePath) // Convert to running OS
//Copy this file if it will not exist in the PR branch
// Copy this file if it will not exist in the PR branch
dat, err := os.ReadFile(codeFilePath)
if err != nil {
log.Fatalf("Failed to cache this code file : %v", err)
@ -192,16 +192,16 @@ func main() {
log.Fatalf("Failed to open the repo : %v", err)
}
//Find remote upstream
// Find remote upstream
remotes, err := repo.Remotes()
if err != nil {
log.Fatalf("Failed to list remotes of repo : %v", err)
}
remoteUpstream := "origin" //Default
remoteUpstream := "origin" // Default
for _, r := range remotes {
if r.Config().URLs[0] == "https://github.com/go-gitea/gitea.git" ||
r.Config().URLs[0] == "https://github.com/go-gitea/gitea" ||
r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { //fetch at index 0
r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { // fetch at index 0
remoteUpstream = r.Config().Name
break
}
@ -212,7 +212,7 @@ func main() {
log.Printf("Fetching PR #%s in %s\n", pr, branch)
if runtime.GOOS == "windows" {
//Use git cli command for windows
// Use git cli command for windows
runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch))
} else {
ref := fmt.Sprintf("%s%s/head:%s", gitea_git.PullPrefix, pr, branchRef)
@ -240,22 +240,23 @@ func main() {
log.Fatalf("Failed to checkout %s : %v", branch, err)
}
//Copy this file if not exist
// Copy this file if not exist
if _, err := os.Stat(codeFilePath); os.IsNotExist(err) {
err = os.MkdirAll(filepath.Dir(codeFilePath), 0755)
err = os.MkdirAll(filepath.Dir(codeFilePath), 0o755)
if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
}
err = os.WriteFile(codeFilePath, dat, 0644)
err = os.WriteFile(codeFilePath, dat, 0o644)
if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
}
}
//Force build of js, css, bin, ...
// Force build of js, css, bin, ...
runCmd("make", "build")
//Start with integration test
// Start with integration test
runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
}
func runCmd(cmd ...string) {
log.Printf("Executing : %s ...\n", cmd)
c := exec.Command(cmd[0], cmd[1:]...)

View File

@ -22,7 +22,7 @@ func TestAPIAdminOrgCreate(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Description: "This organization created by admin for user2",
@ -56,7 +56,7 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Description: "This organization created by admin for user2",
@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {
nonAdminUsername := "user2"
session := loginUser(t, nonAdminUsername)
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Description: "This organization created by admin for user2",

View File

@ -106,7 +106,6 @@ func TestAPICreateBranch(t *testing.T) {
}
func testAPICreateBranches(t *testing.T, giteaURL *url.URL) {
username := "user2"
ctx := NewAPITestContext(t, username, "my-noo-repo")
giteaURL.Path = ctx.GitPath()

View File

@ -44,10 +44,10 @@ func TestAPIListRepoComments(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID})
}
//test before and since filters
// test before and since filters
query := url.Values{}
before := "2000-01-01T00:00:11+00:00" //unix: 946684811
since := "2000-01-01T00:00:12+00:00" //unix: 946684812
before := "2000-01-01T00:00:11+00:00" // unix: 946684811
since := "2000-01-01T00:00:12+00:00" // unix: 946684812
query.Add("before", before)
link.RawQuery = query.Encode()
req = NewRequest(t, "GET", link.String())

View File

@ -28,15 +28,18 @@ func TestGPGKeys(t *testing.T) {
token string
results []int
}{
{name: "NoLogin", makeRequest: MakeRequest, token: "",
{
name: "NoLogin", makeRequest: MakeRequest, token: "",
results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized},
},
{name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token,
results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}},
{
name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token,
results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated},
},
}
for _, tc := range tt {
//Basic test on result code
// Basic test on result code
t.Run(tc.name, func(t *testing.T) {
t.Run("ViewOwnGPGKeys", func(t *testing.T) {
testViewOwnGPGKeys(t, tc.makeRequest, tc.token, tc.results[0])
@ -66,28 +69,27 @@ func TestGPGKeys(t *testing.T) {
})
}
//Check state after basic add
// Check state after basic add
t.Run("CheckState", func(t *testing.T) {
var keys []*api.GPGKey
req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) //GET all keys
req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) // GET all keys
resp := session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &keys)
assert.Len(t, keys, 1)
primaryKey1 := keys[0] //Primary key 1
primaryKey1 := keys[0] // Primary key 1
assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID)
assert.Len(t, primaryKey1.Emails, 1)
assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email)
assert.True(t, primaryKey1.Emails[0].Verified)
subKey := primaryKey1.SubsKey[0] //Subkey of 38EA3BCED732982C
subKey := primaryKey1.SubsKey[0] // Subkey of 38EA3BCED732982C
assert.EqualValues(t, "70D7C694D17D03AD", subKey.KeyID)
assert.Empty(t, subKey.Emails)
var key api.GPGKey
req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) //Primary key 1
req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) // Primary key 1
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &key)
assert.EqualValues(t, "38EA3BCED732982C", key.KeyID)
@ -95,14 +97,14 @@ func TestGPGKeys(t *testing.T) {
assert.EqualValues(t, "user2@example.com", key.Emails[0].Email)
assert.True(t, key.Emails[0].Verified)
req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) //Subkey of 38EA3BCED732982C
req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) // Subkey of 38EA3BCED732982C
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &key)
assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID)
assert.Empty(t, key.Emails)
})
//Check state after basic add
// Check state after basic add
t.Run("CheckCommits", func(t *testing.T) {
t.Run("NotSigned", func(t *testing.T) {
var branch api.Branch
@ -182,7 +184,7 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz
}
func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) {
//User2 <user2@example.com> //primary & activated
// User2 <user2@example.com> //primary & activated
testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW
@ -216,7 +218,7 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h
}
func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) {
//User2 <user2-2@example.com> //secondary and not activated
// User2 <user2-2@example.com> //secondary and not activated
testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
mQGNBGC2K2cBDAC1+Xgk+8UfhASVgRngQi4rnQ8k0t+bWsBz4Czd26+cxVDRwlTT

View File

@ -53,21 +53,21 @@ func TestAPIModifyLabels(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
//ListLabels
// ListLabels
req = NewRequest(t, "GET", urlStr)
resp = session.MakeRequest(t, req, http.StatusOK)
var apiLabels []*api.Label
DecodeJSON(t, resp, &apiLabels)
assert.Len(t, apiLabels, 2)
//GetLabel
// GetLabel
singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d?token=%s", owner.Name, repo.Name, dbLabel.ID, token)
req = NewRequest(t, "GET", singleURLStr)
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &apiLabel)
assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color)
//EditLabel
// EditLabel
newName := "LabelNewName"
newColor := "09876a"
newColorWrong := "09g76a"
@ -83,10 +83,9 @@ func TestAPIModifyLabels(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
//DeleteLabel
// DeleteLabel
req = NewRequest(t, "DELETE", singleURLStr)
session.MakeRequest(t, req, http.StatusNoContent)
}
func TestAPIAddIssueLabels(t *testing.T) {
@ -173,21 +172,21 @@ func TestAPIModifyOrgLabels(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
//ListLabels
// ListLabels
req = NewRequest(t, "GET", urlStr)
resp = session.MakeRequest(t, req, http.StatusOK)
var apiLabels []*api.Label
DecodeJSON(t, resp, &apiLabels)
assert.Len(t, apiLabels, 4)
//GetLabel
// GetLabel
singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token)
req = NewRequest(t, "GET", singleURLStr)
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &apiLabel)
assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color)
//EditLabel
// EditLabel
newName := "LabelNewName"
newColor := "09876a"
newColorWrong := "09g76a"
@ -203,8 +202,7 @@ func TestAPIModifyOrgLabels(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
//DeleteLabel
// DeleteLabel
req = NewRequest(t, "DELETE", singleURLStr)
session.MakeRequest(t, req, http.StatusNoContent)
}

View File

@ -33,19 +33,19 @@ func TestAPIIssuesReactions(t *testing.T) {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s",
owner.Name, issue.Repo.Name, issue.Index, token)
//Try to add not allowed reaction
// Try to add not allowed reaction
req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
Reaction: "wrong",
})
session.MakeRequest(t, req, http.StatusForbidden)
//Delete not allowed reaction
// Delete not allowed reaction
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
Reaction: "zzz",
})
session.MakeRequest(t, req, http.StatusOK)
//Add allowed reaction
// Add allowed reaction
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
Reaction: "rocket",
})
@ -53,10 +53,10 @@ func TestAPIIssuesReactions(t *testing.T) {
var apiNewReaction api.Reaction
DecodeJSON(t, resp, &apiNewReaction)
//Add existing reaction
// Add existing reaction
session.MakeRequest(t, req, http.StatusForbidden)
//Get end result of reaction list of issue #1
// Get end result of reaction list of issue #1
req = NewRequestf(t, "GET", urlStr)
resp = session.MakeRequest(t, req, http.StatusOK)
var apiReactions []*api.Reaction
@ -93,19 +93,19 @@ func TestAPICommentReactions(t *testing.T) {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s",
owner.Name, issue.Repo.Name, comment.ID, token)
//Try to add not allowed reaction
// Try to add not allowed reaction
req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
Reaction: "wrong",
})
session.MakeRequest(t, req, http.StatusForbidden)
//Delete none existing reaction
// Delete none existing reaction
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
Reaction: "eyes",
})
session.MakeRequest(t, req, http.StatusOK)
//Add allowed reaction
// Add allowed reaction
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
Reaction: "+1",
})
@ -113,10 +113,10 @@ func TestAPICommentReactions(t *testing.T) {
var apiNewReaction api.Reaction
DecodeJSON(t, resp, &apiNewReaction)
//Add existing reaction
// Add existing reaction
session.MakeRequest(t, req, http.StatusForbidden)
//Get end result of reaction list of issue #1
// Get end result of reaction list of issue #1
req = NewRequestf(t, "GET", urlStr)
resp = session.MakeRequest(t, req, http.StatusOK)
var apiReactions []*api.Reaction

View File

@ -33,7 +33,6 @@ func TestAPIIssueSubscriptions(t *testing.T) {
token := getTokenForLoggedInUser(t, session)
testSubscription := func(issue *models.Issue, isWatching bool) {
issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token)

View File

@ -210,7 +210,7 @@ func TestAPISearchIssues(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &apiIssues)
assert.EqualValues(t, "15", resp.Header().Get("X-Total-Count"))
assert.Len(t, apiIssues, 10) //there are more but 10 is page item limit
assert.Len(t, apiIssues, 10) // there are more but 10 is page item limit
query.Add("limit", "20")
link.RawQuery = query.Encode()

Some files were not shown because too many files have changed in this diff Show More