mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2024-11-30 21:26:17 +01:00
format with gofumpt (#18184)
* gofumpt -w -l . * gofumpt -w -l -extra . * Add linter * manual fix * change make fmt
This commit is contained in:
parent
1d98d205f5
commit
54e9ee37a7
423 changed files with 1585 additions and 1758 deletions
|
@ -17,6 +17,7 @@ linters:
|
||||||
- bidichk
|
- bidichk
|
||||||
- ineffassign
|
- ineffassign
|
||||||
- revive
|
- revive
|
||||||
|
- gofumpt
|
||||||
enable-all: false
|
enable-all: false
|
||||||
disable-all: true
|
disable-all: true
|
||||||
fast: false
|
fast: false
|
||||||
|
@ -57,6 +58,9 @@ linters-settings:
|
||||||
- name: errorf
|
- name: errorf
|
||||||
- name: duplicated-imports
|
- name: duplicated-imports
|
||||||
- name: modifies-value-receiver
|
- name: modifies-value-receiver
|
||||||
|
gofumpt:
|
||||||
|
extra-rules: true
|
||||||
|
lang-version: 1.16
|
||||||
|
|
||||||
issues:
|
issues:
|
||||||
exclude-rules:
|
exclude-rules:
|
||||||
|
|
6
Makefile
6
Makefile
|
@ -231,8 +231,10 @@ clean:
|
||||||
|
|
||||||
.PHONY: fmt
|
.PHONY: fmt
|
||||||
fmt:
|
fmt:
|
||||||
@echo "Running gitea-fmt(with gofmt)..."
|
@hash xgogofumpt > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
|
||||||
@$(GO) run build/code-batch-process.go gitea-fmt -s -w '{file-list}'
|
$(GO) install mvdan.cc/gofumpt@latest; \
|
||||||
|
fi
|
||||||
|
gofumpt -w -l -extra -lang 1.16 .
|
||||||
|
|
||||||
.PHONY: vet
|
.PHONY: vet
|
||||||
vet:
|
vet:
|
||||||
|
|
|
@ -136,7 +136,7 @@ func (fc *fileCollector) collectFiles() (res [][]string, err error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// substArgFiles expands the {file-list} to a real file list for commands
|
// 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 {
|
for i, s := range args {
|
||||||
if s == "{file-list}" {
|
if s == "{file-list}" {
|
||||||
newArgs := append(args[:i], files...)
|
newArgs := append(args[:i], files...)
|
||||||
|
|
|
@ -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 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 (
|
||||||
var importBlockEnd = []byte("\n)")
|
importBlockBegin = []byte("\nimport (\n")
|
||||||
|
importBlockEnd = []byte("\n)")
|
||||||
|
)
|
||||||
|
|
||||||
type importLineParsed struct {
|
type importLineParsed struct {
|
||||||
group string
|
group string
|
||||||
|
@ -59,8 +61,10 @@ func parseImportLine(line string) (*importLineParsed, error) {
|
||||||
return il, nil
|
return il, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type importLineGroup []*importLineParsed
|
type (
|
||||||
type importLineGroupMap map[string]importLineGroup
|
importLineGroup []*importLineParsed
|
||||||
|
importLineGroupMap map[string]importLineGroup
|
||||||
|
)
|
||||||
|
|
||||||
func formatGoImports(contentBytes []byte) ([]byte, error) {
|
func formatGoImports(contentBytes []byte) ([]byte, error) {
|
||||||
p1 := bytes.Index(contentBytes, importBlockBegin)
|
p1 := bytes.Index(contentBytes, importBlockBegin)
|
||||||
|
@ -153,7 +157,7 @@ func formatGoImports(contentBytes []byte) ([]byte, error) {
|
||||||
return formattedBytes, nil
|
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 {
|
func FormatGoImports(file string) error {
|
||||||
f, err := os.Open(file)
|
f, err := os.Open(file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -177,7 +181,7 @@ func FormatGoImports(file string) error {
|
||||||
if bytes.Equal(contentBytes, formattedBytes) {
|
if bytes.Equal(contentBytes, formattedBytes) {
|
||||||
return nil
|
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 {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,7 +20,7 @@ import (
|
||||||
"github.com/shurcooL/vfsgen"
|
"github.com/shurcooL/vfsgen"
|
||||||
)
|
)
|
||||||
|
|
||||||
func needsUpdate(dir string, filename string) (bool, []byte) {
|
func needsUpdate(dir, filename string) (bool, []byte) {
|
||||||
needRegen := false
|
needRegen := false
|
||||||
_, err := os.Stat(filename)
|
_, err := os.Stat(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -50,7 +50,6 @@ func needsUpdate(dir string, filename string) (bool, []byte) {
|
||||||
newHash := hasher.Sum([]byte{})
|
newHash := hasher.Sum([]byte{})
|
||||||
|
|
||||||
if bytes.Compare(oldHash, newHash) != 0 {
|
if bytes.Compare(oldHash, newHash) != 0 {
|
||||||
|
|
||||||
return true, newHash
|
return true, newHash
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -87,5 +86,5 @@ func main() {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("%v\n", err)
|
log.Fatalf("%v\n", err)
|
||||||
}
|
}
|
||||||
_ = os.WriteFile(filename+".hash", newHash, 0666)
|
_ = os.WriteFile(filename+".hash", newHash, 0o666)
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,9 +30,7 @@ const (
|
||||||
maxUnicodeVersion = 12
|
maxUnicodeVersion = 12
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
|
||||||
flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Gemoji is a set of emoji data.
|
// Gemoji is a set of emoji data.
|
||||||
type Gemoji []Emoji
|
type Gemoji []Emoji
|
||||||
|
@ -68,7 +66,7 @@ func main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// write
|
// write
|
||||||
err = os.WriteFile(*flagOut, buf, 0644)
|
err = os.WriteFile(*flagOut, buf, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
@ -109,7 +107,7 @@ func generate() ([]byte, error) {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var skinTones = make(map[string]string)
|
skinTones := make(map[string]string)
|
||||||
|
|
||||||
skinTones["\U0001f3fb"] = "Light Skin Tone"
|
skinTones["\U0001f3fb"] = "Light Skin Tone"
|
||||||
skinTones["\U0001f3fc"] = "Medium-Light Skin Tone"
|
skinTones["\U0001f3fc"] = "Medium-Light Skin Tone"
|
||||||
|
@ -119,7 +117,7 @@ func generate() ([]byte, error) {
|
||||||
|
|
||||||
var tmp Gemoji
|
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 {
|
for i := range data {
|
||||||
val, _ := strconv.ParseFloat(data[i].UnicodeVersion, 64)
|
val, _ := strconv.ParseFloat(data[i].UnicodeVersion, 64)
|
||||||
if int(val) <= maxUnicodeVersion {
|
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)
|
// 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)
|
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
|
// Add skin tones to emoji that support it
|
||||||
var (
|
var (
|
||||||
|
|
|
@ -34,7 +34,6 @@ func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
file, err := os.CreateTemp(os.TempDir(), prefix)
|
file, err := os.CreateTemp(os.TempDir(), prefix)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to create temp file. %s", err)
|
log.Fatalf("Failed to create temp file. %s", err)
|
||||||
}
|
}
|
||||||
|
@ -65,7 +64,6 @@ func main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
gz, err := gzip.NewReader(file)
|
gz, err := gzip.NewReader(file)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to gunzip the archive. %s", err)
|
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")))
|
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to create new file. %s", err)
|
log.Fatalf("Failed to create new file. %s", err)
|
||||||
}
|
}
|
||||||
|
@ -119,7 +116,7 @@ func main() {
|
||||||
}
|
}
|
||||||
// Write data to dst
|
// Write data to dst
|
||||||
dst = path.Join(destination, dst)
|
dst = path.Join(destination, dst)
|
||||||
err = os.WriteFile(dst, data, 0644)
|
err = os.WriteFile(dst, data, 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to write new file. %s", err)
|
log.Fatalf("Failed to write new file. %s", err)
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,7 +34,6 @@ func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
file, err := os.CreateTemp(os.TempDir(), prefix)
|
file, err := os.CreateTemp(os.TempDir(), prefix)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to create temp file. %s", err)
|
log.Fatalf("Failed to create temp file. %s", err)
|
||||||
}
|
}
|
||||||
|
@ -66,7 +65,6 @@ func main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
gz, err := gzip.NewReader(file)
|
gz, err := gzip.NewReader(file)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to gunzip the archive. %s", err)
|
log.Fatalf("Failed to gunzip the archive. %s", err)
|
||||||
}
|
}
|
||||||
|
@ -100,7 +98,6 @@ func main() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".txt")))
|
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".txt")))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to create new file. %s", err)
|
log.Fatalf("Failed to create new file. %s", err)
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,7 +22,7 @@ import (
|
||||||
"golang.org/x/tools/cover"
|
"golang.org/x/tools/cover"
|
||||||
)
|
)
|
||||||
|
|
||||||
func mergeProfiles(p *cover.Profile, merge *cover.Profile) {
|
func mergeProfiles(p, merge *cover.Profile) {
|
||||||
if p.Mode != merge.Mode {
|
if p.Mode != merge.Mode {
|
||||||
log.Fatalf("cannot merge profiles with different modes")
|
log.Fatalf("cannot merge profiles with different modes")
|
||||||
}
|
}
|
||||||
|
|
10
cmd/admin.go
10
cmd/admin.go
|
@ -525,7 +525,7 @@ func runCreateUser(c *cli.Context) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// always default to true
|
// always default to true
|
||||||
var changePassword = true
|
changePassword := true
|
||||||
|
|
||||||
// If this is the first user being created.
|
// If this is the first user being created.
|
||||||
// Take it as the admin and don't force a password update.
|
// 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()
|
users, err := user_model.GetAllUsers()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -601,7 +600,6 @@ func runListUsers(c *cli.Context) error {
|
||||||
|
|
||||||
w.Flush()
|
w.Flush()
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func runDeleteUser(c *cli.Context) error {
|
func runDeleteUser(c *cli.Context) error {
|
||||||
|
@ -826,7 +824,6 @@ func runUpdateOauth(c *cli.Context) error {
|
||||||
|
|
||||||
if c.IsSet("required-claim-name") {
|
if c.IsSet("required-claim-name") {
|
||||||
oAuth2Config.RequiredClaimName = c.String("required-claim-name")
|
oAuth2Config.RequiredClaimName = c.String("required-claim-name")
|
||||||
|
|
||||||
}
|
}
|
||||||
if c.IsSet("required-claim-value") {
|
if c.IsSet("required-claim-value") {
|
||||||
oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
|
oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
|
||||||
|
@ -843,7 +840,7 @@ func runUpdateOauth(c *cli.Context) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// update custom URL mapping
|
// update custom URL mapping
|
||||||
var customURLMapping = &oauth2.CustomURLMapping{}
|
customURLMapping := &oauth2.CustomURLMapping{}
|
||||||
|
|
||||||
if oAuth2Config.CustomURLMapping != nil {
|
if oAuth2Config.CustomURLMapping != nil {
|
||||||
customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
|
customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
|
||||||
|
@ -926,7 +923,7 @@ func runAddSMTP(c *cli.Context) error {
|
||||||
if !c.IsSet("port") {
|
if !c.IsSet("port") {
|
||||||
return errors.New("port must be set")
|
return errors.New("port must be set")
|
||||||
}
|
}
|
||||||
var active = true
|
active := true
|
||||||
if c.IsSet("active") {
|
if c.IsSet("active") {
|
||||||
active = c.BoolT("active")
|
active = c.BoolT("active")
|
||||||
}
|
}
|
||||||
|
@ -994,7 +991,6 @@ func runListAuth(c *cli.Context) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
authSources, err := auth.Sources()
|
authSources, err := auth.Sources()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,12 +17,12 @@ import (
|
||||||
|
|
||||||
func TestAddLdapBindDn(t *testing.T) {
|
func TestAddLdapBindDn(t *testing.T) {
|
||||||
// Mock cli functions to do not exit on error
|
// Mock cli functions to do not exit on error
|
||||||
var osExiter = cli.OsExiter
|
osExiter := cli.OsExiter
|
||||||
defer func() { cli.OsExiter = osExiter }()
|
defer func() { cli.OsExiter = osExiter }()
|
||||||
cli.OsExiter = func(code int) {}
|
cli.OsExiter = func(code int) {}
|
||||||
|
|
||||||
// Test cases
|
// Test cases
|
||||||
var cases = []struct {
|
cases := []struct {
|
||||||
args []string
|
args []string
|
||||||
source *auth.Source
|
source *auth.Source
|
||||||
errMsg string
|
errMsg string
|
||||||
|
@ -243,12 +243,12 @@ func TestAddLdapBindDn(t *testing.T) {
|
||||||
|
|
||||||
func TestAddLdapSimpleAuth(t *testing.T) {
|
func TestAddLdapSimpleAuth(t *testing.T) {
|
||||||
// Mock cli functions to do not exit on error
|
// Mock cli functions to do not exit on error
|
||||||
var osExiter = cli.OsExiter
|
osExiter := cli.OsExiter
|
||||||
defer func() { cli.OsExiter = osExiter }()
|
defer func() { cli.OsExiter = osExiter }()
|
||||||
cli.OsExiter = func(code int) {}
|
cli.OsExiter = func(code int) {}
|
||||||
|
|
||||||
// Test cases
|
// Test cases
|
||||||
var cases = []struct {
|
cases := []struct {
|
||||||
args []string
|
args []string
|
||||||
authSource *auth.Source
|
authSource *auth.Source
|
||||||
errMsg string
|
errMsg string
|
||||||
|
@ -474,12 +474,12 @@ func TestAddLdapSimpleAuth(t *testing.T) {
|
||||||
|
|
||||||
func TestUpdateLdapBindDn(t *testing.T) {
|
func TestUpdateLdapBindDn(t *testing.T) {
|
||||||
// Mock cli functions to do not exit on error
|
// Mock cli functions to do not exit on error
|
||||||
var osExiter = cli.OsExiter
|
osExiter := cli.OsExiter
|
||||||
defer func() { cli.OsExiter = osExiter }()
|
defer func() { cli.OsExiter = osExiter }()
|
||||||
cli.OsExiter = func(code int) {}
|
cli.OsExiter = func(code int) {}
|
||||||
|
|
||||||
// Test cases
|
// Test cases
|
||||||
var cases = []struct {
|
cases := []struct {
|
||||||
args []string
|
args []string
|
||||||
id int64
|
id int64
|
||||||
existingAuthSource *auth.Source
|
existingAuthSource *auth.Source
|
||||||
|
@ -907,12 +907,12 @@ func TestUpdateLdapBindDn(t *testing.T) {
|
||||||
|
|
||||||
func TestUpdateLdapSimpleAuth(t *testing.T) {
|
func TestUpdateLdapSimpleAuth(t *testing.T) {
|
||||||
// Mock cli functions to do not exit on error
|
// Mock cli functions to do not exit on error
|
||||||
var osExiter = cli.OsExiter
|
osExiter := cli.OsExiter
|
||||||
defer func() { cli.OsExiter = osExiter }()
|
defer func() { cli.OsExiter = osExiter }()
|
||||||
cli.OsExiter = func(code int) {}
|
cli.OsExiter = func(code int) {}
|
||||||
|
|
||||||
// Test cases
|
// Test cases
|
||||||
var cases = []struct {
|
cases := []struct {
|
||||||
args []string
|
args []string
|
||||||
id int64
|
id int64
|
||||||
existingAuthSource *auth.Source
|
existingAuthSource *auth.Source
|
||||||
|
@ -1161,7 +1161,6 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
|
||||||
authSource: &auth.Source{
|
authSource: &auth.Source{
|
||||||
Type: auth.DLDAP,
|
Type: auth.DLDAP,
|
||||||
Cfg: &ldap.Source{
|
Cfg: &ldap.Source{
|
||||||
|
|
||||||
AttributeMail: "mail",
|
AttributeMail: "mail",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
|
@ -180,7 +180,7 @@ func runCert(c *cli.Context) error {
|
||||||
}
|
}
|
||||||
log.Println("Written cert.pem")
|
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 {
|
if err != nil {
|
||||||
log.Fatalf("Failed to open key.pem for writing: %v", err)
|
log.Fatalf("Failed to open key.pem for writing: %v", err)
|
||||||
}
|
}
|
||||||
|
|
|
@ -121,7 +121,6 @@ func runRecreateTable(ctx *cli.Context) error {
|
||||||
}
|
}
|
||||||
return recreateTables(x)
|
return recreateTables(x)
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func runDoctor(ctx *cli.Context) error {
|
func runDoctor(ctx *cli.Context) error {
|
||||||
|
|
|
@ -370,7 +370,7 @@ func runDump(ctx *cli.Context) error {
|
||||||
fatal("Failed to save %s: %v", fileName, err)
|
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)
|
log.Info("Can't change file access permissions mask to 0600: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -107,7 +107,7 @@ func runDumpRepository(ctx *cli.Context) error {
|
||||||
}
|
}
|
||||||
serviceType = convert.ToGitServiceType(serviceStr)
|
serviceType = convert.ToGitServiceType(serviceStr)
|
||||||
|
|
||||||
var opts = base.MigrateOptions{
|
opts := base.MigrateOptions{
|
||||||
GitServiceType: serviceType,
|
GitServiceType: serviceType,
|
||||||
CloneAddr: cloneAddr,
|
CloneAddr: cloneAddr,
|
||||||
AuthUsername: ctx.String("auth_username"),
|
AuthUsername: ctx.String("auth_username"),
|
||||||
|
|
|
@ -109,7 +109,6 @@ type asset struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func initEmbeddedExtractor(c *cli.Context) error {
|
func initEmbeddedExtractor(c *cli.Context) error {
|
||||||
|
|
||||||
// Silence the console logger
|
// Silence the console logger
|
||||||
log.DelNamedLogger("console")
|
log.DelNamedLogger("console")
|
||||||
log.DelNamedLogger(log.DEFAULT)
|
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)
|
return fmt.Errorf("%s: %v", dir, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
perms := os.ModePerm & 0666
|
perms := os.ModePerm & 0o666
|
||||||
|
|
||||||
fi, err := os.Lstat(dest)
|
fi, err := os.Lstat(dest)
|
||||||
if err != nil {
|
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 {
|
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() {
|
for _, name := range sec.Names() {
|
||||||
if isdir, err := sec.IsDir(name); !isdir && err == nil {
|
if isdir, err := sec.IsDir(name); !isdir && err == nil {
|
||||||
if sec.Path == "public" &&
|
if sec.Path == "public" &&
|
||||||
|
@ -307,9 +306,11 @@ func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
|
||||||
matchName := sec.Path + "/" + name
|
matchName := sec.Path + "/" + name
|
||||||
for _, g := range globs {
|
for _, g := range globs {
|
||||||
if g.Match(matchName) {
|
if g.Match(matchName) {
|
||||||
results = append(results, asset{Section: sec,
|
results = append(results, asset{
|
||||||
Name: name,
|
Section: sec,
|
||||||
Path: sec.Path + "/" + name})
|
Name: name,
|
||||||
|
Path: sec.Path + "/" + name,
|
||||||
|
})
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -58,7 +58,8 @@ var (
|
||||||
Name: "timeout",
|
Name: "timeout",
|
||||||
Value: 60 * time.Second,
|
Value: 60 * time.Second,
|
||||||
Usage: "Timeout for the flushing process",
|
Usage: "Timeout for the flushing process",
|
||||||
}, cli.BoolFlag{
|
},
|
||||||
|
cli.BoolFlag{
|
||||||
Name: "non-blocking",
|
Name: "non-blocking",
|
||||||
Usage: "Set to true to not wait for flush to complete before returning",
|
Usage: "Set to true to not wait for flush to complete before returning",
|
||||||
},
|
},
|
||||||
|
|
|
@ -247,7 +247,7 @@ func runServ(c *cli.Context) error {
|
||||||
os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID))
|
os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID))
|
||||||
os.Setenv(models.EnvAppURL, setting.AppURL)
|
os.Setenv(models.EnvAppURL, setting.AppURL)
|
||||||
|
|
||||||
//LFS token authentication
|
// LFS token authentication
|
||||||
if verb == lfsAuthenticateVerb {
|
if verb == lfsAuthenticateVerb {
|
||||||
url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))
|
url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))
|
||||||
|
|
||||||
|
|
|
@ -71,8 +71,7 @@ func runHTTPRedirector() {
|
||||||
http.Redirect(w, r, target, http.StatusTemporaryRedirect)
|
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 {
|
if err != nil {
|
||||||
log.Fatal("Failed to start port redirection: %v", err)
|
log.Fatal("Failed to start port redirection: %v", err)
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,7 +17,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error {
|
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.
|
// 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
|
// 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
|
// 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() {
|
go func() {
|
||||||
log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect)
|
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)
|
// 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 {
|
if err != nil {
|
||||||
log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
|
log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
|
||||||
}
|
}
|
||||||
|
|
|
@ -66,7 +66,7 @@ func generate(name string) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
path := filepath.Join(fixturesDir, name+".yml")
|
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)
|
return fmt.Errorf("%s: %+v", path, err)
|
||||||
}
|
}
|
||||||
fmt.Printf("%s created.\n", path)
|
fmt.Printf("%s created.\n", path)
|
||||||
|
|
|
@ -93,13 +93,13 @@ func runPR() {
|
||||||
|
|
||||||
routers.InitGitServices()
|
routers.InitGitServices()
|
||||||
setting.Database.LogSQL = true
|
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 {
|
db.InitEngineWithMigration(context.Background(), func(_ *xorm.Engine) error {
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
db.HasEngine = true
|
db.HasEngine = true
|
||||||
//x.ShowSQL(true)
|
// x.ShowSQL(true)
|
||||||
err = unittest.InitFixtures(
|
err = unittest.InitFixtures(
|
||||||
unittest.FixturesOptions{
|
unittest.FixturesOptions{
|
||||||
Dir: path.Join(curDir, "models/fixtures/"),
|
Dir: path.Join(curDir, "models/fixtures/"),
|
||||||
|
@ -115,7 +115,7 @@ func runPR() {
|
||||||
util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
|
util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
|
||||||
|
|
||||||
log.Printf("[PR] Setting up router\n")
|
log.Printf("[PR] Setting up router\n")
|
||||||
//routers.GlobalInit()
|
// routers.GlobalInit()
|
||||||
external.RegisterRenderers()
|
external.RegisterRenderers()
|
||||||
markup.Init()
|
markup.Init()
|
||||||
c := routers.NormalRoutes()
|
c := routers.NormalRoutes()
|
||||||
|
@ -137,7 +137,7 @@ func runPR() {
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
//Start the server
|
// Start the server
|
||||||
http.ListenAndServe(":8080", c)
|
http.ListenAndServe(":8080", c)
|
||||||
|
|
||||||
log.Printf("[PR] Cleaning up ...\n")
|
log.Printf("[PR] Cleaning up ...\n")
|
||||||
|
@ -160,7 +160,7 @@ func runPR() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var runPRFlag = flag.Bool("run", false, "Run the PR code")
|
runPRFlag := flag.Bool("run", false, "Run the PR code")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
if *runPRFlag {
|
if *runPRFlag {
|
||||||
runPR()
|
runPR()
|
||||||
|
@ -173,15 +173,15 @@ func main() {
|
||||||
force = false
|
force = false
|
||||||
}
|
}
|
||||||
|
|
||||||
//Otherwise checkout PR
|
// Otherwise checkout PR
|
||||||
if len(os.Args) != 2 {
|
if len(os.Args) != 2 {
|
||||||
log.Fatal("Need only one arg: the PR number")
|
log.Fatal("Need only one arg: the PR number")
|
||||||
}
|
}
|
||||||
pr := os.Args[1]
|
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)
|
dat, err := os.ReadFile(codeFilePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to cache this code file : %v", err)
|
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)
|
log.Fatalf("Failed to open the repo : %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Find remote upstream
|
// Find remote upstream
|
||||||
remotes, err := repo.Remotes()
|
remotes, err := repo.Remotes()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to list remotes of repo : %v", err)
|
log.Fatalf("Failed to list remotes of repo : %v", err)
|
||||||
}
|
}
|
||||||
remoteUpstream := "origin" //Default
|
remoteUpstream := "origin" // Default
|
||||||
for _, r := range remotes {
|
for _, r := range remotes {
|
||||||
if r.Config().URLs[0] == "https://github.com/go-gitea/gitea.git" ||
|
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] == "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
|
remoteUpstream = r.Config().Name
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
@ -212,7 +212,7 @@ func main() {
|
||||||
|
|
||||||
log.Printf("Fetching PR #%s in %s\n", pr, branch)
|
log.Printf("Fetching PR #%s in %s\n", pr, branch)
|
||||||
if runtime.GOOS == "windows" {
|
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))
|
runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch))
|
||||||
} else {
|
} else {
|
||||||
ref := fmt.Sprintf("%s%s/head:%s", gitea_git.PullPrefix, pr, branchRef)
|
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)
|
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) {
|
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 {
|
if err != nil {
|
||||||
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
|
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 {
|
if err != nil {
|
||||||
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
|
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")
|
runCmd("make", "build")
|
||||||
//Start with integration test
|
// Start with integration test
|
||||||
runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
|
runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
|
||||||
}
|
}
|
||||||
|
|
||||||
func runCmd(cmd ...string) {
|
func runCmd(cmd ...string) {
|
||||||
log.Printf("Executing : %s ...\n", cmd)
|
log.Printf("Executing : %s ...\n", cmd)
|
||||||
c := exec.Command(cmd[0], cmd[1:]...)
|
c := exec.Command(cmd[0], cmd[1:]...)
|
||||||
|
|
|
@ -22,7 +22,7 @@ func TestAPIAdminOrgCreate(t *testing.T) {
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
|
|
||||||
var org = api.CreateOrgOption{
|
org := api.CreateOrgOption{
|
||||||
UserName: "user2_org",
|
UserName: "user2_org",
|
||||||
FullName: "User2's organization",
|
FullName: "User2's organization",
|
||||||
Description: "This organization created by admin for user2",
|
Description: "This organization created by admin for user2",
|
||||||
|
@ -56,7 +56,7 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) {
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
|
|
||||||
var org = api.CreateOrgOption{
|
org := api.CreateOrgOption{
|
||||||
UserName: "user2_org",
|
UserName: "user2_org",
|
||||||
FullName: "User2's organization",
|
FullName: "User2's organization",
|
||||||
Description: "This organization created by admin for user2",
|
Description: "This organization created by admin for user2",
|
||||||
|
@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {
|
||||||
nonAdminUsername := "user2"
|
nonAdminUsername := "user2"
|
||||||
session := loginUser(t, nonAdminUsername)
|
session := loginUser(t, nonAdminUsername)
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
var org = api.CreateOrgOption{
|
org := api.CreateOrgOption{
|
||||||
UserName: "user2_org",
|
UserName: "user2_org",
|
||||||
FullName: "User2's organization",
|
FullName: "User2's organization",
|
||||||
Description: "This organization created by admin for user2",
|
Description: "This organization created by admin for user2",
|
||||||
|
|
|
@ -106,7 +106,6 @@ func TestAPICreateBranch(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testAPICreateBranches(t *testing.T, giteaURL *url.URL) {
|
func testAPICreateBranches(t *testing.T, giteaURL *url.URL) {
|
||||||
|
|
||||||
username := "user2"
|
username := "user2"
|
||||||
ctx := NewAPITestContext(t, username, "my-noo-repo")
|
ctx := NewAPITestContext(t, username, "my-noo-repo")
|
||||||
giteaURL.Path = ctx.GitPath()
|
giteaURL.Path = ctx.GitPath()
|
||||||
|
|
|
@ -44,10 +44,10 @@ func TestAPIListRepoComments(t *testing.T) {
|
||||||
unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID})
|
unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID})
|
||||||
}
|
}
|
||||||
|
|
||||||
//test before and since filters
|
// test before and since filters
|
||||||
query := url.Values{}
|
query := url.Values{}
|
||||||
before := "2000-01-01T00:00:11+00:00" //unix: 946684811
|
before := "2000-01-01T00:00:11+00:00" // unix: 946684811
|
||||||
since := "2000-01-01T00:00:12+00:00" //unix: 946684812
|
since := "2000-01-01T00:00:12+00:00" // unix: 946684812
|
||||||
query.Add("before", before)
|
query.Add("before", before)
|
||||||
link.RawQuery = query.Encode()
|
link.RawQuery = query.Encode()
|
||||||
req = NewRequest(t, "GET", link.String())
|
req = NewRequest(t, "GET", link.String())
|
||||||
|
|
|
@ -28,15 +28,18 @@ func TestGPGKeys(t *testing.T) {
|
||||||
token string
|
token string
|
||||||
results []int
|
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},
|
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 {
|
for _, tc := range tt {
|
||||||
//Basic test on result code
|
// Basic test on result code
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
t.Run("ViewOwnGPGKeys", func(t *testing.T) {
|
t.Run("ViewOwnGPGKeys", func(t *testing.T) {
|
||||||
testViewOwnGPGKeys(t, tc.makeRequest, tc.token, tc.results[0])
|
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) {
|
t.Run("CheckState", func(t *testing.T) {
|
||||||
|
|
||||||
var keys []*api.GPGKey
|
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)
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||||
DecodeJSON(t, resp, &keys)
|
DecodeJSON(t, resp, &keys)
|
||||||
assert.Len(t, keys, 1)
|
assert.Len(t, keys, 1)
|
||||||
|
|
||||||
primaryKey1 := keys[0] //Primary key 1
|
primaryKey1 := keys[0] // Primary key 1
|
||||||
assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID)
|
assert.EqualValues(t, "38EA3BCED732982C", primaryKey1.KeyID)
|
||||||
assert.Len(t, primaryKey1.Emails, 1)
|
assert.Len(t, primaryKey1.Emails, 1)
|
||||||
assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email)
|
assert.EqualValues(t, "user2@example.com", primaryKey1.Emails[0].Email)
|
||||||
assert.True(t, primaryKey1.Emails[0].Verified)
|
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.EqualValues(t, "70D7C694D17D03AD", subKey.KeyID)
|
||||||
assert.Empty(t, subKey.Emails)
|
assert.Empty(t, subKey.Emails)
|
||||||
|
|
||||||
var key api.GPGKey
|
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)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
DecodeJSON(t, resp, &key)
|
DecodeJSON(t, resp, &key)
|
||||||
assert.EqualValues(t, "38EA3BCED732982C", key.KeyID)
|
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.EqualValues(t, "user2@example.com", key.Emails[0].Email)
|
||||||
assert.True(t, key.Emails[0].Verified)
|
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)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
DecodeJSON(t, resp, &key)
|
DecodeJSON(t, resp, &key)
|
||||||
assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID)
|
assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID)
|
||||||
assert.Empty(t, key.Emails)
|
assert.Empty(t, key.Emails)
|
||||||
})
|
})
|
||||||
|
|
||||||
//Check state after basic add
|
// Check state after basic add
|
||||||
t.Run("CheckCommits", func(t *testing.T) {
|
t.Run("CheckCommits", func(t *testing.T) {
|
||||||
t.Run("NotSigned", func(t *testing.T) {
|
t.Run("NotSigned", func(t *testing.T) {
|
||||||
var branch api.Branch
|
var branch api.Branch
|
||||||
|
@ -182,7 +184,7 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) {
|
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-----
|
testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||||
|
|
||||||
mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW
|
mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW
|
||||||
|
@ -216,7 +218,7 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h
|
||||||
}
|
}
|
||||||
|
|
||||||
func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) {
|
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-----
|
testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||||
|
|
||||||
mQGNBGC2K2cBDAC1+Xgk+8UfhASVgRngQi4rnQ8k0t+bWsBz4Czd26+cxVDRwlTT
|
mQGNBGC2K2cBDAC1+Xgk+8UfhASVgRngQi4rnQ8k0t+bWsBz4Czd26+cxVDRwlTT
|
||||||
|
|
|
@ -53,21 +53,21 @@ func TestAPIModifyLabels(t *testing.T) {
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||||
|
|
||||||
//ListLabels
|
// ListLabels
|
||||||
req = NewRequest(t, "GET", urlStr)
|
req = NewRequest(t, "GET", urlStr)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
var apiLabels []*api.Label
|
var apiLabels []*api.Label
|
||||||
DecodeJSON(t, resp, &apiLabels)
|
DecodeJSON(t, resp, &apiLabels)
|
||||||
assert.Len(t, apiLabels, 2)
|
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)
|
singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d?token=%s", owner.Name, repo.Name, dbLabel.ID, token)
|
||||||
req = NewRequest(t, "GET", singleURLStr)
|
req = NewRequest(t, "GET", singleURLStr)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
DecodeJSON(t, resp, &apiLabel)
|
DecodeJSON(t, resp, &apiLabel)
|
||||||
assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color)
|
assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color)
|
||||||
|
|
||||||
//EditLabel
|
// EditLabel
|
||||||
newName := "LabelNewName"
|
newName := "LabelNewName"
|
||||||
newColor := "09876a"
|
newColor := "09876a"
|
||||||
newColorWrong := "09g76a"
|
newColorWrong := "09g76a"
|
||||||
|
@ -83,10 +83,9 @@ func TestAPIModifyLabels(t *testing.T) {
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||||
|
|
||||||
//DeleteLabel
|
// DeleteLabel
|
||||||
req = NewRequest(t, "DELETE", singleURLStr)
|
req = NewRequest(t, "DELETE", singleURLStr)
|
||||||
session.MakeRequest(t, req, http.StatusNoContent)
|
session.MakeRequest(t, req, http.StatusNoContent)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAPIAddIssueLabels(t *testing.T) {
|
func TestAPIAddIssueLabels(t *testing.T) {
|
||||||
|
@ -173,21 +172,21 @@ func TestAPIModifyOrgLabels(t *testing.T) {
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||||
|
|
||||||
//ListLabels
|
// ListLabels
|
||||||
req = NewRequest(t, "GET", urlStr)
|
req = NewRequest(t, "GET", urlStr)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
var apiLabels []*api.Label
|
var apiLabels []*api.Label
|
||||||
DecodeJSON(t, resp, &apiLabels)
|
DecodeJSON(t, resp, &apiLabels)
|
||||||
assert.Len(t, apiLabels, 4)
|
assert.Len(t, apiLabels, 4)
|
||||||
|
|
||||||
//GetLabel
|
// GetLabel
|
||||||
singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token)
|
singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token)
|
||||||
req = NewRequest(t, "GET", singleURLStr)
|
req = NewRequest(t, "GET", singleURLStr)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
DecodeJSON(t, resp, &apiLabel)
|
DecodeJSON(t, resp, &apiLabel)
|
||||||
assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color)
|
assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color)
|
||||||
|
|
||||||
//EditLabel
|
// EditLabel
|
||||||
newName := "LabelNewName"
|
newName := "LabelNewName"
|
||||||
newColor := "09876a"
|
newColor := "09876a"
|
||||||
newColorWrong := "09g76a"
|
newColorWrong := "09g76a"
|
||||||
|
@ -203,8 +202,7 @@ func TestAPIModifyOrgLabels(t *testing.T) {
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||||
|
|
||||||
//DeleteLabel
|
// DeleteLabel
|
||||||
req = NewRequest(t, "DELETE", singleURLStr)
|
req = NewRequest(t, "DELETE", singleURLStr)
|
||||||
session.MakeRequest(t, req, http.StatusNoContent)
|
session.MakeRequest(t, req, http.StatusNoContent)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,19 +33,19 @@ func TestAPIIssuesReactions(t *testing.T) {
|
||||||
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s",
|
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s",
|
||||||
owner.Name, issue.Repo.Name, issue.Index, token)
|
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{
|
req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
|
||||||
Reaction: "wrong",
|
Reaction: "wrong",
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusForbidden)
|
session.MakeRequest(t, req, http.StatusForbidden)
|
||||||
|
|
||||||
//Delete not allowed reaction
|
// Delete not allowed reaction
|
||||||
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
|
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
|
||||||
Reaction: "zzz",
|
Reaction: "zzz",
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusOK)
|
session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
||||||
//Add allowed reaction
|
// Add allowed reaction
|
||||||
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
|
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
|
||||||
Reaction: "rocket",
|
Reaction: "rocket",
|
||||||
})
|
})
|
||||||
|
@ -53,10 +53,10 @@ func TestAPIIssuesReactions(t *testing.T) {
|
||||||
var apiNewReaction api.Reaction
|
var apiNewReaction api.Reaction
|
||||||
DecodeJSON(t, resp, &apiNewReaction)
|
DecodeJSON(t, resp, &apiNewReaction)
|
||||||
|
|
||||||
//Add existing reaction
|
// Add existing reaction
|
||||||
session.MakeRequest(t, req, http.StatusForbidden)
|
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)
|
req = NewRequestf(t, "GET", urlStr)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
var apiReactions []*api.Reaction
|
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",
|
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s",
|
||||||
owner.Name, issue.Repo.Name, comment.ID, token)
|
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{
|
req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
|
||||||
Reaction: "wrong",
|
Reaction: "wrong",
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusForbidden)
|
session.MakeRequest(t, req, http.StatusForbidden)
|
||||||
|
|
||||||
//Delete none existing reaction
|
// Delete none existing reaction
|
||||||
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
|
req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{
|
||||||
Reaction: "eyes",
|
Reaction: "eyes",
|
||||||
})
|
})
|
||||||
session.MakeRequest(t, req, http.StatusOK)
|
session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
||||||
//Add allowed reaction
|
// Add allowed reaction
|
||||||
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
|
req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{
|
||||||
Reaction: "+1",
|
Reaction: "+1",
|
||||||
})
|
})
|
||||||
|
@ -113,10 +113,10 @@ func TestAPICommentReactions(t *testing.T) {
|
||||||
var apiNewReaction api.Reaction
|
var apiNewReaction api.Reaction
|
||||||
DecodeJSON(t, resp, &apiNewReaction)
|
DecodeJSON(t, resp, &apiNewReaction)
|
||||||
|
|
||||||
//Add existing reaction
|
// Add existing reaction
|
||||||
session.MakeRequest(t, req, http.StatusForbidden)
|
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)
|
req = NewRequestf(t, "GET", urlStr)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
var apiReactions []*api.Reaction
|
var apiReactions []*api.Reaction
|
||||||
|
|
|
@ -33,7 +33,6 @@ func TestAPIIssueSubscriptions(t *testing.T) {
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
|
|
||||||
testSubscription := func(issue *models.Issue, isWatching bool) {
|
testSubscription := func(issue *models.Issue, isWatching bool) {
|
||||||
|
|
||||||
issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
|
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)
|
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token)
|
||||||
|
|
|
@ -210,7 +210,7 @@ func TestAPISearchIssues(t *testing.T) {
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
DecodeJSON(t, resp, &apiIssues)
|
DecodeJSON(t, resp, &apiIssues)
|
||||||
assert.EqualValues(t, "15", resp.Header().Get("X-Total-Count"))
|
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")
|
query.Add("limit", "20")
|
||||||
link.RawQuery = query.Encode()
|
link.RawQuery = query.Encode()
|
||||||
|
|
|
@ -48,8 +48,8 @@ func TestAPIGetTrackedTimes(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// test filter
|
// test filter
|
||||||
since := "2000-01-01T00%3A00%3A02%2B00%3A00" //946684802
|
since := "2000-01-01T00%3A00%3A02%2B00%3A00" // 946684802
|
||||||
before := "2000-01-01T00%3A00%3A12%2B00%3A00" //946684812
|
before := "2000-01-01T00%3A00%3A12%2B00%3A00" // 946684812
|
||||||
|
|
||||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s&token=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before, token)
|
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s&token=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before, token)
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
@ -71,17 +71,17 @@ func TestAPIDeleteTrackedTime(t *testing.T) {
|
||||||
session := loginUser(t, user2.Name)
|
session := loginUser(t, user2.Name)
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
|
|
||||||
//Deletion not allowed
|
// Deletion not allowed
|
||||||
req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token)
|
req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token)
|
||||||
session.MakeRequest(t, req, http.StatusForbidden)
|
session.MakeRequest(t, req, http.StatusForbidden)
|
||||||
|
|
||||||
time3 := unittest.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime)
|
time3 := unittest.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime)
|
||||||
req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token)
|
req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token)
|
||||||
session.MakeRequest(t, req, http.StatusNoContent)
|
session.MakeRequest(t, req, http.StatusNoContent)
|
||||||
//Delete non existing time
|
// Delete non existing time
|
||||||
session.MakeRequest(t, req, http.StatusNotFound)
|
session.MakeRequest(t, req, http.StatusNotFound)
|
||||||
|
|
||||||
//Reset time of user 2 on issue 2
|
// Reset time of user 2 on issue 2
|
||||||
trackedSeconds, err := models.GetTrackedSeconds(models.FindTrackedTimesOptions{IssueID: 2, UserID: 2})
|
trackedSeconds, err := models.GetTrackedSeconds(models.FindTrackedTimesOptions{IssueID: 2, UserID: 2})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.Equal(t, int64(3661), trackedSeconds)
|
assert.Equal(t, int64(3661), trackedSeconds)
|
||||||
|
|
|
@ -30,7 +30,7 @@ func TestAPINotification(t *testing.T) {
|
||||||
|
|
||||||
// -- GET /notifications --
|
// -- GET /notifications --
|
||||||
// test filter
|
// test filter
|
||||||
since := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801
|
since := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801
|
||||||
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s&token=%s", since, token))
|
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s&token=%s", since, token))
|
||||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||||
var apiNL []api.NotificationThread
|
var apiNL []api.NotificationThread
|
||||||
|
@ -40,7 +40,7 @@ func TestAPINotification(t *testing.T) {
|
||||||
assert.EqualValues(t, 5, apiNL[0].ID)
|
assert.EqualValues(t, 5, apiNL[0].ID)
|
||||||
|
|
||||||
// test filter
|
// test filter
|
||||||
before := "2000-01-01T01%3A06%3A59%2B00%3A00" //946688819
|
before := "2000-01-01T01%3A06%3A59%2B00%3A00" // 946688819
|
||||||
|
|
||||||
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s&token=%s", "true", before, token))
|
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s&token=%s", "true", before, token))
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
@ -113,7 +113,7 @@ func TestAPINotification(t *testing.T) {
|
||||||
DecodeJSON(t, resp, &apiNL)
|
DecodeJSON(t, resp, &apiNL)
|
||||||
assert.Len(t, apiNL, 2)
|
assert.Len(t, apiNL, 2)
|
||||||
|
|
||||||
lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 <- only Notification 4 is in this filter ...
|
lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ...
|
||||||
req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token))
|
req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token))
|
||||||
session.MakeRequest(t, req, http.StatusResetContent)
|
session.MakeRequest(t, req, http.StatusResetContent)
|
||||||
|
|
||||||
|
|
|
@ -23,7 +23,7 @@ func TestAPIOrgCreate(t *testing.T) {
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
|
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
var org = api.CreateOrgOption{
|
org := api.CreateOrgOption{
|
||||||
UserName: "user1_org",
|
UserName: "user1_org",
|
||||||
FullName: "User1's organization",
|
FullName: "User1's organization",
|
||||||
Description: "This organization created by user1",
|
Description: "This organization created by user1",
|
||||||
|
@ -80,7 +80,7 @@ func TestAPIOrgEdit(t *testing.T) {
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
|
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
var org = api.EditOrgOption{
|
org := api.EditOrgOption{
|
||||||
FullName: "User3 organization new full name",
|
FullName: "User3 organization new full name",
|
||||||
Description: "A new description",
|
Description: "A new description",
|
||||||
Website: "https://try.gitea.io/new",
|
Website: "https://try.gitea.io/new",
|
||||||
|
@ -107,7 +107,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) {
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
|
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
var org = api.EditOrgOption{
|
org := api.EditOrgOption{
|
||||||
FullName: "User3 organization new full name",
|
FullName: "User3 organization new full name",
|
||||||
Description: "A new description",
|
Description: "A new description",
|
||||||
Website: "https://try.gitea.io/new",
|
Website: "https://try.gitea.io/new",
|
||||||
|
@ -126,7 +126,7 @@ func TestAPIOrgDeny(t *testing.T) {
|
||||||
setting.Service.RequireSignInView = false
|
setting.Service.RequireSignInView = false
|
||||||
}()
|
}()
|
||||||
|
|
||||||
var orgName = "user1_org"
|
orgName := "user1_org"
|
||||||
req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName)
|
req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName)
|
||||||
MakeRequest(t, req, http.StatusNotFound)
|
MakeRequest(t, req, http.StatusNotFound)
|
||||||
|
|
||||||
|
|
|
@ -150,7 +150,5 @@ func TestAPIPrivateServ(t *testing.T) {
|
||||||
assert.Equal(t, "user15", results.OwnerName)
|
assert.Equal(t, "user15", results.OwnerName)
|
||||||
assert.Equal(t, "big_test_private_2", results.RepoName)
|
assert.Equal(t, "big_test_private_2", results.RepoName)
|
||||||
assert.Equal(t, int64(20), results.RepoID)
|
assert.Equal(t, int64(20), results.RepoID)
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -80,22 +80,23 @@ func TestAPIPullReview(t *testing.T) {
|
||||||
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{
|
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{
|
||||||
Body: "body1",
|
Body: "body1",
|
||||||
// Event: "" # will result in PENDING
|
// Event: "" # will result in PENDING
|
||||||
Comments: []api.CreatePullReviewComment{{
|
Comments: []api.CreatePullReviewComment{
|
||||||
Path: "README.md",
|
{
|
||||||
Body: "first new line",
|
Path: "README.md",
|
||||||
OldLineNum: 0,
|
Body: "first new line",
|
||||||
NewLineNum: 1,
|
OldLineNum: 0,
|
||||||
}, {
|
NewLineNum: 1,
|
||||||
Path: "README.md",
|
}, {
|
||||||
Body: "first old line",
|
Path: "README.md",
|
||||||
OldLineNum: 1,
|
Body: "first old line",
|
||||||
NewLineNum: 0,
|
OldLineNum: 1,
|
||||||
}, {
|
NewLineNum: 0,
|
||||||
Path: "iso-8859-1.txt",
|
}, {
|
||||||
Body: "this line contains a non-utf-8 character",
|
Path: "iso-8859-1.txt",
|
||||||
OldLineNum: 0,
|
Body: "this line contains a non-utf-8 character",
|
||||||
NewLineNum: 1,
|
OldLineNum: 0,
|
||||||
},
|
NewLineNum: 1,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
@ -147,17 +148,18 @@ func TestAPIPullReview(t *testing.T) {
|
||||||
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{
|
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{
|
||||||
// Body: "",
|
// Body: "",
|
||||||
Event: "COMMENT",
|
Event: "COMMENT",
|
||||||
Comments: []api.CreatePullReviewComment{{
|
Comments: []api.CreatePullReviewComment{
|
||||||
Path: "README.md",
|
{
|
||||||
Body: "first new line",
|
Path: "README.md",
|
||||||
OldLineNum: 0,
|
Body: "first new line",
|
||||||
NewLineNum: 1,
|
OldLineNum: 0,
|
||||||
}, {
|
NewLineNum: 1,
|
||||||
Path: "README.md",
|
}, {
|
||||||
Body: "first old line",
|
Path: "README.md",
|
||||||
OldLineNum: 1,
|
Body: "first old line",
|
||||||
NewLineNum: 0,
|
OldLineNum: 1,
|
||||||
},
|
NewLineNum: 0,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
var commentReview api.PullReview
|
var commentReview api.PullReview
|
||||||
|
|
|
@ -175,7 +175,7 @@ func TestAPIRepoEdit(t *testing.T) {
|
||||||
assert.Equal(t, *repoEditOption.Private, *repo1editedOption.Private)
|
assert.Equal(t, *repoEditOption.Private, *repo1editedOption.Private)
|
||||||
assert.Equal(t, *repoEditOption.HasWiki, *repo1editedOption.HasWiki)
|
assert.Equal(t, *repoEditOption.HasWiki, *repo1editedOption.HasWiki)
|
||||||
|
|
||||||
//Test editing repo1 to use internal issue and wiki (default)
|
// Test editing repo1 to use internal issue and wiki (default)
|
||||||
*repoEditOption.HasIssues = true
|
*repoEditOption.HasIssues = true
|
||||||
repoEditOption.ExternalTracker = nil
|
repoEditOption.ExternalTracker = nil
|
||||||
repoEditOption.InternalTracker = &api.InternalTracker{
|
repoEditOption.InternalTracker = &api.InternalTracker{
|
||||||
|
@ -199,7 +199,7 @@ func TestAPIRepoEdit(t *testing.T) {
|
||||||
assert.Equal(t, *repo1editedOption.HasWiki, true)
|
assert.Equal(t, *repo1editedOption.HasWiki, true)
|
||||||
assert.Nil(t, repo1editedOption.ExternalWiki)
|
assert.Nil(t, repo1editedOption.ExternalWiki)
|
||||||
|
|
||||||
//Test editing repo1 to use external issue and wiki
|
// Test editing repo1 to use external issue and wiki
|
||||||
repoEditOption.ExternalTracker = &api.ExternalTracker{
|
repoEditOption.ExternalTracker = &api.ExternalTracker{
|
||||||
ExternalTrackerURL: "http://www.somewebsite.com",
|
ExternalTrackerURL: "http://www.somewebsite.com",
|
||||||
ExternalTrackerFormat: "http://www.somewebsite.com/{user}/{repo}?issue={index}",
|
ExternalTrackerFormat: "http://www.somewebsite.com/{user}/{repo}?issue={index}",
|
||||||
|
@ -233,7 +233,7 @@ func TestAPIRepoEdit(t *testing.T) {
|
||||||
req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption)
|
req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption)
|
||||||
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||||
|
|
||||||
//Test small repo change through API with issue and wiki option not set; They shall not be touched.
|
// Test small repo change through API with issue and wiki option not set; They shall not be touched.
|
||||||
*repoEditOption.Description = "small change"
|
*repoEditOption.Description = "small change"
|
||||||
repoEditOption.HasIssues = nil
|
repoEditOption.HasIssues = nil
|
||||||
repoEditOption.ExternalTracker = nil
|
repoEditOption.ExternalTracker = nil
|
||||||
|
|
|
@ -130,7 +130,6 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) {
|
||||||
assert.EqualValues(t,
|
assert.EqualValues(t,
|
||||||
"From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 <user2@example.com>\nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n",
|
"From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 <user2@example.com>\nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n",
|
||||||
resp.Body.String())
|
resp.Body.String())
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetFileHistory(t *testing.T) {
|
func TestGetFileHistory(t *testing.T) {
|
||||||
|
|
|
@ -53,8 +53,8 @@ func TestAPILFSLocksNotLogin(t *testing.T) {
|
||||||
func TestAPILFSLocksLogged(t *testing.T) {
|
func TestAPILFSLocksLogged(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
setting.LFS.StartServer = true
|
setting.LFS.StartServer = true
|
||||||
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) //in org 3
|
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User) // in org 3
|
||||||
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) //in org 3
|
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}).(*user_model.User) // in org 3
|
||||||
|
|
||||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
|
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository)
|
||||||
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // own by org 3
|
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}).(*repo_model.Repository) // own by org 3
|
||||||
|
@ -101,7 +101,7 @@ func TestAPILFSLocksLogged(t *testing.T) {
|
||||||
lockID string
|
lockID string
|
||||||
}{}
|
}{}
|
||||||
|
|
||||||
//create locks
|
// create locks
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
session := loginUser(t, test.user.Name)
|
session := loginUser(t, test.user.Name)
|
||||||
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks", test.repo.FullName()), map[string]string{"path": test.path})
|
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks", test.repo.FullName()), map[string]string{"path": test.path})
|
||||||
|
@ -111,14 +111,14 @@ func TestAPILFSLocksLogged(t *testing.T) {
|
||||||
if len(test.addTime) > 0 {
|
if len(test.addTime) > 0 {
|
||||||
var lfsLock api.LFSLockResponse
|
var lfsLock api.LFSLockResponse
|
||||||
DecodeJSON(t, resp, &lfsLock)
|
DecodeJSON(t, resp, &lfsLock)
|
||||||
assert.EqualValues(t, lfsLock.Lock.LockedAt.Format(time.RFC3339), lfsLock.Lock.LockedAt.Format(time.RFC3339Nano)) //locked at should be rounded to second
|
assert.EqualValues(t, lfsLock.Lock.LockedAt.Format(time.RFC3339), lfsLock.Lock.LockedAt.Format(time.RFC3339Nano)) // locked at should be rounded to second
|
||||||
for _, id := range test.addTime {
|
for _, id := range test.addTime {
|
||||||
resultsTests[id].locksTimes = append(resultsTests[id].locksTimes, time.Now())
|
resultsTests[id].locksTimes = append(resultsTests[id].locksTimes, time.Now())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//check creation
|
// check creation
|
||||||
for _, test := range resultsTests {
|
for _, test := range resultsTests {
|
||||||
session := loginUser(t, test.user.Name)
|
session := loginUser(t, test.user.Name)
|
||||||
req := NewRequestf(t, "GET", "/%s.git/info/lfs/locks", test.repo.FullName())
|
req := NewRequestf(t, "GET", "/%s.git/info/lfs/locks", test.repo.FullName())
|
||||||
|
@ -130,7 +130,7 @@ func TestAPILFSLocksLogged(t *testing.T) {
|
||||||
for i, lock := range lfsLocks.Locks {
|
for i, lock := range lfsLocks.Locks {
|
||||||
assert.EqualValues(t, test.locksOwners[i].DisplayName(), lock.Owner.Name)
|
assert.EqualValues(t, test.locksOwners[i].DisplayName(), lock.Owner.Name)
|
||||||
assert.WithinDuration(t, test.locksTimes[i], lock.LockedAt, 10*time.Second)
|
assert.WithinDuration(t, test.locksTimes[i], lock.LockedAt, 10*time.Second)
|
||||||
assert.EqualValues(t, lock.LockedAt.Format(time.RFC3339), lock.LockedAt.Format(time.RFC3339Nano)) //locked at should be rounded to second
|
assert.EqualValues(t, lock.LockedAt.Format(time.RFC3339), lock.LockedAt.Format(time.RFC3339Nano)) // locked at should be rounded to second
|
||||||
}
|
}
|
||||||
|
|
||||||
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/verify", test.repo.FullName()), map[string]string{})
|
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/verify", test.repo.FullName()), map[string]string{})
|
||||||
|
@ -154,7 +154,7 @@ func TestAPILFSLocksLogged(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//remove all locks
|
// remove all locks
|
||||||
for _, test := range deleteTests {
|
for _, test := range deleteTests {
|
||||||
session := loginUser(t, test.user.Name)
|
session := loginUser(t, test.user.Name)
|
||||||
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/%s/unlock", test.repo.FullName(), test.lockID), map[string]string{})
|
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s.git/info/lfs/locks/%s/unlock", test.repo.FullName(), test.lockID), map[string]string{})
|
||||||
|
|
|
@ -79,76 +79,99 @@ func TestAPISearchRepo(t *testing.T) {
|
||||||
name, requestURL string
|
name, requestURL string
|
||||||
expectedResults
|
expectedResults
|
||||||
}{
|
}{
|
||||||
{name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 30},
|
name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{
|
||||||
user: {count: 30},
|
nil: {count: 30},
|
||||||
user2: {count: 30}},
|
user: {count: 30},
|
||||||
|
user2: {count: 30},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 10},
|
name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{
|
||||||
user: {count: 10},
|
nil: {count: 10},
|
||||||
user2: {count: 10}},
|
user: {count: 10},
|
||||||
|
user2: {count: 10},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 10},
|
name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{
|
||||||
user: {count: 10},
|
nil: {count: 10},
|
||||||
user2: {count: 10}},
|
user: {count: 10},
|
||||||
|
user2: {count: 10},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 7, repoName: "big_test_"},
|
name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{
|
||||||
user: {count: 7, repoName: "big_test_"},
|
nil: {count: 7, repoName: "big_test_"},
|
||||||
user2: {count: 7, repoName: "big_test_"}},
|
user: {count: 7, repoName: "big_test_"},
|
||||||
|
user2: {count: 7, repoName: "big_test_"},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 5},
|
name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{
|
||||||
user: {count: 9, includesPrivate: true},
|
nil: {count: 5},
|
||||||
user2: {count: 6, includesPrivate: true}},
|
user: {count: 9, includesPrivate: true},
|
||||||
|
user2: {count: 6, includesPrivate: true},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 1},
|
name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{
|
||||||
user: {count: 2, includesPrivate: true},
|
nil: {count: 1},
|
||||||
user2: {count: 2, includesPrivate: true},
|
user: {count: 2, includesPrivate: true},
|
||||||
user4: {count: 1}},
|
user2: {count: 2, includesPrivate: true},
|
||||||
|
user4: {count: 1},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 1},
|
name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{
|
||||||
user: {count: 4, includesPrivate: true},
|
nil: {count: 1},
|
||||||
user2: {count: 3, includesPrivate: true},
|
user: {count: 4, includesPrivate: true},
|
||||||
user3: {count: 4, includesPrivate: true}},
|
user2: {count: 3, includesPrivate: true},
|
||||||
|
user3: {count: 4, includesPrivate: true},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{
|
{
|
||||||
nil: {count: 1, repoOwnerID: orgUser.ID},
|
name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{
|
||||||
user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true},
|
nil: {count: 1, repoOwnerID: orgUser.ID},
|
||||||
user2: {count: 1, repoOwnerID: orgUser.ID}},
|
user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true},
|
||||||
|
user2: {count: 1, repoOwnerID: orgUser.ID},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user4.ID), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user4.ID), expectedResults: expectedResults{
|
||||||
nil: {count: 3},
|
nil: {count: 3},
|
||||||
user: {count: 4, includesPrivate: true},
|
user: {count: 4, includesPrivate: true},
|
||||||
user4: {count: 7, includesPrivate: true}}},
|
user4: {count: 7, includesPrivate: true},
|
||||||
|
}},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeSource", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "source"), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeSource", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "source"), expectedResults: expectedResults{
|
||||||
nil: {count: 0},
|
nil: {count: 0},
|
||||||
user: {count: 1, includesPrivate: true},
|
user: {count: 1, includesPrivate: true},
|
||||||
user4: {count: 1, includesPrivate: true}}},
|
user4: {count: 1, includesPrivate: true},
|
||||||
|
}},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "fork"), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "fork"), expectedResults: expectedResults{
|
||||||
nil: {count: 1},
|
nil: {count: 1},
|
||||||
user: {count: 1},
|
user: {count: 1},
|
||||||
user4: {count: 2, includesPrivate: true}}},
|
user4: {count: 2, includesPrivate: true},
|
||||||
|
}},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "fork"), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "fork"), expectedResults: expectedResults{
|
||||||
nil: {count: 1},
|
nil: {count: 1},
|
||||||
user: {count: 1},
|
user: {count: 1},
|
||||||
user4: {count: 2, includesPrivate: true}}},
|
user4: {count: 2, includesPrivate: true},
|
||||||
|
}},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "mirror"), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "mirror"), expectedResults: expectedResults{
|
||||||
nil: {count: 2},
|
nil: {count: 2},
|
||||||
user: {count: 2},
|
user: {count: 2},
|
||||||
user4: {count: 4, includesPrivate: true}}},
|
user4: {count: 4, includesPrivate: true},
|
||||||
|
}},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "mirror"), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "mirror"), expectedResults: expectedResults{
|
||||||
nil: {count: 1},
|
nil: {count: 1},
|
||||||
user: {count: 1},
|
user: {count: 1},
|
||||||
user4: {count: 2, includesPrivate: true}}},
|
user4: {count: 2, includesPrivate: true},
|
||||||
|
}},
|
||||||
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeCollaborative", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "collaborative"), expectedResults: expectedResults{
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeCollaborative", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "collaborative"), expectedResults: expectedResults{
|
||||||
nil: {count: 0},
|
nil: {count: 0},
|
||||||
user: {count: 1, includesPrivate: true},
|
user: {count: 1, includesPrivate: true},
|
||||||
user4: {count: 1, includesPrivate: true}}},
|
user4: {count: 1, includesPrivate: true},
|
||||||
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, testCase := range testCases {
|
for _, testCase := range testCases {
|
||||||
|
@ -464,7 +487,7 @@ func TestAPIRepoTransfer(t *testing.T) {
|
||||||
|
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
|
|
||||||
//create repo to move
|
// create repo to move
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}).(*user_model.User)
|
||||||
session := loginUser(t, user.Name)
|
session := loginUser(t, user.Name)
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
|
@ -480,7 +503,7 @@ func TestAPIRepoTransfer(t *testing.T) {
|
||||||
resp := session.MakeRequest(t, req, http.StatusCreated)
|
resp := session.MakeRequest(t, req, http.StatusCreated)
|
||||||
DecodeJSON(t, resp, apiRepo)
|
DecodeJSON(t, resp, apiRepo)
|
||||||
|
|
||||||
//start testing
|
// start testing
|
||||||
for _, testCase := range testCases {
|
for _, testCase := range testCases {
|
||||||
user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}).(*user_model.User)
|
user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}).(*user_model.User)
|
||||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
|
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
|
||||||
|
@ -493,13 +516,13 @@ func TestAPIRepoTransfer(t *testing.T) {
|
||||||
session.MakeRequest(t, req, testCase.expectedStatus)
|
session.MakeRequest(t, req, testCase.expectedStatus)
|
||||||
}
|
}
|
||||||
|
|
||||||
//cleanup
|
// cleanup
|
||||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
|
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}).(*repo_model.Repository)
|
||||||
_ = models.DeleteRepository(user, repo.OwnerID, repo.ID)
|
_ = models.DeleteRepository(user, repo.OwnerID, repo.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func transfer(t *testing.T) *repo_model.Repository {
|
func transfer(t *testing.T) *repo_model.Repository {
|
||||||
//create repo to move
|
// create repo to move
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
|
||||||
session := loginUser(t, user.Name)
|
session := loginUser(t, user.Name)
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
|
|
|
@ -155,5 +155,4 @@ func TestAPIRepoTopic(t *testing.T) {
|
||||||
// Test add a topic to repo with write access (requires repo admin access)
|
// Test add a topic to repo with write access (requires repo admin access)
|
||||||
req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user3.Name, repo3.Name, "topicName", token4)
|
req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user3.Name, repo3.Name, "topicName", token4)
|
||||||
session.MakeRequest(t, req, http.StatusForbidden)
|
session.MakeRequest(t, req, http.StatusForbidden)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,7 +22,7 @@ func TestUserHeatmap(t *testing.T) {
|
||||||
normalUsername := "user2"
|
normalUsername := "user2"
|
||||||
session := loginUser(t, adminUsername)
|
session := loginUser(t, adminUsername)
|
||||||
|
|
||||||
var fakeNow = time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local)
|
fakeNow := time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local)
|
||||||
timeutil.Set(fakeNow)
|
timeutil.Set(fakeNow)
|
||||||
defer timeutil.Unset()
|
defer timeutil.Unset()
|
||||||
|
|
||||||
|
|
|
@ -54,7 +54,7 @@ func TestUserOrgs(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) {
|
func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) {
|
||||||
var token = ""
|
token := ""
|
||||||
session := emptyTestSession(t)
|
session := emptyTestSession(t)
|
||||||
if len(userDoer) != 0 {
|
if len(userDoer) != 0 {
|
||||||
session = loginUser(t, userDoer)
|
session = loginUser(t, userDoer)
|
||||||
|
|
|
@ -32,7 +32,7 @@ func generateImg() bytes.Buffer {
|
||||||
func createAttachment(t *testing.T, session *TestSession, repoURL, filename string, buff bytes.Buffer, expectedStatus int) string {
|
func createAttachment(t *testing.T, session *TestSession, repoURL, filename string, buff bytes.Buffer, expectedStatus int) string {
|
||||||
body := &bytes.Buffer{}
|
body := &bytes.Buffer{}
|
||||||
|
|
||||||
//Setup multi-part
|
// Setup multi-part
|
||||||
writer := multipart.NewWriter(body)
|
writer := multipart.NewWriter(body)
|
||||||
part, err := writer.CreateFormFile("file", filename)
|
part, err := writer.CreateFormFile("file", filename)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
@ -86,7 +86,7 @@ func TestCreateIssueAttachment(t *testing.T) {
|
||||||
resp = session.MakeRequest(t, req, http.StatusFound)
|
resp = session.MakeRequest(t, req, http.StatusFound)
|
||||||
test.RedirectURL(resp) // check that redirect URL exists
|
test.RedirectURL(resp) // check that redirect URL exists
|
||||||
|
|
||||||
//Validate that attachment is available
|
// Validate that attachment is available
|
||||||
req = NewRequest(t, "GET", "/attachments/"+uuid)
|
req = NewRequest(t, "GET", "/attachments/"+uuid)
|
||||||
session.MakeRequest(t, req, http.StatusOK)
|
session.MakeRequest(t, req, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
@ -120,12 +120,12 @@ func TestGetAttachment(t *testing.T) {
|
||||||
}
|
}
|
||||||
for _, tc := range testCases {
|
for _, tc := range testCases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
//Write empty file to be available for response
|
// Write empty file to be available for response
|
||||||
if tc.createFile {
|
if tc.createFile {
|
||||||
_, err := storage.Attachments.Save(repo_model.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world"), -1)
|
_, err := storage.Attachments.Save(repo_model.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world"), -1)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
}
|
}
|
||||||
//Actual test
|
// Actual test
|
||||||
req := NewRequest(t, "GET", "/attachments/"+tc.uuid)
|
req := NewRequest(t, "GET", "/attachments/"+tc.uuid)
|
||||||
tc.session.MakeRequest(t, req, tc.want)
|
tc.session.MakeRequest(t, req, tc.want)
|
||||||
})
|
})
|
||||||
|
|
|
@ -58,7 +58,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) {
|
||||||
req := NewRequestf(b, "GET", "/api/v1/repos/%s/branches", repo.FullName())
|
req := NewRequestf(b, "GET", "/api/v1/repos/%s/branches", repo.FullName())
|
||||||
resp := session.MakeRequest(b, req, http.StatusOK)
|
resp := session.MakeRequest(b, req, http.StatusOK)
|
||||||
DecodeJSON(b, resp, &branches)
|
DecodeJSON(b, resp, &branches)
|
||||||
b.ResetTimer() //We measure from here
|
b.ResetTimer() // We measure from here
|
||||||
if len(branches) != 0 {
|
if len(branches) != 0 {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
req := NewRequestf(b, "GET", "/api/v1/repos/%s/commits?sha=%s", repo.FullName(), branches[i%len(branches)].Name)
|
req := NewRequestf(b, "GET", "/api/v1/repos/%s/commits?sha=%s", repo.FullName(), branches[i%len(branches)].Name)
|
||||||
|
|
|
@ -29,7 +29,8 @@ func Test_CmdKeys(t *testing.T) {
|
||||||
}{
|
}{
|
||||||
{"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""},
|
{"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""},
|
||||||
{"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""},
|
{"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""},
|
||||||
{"with_key",
|
{
|
||||||
|
"with_key",
|
||||||
[]string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="},
|
[]string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="},
|
||||||
false,
|
false,
|
||||||
"# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + util.ShellEscape(setting.CustomConf) + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,no-user-rc,restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n",
|
"# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + util.ShellEscape(setting.CustomConf) + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,no-user-rc,restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n",
|
||||||
|
@ -38,7 +39,7 @@ func Test_CmdKeys(t *testing.T) {
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
realStdout := os.Stdout //Backup Stdout
|
realStdout := os.Stdout // Backup Stdout
|
||||||
r, w, _ := os.Pipe()
|
r, w, _ := os.Pipe()
|
||||||
os.Stdout = w
|
os.Stdout = w
|
||||||
|
|
||||||
|
@ -56,7 +57,7 @@ func Test_CmdKeys(t *testing.T) {
|
||||||
if tt.expectedOutput != commandOutput {
|
if tt.expectedOutput != commandOutput {
|
||||||
t.Errorf("expectedOutput: %#v, commandOutput: %#v", tt.expectedOutput, commandOutput)
|
t.Errorf("expectedOutput: %#v, commandOutput: %#v", tt.expectedOutput, commandOutput)
|
||||||
}
|
}
|
||||||
//Restore stdout
|
// Restore stdout
|
||||||
os.Stdout = realStdout
|
os.Stdout = realStdout
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,7 +55,7 @@ func TestDumpRestore(t *testing.T) {
|
||||||
//
|
//
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
var opts = migrations.MigrateOptions{
|
opts := migrations.MigrateOptions{
|
||||||
GitServiceType: structs.GiteaService,
|
GitServiceType: structs.GiteaService,
|
||||||
Issues: true,
|
Issues: true,
|
||||||
Labels: true,
|
Labels: true,
|
||||||
|
@ -109,11 +109,11 @@ func TestDumpRestore(t *testing.T) {
|
||||||
|
|
||||||
beforeBytes, err := os.ReadFile(filepath.Join(d, "issue.yml"))
|
beforeBytes, err := os.ReadFile(filepath.Join(d, "issue.yml"))
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
var before = make([]*base.Issue, 0, 10)
|
before := make([]*base.Issue, 0, 10)
|
||||||
assert.NoError(t, yaml.Unmarshal(beforeBytes, &before))
|
assert.NoError(t, yaml.Unmarshal(beforeBytes, &before))
|
||||||
afterBytes, err := os.ReadFile(filepath.Join(newd, "issue.yml"))
|
afterBytes, err := os.ReadFile(filepath.Join(newd, "issue.yml"))
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
var after = make([]*base.Issue, 0, 10)
|
after := make([]*base.Issue, 0, 10)
|
||||||
assert.NoError(t, yaml.Unmarshal(afterBytes, &after))
|
assert.NoError(t, yaml.Unmarshal(afterBytes, &after))
|
||||||
|
|
||||||
assert.EqualValues(t, len(before), len(after))
|
assert.EqualValues(t, len(before), len(after))
|
||||||
|
|
|
@ -120,7 +120,6 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
|
||||||
}
|
}
|
||||||
|
|
||||||
func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *httptest.ResponseRecorder {
|
func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *httptest.ResponseRecorder {
|
||||||
|
|
||||||
// Get to the 'edit this file' page
|
// Get to the 'edit this file' page
|
||||||
req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath))
|
req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath))
|
||||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
|
@ -69,7 +69,7 @@ func TestEventSourceManagerRun(t *testing.T) {
|
||||||
DecodeJSON(t, resp, &apiNL)
|
DecodeJSON(t, resp, &apiNL)
|
||||||
assert.Len(t, apiNL, 2)
|
assert.Len(t, apiNL, 2)
|
||||||
|
|
||||||
lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" //946687801 <- only Notification 4 is in this filter ...
|
lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ...
|
||||||
req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token))
|
req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token))
|
||||||
session.MakeRequest(t, req, http.StatusResetContent)
|
session.MakeRequest(t, req, http.StatusResetContent)
|
||||||
|
|
||||||
|
|
|
@ -27,12 +27,11 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func withKeyFile(t *testing.T, keyname string, callback func(string)) {
|
func withKeyFile(t *testing.T, keyname string, callback func(string)) {
|
||||||
|
|
||||||
tmpDir, err := os.MkdirTemp("", "key-file")
|
tmpDir, err := os.MkdirTemp("", "key-file")
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
defer util.RemoveAll(tmpDir)
|
defer util.RemoveAll(tmpDir)
|
||||||
|
|
||||||
err = os.Chmod(tmpDir, 0700)
|
err = os.Chmod(tmpDir, 0o700)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
keyFile := filepath.Join(tmpDir, keyname)
|
keyFile := filepath.Join(tmpDir, keyname)
|
||||||
|
@ -40,10 +39,10 @@ func withKeyFile(t *testing.T, keyname string, callback func(string)) {
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
err = os.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+
|
err = os.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+
|
||||||
"ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0700)
|
"ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0o700)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
//Setup ssh wrapper
|
// Setup ssh wrapper
|
||||||
os.Setenv("GIT_SSH", path.Join(tmpDir, "ssh"))
|
os.Setenv("GIT_SSH", path.Join(tmpDir, "ssh"))
|
||||||
os.Setenv("GIT_SSH_COMMAND",
|
os.Setenv("GIT_SSH_COMMAND",
|
||||||
"ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i \""+keyFile+"\"")
|
"ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i \""+keyFile+"\"")
|
||||||
|
@ -103,7 +102,7 @@ func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...
|
||||||
}()
|
}()
|
||||||
|
|
||||||
go s.Serve(listener)
|
go s.Serve(listener)
|
||||||
//Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs)
|
// Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs)
|
||||||
|
|
||||||
callback(t, u)
|
callback(t, u)
|
||||||
}
|
}
|
||||||
|
@ -142,7 +141,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
|
||||||
// forcibly set default branch to master
|
// forcibly set default branch to master
|
||||||
_, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath)
|
_, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644))
|
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644))
|
||||||
assert.NoError(t, git.AddChanges(dstPath, true))
|
assert.NoError(t, git.AddChanges(dstPath, true))
|
||||||
signature := git.Signature{
|
signature := git.Signature{
|
||||||
Email: "test@example.com",
|
Email: "test@example.com",
|
||||||
|
|
|
@ -18,7 +18,7 @@ func TestGitSmartHTTP(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testGitSmartHTTP(t *testing.T, u *url.URL) {
|
func testGitSmartHTTP(t *testing.T, u *url.URL) {
|
||||||
var kases = []struct {
|
kases := []struct {
|
||||||
p string
|
p string
|
||||||
code int
|
code int
|
||||||
}{
|
}{
|
||||||
|
|
|
@ -32,8 +32,8 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
littleSize = 1024 //1ko
|
littleSize = 1024 // 1ko
|
||||||
bigSize = 128 * 1024 * 1024 //128Mo
|
bigSize = 128 * 1024 * 1024 // 128Mo
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGit(t *testing.T) {
|
func TestGit(t *testing.T) {
|
||||||
|
@ -96,15 +96,15 @@ func testGit(t *testing.T, u *url.URL) {
|
||||||
t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, perm.AccessModeRead))
|
t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, perm.AccessModeRead))
|
||||||
t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
|
t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
|
||||||
|
|
||||||
//Setup key the user ssh key
|
// Setup key the user ssh key
|
||||||
withKeyFile(t, keyname, func(keyFile string) {
|
withKeyFile(t, keyname, func(keyFile string) {
|
||||||
t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
|
t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
|
||||||
|
|
||||||
//Setup remote link
|
// Setup remote link
|
||||||
//TODO: get url from api
|
// TODO: get url from api
|
||||||
sshURL := createSSHUrl(sshContext.GitPath(), u)
|
sshURL := createSSHUrl(sshContext.GitPath(), u)
|
||||||
|
|
||||||
//Setup clone folder
|
// Setup clone folder
|
||||||
dstPath, err := os.MkdirTemp("", sshContext.Reponame)
|
dstPath, err := os.MkdirTemp("", sshContext.Reponame)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
defer util.RemoveAll(dstPath)
|
defer util.RemoveAll(dstPath)
|
||||||
|
@ -135,7 +135,6 @@ func ensureAnonymousClone(t *testing.T, u *url.URL) {
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
defer util.RemoveAll(dstLocalPath)
|
defer util.RemoveAll(dstLocalPath)
|
||||||
t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
|
t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
|
func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
|
||||||
|
@ -300,13 +299,13 @@ func lockFileTest(t *testing.T, filename, repoPath string) {
|
||||||
func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
|
func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
|
||||||
name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
|
name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
_, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push
|
_, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) // Push
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
return name
|
return name
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
|
func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
|
||||||
//Generate random file
|
// Generate random file
|
||||||
bufSize := 4 * 1024
|
bufSize := 4 * 1024
|
||||||
if bufSize > size {
|
if bufSize > size {
|
||||||
bufSize = size
|
bufSize = size
|
||||||
|
@ -339,7 +338,7 @@ func generateCommitWithNewData(size int, repoPath, email, fullName, prefix strin
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Commit
|
// Commit
|
||||||
// Now here we should explicitly allow lfs filters to run
|
// Now here we should explicitly allow lfs filters to run
|
||||||
globalArgs := allowLFSFilters()
|
globalArgs := allowLFSFilters()
|
||||||
err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
|
err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
|
||||||
|
@ -639,7 +638,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
|
||||||
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
|
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
|
||||||
|
|
||||||
t.Run("AddCommit", func(t *testing.T) {
|
t.Run("AddCommit", func(t *testing.T) {
|
||||||
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666)
|
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666)
|
||||||
if !assert.NoError(t, err) {
|
if !assert.NoError(t, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -713,7 +712,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("AddCommit2", func(t *testing.T) {
|
t.Run("AddCommit2", func(t *testing.T) {
|
||||||
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666)
|
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666)
|
||||||
if !assert.NoError(t, err) {
|
if !assert.NoError(t, err) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,7 +32,7 @@ func TestGPGGit(t *testing.T) {
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
defer util.RemoveAll(tmpDir)
|
defer util.RemoveAll(tmpDir)
|
||||||
|
|
||||||
err = os.Chmod(tmpDir, 0700)
|
err = os.Chmod(tmpDir, 0o700)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
oldGNUPGHome := os.Getenv("GNUPGHOME")
|
oldGNUPGHome := os.Getenv("GNUPGHOME")
|
||||||
|
@ -257,7 +257,6 @@ func TestGPGGit(t *testing.T) {
|
||||||
}
|
}
|
||||||
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
|
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
|
||||||
}))
|
}))
|
||||||
|
|
||||||
})
|
})
|
||||||
}, false)
|
}, false)
|
||||||
var pr api.PullRequest
|
var pr api.PullRequest
|
||||||
|
@ -321,7 +320,6 @@ func TestGPGGit(t *testing.T) {
|
||||||
assert.NotNil(t, branch.Commit.Verification)
|
assert.NotNil(t, branch.Commit.Verification)
|
||||||
assert.True(t, branch.Commit.Verification.Verified)
|
assert.True(t, branch.Commit.Verification.Verified)
|
||||||
}))
|
}))
|
||||||
|
|
||||||
})
|
})
|
||||||
}, false)
|
}, false)
|
||||||
}
|
}
|
||||||
|
|
|
@ -268,10 +268,10 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
|
||||||
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
||||||
}
|
}
|
||||||
for _, repoDir := range repoDirs {
|
for _, repoDir := range repoDirs {
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -395,7 +395,7 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
|
||||||
return session
|
return session
|
||||||
}
|
}
|
||||||
|
|
||||||
//token has to be unique this counter take care of
|
// token has to be unique this counter take care of
|
||||||
var tokenCounter int64
|
var tokenCounter int64
|
||||||
|
|
||||||
func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
|
func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
|
||||||
|
@ -564,10 +564,10 @@ func resetFixtures(t *testing.T) {
|
||||||
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
||||||
}
|
}
|
||||||
for _, repoDir := range repoDirs {
|
for _, repoDir := range repoDirs {
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -121,7 +121,6 @@ func TestNoLoginViewIssue(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content string) string {
|
func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content string) string {
|
||||||
|
|
||||||
req := NewRequest(t, "GET", path.Join(user, repo, "issues", "new"))
|
req := NewRequest(t, "GET", path.Join(user, repo, "issues", "new"))
|
||||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
||||||
|
@ -149,7 +148,6 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content
|
||||||
}
|
}
|
||||||
|
|
||||||
func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, status string) int64 {
|
func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, status string) int64 {
|
||||||
|
|
||||||
req := NewRequest(t, "GET", issueURL)
|
req := NewRequest(t, "GET", issueURL)
|
||||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
||||||
|
@ -244,7 +242,8 @@ func TestIssueCrossReference(t *testing.T) {
|
||||||
RefIssueID: issueRef.ID,
|
RefIssueID: issueRef.ID,
|
||||||
RefCommentID: 0,
|
RefCommentID: 0,
|
||||||
RefIsPull: false,
|
RefIsPull: false,
|
||||||
RefAction: references.XRefActionNone})
|
RefAction: references.XRefActionNone,
|
||||||
|
})
|
||||||
|
|
||||||
// Edit title, neuter ref
|
// Edit title, neuter ref
|
||||||
testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref")
|
testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref")
|
||||||
|
@ -254,7 +253,8 @@ func TestIssueCrossReference(t *testing.T) {
|
||||||
RefIssueID: issueRef.ID,
|
RefIssueID: issueRef.ID,
|
||||||
RefCommentID: 0,
|
RefCommentID: 0,
|
||||||
RefIsPull: false,
|
RefIsPull: false,
|
||||||
RefAction: references.XRefActionNeutered})
|
RefAction: references.XRefActionNeutered,
|
||||||
|
})
|
||||||
|
|
||||||
// Ref from issue content
|
// Ref from issue content
|
||||||
issueRefURL, issueRef = testIssueWithBean(t, "user2", 1, "TitleXRef", fmt.Sprintf("Description ref #%d", issueBase.Index))
|
issueRefURL, issueRef = testIssueWithBean(t, "user2", 1, "TitleXRef", fmt.Sprintf("Description ref #%d", issueBase.Index))
|
||||||
|
@ -264,7 +264,8 @@ func TestIssueCrossReference(t *testing.T) {
|
||||||
RefIssueID: issueRef.ID,
|
RefIssueID: issueRef.ID,
|
||||||
RefCommentID: 0,
|
RefCommentID: 0,
|
||||||
RefIsPull: false,
|
RefIsPull: false,
|
||||||
RefAction: references.XRefActionNone})
|
RefAction: references.XRefActionNone,
|
||||||
|
})
|
||||||
|
|
||||||
// Edit content, neuter ref
|
// Edit content, neuter ref
|
||||||
testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref")
|
testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref")
|
||||||
|
@ -274,7 +275,8 @@ func TestIssueCrossReference(t *testing.T) {
|
||||||
RefIssueID: issueRef.ID,
|
RefIssueID: issueRef.ID,
|
||||||
RefCommentID: 0,
|
RefCommentID: 0,
|
||||||
RefIsPull: false,
|
RefIsPull: false,
|
||||||
RefAction: references.XRefActionNeutered})
|
RefAction: references.XRefActionNeutered,
|
||||||
|
})
|
||||||
|
|
||||||
// Ref from a comment
|
// Ref from a comment
|
||||||
session := loginUser(t, "user2")
|
session := loginUser(t, "user2")
|
||||||
|
@ -285,7 +287,8 @@ func TestIssueCrossReference(t *testing.T) {
|
||||||
RefIssueID: issueRef.ID,
|
RefIssueID: issueRef.ID,
|
||||||
RefCommentID: commentID,
|
RefCommentID: commentID,
|
||||||
RefIsPull: false,
|
RefIsPull: false,
|
||||||
RefAction: references.XRefActionNone}
|
RefAction: references.XRefActionNone,
|
||||||
|
}
|
||||||
unittest.AssertExistsAndLoadBean(t, comment)
|
unittest.AssertExistsAndLoadBean(t, comment)
|
||||||
|
|
||||||
// Ref from a different repository
|
// Ref from a different repository
|
||||||
|
@ -296,7 +299,8 @@ func TestIssueCrossReference(t *testing.T) {
|
||||||
RefIssueID: issueRef.ID,
|
RefIssueID: issueRef.ID,
|
||||||
RefCommentID: 0,
|
RefCommentID: 0,
|
||||||
RefIsPull: false,
|
RefIsPull: false,
|
||||||
RefAction: references.XRefActionNone})
|
RefAction: references.XRefActionNone,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func testIssueWithBean(t *testing.T, user string, repoID int64, title, content string) (string, *models.Issue) {
|
func testIssueWithBean(t *testing.T, user string, repoID int64, title, content string) (string, *models.Issue) {
|
||||||
|
|
|
@ -29,13 +29,13 @@ func TestDetermineLocalEndpoint(t *testing.T) {
|
||||||
|
|
||||||
rootdotgit, _ := os.MkdirTemp("", "lfs_test")
|
rootdotgit, _ := os.MkdirTemp("", "lfs_test")
|
||||||
defer os.RemoveAll(rootdotgit)
|
defer os.RemoveAll(rootdotgit)
|
||||||
os.Mkdir(filepath.Join(rootdotgit, ".git"), 0700)
|
os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700)
|
||||||
|
|
||||||
lfsroot, _ := os.MkdirTemp("", "lfs_test")
|
lfsroot, _ := os.MkdirTemp("", "lfs_test")
|
||||||
defer os.RemoveAll(lfsroot)
|
defer os.RemoveAll(lfsroot)
|
||||||
|
|
||||||
// Test cases
|
// Test cases
|
||||||
var cases = []struct {
|
cases := []struct {
|
||||||
cloneurl string
|
cloneurl string
|
||||||
lfsurl string
|
lfsurl string
|
||||||
expected *url.URL
|
expected *url.URL
|
||||||
|
|
|
@ -20,7 +20,7 @@ import (
|
||||||
func TestLinksNoLogin(t *testing.T) {
|
func TestLinksNoLogin(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
|
|
||||||
var links = []string{
|
links := []string{
|
||||||
"/explore/repos",
|
"/explore/repos",
|
||||||
"/explore/repos?q=test&tab=",
|
"/explore/repos?q=test&tab=",
|
||||||
"/explore/users",
|
"/explore/users",
|
||||||
|
@ -49,7 +49,7 @@ func TestLinksNoLogin(t *testing.T) {
|
||||||
func TestRedirectsNoLogin(t *testing.T) {
|
func TestRedirectsNoLogin(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
|
|
||||||
var redirects = map[string]string{
|
redirects := map[string]string{
|
||||||
"/user2/repo1/commits/master": "/user2/repo1/commits/branch/master",
|
"/user2/repo1/commits/master": "/user2/repo1/commits/branch/master",
|
||||||
"/user2/repo1/src/master": "/user2/repo1/src/branch/master",
|
"/user2/repo1/src/master": "/user2/repo1/src/branch/master",
|
||||||
"/user2/repo1/src/master/file.txt": "/user2/repo1/src/branch/master/file.txt",
|
"/user2/repo1/src/master/file.txt": "/user2/repo1/src/branch/master/file.txt",
|
||||||
|
@ -67,7 +67,7 @@ func TestRedirectsNoLogin(t *testing.T) {
|
||||||
func TestNoLoginNotExist(t *testing.T) {
|
func TestNoLoginNotExist(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
|
|
||||||
var links = []string{
|
links := []string{
|
||||||
"/user5/repo4/projects",
|
"/user5/repo4/projects",
|
||||||
"/user5/repo4/projects/3",
|
"/user5/repo4/projects/3",
|
||||||
}
|
}
|
||||||
|
@ -79,7 +79,7 @@ func TestNoLoginNotExist(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testLinksAsUser(userName string, t *testing.T) {
|
func testLinksAsUser(userName string, t *testing.T) {
|
||||||
var links = []string{
|
links := []string{
|
||||||
"/explore/repos",
|
"/explore/repos",
|
||||||
"/explore/repos?q=test&tab=",
|
"/explore/repos?q=test&tab=",
|
||||||
"/explore/users",
|
"/explore/users",
|
||||||
|
@ -138,7 +138,7 @@ func testLinksAsUser(userName string, t *testing.T) {
|
||||||
var apiRepos []*api.Repository
|
var apiRepos []*api.Repository
|
||||||
DecodeJSON(t, respAPI, &apiRepos)
|
DecodeJSON(t, respAPI, &apiRepos)
|
||||||
|
|
||||||
var repoLinks = []string{
|
repoLinks := []string{
|
||||||
"",
|
"",
|
||||||
"/issues",
|
"/issues",
|
||||||
"/pulls",
|
"/pulls",
|
||||||
|
|
|
@ -74,10 +74,10 @@ func initMigrationTest(t *testing.T) func() {
|
||||||
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
||||||
}
|
}
|
||||||
for _, repoDir := range repoDirs {
|
for _, repoDir := range repoDirs {
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -315,6 +315,5 @@ func TestMigrations(t *testing.T) {
|
||||||
t.Run(fmt.Sprintf("Migrate-%s-%s", dialect, version), func(t *testing.T) {
|
t.Run(fmt.Sprintf("Migrate-%s-%s", dialect, version), func(t *testing.T) {
|
||||||
doMigrationTest(t, version)
|
doMigrationTest(t, version)
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -210,5 +210,4 @@ func TestNonasciiBranches(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
setDefaultBranch(t, session, user, repo, "master")
|
setDefaultBranch(t, session, user, repo, "master")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,8 +18,10 @@ import (
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
const privateActivityTestAdmin = "user1"
|
const (
|
||||||
const privateActivityTestUser = "user2"
|
privateActivityTestAdmin = "user1"
|
||||||
|
privateActivityTestUser = "user2"
|
||||||
|
)
|
||||||
|
|
||||||
// user3 is an organization so it is not usable here
|
// user3 is an organization so it is not usable here
|
||||||
const privateActivityTestOtherUser = "user4"
|
const privateActivityTestOtherUser = "user4"
|
||||||
|
|
|
@ -65,7 +65,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str
|
||||||
|
|
||||||
func TestPullMerge(t *testing.T) {
|
func TestPullMerge(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
|
hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
hookTasksLenBefore := len(hookTasks)
|
hookTasksLenBefore := len(hookTasks)
|
||||||
|
|
||||||
|
@ -87,7 +87,7 @@ func TestPullMerge(t *testing.T) {
|
||||||
|
|
||||||
func TestPullRebase(t *testing.T) {
|
func TestPullRebase(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
|
hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
hookTasksLenBefore := len(hookTasks)
|
hookTasksLenBefore := len(hookTasks)
|
||||||
|
|
||||||
|
@ -109,7 +109,7 @@ func TestPullRebase(t *testing.T) {
|
||||||
|
|
||||||
func TestPullRebaseMerge(t *testing.T) {
|
func TestPullRebaseMerge(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
|
hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
hookTasksLenBefore := len(hookTasks)
|
hookTasksLenBefore := len(hookTasks)
|
||||||
|
|
||||||
|
@ -131,7 +131,7 @@ func TestPullRebaseMerge(t *testing.T) {
|
||||||
|
|
||||||
func TestPullSquash(t *testing.T) {
|
func TestPullSquash(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
hookTasks, err := webhook.HookTasks(1, 1) //Retrieve previous hook number
|
hookTasks, err := webhook.HookTasks(1, 1) // Retrieve previous hook number
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
hookTasksLenBefore := len(hookTasks)
|
hookTasksLenBefore := len(hookTasks)
|
||||||
|
|
||||||
|
|
|
@ -23,12 +23,12 @@ import (
|
||||||
|
|
||||||
func TestAPIPullUpdate(t *testing.T) {
|
func TestAPIPullUpdate(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
//Create PR to test
|
// Create PR to test
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
|
||||||
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User)
|
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User)
|
||||||
pr := createOutdatedPR(t, user, org26)
|
pr := createOutdatedPR(t, user, org26)
|
||||||
|
|
||||||
//Test GetDiverging
|
// Test GetDiverging
|
||||||
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
|
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.EqualValues(t, 1, diffCount.Behind)
|
assert.EqualValues(t, 1, diffCount.Behind)
|
||||||
|
@ -41,7 +41,7 @@ func TestAPIPullUpdate(t *testing.T) {
|
||||||
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index)
|
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index)
|
||||||
session.MakeRequest(t, req, http.StatusOK)
|
session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
||||||
//Test GetDiverging after update
|
// Test GetDiverging after update
|
||||||
diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr)
|
diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.EqualValues(t, 0, diffCount.Behind)
|
assert.EqualValues(t, 0, diffCount.Behind)
|
||||||
|
@ -51,12 +51,12 @@ func TestAPIPullUpdate(t *testing.T) {
|
||||||
|
|
||||||
func TestAPIPullUpdateByRebase(t *testing.T) {
|
func TestAPIPullUpdateByRebase(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
//Create PR to test
|
// Create PR to test
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
|
||||||
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User)
|
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26}).(*user_model.User)
|
||||||
pr := createOutdatedPR(t, user, org26)
|
pr := createOutdatedPR(t, user, org26)
|
||||||
|
|
||||||
//Test GetDiverging
|
// Test GetDiverging
|
||||||
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
|
diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.EqualValues(t, 1, diffCount.Behind)
|
assert.EqualValues(t, 1, diffCount.Behind)
|
||||||
|
@ -69,7 +69,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
|
||||||
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index)
|
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index)
|
||||||
session.MakeRequest(t, req, http.StatusOK)
|
session.MakeRequest(t, req, http.StatusOK)
|
||||||
|
|
||||||
//Test GetDiverging after update
|
// Test GetDiverging after update
|
||||||
diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr)
|
diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.EqualValues(t, 0, diffCount.Behind)
|
assert.EqualValues(t, 0, diffCount.Behind)
|
||||||
|
@ -98,7 +98,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.NotEmpty(t, headRepo)
|
assert.NotEmpty(t, headRepo)
|
||||||
|
|
||||||
//create a commit on base Repo
|
// create a commit on base Repo
|
||||||
_, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, baseRepo, actor, &files_service.UpdateRepoFileOptions{
|
_, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, baseRepo, actor, &files_service.UpdateRepoFileOptions{
|
||||||
TreePath: "File_A",
|
TreePath: "File_A",
|
||||||
Message: "Add File A",
|
Message: "Add File A",
|
||||||
|
@ -121,7 +121,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
|
||||||
})
|
})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
//create a commit on head Repo
|
// create a commit on head Repo
|
||||||
_, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, headRepo, actor, &files_service.UpdateRepoFileOptions{
|
_, err = files_service.CreateOrUpdateRepoFile(git.DefaultContext, headRepo, actor, &files_service.UpdateRepoFileOptions{
|
||||||
TreePath: "File_B",
|
TreePath: "File_B",
|
||||||
Message: "Add File on PR branch",
|
Message: "Add File on PR branch",
|
||||||
|
@ -144,7 +144,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *models.Pul
|
||||||
})
|
})
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
//create Pull
|
// create Pull
|
||||||
pullIssue := &models.Issue{
|
pullIssue := &models.Issue{
|
||||||
RepoID: baseRepo.ID,
|
RepoID: baseRepo.ID,
|
||||||
Title: "Test Pull -to-update-",
|
Title: "Test Pull -to-update-",
|
||||||
|
|
|
@ -18,7 +18,6 @@ import (
|
||||||
|
|
||||||
func TestRepoActivity(t *testing.T) {
|
func TestRepoActivity(t *testing.T) {
|
||||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||||
|
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
|
|
||||||
// Create PRs (1 merged & 2 proposed)
|
// Create PRs (1 merged & 2 proposed)
|
||||||
|
|
|
@ -71,12 +71,12 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) {
|
||||||
assert.True(t, sel.HasClass(class))
|
assert.True(t, sel.HasClass(class))
|
||||||
}
|
}
|
||||||
|
|
||||||
//By SHA
|
// By SHA
|
||||||
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/statuses")
|
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/statuses")
|
||||||
reqOne := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/status")
|
reqOne := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/status")
|
||||||
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
|
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
|
||||||
|
|
||||||
//By Ref
|
// By Ref
|
||||||
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses")
|
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses")
|
||||||
reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/status")
|
reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/status")
|
||||||
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
|
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
|
||||||
|
|
|
@ -399,7 +399,7 @@ func TestCreateOrUpdateRepoFileErrors(t *testing.T) {
|
||||||
|
|
||||||
t.Run("create file that already exists", func(t *testing.T) {
|
t.Run("create file that already exists", func(t *testing.T) {
|
||||||
opts := getCreateRepoFileOptions(repo)
|
opts := getCreateRepoFileOptions(repo)
|
||||||
opts.TreePath = "README.md" //already exists
|
opts.TreePath = "README.md" // already exists
|
||||||
fileResponse, err := files_service.CreateOrUpdateRepoFile(git.DefaultContext, repo, doer, opts)
|
fileResponse, err := files_service.CreateOrUpdateRepoFile(git.DefaultContext, repo, doer, opts)
|
||||||
assert.Nil(t, fileResponse)
|
assert.Nil(t, fileResponse)
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
|
|
|
@ -77,7 +77,6 @@ func TestSettingShowUserEmailProfile(t *testing.T) {
|
||||||
htmlDoc.doc.Find(".user.profile").Text(),
|
htmlDoc.doc.Find(".user.profile").Text(),
|
||||||
"user2@example.com",
|
"user2@example.com",
|
||||||
)
|
)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSettingLandingPage(t *testing.T) {
|
func TestSettingLandingPage(t *testing.T) {
|
||||||
|
|
|
@ -28,7 +28,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin
|
||||||
|
|
||||||
func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) {
|
func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) {
|
||||||
return func(t *testing.T) {
|
return func(t *testing.T) {
|
||||||
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0644))
|
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644))
|
||||||
assert.NoError(t, git.AddChanges(dstPath, true))
|
assert.NoError(t, git.AddChanges(dstPath, true))
|
||||||
signature := git.Signature{
|
signature := git.Signature{
|
||||||
Email: "test@example.com",
|
Email: "test@example.com",
|
||||||
|
@ -67,7 +67,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) {
|
||||||
|
|
||||||
t.Run("InitTestRepository", doGitInitTestRepository(dstPath))
|
t.Run("InitTestRepository", doGitInitTestRepository(dstPath))
|
||||||
|
|
||||||
//Setup remote link
|
// Setup remote link
|
||||||
sshURL := createSSHUrl(ctx.GitPath(), u)
|
sshURL := createSSHUrl(ctx.GitPath(), u)
|
||||||
|
|
||||||
t.Run("AddRemote", doGitAddRemote(dstPath, "origin", sshURL))
|
t.Run("AddRemote", doGitAddRemote(dstPath, "origin", sshURL))
|
||||||
|
|
|
@ -185,7 +185,7 @@ func (log *TestLogger) Init(config string) error {
|
||||||
func (log *TestLogger) Flush() {
|
func (log *TestLogger) Flush() {
|
||||||
}
|
}
|
||||||
|
|
||||||
//ReleaseReopen does nothing
|
// ReleaseReopen does nothing
|
||||||
func (log *TestLogger) ReleaseReopen() error {
|
func (log *TestLogger) ReleaseReopen() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,15 +19,16 @@ func TestViewTimetrackingControls(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
session := loginUser(t, "user2")
|
session := loginUser(t, "user2")
|
||||||
testViewTimetrackingControls(t, session, "user2", "repo1", "1", true)
|
testViewTimetrackingControls(t, session, "user2", "repo1", "1", true)
|
||||||
//user2/repo1
|
// user2/repo1
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNotViewTimetrackingControls(t *testing.T) {
|
func TestNotViewTimetrackingControls(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
session := loginUser(t, "user5")
|
session := loginUser(t, "user5")
|
||||||
testViewTimetrackingControls(t, session, "user2", "repo1", "1", false)
|
testViewTimetrackingControls(t, session, "user2", "repo1", "1", false)
|
||||||
//user2/repo1
|
// user2/repo1
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestViewTimetrackingControlsDisabled(t *testing.T) {
|
func TestViewTimetrackingControlsDisabled(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
session := loginUser(t, "user2")
|
session := loginUser(t, "user2")
|
||||||
|
|
|
@ -42,7 +42,7 @@ func TestUserAvatar(t *testing.T) {
|
||||||
|
|
||||||
body := &bytes.Buffer{}
|
body := &bytes.Buffer{}
|
||||||
|
|
||||||
//Setup multi-part
|
// Setup multi-part
|
||||||
writer := multipart.NewWriter(body)
|
writer := multipart.NewWriter(body)
|
||||||
writer.WriteField("source", "local")
|
writer.WriteField("source", "local")
|
||||||
part, err := writer.CreateFormFile("avatar", "avatar-for-testuseravatar.png")
|
part, err := writer.CreateFormFile("avatar", "avatar-for-testuseravatar.png")
|
||||||
|
|
|
@ -119,15 +119,15 @@ func TestRenameReservedUsername(t *testing.T) {
|
||||||
|
|
||||||
func TestExportUserGPGKeys(t *testing.T) {
|
func TestExportUserGPGKeys(t *testing.T) {
|
||||||
defer prepareTestEnv(t)()
|
defer prepareTestEnv(t)()
|
||||||
//Export empty key list
|
// Export empty key list
|
||||||
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||||
|
|
||||||
|
|
||||||
=twTO
|
=twTO
|
||||||
-----END PGP PUBLIC KEY BLOCK-----
|
-----END PGP PUBLIC KEY BLOCK-----
|
||||||
`)
|
`)
|
||||||
//Import key
|
// Import key
|
||||||
//User1 <user1@example.com>
|
// User1 <user1@example.com>
|
||||||
session := loginUser(t, "user1")
|
session := loginUser(t, "user1")
|
||||||
token := getTokenForLoggedInUser(t, session)
|
token := getTokenForLoggedInUser(t, session)
|
||||||
testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
testCreateGPGKey(t, session.MakeRequest, token, http.StatusCreated, `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||||
|
@ -161,7 +161,7 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH
|
||||||
=DDXw
|
=DDXw
|
||||||
-----END PGP PUBLIC KEY BLOCK-----
|
-----END PGP PUBLIC KEY BLOCK-----
|
||||||
`)
|
`)
|
||||||
//Export new key
|
// Export new key
|
||||||
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||||
|
|
||||||
xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo
|
xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo
|
||||||
|
@ -200,6 +200,6 @@ func testExportUserGPGKeys(t *testing.T, user, expected string) {
|
||||||
t.Logf("Testing username %s export gpg keys", user)
|
t.Logf("Testing username %s export gpg keys", user)
|
||||||
req := NewRequest(t, "GET", "/"+user+".gpg")
|
req := NewRequest(t, "GET", "/"+user+".gpg")
|
||||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||||
//t.Log(resp.Body.String())
|
// t.Log(resp.Body.String())
|
||||||
assert.Equal(t, expected, resp.Body.String())
|
assert.Equal(t, expected, resp.Body.String())
|
||||||
}
|
}
|
||||||
|
|
2
main.go
2
main.go
|
@ -186,7 +186,7 @@ DEFAULT CONFIGURATION:
|
||||||
}
|
}
|
||||||
|
|
||||||
func formatBuiltWith() string {
|
func formatBuiltWith() string {
|
||||||
var version = runtime.Version()
|
version := runtime.Version()
|
||||||
if len(MakeVersion) > 0 {
|
if len(MakeVersion) > 0 {
|
||||||
version = MakeVersion + ", " + runtime.Version()
|
version = MakeVersion + ", " + runtime.Version()
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,9 +12,9 @@ import (
|
||||||
|
|
||||||
"code.gitea.io/gitea/models/db"
|
"code.gitea.io/gitea/models/db"
|
||||||
"code.gitea.io/gitea/modules/timeutil"
|
"code.gitea.io/gitea/modules/timeutil"
|
||||||
"xorm.io/xorm"
|
|
||||||
|
|
||||||
"github.com/duo-labs/webauthn/webauthn"
|
"github.com/duo-labs/webauthn/webauthn"
|
||||||
|
"xorm.io/xorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrWebAuthnCredentialNotExist represents a "ErrWebAuthnCRedentialNotExist" kind of error.
|
// ErrWebAuthnCredentialNotExist represents a "ErrWebAuthnCRedentialNotExist" kind of error.
|
||||||
|
@ -30,14 +30,14 @@ func (err ErrWebAuthnCredentialNotExist) Error() string {
|
||||||
return fmt.Sprintf("WebAuthn credential does not exist [credential_id: %s]", err.CredentialID)
|
return fmt.Sprintf("WebAuthn credential does not exist [credential_id: %s]", err.CredentialID)
|
||||||
}
|
}
|
||||||
|
|
||||||
//IsErrWebAuthnCredentialNotExist checks if an error is a ErrWebAuthnCredentialNotExist.
|
// IsErrWebAuthnCredentialNotExist checks if an error is a ErrWebAuthnCredentialNotExist.
|
||||||
func IsErrWebAuthnCredentialNotExist(err error) bool {
|
func IsErrWebAuthnCredentialNotExist(err error) bool {
|
||||||
_, ok := err.(ErrWebAuthnCredentialNotExist)
|
_, ok := err.(ErrWebAuthnCredentialNotExist)
|
||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
//WebAuthnCredential represents the WebAuthn credential data for a public-key
|
// WebAuthnCredential represents the WebAuthn credential data for a public-key
|
||||||
//credential conformant to WebAuthn Level 1
|
// credential conformant to WebAuthn Level 1
|
||||||
type WebAuthnCredential struct {
|
type WebAuthnCredential struct {
|
||||||
ID int64 `xorm:"pk autoincr"`
|
ID int64 `xorm:"pk autoincr"`
|
||||||
Name string
|
Name string
|
||||||
|
@ -109,7 +109,7 @@ func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
|
||||||
return creds
|
return creds
|
||||||
}
|
}
|
||||||
|
|
||||||
//GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user
|
// GetWebAuthnCredentialsByUID returns all WebAuthn credentials of the given user
|
||||||
func GetWebAuthnCredentialsByUID(uid int64) (WebAuthnCredentialList, error) {
|
func GetWebAuthnCredentialsByUID(uid int64) (WebAuthnCredentialList, error) {
|
||||||
return getWebAuthnCredentialsByUID(db.DefaultContext, uid)
|
return getWebAuthnCredentialsByUID(db.DefaultContext, uid)
|
||||||
}
|
}
|
||||||
|
@ -119,7 +119,7 @@ func getWebAuthnCredentialsByUID(ctx context.Context, uid int64) (WebAuthnCreden
|
||||||
return creds, db.GetEngine(ctx).Where("user_id = ?", uid).Find(&creds)
|
return creds, db.GetEngine(ctx).Where("user_id = ?", uid).Find(&creds)
|
||||||
}
|
}
|
||||||
|
|
||||||
//ExistsWebAuthnCredentialsForUID returns if the given user has credentials
|
// ExistsWebAuthnCredentialsForUID returns if the given user has credentials
|
||||||
func ExistsWebAuthnCredentialsForUID(uid int64) (bool, error) {
|
func ExistsWebAuthnCredentialsForUID(uid int64) (bool, error) {
|
||||||
return existsWebAuthnCredentialsByUID(db.DefaultContext, uid)
|
return existsWebAuthnCredentialsByUID(db.DefaultContext, uid)
|
||||||
}
|
}
|
||||||
|
@ -211,7 +211,7 @@ func deleteCredential(ctx context.Context, id, userID int64) (bool, error) {
|
||||||
return had > 0, err
|
return had > 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
//WebAuthnCredentials implementns the webauthn.User interface
|
// WebAuthnCredentials implementns the webauthn.User interface
|
||||||
func WebAuthnCredentials(userID int64) ([]webauthn.Credential, error) {
|
func WebAuthnCredentials(userID int64) ([]webauthn.Credential, error) {
|
||||||
dbCreds, err := GetWebAuthnCredentialsByUID(userID)
|
dbCreds, err := GetWebAuthnCredentialsByUID(userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -175,12 +175,12 @@ func generateEmailAvatarLink(email string, size int, final bool) string {
|
||||||
return DefaultAvatarLink()
|
return DefaultAvatarLink()
|
||||||
}
|
}
|
||||||
|
|
||||||
//GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}")
|
// GenerateEmailAvatarFastLink returns a avatar link (fast, the link may be a delegated one: "/avatar/${hash}")
|
||||||
func GenerateEmailAvatarFastLink(email string, size int) string {
|
func GenerateEmailAvatarFastLink(email string, size int) string {
|
||||||
return generateEmailAvatarLink(email, size, false)
|
return generateEmailAvatarLink(email, size, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
//GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow)
|
// GenerateEmailAvatarFinalLink returns a avatar final link (maybe slow)
|
||||||
func GenerateEmailAvatarFinalLink(email string, size int) string {
|
func GenerateEmailAvatarFinalLink(email string, size int) string {
|
||||||
return generateEmailAvatarLink(email, size, true)
|
return generateEmailAvatarLink(email, size, true)
|
||||||
}
|
}
|
||||||
|
|
|
@ -240,7 +240,6 @@ func FixIssueLabelWithOutsideLabels() (int64, error) {
|
||||||
WHERE
|
WHERE
|
||||||
(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)
|
(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)
|
||||||
) AS il_too )`)
|
) AS il_too )`)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
|
@ -121,7 +121,7 @@ func newXORMEngine() (*xorm.Engine, error) {
|
||||||
return engine, nil
|
return engine, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//SyncAllTables sync the schemas of all tables, is required by unit test code
|
// SyncAllTables sync the schemas of all tables, is required by unit test code
|
||||||
func SyncAllTables() error {
|
func SyncAllTables() error {
|
||||||
return x.StoreEngine("InnoDB").Sync2(tables...)
|
return x.StoreEngine("InnoDB").Sync2(tables...)
|
||||||
}
|
}
|
||||||
|
|
|
@ -394,7 +394,6 @@ func TestIssue_InsertIssue(t *testing.T) {
|
||||||
issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
|
issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
|
||||||
_, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue))
|
_, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue))
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIssue_ResolveMentions(t *testing.T) {
|
func TestIssue_ResolveMentions(t *testing.T) {
|
||||||
|
|
|
@ -155,7 +155,6 @@ func FetchIssueContentHistoryList(dbCtx context.Context, issueID, commentID int6
|
||||||
Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}).
|
Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}).
|
||||||
OrderBy("edited_unix DESC").
|
OrderBy("edited_unix DESC").
|
||||||
Find(&res)
|
Find(&res)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("can not fetch issue content history list. err=%v", err)
|
log.Error("can not fetch issue content history list. err=%v", err)
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|
|
@ -209,7 +209,7 @@ func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int6
|
||||||
func IterateLFS(f func(mo *LFSMetaObject) error) error {
|
func IterateLFS(f func(mo *LFSMetaObject) error) error {
|
||||||
var start int
|
var start int
|
||||||
const batchSize = 100
|
const batchSize = 100
|
||||||
var e = db.GetEngine(db.DefaultContext)
|
e := db.GetEngine(db.DefaultContext)
|
||||||
for {
|
for {
|
||||||
mos := make([]*LFSMetaObject, 0, batchSize)
|
mos := make([]*LFSMetaObject, 0, batchSize)
|
||||||
if err := e.Limit(batchSize, start).Find(&mos); err != nil {
|
if err := e.Limit(batchSize, start).Find(&mos); err != nil {
|
||||||
|
|
|
@ -45,7 +45,7 @@ func assertCreateIssues(t *testing.T, reponame string, isPull bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
title := "issuetitle1"
|
title := "issuetitle1"
|
||||||
var is = &Issue{
|
is := &Issue{
|
||||||
RepoID: repo.ID,
|
RepoID: repo.ID,
|
||||||
MilestoneID: milestone.ID,
|
MilestoneID: milestone.ID,
|
||||||
Repo: repo,
|
Repo: repo,
|
||||||
|
@ -130,7 +130,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
|
||||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}).(*repo_model.Repository)
|
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}).(*repo_model.Repository)
|
||||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
|
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
|
||||||
|
|
||||||
var i = &Issue{
|
i := &Issue{
|
||||||
RepoID: repo.ID,
|
RepoID: repo.ID,
|
||||||
Repo: repo,
|
Repo: repo,
|
||||||
Title: "title1",
|
Title: "title1",
|
||||||
|
@ -140,7 +140,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
|
||||||
Poster: owner,
|
Poster: owner,
|
||||||
}
|
}
|
||||||
|
|
||||||
var p = &PullRequest{
|
p := &PullRequest{
|
||||||
Issue: i,
|
Issue: i,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -219,10 +219,10 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En
|
||||||
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
||||||
}
|
}
|
||||||
for _, repoDir := range repoDirs {
|
for _, repoDir := range repoDirs {
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -170,7 +170,7 @@ func (log *TestLogger) Init(config string) error {
|
||||||
func (log *TestLogger) Flush() {
|
func (log *TestLogger) Flush() {
|
||||||
}
|
}
|
||||||
|
|
||||||
//ReleaseReopen does nothing
|
// ReleaseReopen does nothing
|
||||||
func (log *TestLogger) ReleaseReopen() error {
|
func (log *TestLogger) ReleaseReopen() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -124,5 +124,4 @@ func Test_removeInvalidLabels(t *testing.T) {
|
||||||
t.Errorf("IssueLabel[%d] was deleted but should have remained", id)
|
t.Errorf("IssueLabel[%d] was deleted but should have remained", id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -85,5 +85,4 @@ func Test_deleteOrphanedIssueLabels(t *testing.T) {
|
||||||
pre := preMigration[id]
|
pre := preMigration[id]
|
||||||
assert.Equal(t, pre, post, "migration changed issueLabel %d", id)
|
assert.Equal(t, pre, post, "migration changed issueLabel %d", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -38,7 +38,7 @@ func Test_addPrimaryEmail2EmailAddress(t *testing.T) {
|
||||||
IsPrimary bool `xorm:"DEFAULT(false) NOT NULL"`
|
IsPrimary bool `xorm:"DEFAULT(false) NOT NULL"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var users = make([]User, 0, 20)
|
users := make([]User, 0, 20)
|
||||||
err = x.Find(&users)
|
err = x.Find(&users)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
|
|
@ -37,10 +37,10 @@ func Test_addIssueResourceIndexTable(t *testing.T) {
|
||||||
MaxIndex int64 `xorm:"index"`
|
MaxIndex int64 `xorm:"index"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var start = 0
|
start := 0
|
||||||
const batchSize = 1000
|
const batchSize = 1000
|
||||||
for {
|
for {
|
||||||
var indexes = make([]ResourceIndex, 0, batchSize)
|
indexes := make([]ResourceIndex, 0, batchSize)
|
||||||
err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes)
|
err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
|
|
@ -26,7 +26,6 @@ func (ls *LoginSourceOriginalV189) TableName() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_unwrapLDAPSourceCfg(t *testing.T) {
|
func Test_unwrapLDAPSourceCfg(t *testing.T) {
|
||||||
|
|
||||||
// Prepare and load the testing database
|
// Prepare and load the testing database
|
||||||
x, deferable := prepareTestEnv(t, 0, new(LoginSourceOriginalV189))
|
x, deferable := prepareTestEnv(t, 0, new(LoginSourceOriginalV189))
|
||||||
if x == nil || t.Failed() {
|
if x == nil || t.Failed() {
|
||||||
|
@ -80,5 +79,4 @@ func Test_unwrapLDAPSourceCfg(t *testing.T) {
|
||||||
assert.EqualValues(t, source.ID%2 == 0, source.IsActive, "unwrapLDAPSourceCfg failed for %d", source.ID)
|
assert.EqualValues(t, source.ID%2 == 0, source.IsActive, "unwrapLDAPSourceCfg failed for %d", source.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func alterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error {
|
func alterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error {
|
||||||
|
|
||||||
sess := x.NewSession()
|
sess := x.NewSession()
|
||||||
defer sess.Close()
|
defer sess.Close()
|
||||||
if err := sess.Begin(); err != nil {
|
if err := sess.Begin(); err != nil {
|
||||||
|
|
|
@ -40,10 +40,10 @@ func Test_addTableCommitStatusIndex(t *testing.T) {
|
||||||
MaxIndex int64 `xorm:"index"`
|
MaxIndex int64 `xorm:"index"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var start = 0
|
start := 0
|
||||||
const batchSize = 1000
|
const batchSize = 1000
|
||||||
for {
|
for {
|
||||||
var indexes = make([]CommitStatusIndex, 0, batchSize)
|
indexes := make([]CommitStatusIndex, 0, batchSize)
|
||||||
err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
|
err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
|
|
@ -16,7 +16,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func addWebAuthnCred(x *xorm.Engine) error {
|
func addWebAuthnCred(x *xorm.Engine) error {
|
||||||
|
|
||||||
// Create webauthnCredential table
|
// Create webauthnCredential table
|
||||||
type webauthnCredential struct {
|
type webauthnCredential struct {
|
||||||
ID int64 `xorm:"pk autoincr"`
|
ID int64 `xorm:"pk autoincr"`
|
||||||
|
|
|
@ -12,7 +12,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func useBase32HexForCredIDInWebAuthnCredential(x *xorm.Engine) error {
|
func useBase32HexForCredIDInWebAuthnCredential(x *xorm.Engine) error {
|
||||||
|
|
||||||
// Create webauthnCredential table
|
// Create webauthnCredential table
|
||||||
type webauthnCredential struct {
|
type webauthnCredential struct {
|
||||||
ID int64 `xorm:"pk autoincr"`
|
ID int64 `xorm:"pk autoincr"`
|
||||||
|
|
|
@ -718,7 +718,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("listDeployKeys: %v", err)
|
return fmt.Errorf("listDeployKeys: %v", err)
|
||||||
}
|
}
|
||||||
var needRewriteKeysFile = len(deployKeys) > 0
|
needRewriteKeysFile := len(deployKeys) > 0
|
||||||
for _, dKey := range deployKeys {
|
for _, dKey := range deployKeys {
|
||||||
if err := DeleteDeployKey(ctx, doer, dKey.ID); err != nil {
|
if err := DeleteDeployKey(ctx, doer, dKey.ID); err != nil {
|
||||||
return fmt.Errorf("deleteDeployKeys: %v", err)
|
return fmt.Errorf("deleteDeployKeys: %v", err)
|
||||||
|
@ -844,7 +844,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var lfsPaths = make([]string, 0, len(lfsObjects))
|
lfsPaths := make([]string, 0, len(lfsObjects))
|
||||||
for _, v := range lfsObjects {
|
for _, v := range lfsObjects {
|
||||||
count, err := sess.Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}})
|
count, err := sess.Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -867,7 +867,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var archivePaths = make([]string, 0, len(archives))
|
archivePaths := make([]string, 0, len(archives))
|
||||||
for _, v := range archives {
|
for _, v := range archives {
|
||||||
p, _ := v.RelativePath()
|
p, _ := v.RelativePath()
|
||||||
archivePaths = append(archivePaths, p)
|
archivePaths = append(archivePaths, p)
|
||||||
|
@ -893,7 +893,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var newAttachmentPaths = make([]string, 0, len(newAttachments))
|
newAttachmentPaths := make([]string, 0, len(newAttachments))
|
||||||
for _, attach := range newAttachments {
|
for _, attach := range newAttachments {
|
||||||
newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
|
newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
|
||||||
}
|
}
|
||||||
|
|
|
@ -90,7 +90,7 @@ type FindRepoArchiversOption struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (opts FindRepoArchiversOption) toConds() builder.Cond {
|
func (opts FindRepoArchiversOption) toConds() builder.Cond {
|
||||||
var cond = builder.NewCond()
|
cond := builder.NewCond()
|
||||||
if opts.OlderThan > 0 {
|
if opts.OlderThan > 0 {
|
||||||
cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-opts.OlderThan).Unix()})
|
cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-opts.OlderThan).Unix()})
|
||||||
}
|
}
|
||||||
|
@ -99,7 +99,7 @@ func (opts FindRepoArchiversOption) toConds() builder.Cond {
|
||||||
|
|
||||||
// FindRepoArchives find repo archivers
|
// FindRepoArchives find repo archivers
|
||||||
func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) {
|
func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) {
|
||||||
var archivers = make([]*RepoArchiver, 0, opts.PageSize)
|
archivers := make([]*RepoArchiver, 0, opts.PageSize)
|
||||||
start, limit := opts.GetSkipTake()
|
start, limit := opts.GetSkipTake()
|
||||||
err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).
|
err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).
|
||||||
Asc("created_unix").
|
Asc("created_unix").
|
||||||
|
|
|
@ -241,7 +241,7 @@ func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...str
|
||||||
|
|
||||||
// UpdateAttachmentCtx updates the given attachment in database
|
// UpdateAttachmentCtx updates the given attachment in database
|
||||||
func UpdateAttachmentCtx(ctx context.Context, atta *Attachment) error {
|
func UpdateAttachmentCtx(ctx context.Context, atta *Attachment) error {
|
||||||
var sess = db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
|
sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
|
||||||
if atta.ID != 0 && atta.UUID == "" {
|
if atta.ID != 0 && atta.UUID == "" {
|
||||||
sess = sess.ID(atta.ID)
|
sess = sess.ID(atta.ID)
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -17,10 +17,8 @@ import (
|
||||||
"xorm.io/xorm"
|
"xorm.io/xorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
// ErrMirrorNotExist mirror does not exist error
|
||||||
// ErrMirrorNotExist mirror does not exist error
|
var ErrMirrorNotExist = errors.New("Mirror does not exist")
|
||||||
ErrMirrorNotExist = errors.New("Mirror does not exist")
|
|
||||||
)
|
|
||||||
|
|
||||||
// RemoteMirrorer defines base methods for pull/push mirrors.
|
// RemoteMirrorer defines base methods for pull/push mirrors.
|
||||||
type RemoteMirrorer interface {
|
type RemoteMirrorer interface {
|
||||||
|
|
|
@ -15,10 +15,8 @@ import (
|
||||||
"xorm.io/xorm"
|
"xorm.io/xorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
// ErrPushMirrorNotExist mirror does not exist error
|
||||||
// ErrPushMirrorNotExist mirror does not exist error
|
var ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
|
||||||
ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
|
|
||||||
)
|
|
||||||
|
|
||||||
// PushMirror represents mirror information of a repository.
|
// PushMirror represents mirror information of a repository.
|
||||||
type PushMirror struct {
|
type PushMirror struct {
|
||||||
|
|
|
@ -199,5 +199,4 @@ func TestDismissReview(t *testing.T) {
|
||||||
assert.False(t, rejectReviewExample.Dismissed)
|
assert.False(t, rejectReviewExample.Dismissed)
|
||||||
assert.False(t, requestReviewExample.Dismissed)
|
assert.False(t, requestReviewExample.Dismissed)
|
||||||
assert.True(t, approveReviewExample.Dismissed)
|
assert.True(t, approveReviewExample.Dismissed)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -117,10 +117,10 @@ func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) {
|
||||||
fatalTestError("unable to read the new repo root: %v\n", err)
|
fatalTestError("unable to read the new repo root: %v\n", err)
|
||||||
}
|
}
|
||||||
for _, repoDir := range repoDirs {
|
for _, repoDir := range repoDirs {
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -182,10 +182,10 @@ func PrepareTestEnv(t testing.TB) {
|
||||||
repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
|
repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
for _, repoDir := range repoDirs {
|
for _, repoDir := range repoDirs {
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
|
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -21,10 +21,8 @@ import (
|
||||||
"xorm.io/builder"
|
"xorm.io/builder"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
// ErrEmailNotActivated e-mail address has not been activated error
|
||||||
// ErrEmailNotActivated e-mail address has not been activated error
|
var ErrEmailNotActivated = errors.New("E-mail address has not been activated")
|
||||||
ErrEmailNotActivated = errors.New("E-mail address has not been activated")
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrEmailInvalid represents an error where the email address does not comply with RFC 5322
|
// ErrEmailInvalid represents an error where the email address does not comply with RFC 5322
|
||||||
type ErrEmailInvalid struct {
|
type ErrEmailInvalid struct {
|
||||||
|
|
|
@ -26,7 +26,6 @@ func TestKeygen(t *testing.T) {
|
||||||
|
|
||||||
assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv)
|
assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv)
|
||||||
assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub)
|
assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSignUsingKeys(t *testing.T) {
|
func TestSignUsingKeys(t *testing.T) {
|
||||||
|
|
|
@ -12,8 +12,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// DBStore can be used to store app state items in local filesystem
|
// DBStore can be used to store app state items in local filesystem
|
||||||
type DBStore struct {
|
type DBStore struct{}
|
||||||
}
|
|
||||||
|
|
||||||
// Get reads the state item
|
// Get reads the state item
|
||||||
func (f *DBStore) Get(item StateItem) error {
|
func (f *DBStore) Get(item StateItem) error {
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue