mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
test: consolidate Go tests (#39962)
Consolidate all Go tests. Coverage is identical to before. Go tests are around 5% faster while being 7% smaller. No non-test code is touched.
This commit is contained in:
1 parent
ce7364e215
commit
8abda62312
388 files changed
+18344
-29495
No files matched your search
@@ -42,27 +42,19 @@ func TestDeriveEnumName_miss(t *testing.T) {
|
||||
func TestExtractSharedEnums_usesASTMap(t *testing.T) {
|
||||
doc := &openapi3.T{
|
||||
Components: &openapi3.Components{
|
||||
Schemas: openapi3.Schemas{
|
||||
"A": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"object"},
|
||||
Properties: openapi3.Schemas{
|
||||
"color": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"string"},
|
||||
Enum: []any{"red", "green", "blue"},
|
||||
}},
|
||||
},
|
||||
}},
|
||||
"B": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"object"},
|
||||
Properties: openapi3.Schemas{
|
||||
"color": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"string"},
|
||||
Enum: []any{"red", "green", "blue"},
|
||||
}},
|
||||
},
|
||||
Schemas: openapi3.Schemas{},
|
||||
},
|
||||
}
|
||||
for _, name := range []string{"A", "B"} {
|
||||
doc.Components.Schemas[name] = &openapi3.SchemaRef{Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"object"},
|
||||
Properties: openapi3.Schemas{
|
||||
"color": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"string"},
|
||||
Enum: []any{"red", "green", "blue"},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}}
|
||||
}
|
||||
astMap := map[string][]string{EnumKey([]any{"red", "green", "blue"}): {"Color"}}
|
||||
if err := extractSharedEnums(doc, astMap); err != nil {
|
||||
@@ -190,27 +182,19 @@ func TestExtractEnumTypeName_rejectsIncidentalPrefix(t *testing.T) {
|
||||
func TestExtractSharedEnums_missReturnsError(t *testing.T) {
|
||||
doc := &openapi3.T{
|
||||
Components: &openapi3.Components{
|
||||
Schemas: openapi3.Schemas{
|
||||
"A": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"object"},
|
||||
Properties: openapi3.Schemas{
|
||||
"color": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"string"},
|
||||
Enum: []any{"red", "green"},
|
||||
}},
|
||||
},
|
||||
}},
|
||||
"B": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"object"},
|
||||
Properties: openapi3.Schemas{
|
||||
"color": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"string"},
|
||||
Enum: []any{"red", "green"},
|
||||
}},
|
||||
},
|
||||
Schemas: openapi3.Schemas{},
|
||||
},
|
||||
}
|
||||
for _, name := range []string{"A", "B"} {
|
||||
doc.Components.Schemas[name] = &openapi3.SchemaRef{Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"object"},
|
||||
Properties: openapi3.Schemas{
|
||||
"color": {Value: &openapi3.Schema{
|
||||
Type: &openapi3.Types{"string"},
|
||||
Enum: []any{"red", "green"},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}}
|
||||
}
|
||||
if err := extractSharedEnums(doc, map[string][]string{}); err == nil {
|
||||
t.Fatal("expected miss error")
|
||||
|
||||
+110
-141
@@ -33,9 +33,17 @@ func TestEnumKey_handlesNonStringValues(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_basic(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := `package fixture
|
||||
func TestScanSwaggerEnumTypes(t *testing.T) {
|
||||
scan := func(t *testing.T, filename, src string) (map[string][]string, error) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, filename), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ScanSwaggerEnumTypes([]string{dir})
|
||||
}
|
||||
|
||||
t.Run("basic", func(t *testing.T) {
|
||||
got, err := scan(t, "color.go", `package fixture
|
||||
|
||||
// Color is a primary color.
|
||||
// swagger:enum Color
|
||||
@@ -46,24 +54,18 @@ const (
|
||||
ColorGreen Color = "green"
|
||||
ColorBlue Color = "blue"
|
||||
)
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "color.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
wantKey := EnumKey([]any{"red", "green", "blue"})
|
||||
if single(got, wantKey) != "Color" {
|
||||
t.Fatalf("map[%q] = %q, want %q", wantKey, got[wantKey], "Color")
|
||||
}
|
||||
})
|
||||
|
||||
got, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
wantKey := EnumKey([]any{"red", "green", "blue"})
|
||||
if single(got, wantKey) != "Color" {
|
||||
t.Fatalf("map[%q] = %q, want %q", wantKey, got[wantKey], "Color")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_orphanAnnotation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := `package fixture
|
||||
t.Run("orphanAnnotation", func(t *testing.T) {
|
||||
_, err := scan(t, "typo.go", `package fixture
|
||||
|
||||
// swagger:enum Sttype
|
||||
type StateType string
|
||||
@@ -71,23 +73,17 @@ type StateType string
|
||||
const (
|
||||
StateOpen StateType = "open"
|
||||
)
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "typo.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for annotation referencing a non-matching type name")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Sttype") {
|
||||
t.Fatalf("error %q should mention the typo'd name Sttype", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
_, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for annotation referencing a non-matching type name")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Sttype") {
|
||||
t.Fatalf("error %q should mention the typo'd name Sttype", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_collision(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := `package fixture
|
||||
t.Run("collision", func(t *testing.T) {
|
||||
got, err := scan(t, "dup.go", `package fixture
|
||||
|
||||
// swagger:enum Alpha
|
||||
type Alpha string
|
||||
@@ -102,52 +98,90 @@ const (
|
||||
BetaX Beta = "x"
|
||||
BetaY Beta = "y"
|
||||
)
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "dup.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
key := EnumKey([]any{"x", "y"})
|
||||
names := got[key]
|
||||
if !slices.Equal(names, []string{"Alpha", "Beta"}) {
|
||||
t.Fatalf("map[%q] = %v, want [Alpha Beta]", key, names)
|
||||
}
|
||||
})
|
||||
|
||||
got, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
key := EnumKey([]any{"x", "y"})
|
||||
names := got[key]
|
||||
if !slices.Equal(names, []string{"Alpha", "Beta"}) {
|
||||
t.Fatalf("map[%q] = %v, want [Alpha Beta]", key, names)
|
||||
}
|
||||
}
|
||||
t.Run("parseFailure", func(t *testing.T) {
|
||||
_, err := scan(t, "bad.go", "package fixture\nfunc Foo() {")
|
||||
if err == nil {
|
||||
t.Fatal("expected parse error, got nil")
|
||||
}
|
||||
})
|
||||
|
||||
func TestScanSwaggerEnumTypes_parseFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "bad.go"), []byte("package fixture\nfunc Foo() {"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err == nil {
|
||||
t.Fatal("expected parse error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_annotationWithoutConsts(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := `package fixture
|
||||
t.Run("annotationWithoutConsts", func(t *testing.T) {
|
||||
_, err := scan(t, "lonely.go", `package fixture
|
||||
|
||||
// swagger:enum Lonely
|
||||
type Lonely string
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "lonely.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for annotation without consts")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Lonely") {
|
||||
t.Fatalf("error %q should mention Lonely", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
_, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for annotation without consts")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "Lonely") {
|
||||
t.Fatalf("error %q should mention Lonely", err.Error())
|
||||
}
|
||||
t.Run("constsBeforeType", func(t *testing.T) {
|
||||
got, err := scan(t, "shade.go", `package fixture
|
||||
|
||||
const (
|
||||
ShadeDark Shade = "dark"
|
||||
ShadeLight Shade = "light"
|
||||
)
|
||||
|
||||
// swagger:enum Shade
|
||||
type Shade string
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
wantKey := EnumKey([]any{"dark", "light"})
|
||||
if single(got, wantKey) != "Shade" {
|
||||
t.Fatalf("map[%q] = %q, want %q", wantKey, got[wantKey], "Shade")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("groupedTypeDecl", func(t *testing.T) {
|
||||
got, err := scan(t, "grouped.go", `package fixture
|
||||
|
||||
type (
|
||||
// swagger:enum Color
|
||||
Color string
|
||||
// swagger:enum Shade
|
||||
Shade string
|
||||
)
|
||||
|
||||
const (
|
||||
ColorRed Color = "red"
|
||||
ColorBlue Color = "blue"
|
||||
)
|
||||
|
||||
const (
|
||||
ShadeDark Shade = "dark"
|
||||
ShadeLight Shade = "light"
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
colorKey := EnumKey([]any{"red", "blue"})
|
||||
shadeKey := EnumKey([]any{"dark", "light"})
|
||||
if single(got, colorKey) != "Color" {
|
||||
t.Fatalf("Color: map[%q] = %q, want %q", colorKey, got[colorKey], "Color")
|
||||
}
|
||||
if single(got, shadeKey) != "Shade" {
|
||||
t.Fatalf("Shade: map[%q] = %q, want %q", shadeKey, got[shadeKey], "Shade")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_constsAndTypeInDifferentFiles(t *testing.T) {
|
||||
@@ -182,68 +216,3 @@ type Hue string
|
||||
t.Fatalf("map[%q] = %q, want %q", wantKey, got[wantKey], "Hue")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_constsBeforeType(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := `package fixture
|
||||
|
||||
const (
|
||||
ShadeDark Shade = "dark"
|
||||
ShadeLight Shade = "light"
|
||||
)
|
||||
|
||||
// swagger:enum Shade
|
||||
type Shade string
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "shade.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
wantKey := EnumKey([]any{"dark", "light"})
|
||||
if single(got, wantKey) != "Shade" {
|
||||
t.Fatalf("map[%q] = %q, want %q", wantKey, got[wantKey], "Shade")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSwaggerEnumTypes_groupedTypeDecl(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := `package fixture
|
||||
|
||||
type (
|
||||
// swagger:enum Color
|
||||
Color string
|
||||
// swagger:enum Shade
|
||||
Shade string
|
||||
)
|
||||
|
||||
const (
|
||||
ColorRed Color = "red"
|
||||
ColorBlue Color = "blue"
|
||||
)
|
||||
|
||||
const (
|
||||
ShadeDark Shade = "dark"
|
||||
ShadeLight Shade = "light"
|
||||
)
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "grouped.go"), []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := ScanSwaggerEnumTypes([]string{dir})
|
||||
if err != nil {
|
||||
t.Fatalf("ScanSwaggerEnumTypes: %v", err)
|
||||
}
|
||||
colorKey := EnumKey([]any{"red", "blue"})
|
||||
shadeKey := EnumKey([]any{"dark", "light"})
|
||||
if single(got, colorKey) != "Color" {
|
||||
t.Fatalf("Color: map[%q] = %q, want %q", colorKey, got[colorKey], "Color")
|
||||
}
|
||||
if single(got, shadeKey) != "Shade" {
|
||||
t.Fatalf("Shade: map[%q] = %q, want %q", shadeKey, got[shadeKey], "Shade")
|
||||
}
|
||||
}
|
||||
+70
-401
@@ -489,13 +489,20 @@ func TestUpdateLdapBindDn(t *testing.T) {
|
||||
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
|
||||
|
||||
// Test cases
|
||||
cases := []struct {
|
||||
type testCase struct {
|
||||
args []string
|
||||
id int64
|
||||
existingAuthSource *auth.Source
|
||||
authSource *auth.Source
|
||||
errMsg string
|
||||
}{
|
||||
}
|
||||
withConfig := func(config *ldap.Source, args ...string) testCase {
|
||||
return testCase{
|
||||
args: append([]string{"ldap-test", "--id", "1"}, args...),
|
||||
authSource: &auth.Source{Type: auth.LDAP, Cfg: config},
|
||||
}
|
||||
}
|
||||
cases := []testCase{
|
||||
// case 0
|
||||
{
|
||||
args: []string{
|
||||
@@ -574,16 +581,7 @@ func TestUpdateLdapBindDn(t *testing.T) {
|
||||
},
|
||||
},
|
||||
// case 1
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{}),
|
||||
// case 2
|
||||
{
|
||||
args: []string{
|
||||
@@ -618,215 +616,44 @@ func TestUpdateLdapBindDn(t *testing.T) {
|
||||
},
|
||||
},
|
||||
// case 4
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--security-protocol", "LDAPS",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
SecurityProtocol: ldap.SecurityProtocol(1),
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{SecurityProtocol: ldap.SecurityProtocol(1)}, "--security-protocol", "LDAPS"),
|
||||
// case 5
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--skip-tls-verify",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
SkipVerify: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{SkipVerify: true}, "--skip-tls-verify"),
|
||||
// case 6
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--host", "ldap-server",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
Host: "ldap-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{Host: "ldap-server"}, "--host", "ldap-server"),
|
||||
// case 7
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--port", "389",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
Port: 389,
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{Port: 389}, "--port", "389"),
|
||||
// case 8
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--user-search-base", "ou=Users,dc=domain,dc=org",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
UserBase: "ou=Users,dc=domain,dc=org",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{UserBase: "ou=Users,dc=domain,dc=org"},
|
||||
"--user-search-base", "ou=Users,dc=domain,dc=org",
|
||||
),
|
||||
// case 9
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--user-filter", "(memberOf=cn=user-group,ou=example,dc=domain,dc=org)",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
Filter: "(memberOf=cn=user-group,ou=example,dc=domain,dc=org)",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{Filter: "(memberOf=cn=user-group,ou=example,dc=domain,dc=org)"},
|
||||
"--user-filter", "(memberOf=cn=user-group,ou=example,dc=domain,dc=org)",
|
||||
),
|
||||
// case 10
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--admin-filter", "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AdminFilter: "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{AdminFilter: "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)"},
|
||||
"--admin-filter", "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)",
|
||||
),
|
||||
// case 11
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--username-attribute", "uid",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeUsername: "uid",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeUsername: "uid"}, "--username-attribute", "uid"),
|
||||
// case 12
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--firstname-attribute", "givenName",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeName: "givenName",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeName: "givenName"}, "--firstname-attribute", "givenName"),
|
||||
// case 13
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--surname-attribute", "sn",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeSurname: "sn",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeSurname: "sn"}, "--surname-attribute", "sn"),
|
||||
// case 14
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--email-attribute", "mail",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeMail: "mail",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeMail: "mail"}, "--email-attribute", "mail"),
|
||||
// case 15
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--attributes-in-bind",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributesInBind: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributesInBind: true}, "--attributes-in-bind"),
|
||||
// case 16
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--public-ssh-key-attribute", "publickey",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeSSHPublicKey: "publickey",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeSSHPublicKey: "publickey"}, "--public-ssh-key-attribute", "publickey"),
|
||||
// case 17
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--bind-dn", "cn=readonly,dc=domain,dc=org",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
BindDN: "cn=readonly,dc=domain,dc=org",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{BindDN: "cn=readonly,dc=domain,dc=org"}, "--bind-dn", "cn=readonly,dc=domain,dc=org"),
|
||||
// case 18
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--bind-password", "secret",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
BindPassword: "secret",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{BindPassword: "secret"}, "--bind-password", "secret"),
|
||||
// case 19
|
||||
{
|
||||
args: []string{
|
||||
@@ -841,19 +668,7 @@ func TestUpdateLdapBindDn(t *testing.T) {
|
||||
},
|
||||
},
|
||||
// case 20
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--page-size", "12",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.LDAP,
|
||||
Cfg: &ldap.Source{
|
||||
SearchPageSize: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{SearchPageSize: 12}, "--page-size", "12"),
|
||||
// case 21
|
||||
{
|
||||
args: []string{
|
||||
@@ -964,13 +779,20 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
|
||||
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
|
||||
|
||||
// Test cases
|
||||
cases := []struct {
|
||||
type testCase struct {
|
||||
args []string
|
||||
id int64
|
||||
existingAuthSource *auth.Source
|
||||
authSource *auth.Source
|
||||
errMsg string
|
||||
}{
|
||||
}
|
||||
withConfig := func(config *ldap.Source, args ...string) testCase {
|
||||
return testCase{
|
||||
args: append([]string{"ldap-test", "--id", "1"}, args...),
|
||||
authSource: &auth.Source{Type: auth.DLDAP, Cfg: config},
|
||||
}
|
||||
}
|
||||
cases := []testCase{
|
||||
// case 0
|
||||
{
|
||||
args: []string{
|
||||
@@ -1020,16 +842,7 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
|
||||
},
|
||||
},
|
||||
// case 1
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{}),
|
||||
// case 2
|
||||
{
|
||||
args: []string{
|
||||
@@ -1064,187 +877,43 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
|
||||
},
|
||||
},
|
||||
// case 4
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--security-protocol", "starttls",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
SecurityProtocol: ldap.SecurityProtocol(2),
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{SecurityProtocol: ldap.SecurityProtocol(2)}, "--security-protocol", "starttls"),
|
||||
// case 5
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--skip-tls-verify",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
SkipVerify: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{SkipVerify: true}, "--skip-tls-verify"),
|
||||
// case 6
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--host", "ldap-server",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
Host: "ldap-server",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{Host: "ldap-server"}, "--host", "ldap-server"),
|
||||
// case 7
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--port", "987",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
Port: 987,
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{Port: 987}, "--port", "987"),
|
||||
// case 8
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--user-search-base", "ou=Users,dc=domain,dc=org",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
UserBase: "ou=Users,dc=domain,dc=org",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{UserBase: "ou=Users,dc=domain,dc=org"},
|
||||
"--user-search-base", "ou=Users,dc=domain,dc=org",
|
||||
),
|
||||
// case 9
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--user-filter", "(&(objectClass=posixAccount)(cn=%s))",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
Filter: "(&(objectClass=posixAccount)(cn=%s))",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{Filter: "(&(objectClass=posixAccount)(cn=%s))"},
|
||||
"--user-filter", "(&(objectClass=posixAccount)(cn=%s))",
|
||||
),
|
||||
// case 10
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--admin-filter", "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AdminFilter: "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{AdminFilter: "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)"},
|
||||
"--admin-filter", "(memberOf=cn=admin-group,ou=example,dc=domain,dc=org)",
|
||||
),
|
||||
// case 11
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--username-attribute", "uid",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeUsername: "uid",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeUsername: "uid"}, "--username-attribute", "uid"),
|
||||
// case 12
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--firstname-attribute", "givenName",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeName: "givenName",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeName: "givenName"}, "--firstname-attribute", "givenName"),
|
||||
// case 13
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--surname-attribute", "sn",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeSurname: "sn",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeSurname: "sn"}, "--surname-attribute", "sn"),
|
||||
// case 14
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--email-attribute", "mail",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeMail: "mail",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeMail: "mail"}, "--email-attribute", "mail"),
|
||||
// case 15
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--public-ssh-key-attribute", "publickey",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
AttributeSSHPublicKey: "publickey",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(&ldap.Source{AttributeSSHPublicKey: "publickey"}, "--public-ssh-key-attribute", "publickey"),
|
||||
// case 16
|
||||
{
|
||||
args: []string{
|
||||
"ldap-test",
|
||||
"--id", "1",
|
||||
"--user-dn", "cn=%s,ou=Users,dc=domain,dc=org",
|
||||
},
|
||||
authSource: &auth.Source{
|
||||
Type: auth.DLDAP,
|
||||
Cfg: &ldap.Source{
|
||||
UserDN: "cn=%s,ou=Users,dc=domain,dc=org",
|
||||
},
|
||||
},
|
||||
},
|
||||
withConfig(
|
||||
&ldap.Source{UserDN: "cn=%s,ou=Users,dc=domain,dc=org"},
|
||||
"--user-dn", "cn=%s,ou=Users,dc=domain,dc=org",
|
||||
),
|
||||
// case 17
|
||||
{
|
||||
args: []string{
|
||||
|
||||
+49
-105
@@ -16,10 +16,11 @@ import (
|
||||
|
||||
func TestAddOauth(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
args []string
|
||||
source *auth_model.Source
|
||||
errMsg string
|
||||
name string
|
||||
args []string
|
||||
config *oauth2.Source
|
||||
twoFactorPolicy string
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid config",
|
||||
@@ -29,17 +30,11 @@ func TestAddOauth(t *testing.T) {
|
||||
"--key", "some_key",
|
||||
"--secret", "some_secret",
|
||||
},
|
||||
source: &auth_model.Source{
|
||||
Type: auth_model.OAuth2,
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
Cfg: &oauth2.Source{
|
||||
Scopes: []string{},
|
||||
Provider: "github",
|
||||
ClientID: "some_key",
|
||||
ClientSecret: "some_secret",
|
||||
},
|
||||
TwoFactorPolicy: "",
|
||||
config: &oauth2.Source{
|
||||
Scopes: []string{},
|
||||
Provider: "github",
|
||||
ClientID: "some_key",
|
||||
ClientSecret: "some_secret",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -51,18 +46,12 @@ func TestAddOauth(t *testing.T) {
|
||||
"--secret", "some_secret",
|
||||
"--auto-discover-url", "https://example.com",
|
||||
},
|
||||
source: &auth_model.Source{
|
||||
Type: auth_model.OAuth2,
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
Cfg: &oauth2.Source{
|
||||
Scopes: []string{},
|
||||
Provider: "openidConnect",
|
||||
ClientID: "some_key",
|
||||
ClientSecret: "some_secret",
|
||||
OpenIDConnectAutoDiscoveryURL: "https://example.com",
|
||||
},
|
||||
TwoFactorPolicy: "",
|
||||
config: &oauth2.Source{
|
||||
Scopes: []string{},
|
||||
Provider: "openidConnect",
|
||||
ClientID: "some_key",
|
||||
ClientSecret: "some_secret",
|
||||
OpenIDConnectAutoDiscoveryURL: "https://example.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -91,35 +80,30 @@ func TestAddOauth(t *testing.T) {
|
||||
"--ssh-public-key-claim-name", "attr_ssh_pub_key",
|
||||
"--full-name-claim-name", "attr_full_name",
|
||||
},
|
||||
source: &auth_model.Source{
|
||||
Type: auth_model.OAuth2,
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
Cfg: &oauth2.Source{
|
||||
Provider: "gitlab",
|
||||
ClientID: "some_key",
|
||||
ClientSecret: "some_secret",
|
||||
CustomURLMapping: &oauth2.CustomURLMapping{
|
||||
TokenURL: "https://example.com/token",
|
||||
AuthURL: "https://example.com/auth",
|
||||
ProfileURL: "https://example.com/profile",
|
||||
EmailURL: "https://example.com/email",
|
||||
Tenant: "some_tenant",
|
||||
},
|
||||
IconURL: "https://example.com/icon",
|
||||
Scopes: []string{"scope1", "scope2"},
|
||||
RequiredClaimName: "claim_name",
|
||||
RequiredClaimValue: "claim_value",
|
||||
GroupClaimName: "group_name",
|
||||
AdminGroup: "admin",
|
||||
RestrictedGroup: "restricted",
|
||||
GroupTeamMap: `{"group1": [1,2]}`,
|
||||
GroupTeamMapRemoval: true,
|
||||
SSHPublicKeyClaimName: "attr_ssh_pub_key",
|
||||
FullNameClaimName: "attr_full_name",
|
||||
config: &oauth2.Source{
|
||||
Provider: "gitlab",
|
||||
ClientID: "some_key",
|
||||
ClientSecret: "some_secret",
|
||||
CustomURLMapping: &oauth2.CustomURLMapping{
|
||||
TokenURL: "https://example.com/token",
|
||||
AuthURL: "https://example.com/auth",
|
||||
ProfileURL: "https://example.com/profile",
|
||||
EmailURL: "https://example.com/email",
|
||||
Tenant: "some_tenant",
|
||||
},
|
||||
TwoFactorPolicy: "skip",
|
||||
IconURL: "https://example.com/icon",
|
||||
Scopes: []string{"scope1", "scope2"},
|
||||
RequiredClaimName: "claim_name",
|
||||
RequiredClaimValue: "claim_value",
|
||||
GroupClaimName: "group_name",
|
||||
AdminGroup: "admin",
|
||||
RestrictedGroup: "restricted",
|
||||
GroupTeamMap: `{"group1": [1,2]}`,
|
||||
GroupTeamMapRemoval: true,
|
||||
SSHPublicKeyClaimName: "attr_ssh_pub_key",
|
||||
FullNameClaimName: "attr_full_name",
|
||||
},
|
||||
twoFactorPolicy: "skip",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -150,7 +134,13 @@ func TestAddOauth(t *testing.T) {
|
||||
assert.EqualError(t, err, tc.errMsg)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.source, createdSource)
|
||||
assert.Equal(t, &auth_model.Source{
|
||||
Type: auth_model.OAuth2,
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
Cfg: tc.config,
|
||||
TwoFactorPolicy: tc.twoFactorPolicy,
|
||||
}, createdSource)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -158,12 +148,10 @@ func TestAddOauth(t *testing.T) {
|
||||
|
||||
func TestUpdateOauth(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
args []string
|
||||
id int64
|
||||
existingAuthSource *auth_model.Source
|
||||
authSource *auth_model.Source
|
||||
errMsg string
|
||||
name string
|
||||
args []string
|
||||
authSource *auth_model.Source
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "missing id",
|
||||
@@ -174,19 +162,6 @@ func TestUpdateOauth(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "valid config",
|
||||
id: 1,
|
||||
existingAuthSource: &auth_model.Source{
|
||||
ID: 1,
|
||||
Type: auth_model.OAuth2,
|
||||
Name: "old name",
|
||||
IsActive: true,
|
||||
Cfg: &oauth2.Source{
|
||||
Provider: "github",
|
||||
ClientID: "old_key",
|
||||
ClientSecret: "old_secret",
|
||||
},
|
||||
TwoFactorPolicy: "",
|
||||
},
|
||||
args: []string{
|
||||
"--id", "1",
|
||||
"--name", "test",
|
||||
@@ -210,37 +185,6 @@ func TestUpdateOauth(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "valid config with options",
|
||||
id: 1,
|
||||
existingAuthSource: &auth_model.Source{
|
||||
ID: 1,
|
||||
Type: auth_model.OAuth2,
|
||||
Name: "old name",
|
||||
IsActive: true,
|
||||
Cfg: &oauth2.Source{
|
||||
Provider: "gitlab",
|
||||
ClientID: "old_key",
|
||||
ClientSecret: "old_secret",
|
||||
CustomURLMapping: &oauth2.CustomURLMapping{
|
||||
TokenURL: "https://old.example.com/token",
|
||||
AuthURL: "https://old.example.com/auth",
|
||||
ProfileURL: "https://old.example.com/profile",
|
||||
EmailURL: "https://old.example.com/email",
|
||||
Tenant: "old_tenant",
|
||||
},
|
||||
IconURL: "https://old.example.com/icon",
|
||||
Scopes: []string{"old_scope1", "old_scope2"},
|
||||
RequiredClaimName: "old_claim_name",
|
||||
RequiredClaimValue: "old_claim_value",
|
||||
GroupClaimName: "old_group_name",
|
||||
AdminGroup: "old_admin",
|
||||
RestrictedGroup: "old_restricted",
|
||||
GroupTeamMap: `{"old_group1": [1,2]}`,
|
||||
GroupTeamMapRemoval: true,
|
||||
SSHPublicKeyClaimName: "old_ssh_pub_key",
|
||||
FullNameClaimName: "old_full_name",
|
||||
},
|
||||
TwoFactorPolicy: "",
|
||||
},
|
||||
args: []string{
|
||||
"--id", "1",
|
||||
"--name", "test",
|
||||
|
||||
@@ -132,11 +132,10 @@ func TestAddSMTP(t *testing.T) {
|
||||
|
||||
func TestUpdateSMTP(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
args []string
|
||||
existingAuthSource *auth_model.Source
|
||||
authSource *auth_model.Source
|
||||
errMsg string
|
||||
name string
|
||||
args []string
|
||||
authSource *auth_model.Source
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "missing id",
|
||||
@@ -149,17 +148,6 @@ func TestUpdateSMTP(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "valid config",
|
||||
existingAuthSource: &auth_model.Source{
|
||||
ID: 1,
|
||||
Type: auth_model.SMTP,
|
||||
Name: "old name",
|
||||
IsActive: true,
|
||||
Cfg: &smtp.Source{
|
||||
Auth: "PLAIN",
|
||||
Host: "old host",
|
||||
Port: 26,
|
||||
},
|
||||
},
|
||||
args: []string{
|
||||
"--id", "1",
|
||||
"--name", "test",
|
||||
@@ -180,20 +168,6 @@ func TestUpdateSMTP(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "valid config with options",
|
||||
existingAuthSource: &auth_model.Source{
|
||||
ID: 1,
|
||||
Type: auth_model.SMTP,
|
||||
Name: "old name",
|
||||
IsActive: true,
|
||||
Cfg: &smtp.Source{
|
||||
Auth: "PLAIN",
|
||||
Host: "old host",
|
||||
Port: 26,
|
||||
HeloHostname: "old.example.com",
|
||||
AllowedDomains: "old.example.com",
|
||||
},
|
||||
TwoFactorPolicy: "",
|
||||
},
|
||||
args: []string{
|
||||
"--id", "1",
|
||||
"--name", "test",
|
||||
|
||||
@@ -24,42 +24,29 @@ func TestAdminUserDelete(t *testing.T) {
|
||||
require.NoError(t, db.TruncateBeans(t.Context(), &auth_model.AccessToken{}))
|
||||
}()
|
||||
|
||||
setupTestUser := func(t *testing.T) {
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
err := microcmdUserCreate().Run(t.Context(), []string{"create", "--username", "testuser", "--email", "testuser@gitea.local", "--random-password"})
|
||||
require.NoError(t, err)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"delete user by id", []string{"delete-test", "--id", ""}},
|
||||
{"delete user by username", []string{"delete-test", "--username", "testuser"}},
|
||||
{"delete user by email", []string{"delete-test", "--email", "testuser@gitea.local"}},
|
||||
{"delete user by all 3 attributes", []string{"delete", "--id", "", "--username", "testuser", "--email", "testuser@gitea.local"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
err := microcmdUserCreate().Run(t.Context(), []string{"create", "--username", "testuser", "--email", "testuser@gitea.local", "--random-password"})
|
||||
require.NoError(t, err)
|
||||
|
||||
if tc.args[1] == "--id" {
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
tc.args[2] = strconv.FormatInt(user.ID, 10)
|
||||
}
|
||||
err = microcmdUserDelete().Run(ctx, tc.args)
|
||||
require.NoError(t, err)
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("delete user by id", func(t *testing.T) {
|
||||
setupTestUser(t)
|
||||
|
||||
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
err := microcmdUserDelete().Run(ctx, []string{"delete-test", "--id", strconv.FormatInt(u.ID, 10)})
|
||||
require.NoError(t, err)
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
})
|
||||
t.Run("delete user by username", func(t *testing.T) {
|
||||
setupTestUser(t)
|
||||
|
||||
err := microcmdUserDelete().Run(ctx, []string{"delete-test", "--username", "testuser"})
|
||||
require.NoError(t, err)
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
})
|
||||
t.Run("delete user by email", func(t *testing.T) {
|
||||
setupTestUser(t)
|
||||
|
||||
err := microcmdUserDelete().Run(ctx, []string{"delete-test", "--email", "testuser@gitea.local"})
|
||||
require.NoError(t, err)
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
})
|
||||
t.Run("delete user by all 3 attributes", func(t *testing.T) {
|
||||
setupTestUser(t)
|
||||
|
||||
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
err := microcmdUserDelete().Run(ctx, []string{"delete", "--id", strconv.FormatInt(u.ID, 10), "--username", "testuser", "--email", "testuser@gitea.local"})
|
||||
require.NoError(t, err)
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})
|
||||
})
|
||||
}
|
||||
|
||||
func TestAdminUserDeleteFailure(t *testing.T) {
|
||||
|
||||
@@ -18,61 +18,28 @@ func TestMustChangePassword(t *testing.T) {
|
||||
defer func() {
|
||||
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
|
||||
}()
|
||||
err := microcmdUserCreate().Run(t.Context(), []string{"create", "--username", "testuser", "--email", "testuser@gitea.local", "--random-password"})
|
||||
require.NoError(t, err)
|
||||
err = microcmdUserCreate().Run(t.Context(), []string{"create", "--username", "testuserexclude", "--email", "testuserexclude@gitea.local", "--random-password"})
|
||||
require.NoError(t, err)
|
||||
// Reset password change flag
|
||||
err = microcmdUserMustChangePassword().Run(t.Context(), []string{"change-test", "--all", "--unset"})
|
||||
require.NoError(t, err)
|
||||
|
||||
testUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
assert.False(t, testUser.MustChangePassword)
|
||||
testUserExclude := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"})
|
||||
assert.False(t, testUserExclude.MustChangePassword)
|
||||
|
||||
// Make all users change password
|
||||
err = microcmdUserMustChangePassword().Run(t.Context(), []string{"change-test", "--all"})
|
||||
require.NoError(t, err)
|
||||
|
||||
testUser = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
assert.True(t, testUser.MustChangePassword)
|
||||
testUserExclude = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"})
|
||||
assert.True(t, testUserExclude.MustChangePassword)
|
||||
|
||||
// Reset password change flag but exclude all tested users
|
||||
err = microcmdUserMustChangePassword().Run(t.Context(), []string{"change-test", "--all", "--unset", "--exclude", "testuser,testuserexclude"})
|
||||
require.NoError(t, err)
|
||||
|
||||
testUser = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
assert.True(t, testUser.MustChangePassword)
|
||||
testUserExclude = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"})
|
||||
assert.True(t, testUserExclude.MustChangePassword)
|
||||
|
||||
// Reset password change flag by listing multiple users
|
||||
err = microcmdUserMustChangePassword().Run(t.Context(), []string{"change-test", "--unset", "testuser", "testuserexclude"})
|
||||
require.NoError(t, err)
|
||||
|
||||
testUser = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
assert.False(t, testUser.MustChangePassword)
|
||||
testUserExclude = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"})
|
||||
assert.False(t, testUserExclude.MustChangePassword)
|
||||
|
||||
// Exclude a user from all user
|
||||
err = microcmdUserMustChangePassword().Run(t.Context(), []string{"change-test", "--all", "--exclude", "testuserexclude"})
|
||||
require.NoError(t, err)
|
||||
|
||||
testUser = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
assert.True(t, testUser.MustChangePassword)
|
||||
testUserExclude = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"})
|
||||
assert.False(t, testUserExclude.MustChangePassword)
|
||||
|
||||
// Unset a flag for single user
|
||||
err = microcmdUserMustChangePassword().Run(t.Context(), []string{"change-test", "--unset", "testuser"})
|
||||
require.NoError(t, err)
|
||||
|
||||
testUser = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"})
|
||||
assert.False(t, testUser.MustChangePassword)
|
||||
testUserExclude = unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"})
|
||||
assert.False(t, testUserExclude.MustChangePassword)
|
||||
for _, name := range []string{"testuser", "testuserexclude"} {
|
||||
require.NoError(t, microcmdUserCreate().Run(t.Context(), []string{"create", "--username", name, "--email", name + "@gitea.local", "--random-password"}))
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
assertUser, assertExcludedUser assert.BoolAssertionFunc
|
||||
}{
|
||||
// Reset password change flag
|
||||
{[]string{"change-test", "--all", "--unset"}, assert.False, assert.False},
|
||||
// Make all users change password
|
||||
{[]string{"change-test", "--all"}, assert.True, assert.True},
|
||||
// Reset password change flag but exclude all tested users
|
||||
{[]string{"change-test", "--all", "--unset", "--exclude", "testuser,testuserexclude"}, assert.True, assert.True},
|
||||
// Reset password change flag by listing multiple users
|
||||
{[]string{"change-test", "--unset", "testuser", "testuserexclude"}, assert.False, assert.False},
|
||||
// Exclude a user from all user
|
||||
{[]string{"change-test", "--all", "--exclude", "testuserexclude"}, assert.True, assert.False},
|
||||
// Unset a flag for single user
|
||||
{[]string{"change-test", "--unset", "testuser"}, assert.False, assert.False},
|
||||
} {
|
||||
require.NoError(t, microcmdUserMustChangePassword().Run(t.Context(), tc.args))
|
||||
tc.assertUser(t, unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuser"}).MustChangePassword)
|
||||
tc.assertExcludedUser(t, unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "testuserexclude"}).MustChangePassword)
|
||||
}
|
||||
}
|
||||
+51
-79
@@ -76,110 +76,82 @@ func TestCliCmd(t *testing.T) {
|
||||
cli.SubcommandHelpTemplate = "(subcommand help template)"
|
||||
|
||||
cases := []struct {
|
||||
env map[string]string
|
||||
cmd string
|
||||
exp string
|
||||
env map[string]string
|
||||
cmds []string
|
||||
exp string
|
||||
}{
|
||||
// help commands
|
||||
{
|
||||
cmd: "./gitea -h",
|
||||
exp: "DEFAULT CONFIGURATION:",
|
||||
cmds: []string{"./gitea -h", "./gitea help"},
|
||||
exp: "DEFAULT CONFIGURATION:",
|
||||
},
|
||||
{
|
||||
cmd: "./gitea help",
|
||||
exp: "DEFAULT CONFIGURATION:",
|
||||
},
|
||||
|
||||
{
|
||||
cmd: "./gitea -c /dev/null -h",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
|
||||
{
|
||||
cmd: "./gitea -c /dev/null help",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
{
|
||||
cmd: "./gitea help -c /dev/null",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
|
||||
{
|
||||
cmd: "./gitea -c /dev/null test-cmd -h",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
{
|
||||
cmd: "./gitea test-cmd -c /dev/null -h",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
{
|
||||
cmd: "./gitea test-cmd -h -c /dev/null",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
|
||||
{
|
||||
cmd: "./gitea -c /dev/null test-cmd help",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
{
|
||||
cmd: "./gitea test-cmd -c /dev/null help",
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
{
|
||||
cmd: "./gitea test-cmd help -c /dev/null",
|
||||
cmds: []string{
|
||||
"./gitea -c /dev/null -h",
|
||||
"./gitea -c /dev/null help",
|
||||
"./gitea help -c /dev/null",
|
||||
"./gitea -c /dev/null test-cmd -h",
|
||||
"./gitea test-cmd -c /dev/null -h",
|
||||
"./gitea test-cmd -h -c /dev/null",
|
||||
"./gitea -c /dev/null test-cmd help",
|
||||
"./gitea test-cmd -c /dev/null help",
|
||||
"./gitea test-cmd help -c /dev/null",
|
||||
},
|
||||
exp: "ConfigFile: /dev/null",
|
||||
},
|
||||
|
||||
// parse paths
|
||||
{
|
||||
cmd: "./gitea test-cmd",
|
||||
exp: makePathOutput(defaultWorkPath, defaultCustomPath, defaultCustomConf),
|
||||
cmds: []string{"./gitea test-cmd"},
|
||||
exp: makePathOutput(defaultWorkPath, defaultCustomPath, defaultCustomConf),
|
||||
},
|
||||
{
|
||||
cmd: "./gitea -c /tmp/app.ini test-cmd",
|
||||
exp: makePathOutput(defaultWorkPath, defaultCustomPath, "/tmp/app.ini"),
|
||||
cmds: []string{"./gitea -c /tmp/app.ini test-cmd"},
|
||||
exp: makePathOutput(defaultWorkPath, defaultCustomPath, "/tmp/app.ini"),
|
||||
},
|
||||
{
|
||||
cmd: "./gitea test-cmd -c /tmp/app.ini",
|
||||
exp: makePathOutput(defaultWorkPath, defaultCustomPath, "/tmp/app.ini"),
|
||||
cmds: []string{"./gitea test-cmd -c /tmp/app.ini"},
|
||||
exp: makePathOutput(defaultWorkPath, defaultCustomPath, "/tmp/app.ini"),
|
||||
},
|
||||
{
|
||||
env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
|
||||
cmd: "./gitea test-cmd",
|
||||
exp: makePathOutput("/tmp", "/tmp/custom", "/tmp/custom/conf/app.ini"),
|
||||
env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
|
||||
cmds: []string{"./gitea test-cmd"},
|
||||
exp: makePathOutput("/tmp", "/tmp/custom", "/tmp/custom/conf/app.ini"),
|
||||
},
|
||||
{
|
||||
env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
|
||||
cmd: "./gitea test-cmd --work-path /tmp/other",
|
||||
exp: makePathOutput("/tmp/other", "/tmp/other/custom", "/tmp/other/custom/conf/app.ini"),
|
||||
env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
|
||||
cmds: []string{"./gitea test-cmd --work-path /tmp/other"},
|
||||
exp: makePathOutput("/tmp/other", "/tmp/other/custom", "/tmp/other/custom/conf/app.ini"),
|
||||
},
|
||||
{
|
||||
env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
|
||||
cmd: "./gitea test-cmd --config /tmp/app-other.ini",
|
||||
exp: makePathOutput("/tmp", "/tmp/custom", "/tmp/app-other.ini"),
|
||||
env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
|
||||
cmds: []string{"./gitea test-cmd --config /tmp/app-other.ini"},
|
||||
exp: makePathOutput("/tmp", "/tmp/custom", "/tmp/app-other.ini"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.cmd, func(t *testing.T) {
|
||||
app := newTestApp(cli.Command{
|
||||
Action: func(ctx context.Context, cmd *cli.Command) error {
|
||||
_, _ = fmt.Fprint(cmd.Root().Writer, makePathOutput(setting.AppWorkPath, setting.CustomPath, setting.CustomConf))
|
||||
return nil
|
||||
},
|
||||
for _, command := range c.cmds {
|
||||
t.Run(command, func(t *testing.T) {
|
||||
app := newTestApp(cli.Command{
|
||||
Action: func(ctx context.Context, cmd *cli.Command) error {
|
||||
_, _ = fmt.Fprint(cmd.Root().Writer, makePathOutput(setting.AppWorkPath, setting.CustomPath, setting.CustomConf))
|
||||
return nil
|
||||
},
|
||||
})
|
||||
for k, v := range c.env {
|
||||
t.Setenv(k, v)
|
||||
}
|
||||
args := strings.Split(command, " ") // for test only, "split" is good enough
|
||||
r, err := runTestApp(app, args...)
|
||||
assert.NoError(t, err, command)
|
||||
assert.NotEmpty(t, c.exp, command)
|
||||
if !assert.Contains(t, r.Stdout, c.exp, command) {
|
||||
t.Log("Full output:\n" + r.Stdout)
|
||||
t.Log("Expected:\n" + c.exp)
|
||||
}
|
||||
})
|
||||
for k, v := range c.env {
|
||||
t.Setenv(k, v)
|
||||
}
|
||||
args := strings.Split(c.cmd, " ") // for test only, "split" is good enough
|
||||
r, err := runTestApp(app, args...)
|
||||
assert.NoError(t, err, c.cmd)
|
||||
assert.NotEmpty(t, c.exp, c.cmd)
|
||||
if !assert.Contains(t, r.Stdout, c.exp, c.cmd) {
|
||||
t.Log("Full output:\n" + r.Stdout)
|
||||
t.Log("Expected:\n" + c.exp)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,38 +45,15 @@ func Test_DropTableColumns(t *testing.T) {
|
||||
x.SetMapper(names.GonicMapper{})
|
||||
|
||||
for i := range columns {
|
||||
if err := x.Sync(new(DropTest)); err != nil {
|
||||
t.Errorf("unable to create DropTest table: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
sess := x.NewSession()
|
||||
if err := sess.Begin(); err != nil {
|
||||
sess.Close()
|
||||
t.Errorf("unable to begin transaction: %v", err)
|
||||
return
|
||||
}
|
||||
if err := base.DropTableColumns(sess, "drop_test", columns[i:]...); err != nil {
|
||||
sess.Close()
|
||||
t.Errorf("Unable to drop columns[%d:]: %s from drop_test: %v", i, columns[i:], err)
|
||||
return
|
||||
}
|
||||
if err := sess.Commit(); err != nil {
|
||||
sess.Close()
|
||||
t.Errorf("unable to commit transaction: %v", err)
|
||||
return
|
||||
}
|
||||
sess.Close()
|
||||
if err := x.DropTables(new(DropTest)); err != nil {
|
||||
t.Errorf("unable to drop table: %v", err)
|
||||
return
|
||||
}
|
||||
for j := range columns[i+1:] {
|
||||
for j := i; j < len(columns); j++ {
|
||||
if err := x.Sync(new(DropTest)); err != nil {
|
||||
t.Errorf("unable to create DropTest table: %v", err)
|
||||
return
|
||||
}
|
||||
dropcols := append([]string{columns[i]}, columns[j+i+1:]...)
|
||||
dropcols := columns[i:]
|
||||
if j > i {
|
||||
dropcols = append([]string{columns[i]}, columns[j:]...)
|
||||
}
|
||||
sess := x.NewSession()
|
||||
if err := sess.Begin(); err != nil {
|
||||
sess.Close()
|
||||
@@ -85,7 +62,11 @@ func Test_DropTableColumns(t *testing.T) {
|
||||
}
|
||||
if err := base.DropTableColumns(sess, "drop_test", dropcols...); err != nil {
|
||||
sess.Close()
|
||||
t.Errorf("Unable to drop columns: %s from drop_test: %v", dropcols, err)
|
||||
if j == i {
|
||||
t.Errorf("Unable to drop columns[%d:]: %s from drop_test: %v", i, columns[i:], err)
|
||||
} else {
|
||||
t.Errorf("Unable to drop columns: %s from drop_test: %v", dropcols, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := sess.Commit(); err != nil {
|
||||
|
||||
@@ -78,12 +78,17 @@ func Test_ConvertScopedAccessTokens(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
session := x.NewSession()
|
||||
defer session.Close()
|
||||
assert.NoError(t, session.Begin())
|
||||
|
||||
for _, tc := range tests {
|
||||
_, err = x.Insert(&AccessToken{
|
||||
_, err = session.Insert(&AccessToken{
|
||||
Scope: string(tc.Old),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
assert.NoError(t, session.Commit())
|
||||
|
||||
// migrate the scopes
|
||||
err = ConvertScopedAccessTokens(t.Context(), x)
|
||||
|
||||
@@ -43,13 +43,11 @@ func Test_AddUniqueIndexForUserBadge(t *testing.T) {
|
||||
}
|
||||
|
||||
// check that we have duplicates
|
||||
count, err := x.Where("user_id = ? AND badge_id = ?", 1, 1).Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
|
||||
count, err = x.Where("user_id = ? AND badge_id = ?", 3, 3).Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
for _, userID := range []int{1, 3} {
|
||||
count, err := x.Where("user_id = ? AND badge_id = ?", userID, userID).Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
}
|
||||
|
||||
totalCount, err := x.Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
@@ -62,13 +60,11 @@ func Test_AddUniqueIndexForUserBadge(t *testing.T) {
|
||||
}
|
||||
|
||||
// verify the duplicates were removed
|
||||
count, err = x.Where("user_id = ? AND badge_id = ?", 1, 1).Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
count, err = x.Where("user_id = ? AND badge_id = ?", 3, 3).Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
for _, userID := range []int{1, 3} {
|
||||
count, err := x.Where("user_id = ? AND badge_id = ?", userID, userID).Count(&UserBadgeBefore{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
// check total count
|
||||
totalCount, err = x.Count(&UserBadgeBefore{})
|
||||
|
||||
@@ -10,22 +10,6 @@ import (
|
||||
)
|
||||
|
||||
func TestAggregateJobStatus(t *testing.T) {
|
||||
testStatuses := func(expected Status, statuses []Status) {
|
||||
t.Helper()
|
||||
var jobs []*ActionRunJob
|
||||
for _, v := range statuses {
|
||||
jobs = append(jobs, &ActionRunJob{Status: v})
|
||||
}
|
||||
actual := AggregateJobStatus(jobs)
|
||||
if !assert.Equal(t, expected, actual) {
|
||||
var statusStrings []string
|
||||
for _, s := range statuses {
|
||||
statusStrings = append(statusStrings, s.String())
|
||||
}
|
||||
t.Errorf("AggregateJobStatus(%v) = %v, want %v", statusStrings, statusNames[actual], statusNames[expected])
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
statuses []Status
|
||||
expected Status
|
||||
@@ -92,6 +76,17 @@ func TestAggregateJobStatus(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
testStatuses(c.expected, c.statuses)
|
||||
var jobs []*ActionRunJob
|
||||
for _, status := range c.statuses {
|
||||
jobs = append(jobs, &ActionRunJob{Status: status})
|
||||
}
|
||||
actual := AggregateJobStatus(jobs)
|
||||
if !assert.Equal(t, c.expected, actual) {
|
||||
var statusStrings []string
|
||||
for _, status := range c.statuses {
|
||||
statusStrings = append(statusStrings, status.String())
|
||||
}
|
||||
t.Errorf("AggregateJobStatus(%v) = %v, want %v", statusStrings, statusNames[actual], statusNames[c.expected])
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
-274
@@ -16,189 +16,267 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetPriorAttemptChildrenByParent(t *testing.T) {
|
||||
func TestRunJobDatabase(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
|
||||
// 3 attempts of one run:
|
||||
// 1: caller expanded with 3 matrix instances of "work" + non-matrix sibling "summary".
|
||||
// 2: caller skipped, no children rows.
|
||||
// 3: placeholder "current" attempt for the walkback subtest.
|
||||
t.Run("prior attempt children by parent", func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
run := &ActionRun{
|
||||
Title: "prior-children-test",
|
||||
RepoID: 4,
|
||||
Index: 9501,
|
||||
OwnerID: 1,
|
||||
WorkflowID: "matrix.yaml",
|
||||
TriggerUserID: 1,
|
||||
Ref: "refs/heads/master",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
EventPayload: "{}",
|
||||
Status: StatusSuccess,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, run))
|
||||
// 3 attempts of one run:
|
||||
// 1: caller expanded with 3 matrix instances of "work" + non-matrix sibling "summary".
|
||||
// 2: caller skipped, no children rows.
|
||||
// 3: placeholder "current" attempt for the walkback subtest.
|
||||
|
||||
const callerAttemptJobID int64 = 9001
|
||||
insertAttempt := func(t *testing.T, num int64, status Status) *ActionRunAttempt {
|
||||
t.Helper()
|
||||
a := &ActionRunAttempt{
|
||||
RepoID: run.RepoID,
|
||||
RunID: run.ID,
|
||||
Attempt: num,
|
||||
run := &ActionRun{
|
||||
Title: "prior-children-test",
|
||||
RepoID: 4,
|
||||
Index: 9501,
|
||||
OwnerID: 1,
|
||||
WorkflowID: "matrix.yaml",
|
||||
TriggerUserID: 1,
|
||||
Status: status,
|
||||
Ref: "refs/heads/master",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
EventPayload: "{}",
|
||||
Status: StatusSuccess,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, a))
|
||||
return a
|
||||
}
|
||||
insertCaller := func(t *testing.T, attemptID int64, status Status, expanded bool) *ActionRunJob {
|
||||
t.Helper()
|
||||
caller := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RunAttemptID: attemptID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: "caller",
|
||||
JobID: "caller",
|
||||
Attempt: 1,
|
||||
Status: status,
|
||||
AttemptJobID: callerAttemptJobID,
|
||||
IsReusableCaller: true,
|
||||
IsExpanded: expanded,
|
||||
require.NoError(t, db.Insert(ctx, run))
|
||||
|
||||
const callerAttemptJobID int64 = 9001
|
||||
insertAttempt := func(t *testing.T, num int64, status Status) *ActionRunAttempt {
|
||||
t.Helper()
|
||||
a := &ActionRunAttempt{
|
||||
RepoID: run.RepoID,
|
||||
RunID: run.ID,
|
||||
Attempt: num,
|
||||
TriggerUserID: 1,
|
||||
Status: status,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, a))
|
||||
return a
|
||||
}
|
||||
insertCaller := func(t *testing.T, attemptID int64, status Status, expanded bool) *ActionRunJob {
|
||||
t.Helper()
|
||||
caller := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RunAttemptID: attemptID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: "caller",
|
||||
JobID: "caller",
|
||||
Attempt: 1,
|
||||
Status: status,
|
||||
AttemptJobID: callerAttemptJobID,
|
||||
IsReusableCaller: true,
|
||||
IsExpanded: expanded,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, caller))
|
||||
return caller
|
||||
}
|
||||
insertChild := func(t *testing.T, attemptID, parentID, attemptJobID int64, name, jobID string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Insert(ctx, &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RunAttemptID: attemptID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: name,
|
||||
JobID: jobID,
|
||||
Attempt: 1,
|
||||
Status: StatusSuccess,
|
||||
AttemptJobID: attemptJobID,
|
||||
ParentJobID: parentID,
|
||||
}))
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, caller))
|
||||
return caller
|
||||
}
|
||||
insertChild := func(t *testing.T, attemptID, parentID, attemptJobID int64, name, jobID string) {
|
||||
t.Helper()
|
||||
require.NoError(t, db.Insert(ctx, &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RunAttemptID: attemptID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: name,
|
||||
JobID: jobID,
|
||||
Attempt: 1,
|
||||
Status: StatusSuccess,
|
||||
AttemptJobID: attemptJobID,
|
||||
ParentJobID: parentID,
|
||||
}))
|
||||
}
|
||||
|
||||
attempt1 := insertAttempt(t, 1, StatusSuccess)
|
||||
caller1 := insertCaller(t, attempt1.ID, StatusSuccess, true)
|
||||
insertChild(t, attempt1.ID, caller1.ID, 101, "work (alpha)", "work")
|
||||
insertChild(t, attempt1.ID, caller1.ID, 102, "work (beta)", "work")
|
||||
insertChild(t, attempt1.ID, caller1.ID, 103, "work (gamma)", "work")
|
||||
insertChild(t, attempt1.ID, caller1.ID, 104, "summary", "summary")
|
||||
attempt1 := insertAttempt(t, 1, StatusSuccess)
|
||||
caller1 := insertCaller(t, attempt1.ID, StatusSuccess, true)
|
||||
insertChild(t, attempt1.ID, caller1.ID, 101, "work (alpha)", "work")
|
||||
insertChild(t, attempt1.ID, caller1.ID, 102, "work (beta)", "work")
|
||||
insertChild(t, attempt1.ID, caller1.ID, 103, "work (gamma)", "work")
|
||||
insertChild(t, attempt1.ID, caller1.ID, 104, "summary", "summary")
|
||||
|
||||
attempt2 := insertAttempt(t, 2, StatusSkipped)
|
||||
insertCaller(t, attempt2.ID, StatusSkipped, false) // no children intentionally
|
||||
attempt2 := insertAttempt(t, 2, StatusSkipped)
|
||||
insertCaller(t, attempt2.ID, StatusSkipped, false) // no children intentionally
|
||||
|
||||
// both subtests expect attempt 1's expansion, differing only in the "current" attempt id
|
||||
assertAttempt1Children := func(t *testing.T, out map[string]map[string]*ActionRunJob) {
|
||||
t.Helper()
|
||||
// outer map keyed by JobID: "work" has 3 matrix instances, "summary" 1
|
||||
assert.Len(t, out, 2)
|
||||
assert.Len(t, out["work"], 3, "matrix instances must each get their own inner-map entry")
|
||||
assert.Len(t, out["summary"], 1)
|
||||
// both subtests expect attempt 1's expansion, differing only in the "current" attempt id
|
||||
assertAttempt1Children := func(t *testing.T, out map[string]map[string]*ActionRunJob) {
|
||||
t.Helper()
|
||||
// outer map keyed by JobID: "work" has 3 matrix instances, "summary" 1
|
||||
assert.Len(t, out, 2)
|
||||
assert.Len(t, out["work"], 3, "matrix instances must each get their own inner-map entry")
|
||||
assert.Len(t, out["summary"], 1)
|
||||
|
||||
require.NotNil(t, out["work"]["work (alpha)"])
|
||||
require.NotNil(t, out["work"]["work (beta)"])
|
||||
require.NotNil(t, out["work"]["work (gamma)"])
|
||||
require.NotNil(t, out["summary"]["summary"])
|
||||
require.NotNil(t, out["work"]["work (alpha)"])
|
||||
require.NotNil(t, out["work"]["work (beta)"])
|
||||
require.NotNil(t, out["work"]["work (gamma)"])
|
||||
require.NotNil(t, out["summary"]["summary"])
|
||||
|
||||
assert.Equal(t, int64(101), out["work"]["work (alpha)"].AttemptJobID)
|
||||
assert.Equal(t, int64(102), out["work"]["work (beta)"].AttemptJobID)
|
||||
assert.Equal(t, int64(103), out["work"]["work (gamma)"].AttemptJobID)
|
||||
assert.Equal(t, int64(104), out["summary"]["summary"].AttemptJobID)
|
||||
}
|
||||
assert.Equal(t, int64(101), out["work"]["work (alpha)"].AttemptJobID)
|
||||
assert.Equal(t, int64(102), out["work"]["work (beta)"].AttemptJobID)
|
||||
assert.Equal(t, int64(103), out["work"]["work (gamma)"].AttemptJobID)
|
||||
assert.Equal(t, int64(104), out["summary"]["summary"].AttemptJobID)
|
||||
}
|
||||
|
||||
t.Run("matrix instances and non-matrix sibling are indexed by (JobID, Name)", func(t *testing.T) {
|
||||
// "current" = attempt 2; prior = attempt 1, which is the immediately preceding attempt.
|
||||
out, err := GetPriorAttemptChildrenByParent(ctx, run.ID, attempt2.ID, callerAttemptJobID)
|
||||
require.NoError(t, err)
|
||||
assertAttempt1Children(t, out)
|
||||
t.Run("matrix instances and non-matrix sibling are indexed by (JobID, Name)", func(t *testing.T) {
|
||||
// "current" = attempt 2; prior = attempt 1, which is the immediately preceding attempt.
|
||||
out, err := GetPriorAttemptChildrenByParent(ctx, run.ID, attempt2.ID, callerAttemptJobID)
|
||||
require.NoError(t, err)
|
||||
assertAttempt1Children(t, out)
|
||||
})
|
||||
|
||||
t.Run("walkback past an attempt where the caller had no children", func(t *testing.T) {
|
||||
attempt3 := insertAttempt(t, 3, StatusRunning)
|
||||
// "current" = attempt 3; the immediately preceding attempt 2 has no children, so the lookup must walk further back to attempt 1.
|
||||
out, err := GetPriorAttemptChildrenByParent(ctx, run.ID, attempt3.ID, callerAttemptJobID)
|
||||
require.NoError(t, err)
|
||||
assertAttempt1Children(t, out)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("walkback past an attempt where the caller had no children", func(t *testing.T) {
|
||||
attempt3 := insertAttempt(t, 3, StatusRunning)
|
||||
// "current" = attempt 3; the immediately preceding attempt 2 has no children, so the lookup must walk further back to attempt 1.
|
||||
out, err := GetPriorAttemptChildrenByParent(ctx, run.ID, attempt3.ID, callerAttemptJobID)
|
||||
require.NoError(t, err)
|
||||
assertAttempt1Children(t, out)
|
||||
})
|
||||
}
|
||||
t.Run("cancel reusable callers", func(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, title, workflowID string
|
||||
index int64
|
||||
status Status
|
||||
}{
|
||||
{"NestedBlockedReusableCaller", "cancel-nested-caller", "caller.yaml", 9701, StatusBlocked},
|
||||
{"CallerWaitsForCancellingChild", "caller-cancelling-child", "test.yaml", 9811, StatusRunning},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
// A reusable caller subtree with a Blocked descendant (e.g. a nested caller stuck on an invalid `uses:`) must aggregate to Cancelled, when the run is cancelled.
|
||||
func TestCancelJobs_NestedBlockedReusableCaller(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
run := &ActionRun{
|
||||
Title: tc.title,
|
||||
RepoID: 4,
|
||||
Index: tc.index,
|
||||
OwnerID: 1,
|
||||
WorkflowID: tc.workflowID,
|
||||
TriggerUserID: 1,
|
||||
Ref: "refs/heads/master",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
EventPayload: "{}",
|
||||
Status: tc.status,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, run))
|
||||
|
||||
run := &ActionRun{
|
||||
Title: "cancel-nested-caller",
|
||||
RepoID: 4,
|
||||
Index: 9701,
|
||||
OwnerID: 1,
|
||||
WorkflowID: "caller.yaml",
|
||||
TriggerUserID: 1,
|
||||
Ref: "refs/heads/master",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
EventPayload: "{}",
|
||||
Status: StatusBlocked,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, run))
|
||||
attempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 1, TriggerUserID: 1, Status: tc.status}
|
||||
require.NoError(t, db.Insert(ctx, attempt))
|
||||
run.LatestAttemptID = attempt.ID
|
||||
require.NoError(t, UpdateRun(ctx, run, "latest_attempt_id"))
|
||||
|
||||
attempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 1, TriggerUserID: 1, Status: StatusBlocked}
|
||||
require.NoError(t, db.Insert(ctx, attempt))
|
||||
run.LatestAttemptID = attempt.ID
|
||||
require.NoError(t, UpdateRun(ctx, run, "latest_attempt_id"))
|
||||
newJob := func(job *ActionRunJob) *ActionRunJob {
|
||||
job.RunID = run.ID
|
||||
job.RunAttemptID = attempt.ID
|
||||
job.RepoID = run.RepoID
|
||||
job.OwnerID = run.OwnerID
|
||||
job.CommitSHA = run.CommitSHA
|
||||
job.JobID = job.Name
|
||||
job.Attempt = 1
|
||||
job.Status = tc.status
|
||||
require.NoError(t, db.Insert(ctx, job))
|
||||
return job
|
||||
}
|
||||
|
||||
newJob := func(name string, attemptJobID, parentID int64, callUses string) *ActionRunJob {
|
||||
job := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RunAttemptID: attempt.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: name,
|
||||
JobID: name,
|
||||
Attempt: 1,
|
||||
Status: StatusBlocked,
|
||||
AttemptJobID: attemptJobID,
|
||||
IsReusableCaller: true,
|
||||
CallUses: callUses,
|
||||
ParentJobID: parentID,
|
||||
// A reusable caller subtree with a Blocked descendant (e.g. a nested caller stuck on an invalid `uses:`) must aggregate to Cancelled, when the run is cancelled.
|
||||
if tc.status == StatusBlocked {
|
||||
// outer: a valid top-level caller that expanded; inner: a nested caller stuck Blocked (invalid uses, never expands).
|
||||
outer := newJob(&ActionRunJob{Name: "outer", AttemptJobID: 1, IsReusableCaller: true, CallUses: "./.gitea/workflows/lib.yml"})
|
||||
inner := newJob(&ActionRunJob{Name: "inner", AttemptJobID: 2, ParentJobID: outer.ID, IsReusableCaller: true, CallUses: "https://other.example.com/o/r/.gitea/workflows/ci.yml@v1"})
|
||||
|
||||
// Cancel all jobs of the attempt, ordered by id (parent before child).
|
||||
jobs, err := GetRunJobsByRunAndAttemptID(ctx, run.ID, attempt.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = CancelJobs(ctx, jobs, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, j := range []*ActionRunJob{outer, inner} {
|
||||
got := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: j.ID})
|
||||
assert.Equal(t, StatusCancelled, got.Status, "job %q should be cancelled", j.JobID)
|
||||
}
|
||||
gotAttempt := unittest.AssertExistsAndLoadBean(t, &ActionRunAttempt{ID: attempt.ID})
|
||||
assert.Equal(t, StatusCancelled, gotAttempt.Status, "attempt must aggregate to Cancelled")
|
||||
gotRun := unittest.AssertExistsAndLoadBean(t, &ActionRun{ID: run.ID})
|
||||
assert.Equal(t, StatusCancelled, gotRun.Status, "run must aggregate to Cancelled, not stay Blocked")
|
||||
} else {
|
||||
outer := newJob(&ActionRunJob{Name: "outer", IsReusableCaller: true, IsExpanded: true})
|
||||
inner := newJob(&ActionRunJob{Name: "inner", ParentJobID: outer.ID, IsReusableCaller: true, IsExpanded: true})
|
||||
child := newJob(&ActionRunJob{Name: "child", ParentJobID: inner.ID})
|
||||
|
||||
runner := &ActionRunner{UUID: "caller-cancelling-child", Name: "caller-cancelling-child", HasCancellingSupport: true}
|
||||
require.NoError(t, db.Insert(ctx, runner))
|
||||
task := &ActionTask{JobID: child.ID, Attempt: 1, RunnerID: runner.ID, Status: StatusRunning, Started: timeutil.TimeStampNow(), RepoID: run.RepoID, OwnerID: run.OwnerID, CommitSHA: run.CommitSHA}
|
||||
require.NoError(t, db.Insert(ctx, task))
|
||||
child.TaskID = task.ID
|
||||
_, err := UpdateRunJob(ctx, child, nil, "task_id")
|
||||
require.NoError(t, err)
|
||||
|
||||
cancelled, err := CancelJobs(ctx, []*ActionRunJob{outer}, false)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cancelled, 3)
|
||||
for _, job := range []*ActionRunJob{outer, inner, child} {
|
||||
assert.Equal(t, StatusCancelling, unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID}).Status, job.Name)
|
||||
}
|
||||
|
||||
_, err = UpdateTaskByState(ctx, runner.ID, &runnerv1.TaskState{Id: task.ID, Result: runnerv1.Result_RESULT_CANCELLED})
|
||||
require.NoError(t, err)
|
||||
for _, job := range []*ActionRunJob{outer, inner, child} {
|
||||
assert.Equal(t, StatusCancelled, unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID}).Status, job.Name)
|
||||
}
|
||||
assert.Equal(t, StatusCancelled, unittest.AssertExistsAndLoadBean(t, &ActionRun{ID: run.ID}).Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, job))
|
||||
return job
|
||||
}
|
||||
})
|
||||
|
||||
// outer: a valid top-level caller that expanded; inner: a nested caller stuck Blocked (invalid uses, never expands).
|
||||
outer := newJob("outer", 1, 0, "./.gitea/workflows/lib.yml")
|
||||
inner := newJob("inner", 2, outer.ID, "https://other.example.com/o/r/.gitea/workflows/ci.yml@v1")
|
||||
t.Run("batch load and cancel run jobs", func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
// Cancel all jobs of the attempt, ordered by id (parent before child).
|
||||
jobs, err := GetRunJobsByRunAndAttemptID(ctx, run.ID, attempt.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = CancelJobs(ctx, jobs, false)
|
||||
require.NoError(t, err)
|
||||
legacyRun := &ActionRun{RepoID: 4, OwnerID: 1, Index: 9600, TriggerUserID: 1, Ref: "refs/heads/batch", Status: StatusRunning}
|
||||
run := &ActionRun{RepoID: 4, OwnerID: 1, Index: 9601, TriggerUserID: 1, Ref: "refs/heads/batch", Status: StatusRunning}
|
||||
require.NoError(t, db.Insert(ctx, legacyRun, run))
|
||||
require.NoError(t, db.Insert(ctx, &ActionRunJob{RunID: legacyRun.ID, RepoID: legacyRun.RepoID, OwnerID: legacyRun.OwnerID}))
|
||||
oldAttempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 1, TriggerUserID: 1}
|
||||
latestAttempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 2, TriggerUserID: 2}
|
||||
require.NoError(t, db.Insert(ctx, oldAttempt, latestAttempt))
|
||||
for _, attemptID := range []int64{oldAttempt.ID, latestAttempt.ID, latestAttempt.ID} {
|
||||
require.NoError(t, db.Insert(ctx, &ActionRunJob{RunID: run.ID, RunAttemptID: attemptID, RepoID: run.RepoID, OwnerID: run.OwnerID}))
|
||||
}
|
||||
run.LatestAttemptID = latestAttempt.ID
|
||||
require.NoError(t, UpdateRun(ctx, run, "latest_attempt_id"))
|
||||
|
||||
for _, j := range []*ActionRunJob{outer, inner} {
|
||||
got := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: j.ID})
|
||||
assert.Equal(t, StatusCancelled, got.Status, "job %q should be cancelled", j.JobID)
|
||||
}
|
||||
gotAttempt := unittest.AssertExistsAndLoadBean(t, &ActionRunAttempt{ID: attempt.ID})
|
||||
assert.Equal(t, StatusCancelled, gotAttempt.Status, "attempt must aggregate to Cancelled")
|
||||
gotRun := unittest.AssertExistsAndLoadBean(t, &ActionRun{ID: run.ID})
|
||||
assert.Equal(t, StatusCancelled, gotRun.Status, "run must aggregate to Cancelled, not stay Blocked")
|
||||
runs := RunList{legacyRun, run}
|
||||
jobsByRun, err := GetLatestAttemptJobsByRuns(ctx, runs)
|
||||
require.NoError(t, err)
|
||||
for _, listedRun := range runs {
|
||||
expected, err := GetLatestAttemptJobsByRun(ctx, listedRun)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, expected)
|
||||
assert.Equal(t, expected, jobsByRun[listedRun.ID])
|
||||
}
|
||||
|
||||
attempts, err := runs.GetLatestAttempts(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, attempts, 1)
|
||||
assert.EqualValues(t, 2, attempts[latestAttempt.ID].TriggerUser.ID)
|
||||
|
||||
chunkedAttempts := []*ActionRunAttempt{oldAttempt}
|
||||
for i := range db.DefaultMaxInSize {
|
||||
chunkedAttempts = append(chunkedAttempts, &ActionRunAttempt{ID: -int64(i + 1)})
|
||||
}
|
||||
attemptJobs, err := getRunJobsByAttempts(ctx, append(chunkedAttempts, latestAttempt))
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, attemptJobs, 3)
|
||||
|
||||
cancelled, err := CancelPreviousJobs(ctx, run.RepoID, run.Ref, "", "")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cancelled, 4)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSettleRunAfterCancel(t *testing.T) {
|
||||
@@ -398,117 +476,3 @@ func TestForceCancelJobs(t *testing.T) {
|
||||
assert.Equal(t, StatusCancelled, callerAfter.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCancelJobs_CallerWaitsForCancellingChild(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
|
||||
run := &ActionRun{
|
||||
Title: "caller-cancelling-child",
|
||||
RepoID: 4,
|
||||
Index: 9811,
|
||||
OwnerID: 1,
|
||||
WorkflowID: "test.yaml",
|
||||
TriggerUserID: 1,
|
||||
Ref: "refs/heads/master",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
EventPayload: "{}",
|
||||
Status: StatusRunning,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, run))
|
||||
attempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 1, TriggerUserID: 1, Status: StatusRunning}
|
||||
require.NoError(t, db.Insert(ctx, attempt))
|
||||
run.LatestAttemptID = attempt.ID
|
||||
require.NoError(t, UpdateRun(ctx, run, "latest_attempt_id"))
|
||||
|
||||
newJob := func(name string, parentID int64, isCaller bool) *ActionRunJob {
|
||||
job := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RunAttemptID: attempt.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: name,
|
||||
JobID: name,
|
||||
Attempt: 1,
|
||||
Status: StatusRunning,
|
||||
ParentJobID: parentID,
|
||||
IsReusableCaller: isCaller,
|
||||
IsExpanded: isCaller,
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, job))
|
||||
return job
|
||||
}
|
||||
outer := newJob("outer", 0, true)
|
||||
inner := newJob("inner", outer.ID, true)
|
||||
child := newJob("child", inner.ID, false)
|
||||
|
||||
runner := &ActionRunner{UUID: "caller-cancelling-child", Name: "caller-cancelling-child", HasCancellingSupport: true}
|
||||
require.NoError(t, db.Insert(ctx, runner))
|
||||
task := &ActionTask{JobID: child.ID, Attempt: 1, RunnerID: runner.ID, Status: StatusRunning, Started: timeutil.TimeStampNow(), RepoID: run.RepoID, OwnerID: run.OwnerID, CommitSHA: run.CommitSHA}
|
||||
require.NoError(t, db.Insert(ctx, task))
|
||||
child.TaskID = task.ID
|
||||
_, err := UpdateRunJob(ctx, child, nil, "task_id")
|
||||
require.NoError(t, err)
|
||||
|
||||
cancelled, err := CancelJobs(ctx, []*ActionRunJob{outer}, false)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cancelled, 3)
|
||||
for _, job := range []*ActionRunJob{outer, inner, child} {
|
||||
assert.Equal(t, StatusCancelling, unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID}).Status, job.Name)
|
||||
}
|
||||
|
||||
_, err = UpdateTaskByState(ctx, runner.ID, &runnerv1.TaskState{Id: task.ID, Result: runnerv1.Result_RESULT_CANCELLED})
|
||||
require.NoError(t, err)
|
||||
for _, job := range []*ActionRunJob{outer, inner, child} {
|
||||
assert.Equal(t, StatusCancelled, unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID}).Status, job.Name)
|
||||
}
|
||||
assert.Equal(t, StatusCancelled, unittest.AssertExistsAndLoadBean(t, &ActionRun{ID: run.ID}).Status)
|
||||
}
|
||||
|
||||
func TestBatchLoadAndCancelRunJobs(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
|
||||
legacyRun := &ActionRun{RepoID: 4, OwnerID: 1, Index: 9600, TriggerUserID: 1, Ref: "refs/heads/batch", Status: StatusRunning}
|
||||
run := &ActionRun{RepoID: 4, OwnerID: 1, Index: 9601, TriggerUserID: 1, Ref: "refs/heads/batch", Status: StatusRunning}
|
||||
require.NoError(t, db.Insert(ctx, legacyRun, run))
|
||||
require.NoError(t, db.Insert(ctx, &ActionRunJob{RunID: legacyRun.ID, RepoID: legacyRun.RepoID, OwnerID: legacyRun.OwnerID}))
|
||||
oldAttempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 1, TriggerUserID: 1}
|
||||
latestAttempt := &ActionRunAttempt{RepoID: run.RepoID, RunID: run.ID, Attempt: 2, TriggerUserID: 2}
|
||||
require.NoError(t, db.Insert(ctx, oldAttempt, latestAttempt))
|
||||
for _, attemptID := range []int64{oldAttempt.ID, latestAttempt.ID, latestAttempt.ID} {
|
||||
require.NoError(t, db.Insert(ctx, &ActionRunJob{RunID: run.ID, RunAttemptID: attemptID, RepoID: run.RepoID, OwnerID: run.OwnerID}))
|
||||
}
|
||||
run.LatestAttemptID = latestAttempt.ID
|
||||
require.NoError(t, UpdateRun(ctx, run, "latest_attempt_id"))
|
||||
|
||||
runs := RunList{legacyRun, run}
|
||||
jobsByRun, err := GetLatestAttemptJobsByRuns(ctx, runs)
|
||||
require.NoError(t, err)
|
||||
for _, listedRun := range runs {
|
||||
expected, err := GetLatestAttemptJobsByRun(ctx, listedRun)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, expected)
|
||||
assert.Equal(t, expected, jobsByRun[listedRun.ID])
|
||||
}
|
||||
|
||||
attempts, err := runs.GetLatestAttempts(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, attempts, 1)
|
||||
assert.EqualValues(t, 2, attempts[latestAttempt.ID].TriggerUser.ID)
|
||||
|
||||
chunkedAttempts := []*ActionRunAttempt{oldAttempt}
|
||||
for i := range db.DefaultMaxInSize {
|
||||
chunkedAttempts = append(chunkedAttempts, &ActionRunAttempt{ID: -int64(i + 1)})
|
||||
}
|
||||
attemptJobs, err := getRunJobsByAttempts(ctx, append(chunkedAttempts, latestAttempt))
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, attemptJobs, 3)
|
||||
|
||||
cancelled, err := CancelPreviousJobs(ctx, run.RepoID, run.Ref, "", "")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cancelled, 4)
|
||||
}
|
||||
@@ -12,72 +12,32 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestShouldPersistLastOnline(t *testing.T) {
|
||||
now := time.Now()
|
||||
tests := []struct {
|
||||
name string
|
||||
last timeutil.TimeStamp
|
||||
want bool
|
||||
func TestShouldPersistRunnerTimestamps(t *testing.T) {
|
||||
for _, scenario := range []struct {
|
||||
name string
|
||||
persist func(timeutil.TimeStamp, time.Time) bool
|
||||
interval time.Duration
|
||||
freshAge time.Duration
|
||||
}{
|
||||
{
|
||||
name: "fresh, skip write",
|
||||
last: timeutil.TimeStamp(now.Add(-5 * time.Second).Unix()),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "exactly at interval, write",
|
||||
last: timeutil.TimeStamp(now.Add(-RunnerHeartbeatInterval).Unix()),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "stale, write",
|
||||
last: timeutil.TimeStamp(now.Add(-2 * RunnerHeartbeatInterval).Unix()),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "zero (never seen), write",
|
||||
last: 0,
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, ShouldPersistLastOnline(tt.last, now))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldPersistLastActive(t *testing.T) {
|
||||
now := time.Now()
|
||||
tests := []struct {
|
||||
name string
|
||||
last timeutil.TimeStamp
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "fresh, skip write",
|
||||
last: timeutil.TimeStamp(now.Add(-1 * time.Second).Unix()),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "exactly at interval, write",
|
||||
last: timeutil.TimeStamp(now.Add(-RunnerActiveInterval).Unix()),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "stale, write",
|
||||
last: timeutil.TimeStamp(now.Add(-2 * RunnerActiveInterval).Unix()),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "zero (never seen), write",
|
||||
last: 0,
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, ShouldPersistLastActive(tt.last, now))
|
||||
{"online", ShouldPersistLastOnline, RunnerHeartbeatInterval, 5 * time.Second},
|
||||
{"active", ShouldPersistLastActive, RunnerActiveInterval, time.Second},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
now := time.Now()
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
last timeutil.TimeStamp
|
||||
want bool
|
||||
}{
|
||||
{"fresh, skip write", timeutil.TimeStamp(now.Add(-scenario.freshAge).Unix()), false},
|
||||
{"exactly at interval, write", timeutil.TimeStamp(now.Add(-scenario.interval).Unix()), true},
|
||||
{"stale, write", timeutil.TimeStamp(now.Add(-2 * scenario.interval).Unix()), true},
|
||||
{"zero (never seen), write", 0, true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, scenario.persist(tt.last, now))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,41 +11,28 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestStatusAsResult(t *testing.T) {
|
||||
func TestStatusResultConversions(t *testing.T) {
|
||||
cases := []struct {
|
||||
status Status
|
||||
want runnerv1.Result
|
||||
status Status
|
||||
result runnerv1.Result
|
||||
fromResult bool
|
||||
}{
|
||||
{StatusUnknown, runnerv1.Result_RESULT_UNSPECIFIED},
|
||||
{StatusWaiting, runnerv1.Result_RESULT_UNSPECIFIED},
|
||||
{StatusRunning, runnerv1.Result_RESULT_UNSPECIFIED},
|
||||
{StatusBlocked, runnerv1.Result_RESULT_UNSPECIFIED},
|
||||
{StatusSuccess, runnerv1.Result_RESULT_SUCCESS},
|
||||
{StatusFailure, runnerv1.Result_RESULT_FAILURE},
|
||||
{StatusCancelled, runnerv1.Result_RESULT_CANCELLED},
|
||||
{StatusCancelling, runnerv1.Result_RESULT_CANCELLED},
|
||||
{StatusSkipped, runnerv1.Result_RESULT_SKIPPED},
|
||||
{StatusUnknown, runnerv1.Result_RESULT_UNSPECIFIED, true},
|
||||
{StatusWaiting, runnerv1.Result_RESULT_UNSPECIFIED, false},
|
||||
{StatusRunning, runnerv1.Result_RESULT_UNSPECIFIED, false},
|
||||
{StatusBlocked, runnerv1.Result_RESULT_UNSPECIFIED, false},
|
||||
{StatusSuccess, runnerv1.Result_RESULT_SUCCESS, true},
|
||||
{StatusFailure, runnerv1.Result_RESULT_FAILURE, true},
|
||||
{StatusCancelled, runnerv1.Result_RESULT_CANCELLED, true},
|
||||
{StatusCancelling, runnerv1.Result_RESULT_CANCELLED, false},
|
||||
{StatusSkipped, runnerv1.Result_RESULT_SKIPPED, true},
|
||||
}
|
||||
|
||||
for _, tt := range cases {
|
||||
assert.Equal(t, tt.want, tt.status.AsResult(), "status=%s", tt.status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusFromResult(t *testing.T) {
|
||||
cases := []struct {
|
||||
result runnerv1.Result
|
||||
want Status
|
||||
}{
|
||||
{runnerv1.Result_RESULT_UNSPECIFIED, StatusUnknown},
|
||||
{runnerv1.Result_RESULT_SUCCESS, StatusSuccess},
|
||||
{runnerv1.Result_RESULT_FAILURE, StatusFailure},
|
||||
{runnerv1.Result_RESULT_CANCELLED, StatusCancelled},
|
||||
{runnerv1.Result_RESULT_SKIPPED, StatusSkipped},
|
||||
}
|
||||
|
||||
for _, tt := range cases {
|
||||
assert.Equal(t, tt.want, StatusFromResult(tt.result), "result=%s", tt.result)
|
||||
assert.Equal(t, tt.result, tt.status.AsResult(), "status=%s", tt.status)
|
||||
if tt.fromResult {
|
||||
assert.Equal(t, tt.status, StatusFromResult(tt.result), "result=%s", tt.result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+98
-128
@@ -241,136 +241,106 @@ func TestStopTaskCancellingKeepsReportTime(t *testing.T) {
|
||||
// its job to the waiting queue and deletes the task and its steps, so a failure
|
||||
// while assembling the runner response cannot strand the job in running state.
|
||||
func TestReleaseTaskForRunner(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
runTitle string
|
||||
runIndex int64
|
||||
jobName string
|
||||
batchSize int
|
||||
}{
|
||||
{"release", "release-task-test-run", 9902, "release-job", 0},
|
||||
{"pagination", "pagination-test-run", 9903, "target-job", 2},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
if tt.batchSize != 0 {
|
||||
defer func(orig int) { pickTaskBatchSize = orig }(pickTaskBatchSize)
|
||||
pickTaskBatchSize = tt.batchSize
|
||||
}
|
||||
|
||||
run := &ActionRun{
|
||||
Title: "release-task-test-run",
|
||||
RepoID: 1,
|
||||
OwnerID: 2,
|
||||
WorkflowID: "test.yaml",
|
||||
Index: 9902,
|
||||
TriggerUserID: 2,
|
||||
Ref: "refs/heads/main",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
Status: StatusWaiting,
|
||||
run := &ActionRun{
|
||||
Title: tt.runTitle,
|
||||
RepoID: 1,
|
||||
OwnerID: 2,
|
||||
WorkflowID: "test.yaml",
|
||||
Index: tt.runIndex,
|
||||
TriggerUserID: 2,
|
||||
Ref: "refs/heads/main",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
Status: StatusWaiting,
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), run))
|
||||
|
||||
if tt.batchSize != 0 {
|
||||
// Five waiting jobs the runner cannot run, then one it can.
|
||||
// With a page size of 2 the matching job only appears on the third page.
|
||||
for i := range 5 {
|
||||
mismatch := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: "mismatch-" + string(rune('a'+i)),
|
||||
Attempt: 1,
|
||||
JobID: "mismatch-" + string(rune('a'+i)),
|
||||
Status: StatusWaiting,
|
||||
RunsOn: []string{"windows-latest"},
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), mismatch))
|
||||
}
|
||||
}
|
||||
|
||||
job := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: tt.jobName,
|
||||
Attempt: 1,
|
||||
JobID: tt.jobName,
|
||||
Status: StatusWaiting,
|
||||
RunsOn: []string{"ubuntu-latest"},
|
||||
WorkflowPayload: []byte("on: push\njobs:\n " + tt.jobName + ":\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n"),
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), job))
|
||||
|
||||
runner := &ActionRunner{
|
||||
UUID: tt.name + "-runner-uuid",
|
||||
Name: tt.name + "-runner",
|
||||
AgentLabels: []string{"ubuntu-latest"},
|
||||
}
|
||||
runner.GenerateAndFillToken()
|
||||
require.NoError(t, db.Insert(t.Context(), runner))
|
||||
|
||||
task, ok, err := CreateTaskForRunner(t.Context(), runner)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
require.NotNil(t, task)
|
||||
|
||||
claimed := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID})
|
||||
if tt.batchSize != 0 {
|
||||
assert.Equal(t, StatusRunning, claimed.Status)
|
||||
assert.Equal(t, task.ID, claimed.TaskID)
|
||||
} else {
|
||||
require.Equal(t, StatusRunning, claimed.Status)
|
||||
require.Equal(t, task.ID, claimed.TaskID)
|
||||
|
||||
require.NoError(t, ReleaseTaskForRunner(t.Context(), task))
|
||||
|
||||
// Job is back in the waiting queue with no task assigned.
|
||||
released := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID})
|
||||
assert.Equal(t, StatusWaiting, released.Status)
|
||||
assert.Zero(t, released.TaskID)
|
||||
assert.Zero(t, released.Started)
|
||||
|
||||
// The task and its steps are gone.
|
||||
unittest.AssertNotExistsBean(t, &ActionTask{ID: task.ID})
|
||||
unittest.AssertNotExistsBean(t, &ActionTaskStep{TaskID: task.ID})
|
||||
}
|
||||
})
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), run))
|
||||
|
||||
job := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: "release-job",
|
||||
Attempt: 1,
|
||||
JobID: "release-job",
|
||||
Status: StatusWaiting,
|
||||
RunsOn: []string{"ubuntu-latest"},
|
||||
WorkflowPayload: []byte("on: push\njobs:\n release-job:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n"),
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), job))
|
||||
|
||||
runner := &ActionRunner{
|
||||
UUID: "release-runner-uuid",
|
||||
Name: "release-runner",
|
||||
AgentLabels: []string{"ubuntu-latest"},
|
||||
}
|
||||
runner.GenerateAndFillToken()
|
||||
require.NoError(t, db.Insert(t.Context(), runner))
|
||||
|
||||
task, ok, err := CreateTaskForRunner(t.Context(), runner)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
require.NotNil(t, task)
|
||||
|
||||
claimed := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID})
|
||||
require.Equal(t, StatusRunning, claimed.Status)
|
||||
require.Equal(t, task.ID, claimed.TaskID)
|
||||
|
||||
require.NoError(t, ReleaseTaskForRunner(t.Context(), task))
|
||||
|
||||
// Job is back in the waiting queue with no task assigned.
|
||||
released := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: job.ID})
|
||||
assert.Equal(t, StatusWaiting, released.Status)
|
||||
assert.Zero(t, released.TaskID)
|
||||
assert.Zero(t, released.Started)
|
||||
|
||||
// The task and its steps are gone.
|
||||
unittest.AssertNotExistsBean(t, &ActionTask{ID: task.ID})
|
||||
unittest.AssertNotExistsBean(t, &ActionTaskStep{TaskID: task.ID})
|
||||
}
|
||||
|
||||
// TestCreateTaskForRunnerPagination verifies that a job sitting beyond the first page is still claimed
|
||||
func TestCreateTaskForRunnerPagination(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
defer func(orig int) { pickTaskBatchSize = orig }(pickTaskBatchSize)
|
||||
pickTaskBatchSize = 2
|
||||
|
||||
run := &ActionRun{
|
||||
Title: "pagination-test-run",
|
||||
RepoID: 1,
|
||||
OwnerID: 2,
|
||||
WorkflowID: "test.yaml",
|
||||
Index: 9903,
|
||||
TriggerUserID: 2,
|
||||
Ref: "refs/heads/main",
|
||||
CommitSHA: "c2d72f548424103f01ee1dc02889c1e2bff816b0",
|
||||
Event: "push",
|
||||
TriggerEvent: "push",
|
||||
Status: StatusWaiting,
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), run))
|
||||
|
||||
// Five waiting jobs the runner cannot run, then one it can.
|
||||
// With a page size of 2 the matching job only appears on the third page.
|
||||
for i := range 5 {
|
||||
mismatch := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: "mismatch-" + string(rune('a'+i)),
|
||||
Attempt: 1,
|
||||
JobID: "mismatch-" + string(rune('a'+i)),
|
||||
Status: StatusWaiting,
|
||||
RunsOn: []string{"windows-latest"},
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), mismatch))
|
||||
}
|
||||
|
||||
target := &ActionRunJob{
|
||||
RunID: run.ID,
|
||||
RepoID: run.RepoID,
|
||||
OwnerID: run.OwnerID,
|
||||
CommitSHA: run.CommitSHA,
|
||||
Name: "target-job",
|
||||
Attempt: 1,
|
||||
JobID: "target-job",
|
||||
Status: StatusWaiting,
|
||||
RunsOn: []string{"ubuntu-latest"},
|
||||
WorkflowPayload: []byte("on: push\njobs:\n target-job:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n"),
|
||||
}
|
||||
require.NoError(t, db.Insert(t.Context(), target))
|
||||
|
||||
runner := &ActionRunner{
|
||||
UUID: "pagination-runner-uuid",
|
||||
Name: "pagination-runner",
|
||||
AgentLabels: []string{"ubuntu-latest"},
|
||||
}
|
||||
runner.GenerateAndFillToken()
|
||||
require.NoError(t, db.Insert(t.Context(), runner))
|
||||
|
||||
task, ok, err := CreateTaskForRunner(t.Context(), runner)
|
||||
require.NoError(t, err)
|
||||
require.True(t, ok)
|
||||
require.NotNil(t, task)
|
||||
|
||||
claimed := unittest.AssertExistsAndLoadBean(t, &ActionRunJob{ID: target.ID})
|
||||
assert.Equal(t, StatusRunning, claimed.Status)
|
||||
assert.Equal(t, task.ID, claimed.TaskID)
|
||||
}
|
||||
|
||||
type failFirstStepWrite struct{ fired atomic.Bool }
|
||||
|
||||
@@ -15,24 +15,14 @@ import (
|
||||
)
|
||||
|
||||
func TestLogIndexes_ToDB(t *testing.T) {
|
||||
tests := []struct {
|
||||
indexes LogIndexes
|
||||
}{
|
||||
{
|
||||
indexes: []int64{1, 2, 0, -1, -2, math.MaxInt64, math.MinInt64},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run("", func(t *testing.T) {
|
||||
got, err := tt.indexes.ToDB()
|
||||
require.NoError(t, err)
|
||||
inputIndexes := LogIndexes{1, 2, 0, -1, -2, math.MaxInt64, math.MinInt64}
|
||||
got, err := inputIndexes.ToDB()
|
||||
require.NoError(t, err)
|
||||
|
||||
indexes := LogIndexes{}
|
||||
require.NoError(t, indexes.FromDB(got))
|
||||
indexes := LogIndexes{}
|
||||
require.NoError(t, indexes.FromDB(got))
|
||||
|
||||
assert.Equal(t, tt.indexes, indexes)
|
||||
})
|
||||
}
|
||||
assert.Equal(t, inputIndexes, indexes)
|
||||
}
|
||||
|
||||
func Test_calculateDuration(t *testing.T) {
|
||||
|
||||
@@ -104,19 +104,14 @@ func TestConsistencyUpdateAction(t *testing.T) {
|
||||
//
|
||||
// Get rid of incorrectly set created_unix
|
||||
//
|
||||
count, err := activities_model.CountActionCreatedUnixString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, count)
|
||||
count, err = activities_model.FixActionCreatedUnixString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, count)
|
||||
|
||||
count, err = activities_model.CountActionCreatedUnixString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
count, err = activities_model.FixActionCreatedUnixString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
for _, wantCount := range []int{1, 0} {
|
||||
count, err := activities_model.CountActionCreatedUnixString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, wantCount, count)
|
||||
count, err = activities_model.FixActionCreatedUnixString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, wantCount, count)
|
||||
}
|
||||
|
||||
//
|
||||
// XORM must be happy now
|
||||
|
||||
@@ -196,23 +196,17 @@ func TestNotification_GetIssue(t *testing.T) {
|
||||
func TestGetNotificationCount(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
cnt, err := db.Count[activities_model.Notification](t.Context(), activities_model.FindNotificationOptions{
|
||||
UserID: user.ID,
|
||||
Status: []activities_model.NotificationStatus{
|
||||
activities_model.NotificationStatusRead,
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, cnt)
|
||||
|
||||
cnt, err = db.Count[activities_model.Notification](t.Context(), activities_model.FindNotificationOptions{
|
||||
UserID: user.ID,
|
||||
Status: []activities_model.NotificationStatus{
|
||||
activities_model.NotificationStatusUnread,
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, cnt)
|
||||
for count, status := range []activities_model.NotificationStatus{
|
||||
activities_model.NotificationStatusRead,
|
||||
activities_model.NotificationStatusUnread,
|
||||
} {
|
||||
cnt, err := db.Count[activities_model.Notification](t.Context(), activities_model.FindNotificationOptions{
|
||||
UserID: user.ID,
|
||||
Status: []activities_model.NotificationStatus{status},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, count, cnt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetNotificationStatus(t *testing.T) {
|
||||
|
||||
@@ -18,43 +18,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCheckArmoredGPGKeyString(t *testing.T) {
|
||||
testGPGArmor := `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mQENBFh91QoBCADciaDd7aqegYkn4ZIG7J0p1CRwpqMGjxFroJEMg6M1ZiuEVTRv
|
||||
z49P4kcr1+98NvFmcNc+x5uJgvPCwr/N8ZW5nqBUs2yrklbFF4MeQomyZJJegP8m
|
||||
/dsRT3BwIT8YMUtJuCj0iqD9vuKYfjrztcMgC1sYwcE9E9OlA0pWBvUdU2i0TIB1
|
||||
vOq6slWGvHHa5l5gPfm09idlVxfH5+I+L1uIMx5ovbiVVU5x2f1AR1T18f0t2TVN
|
||||
0agFTyuoYE1ATmvJHmMcsfgM1Gpd9hIlr9vlupT2kKTPoNzVzsJsOU6Ku/Lf/bac
|
||||
mF+TfSbRCtmG7dkYZ4metLj7zG/WkW8IvJARABEBAAG0HUFudG9pbmUgR0lSQVJE
|
||||
IDxzYXBrQHNhcGsuZnI+iQFUBBMBCAA+FiEEEIOwJg/1vpF1itJ4roJVuKDYKOQF
|
||||
Alh91QoCGwMFCQPCZwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQroJVuKDY
|
||||
KORreggAlIkC2QjHP5tb7b0+LksB2JMXdY+UzZBcJxtNmvA7gNQaGvWRrhrbePpa
|
||||
MKDP+3A4BPDBsWFbbB7N56vQ5tROpmWbNKuFOVER4S1bj0JZV0E+xkDLqt9QwQtQ
|
||||
ojd7oIZJwDUwdud1PvCza2mjgBqqiFE+twbc3i9xjciCGspMniUul1eQYLxRJ0w+
|
||||
sbvSOUnujnq5ByMSz9ij00O6aiPfNQS5oB5AALfpjYZDvWAAljLVrtmlQJWZ6dZo
|
||||
T/YNwsW2dECPuti8+Nmu5FxPGDTXxdbnRaeJTQ3T6q1oUVAv7yTXBx5NXfXkMa5i
|
||||
iEayQIH8Joq5Ev5ja/lRGQQhArMQ2bkBDQRYfdUKAQgAv7B3coLSrOQbuTZSlgWE
|
||||
QeT+7DWbmqE1LAQA1pQPcUPXLBUVd60amZJxF9nzUYcY83ylDi0gUNJS+DJGOXpT
|
||||
pzX2IOuOMGbtUSeKwg5s9O4SUO7f2yCc3RGaegER5zgESxelmOXG+b/hoNt7JbdU
|
||||
JtxcnLr91Jw2PBO/Xf0ZKJ01CQG2Yzdrrj6jnrHyx94seHy0i6xH1o0OuvfVMLfN
|
||||
/Vbb/ZHh6ym2wHNqRX62b0VAbchcJXX/MEehXGknKTkO6dDUd+mhRgWMf9ZGRFWx
|
||||
ag4qALimkf1FXtAyD0vxFYeyoWUQzrOvUsm2BxIN/986R08fhkBQnp5nz07mrU02
|
||||
cQARAQABiQE8BBgBCAAmFiEEEIOwJg/1vpF1itJ4roJVuKDYKOQFAlh91QoCGwwF
|
||||
CQPCZwAACgkQroJVuKDYKOT32wf/UZqMdPn5OhyhffFzjQx7wolrf92WkF2JkxtH
|
||||
6c3Htjlt/p5RhtKEeErSrNAxB4pqB7dznHaJXiOdWEZtRVXXjlNHjrokGTesqtKk
|
||||
lHWtK62/MuyLdr+FdCl68F3ewuT2iu/MDv+D4HPqA47zma9xVgZ9ZNwJOpv3fCOo
|
||||
RfY66UjGEnfgYifgtI5S84/mp2jaSc9UNvlZB6RSf8cfbJUL74kS2lq+xzSlf0yP
|
||||
Av844q/BfRuVsJsK1NDNG09LC30B0l3LKBqlrRmRTUMHtgchdX2dY+p7GPOoSzlR
|
||||
MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg==
|
||||
=i9b7
|
||||
-----END PGP PUBLIC KEY BLOCK-----`
|
||||
|
||||
key, err := CheckArmoredGPGKeyString(testGPGArmor)
|
||||
assert.NoError(t, err, "Could not parse a valid GPG public armored rsa key", key)
|
||||
// TODO verify value of key
|
||||
}
|
||||
|
||||
func TestCheckArmoredbrainpoolP256r1GPGKeyString(t *testing.T) {
|
||||
testGPGArmor := `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
Version: GnuPG v2
|
||||
@@ -108,6 +71,10 @@ MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg==
|
||||
=i9b7
|
||||
-----END PGP PUBLIC KEY BLOCK-----`
|
||||
keys, err := CheckArmoredGPGKeyString(testGPGArmor)
|
||||
assert.NoError(t, err, "Could not parse a valid GPG public armored rsa key", keys)
|
||||
// TODO verify value of key
|
||||
|
||||
keys, err = CheckArmoredGPGKeyString(testGPGArmor)
|
||||
require.NotEmpty(t, keys)
|
||||
|
||||
ekey := keys[0]
|
||||
|
||||
@@ -23,18 +23,18 @@ import (
|
||||
|
||||
func Test_SSHParsePublicKey(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
skipSSHKeygen bool
|
||||
keyType string
|
||||
length int
|
||||
content string
|
||||
name string
|
||||
keyType string
|
||||
length int
|
||||
fp string
|
||||
content string
|
||||
}{
|
||||
{"rsa-1024", false, "rsa", 1024, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n"},
|
||||
{"rsa-2048", false, "rsa", 2048, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMZXh+1OBUwSH9D45wTaxErQIN9IoC9xl7MKJkqvTvv6O5RR9YW/IK9FbfjXgXsppYGhsCZo1hFOOsXHMnfOORqu/xMDx4yPuyvKpw4LePEcg4TDipaDFuxbWOqc/BUZRZcXu41QAWfDLrInwsltWZHSeG7hjhpacl4FrVv9V1pS6Oc5Q1NxxEzTzuNLS/8diZrTm/YAQQ/+B+mzWI3zEtF4miZjjAljWd1LTBPvU23d29DcBmmFahcZ441XZsTeAwGxG/Q6j8NgNXj9WxMeWwxXV2jeAX/EBSpZrCVlCQ1yJswT6xCp8TuBnTiGWYMBNTbOZvPC4e0WI2/yZW/s5F nocomment"},
|
||||
{"ecdsa-256", false, "ecdsa", 256, "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFQacN3PrOll7PXmN5B/ZNVahiUIqI05nbBlZk1KXsO3d06ktAWqbNflv2vEmA38bTFTfJ2sbn2B5ksT52cDDbA= nocomment"},
|
||||
{"ecdsa-384", false, "ecdsa", 384, "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBINmioV+XRX1Fm9Qk2ehHXJ2tfVxW30ypUWZw670Zyq5GQfBAH6xjygRsJ5wWsHXBsGYgFUXIHvMKVAG1tpw7s6ax9oA+dJOJ7tj+vhn8joFqT+sg3LYHgZkHrfqryRasQ== nocomment"},
|
||||
{"ecdsa-sk", true, "ecdsa-sk", 256, "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment"},
|
||||
{"ed25519-sk", true, "ed25519-sk", 256, "sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIE7kM1R02+4ertDKGKEDcKG0s+2vyDDcIvceJ0Gqv5f1AAAABHNzaDo= nocomment"},
|
||||
{"rsa-1024", "rsa", 1024, "SHA256:vSnDkvRh/xM6kMxPidLgrUhq3mCN7CDaronCEm2joyQ", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n"},
|
||||
{"rsa-2048", "rsa", 2048, "SHA256:ZHD//a1b9VuTq9XSunAeYjKeU1xDa2tBFZYrFr2Okkg", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMZXh+1OBUwSH9D45wTaxErQIN9IoC9xl7MKJkqvTvv6O5RR9YW/IK9FbfjXgXsppYGhsCZo1hFOOsXHMnfOORqu/xMDx4yPuyvKpw4LePEcg4TDipaDFuxbWOqc/BUZRZcXu41QAWfDLrInwsltWZHSeG7hjhpacl4FrVv9V1pS6Oc5Q1NxxEzTzuNLS/8diZrTm/YAQQ/+B+mzWI3zEtF4miZjjAljWd1LTBPvU23d29DcBmmFahcZ441XZsTeAwGxG/Q6j8NgNXj9WxMeWwxXV2jeAX/EBSpZrCVlCQ1yJswT6xCp8TuBnTiGWYMBNTbOZvPC4e0WI2/yZW/s5F nocomment"},
|
||||
{"ecdsa-256", "ecdsa", 256, "SHA256:Bqx/xgWqRKLtkZ0Lr4iZpgb+5lYsFpSwXwVZbPwuTRw", "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFQacN3PrOll7PXmN5B/ZNVahiUIqI05nbBlZk1KXsO3d06ktAWqbNflv2vEmA38bTFTfJ2sbn2B5ksT52cDDbA= nocomment"},
|
||||
{"ecdsa-384", "ecdsa", 384, "SHA256:4qfJOgJDtUd8BrEjyVNdI8IgjiZKouztVde43aDhe1E", "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBINmioV+XRX1Fm9Qk2ehHXJ2tfVxW30ypUWZw670Zyq5GQfBAH6xjygRsJ5wWsHXBsGYgFUXIHvMKVAG1tpw7s6ax9oA+dJOJ7tj+vhn8joFqT+sg3LYHgZkHrfqryRasQ== nocomment"},
|
||||
{"ecdsa-sk", "ecdsa-sk", 256, "SHA256:4wcIu4z+53gHc+db85OPfy8IydyNzPLCr6kHIs625LQ", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment"},
|
||||
{"ed25519-sk", "ed25519-sk", 256, "SHA256:RB4ku1OeWKN7fLMrjxz38DK0mp1BnOPBx4BItjTvJ0g", "sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIE7kM1R02+4ertDKGKEDcKG0s+2vyDDcIvceJ0Gqv5f1AAAABHNzaDo= nocomment"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
@@ -44,6 +44,10 @@ func Test_SSHParsePublicKey(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.keyType, keyTypeN)
|
||||
assert.Equal(t, tc.length, lengthN)
|
||||
|
||||
fpN, err := calcFingerprintNative(tc.content)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.fp, fpN)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -143,32 +147,6 @@ AAAAC3NzaC1lZDI1NTE5AAAAICV0MGX/W9IvLA4FXpIuUcdDcbj5KX4syHgsTy7soVgf
|
||||
}
|
||||
}
|
||||
|
||||
func Test_calcFingerprint(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
skipSSHKeygen bool
|
||||
fp string
|
||||
content string
|
||||
}{
|
||||
{"rsa-1024", false, "SHA256:vSnDkvRh/xM6kMxPidLgrUhq3mCN7CDaronCEm2joyQ", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n"},
|
||||
{"rsa-2048", false, "SHA256:ZHD//a1b9VuTq9XSunAeYjKeU1xDa2tBFZYrFr2Okkg", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMZXh+1OBUwSH9D45wTaxErQIN9IoC9xl7MKJkqvTvv6O5RR9YW/IK9FbfjXgXsppYGhsCZo1hFOOsXHMnfOORqu/xMDx4yPuyvKpw4LePEcg4TDipaDFuxbWOqc/BUZRZcXu41QAWfDLrInwsltWZHSeG7hjhpacl4FrVv9V1pS6Oc5Q1NxxEzTzuNLS/8diZrTm/YAQQ/+B+mzWI3zEtF4miZjjAljWd1LTBPvU23d29DcBmmFahcZ441XZsTeAwGxG/Q6j8NgNXj9WxMeWwxXV2jeAX/EBSpZrCVlCQ1yJswT6xCp8TuBnTiGWYMBNTbOZvPC4e0WI2/yZW/s5F nocomment"},
|
||||
{"ecdsa-256", false, "SHA256:Bqx/xgWqRKLtkZ0Lr4iZpgb+5lYsFpSwXwVZbPwuTRw", "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFQacN3PrOll7PXmN5B/ZNVahiUIqI05nbBlZk1KXsO3d06ktAWqbNflv2vEmA38bTFTfJ2sbn2B5ksT52cDDbA= nocomment"},
|
||||
{"ecdsa-384", false, "SHA256:4qfJOgJDtUd8BrEjyVNdI8IgjiZKouztVde43aDhe1E", "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBINmioV+XRX1Fm9Qk2ehHXJ2tfVxW30ypUWZw670Zyq5GQfBAH6xjygRsJ5wWsHXBsGYgFUXIHvMKVAG1tpw7s6ax9oA+dJOJ7tj+vhn8joFqT+sg3LYHgZkHrfqryRasQ== nocomment"},
|
||||
{"ecdsa-sk", true, "SHA256:4wcIu4z+53gHc+db85OPfy8IydyNzPLCr6kHIs625LQ", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment"},
|
||||
{"ed25519-sk", true, "SHA256:RB4ku1OeWKN7fLMrjxz38DK0mp1BnOPBx4BItjTvJ0g", "sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIE7kM1R02+4ertDKGKEDcKG0s+2vyDDcIvceJ0Gqv5f1AAAABHNzaDo= nocomment"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Run("Native", func(t *testing.T) {
|
||||
fpN, err := calcFingerprintNative(tc.content)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.fp, fpN)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
// Generated with "ssh-keygen -C test@rekor.dev -f id_rsa"
|
||||
sshPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
|
||||
@@ -17,35 +17,29 @@ import (
|
||||
func TestFindEventsScopeFilters(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
events := []*Event{
|
||||
for _, event := range []*Event{
|
||||
{Action: UserCreate, ScopeType: ScopeUser, ScopeID: 5, Origin: OriginUI, TimestampUnix: timeutil.TimeStamp(1)},
|
||||
{Action: RepositoryCreate, ScopeType: ScopeRepository, ScopeID: 5, Origin: OriginAPI, TimestampUnix: timeutil.TimeStamp(1)},
|
||||
{Action: RepositoryCreate, ScopeType: ScopeRepository, ScopeID: 6, Origin: OriginCLI, TimestampUnix: timeutil.TimeStamp(1)},
|
||||
{Action: RepositoryCreate, ScopeType: ScopeRepository, ScopeID: 7, Origin: OriginSystem, TimestampUnix: timeutil.TimeStamp(1)},
|
||||
}
|
||||
for _, event := range events {
|
||||
} {
|
||||
require.NoError(t, InsertEvent(t.Context(), event))
|
||||
}
|
||||
|
||||
byType, _, err := FindEvents(t.Context(), &EventSearchOptions{ScopeType: ScopeRepository})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, byType, 3)
|
||||
|
||||
byID, _, err := FindEvents(t.Context(), &EventSearchOptions{ScopeID: 5})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, byID, 2)
|
||||
|
||||
byScope, _, err := FindEvents(t.Context(), &EventSearchOptions{ScopeType: ScopeRepository, ScopeID: 5})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, byScope, 1)
|
||||
|
||||
byOrigin, _, err := FindEvents(t.Context(), &EventSearchOptions{Origin: OriginAPI})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, byOrigin, 1)
|
||||
|
||||
bySystemOrigin, _, err := FindEvents(t.Context(), &EventSearchOptions{Origin: OriginSystem})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, bySystemOrigin, 1)
|
||||
for _, test := range []struct {
|
||||
options EventSearchOptions
|
||||
count int
|
||||
}{
|
||||
{EventSearchOptions{ScopeType: ScopeRepository}, 3},
|
||||
{EventSearchOptions{ScopeID: 5}, 2},
|
||||
{EventSearchOptions{ScopeType: ScopeRepository, ScopeID: 5}, 1},
|
||||
{EventSearchOptions{Origin: OriginAPI}, 1},
|
||||
{EventSearchOptions{Origin: OriginSystem}, 1},
|
||||
} {
|
||||
events, _, err := FindEvents(t.Context(), &test.options)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, events, test.count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindEventsActionPrefixFilter(t *testing.T) {
|
||||
|
||||
+127
-131
@@ -14,97 +14,148 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNewAccessToken(t *testing.T) {
|
||||
func TestAccessTokenLifecycle(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
token := &auth_model.AccessToken{
|
||||
UID: 3,
|
||||
Name: "Token C",
|
||||
}
|
||||
assert.NoError(t, auth_model.NewAccessToken(t.Context(), token))
|
||||
unittest.AssertExistsAndLoadBean(t, token)
|
||||
|
||||
invalidToken := &auth_model.AccessToken{
|
||||
ID: token.ID, // duplicate
|
||||
UID: 2,
|
||||
Name: "Token F",
|
||||
}
|
||||
assert.Error(t, auth_model.NewAccessToken(t.Context(), invalidToken))
|
||||
}
|
||||
t.Run("GetAccessTokenBySHA", func(t *testing.T) {
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "d2c6c1ba3890b309189a8e618c72a162e4efbf36")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), token.UID)
|
||||
assert.Equal(t, "Token A", token.Name)
|
||||
assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash)
|
||||
assert.Equal(t, "e4efbf36", token.TokenLastEight)
|
||||
|
||||
func TestAccessTokenByNameExists(t *testing.T) {
|
||||
name := "Token Gitea"
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "notahash")
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
token := &auth_model.AccessToken{
|
||||
UID: 3,
|
||||
Name: name,
|
||||
}
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "")
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
})
|
||||
|
||||
// Check to make sure it doesn't exists already
|
||||
exist, err := auth_model.AccessTokenByNameExists(t.Context(), token)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exist)
|
||||
t.Run("ListAccessTokens", func(t *testing.T) {
|
||||
tokens, err := db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 1})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, tokens, 2) {
|
||||
assert.Equal(t, int64(1), tokens[0].UID)
|
||||
assert.Equal(t, int64(1), tokens[1].UID)
|
||||
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token A")
|
||||
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B")
|
||||
}
|
||||
|
||||
// Save it to the database
|
||||
assert.NoError(t, auth_model.NewAccessToken(t.Context(), token))
|
||||
unittest.AssertExistsAndLoadBean(t, token)
|
||||
tokens, err = db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 2})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, tokens, 1) {
|
||||
assert.Equal(t, int64(2), tokens[0].UID)
|
||||
assert.Equal(t, "Token A", tokens[0].Name)
|
||||
}
|
||||
|
||||
// This token must be found by name in the DB now
|
||||
exist, err = auth_model.AccessTokenByNameExists(t.Context(), token)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exist)
|
||||
tokens, err = db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 100})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, tokens)
|
||||
})
|
||||
|
||||
user4Token := &auth_model.AccessToken{
|
||||
UID: 4,
|
||||
Name: name,
|
||||
}
|
||||
t.Run("NewAccessToken", func(t *testing.T) {
|
||||
token := &auth_model.AccessToken{
|
||||
UID: 3,
|
||||
Name: "Token C",
|
||||
}
|
||||
assert.NoError(t, auth_model.NewAccessToken(t.Context(), token))
|
||||
unittest.AssertExistsAndLoadBean(t, token)
|
||||
|
||||
// Name matches but different user ID, this shouldn't exists in the
|
||||
// database
|
||||
exist, err = auth_model.AccessTokenByNameExists(t.Context(), user4Token)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exist)
|
||||
}
|
||||
invalidToken := &auth_model.AccessToken{
|
||||
ID: token.ID, // duplicate
|
||||
UID: 2,
|
||||
Name: "Token F",
|
||||
}
|
||||
assert.Error(t, auth_model.NewAccessToken(t.Context(), invalidToken))
|
||||
})
|
||||
|
||||
func TestGetAccessTokenBySHA(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "d2c6c1ba3890b309189a8e618c72a162e4efbf36")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), token.UID)
|
||||
assert.Equal(t, "Token A", token.Name)
|
||||
assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash)
|
||||
assert.Equal(t, "e4efbf36", token.TokenLastEight)
|
||||
t.Run("AccessTokenByNameExists", func(t *testing.T) {
|
||||
name := "Token Gitea"
|
||||
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "notahash")
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
token := &auth_model.AccessToken{
|
||||
UID: 3,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "")
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
}
|
||||
// Check to make sure it doesn't exists already
|
||||
exist, err := auth_model.AccessTokenByNameExists(t.Context(), token)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exist)
|
||||
|
||||
func TestListAccessTokens(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
tokens, err := db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 1})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, tokens, 2) {
|
||||
assert.Equal(t, int64(1), tokens[0].UID)
|
||||
assert.Equal(t, int64(1), tokens[1].UID)
|
||||
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token A")
|
||||
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B")
|
||||
}
|
||||
// Save it to the database
|
||||
assert.NoError(t, auth_model.NewAccessToken(t.Context(), token))
|
||||
unittest.AssertExistsAndLoadBean(t, token)
|
||||
|
||||
tokens, err = db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 2})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, tokens, 1) {
|
||||
assert.Equal(t, int64(2), tokens[0].UID)
|
||||
assert.Equal(t, "Token A", tokens[0].Name)
|
||||
}
|
||||
// This token must be found by name in the DB now
|
||||
exist, err = auth_model.AccessTokenByNameExists(t.Context(), token)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exist)
|
||||
|
||||
tokens, err = db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 100})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, tokens)
|
||||
user4Token := &auth_model.AccessToken{
|
||||
UID: 4,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
// Name matches but different user ID, this shouldn't exists in the
|
||||
// database
|
||||
exist, err = auth_model.AccessTokenByNameExists(t.Context(), user4Token)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exist)
|
||||
})
|
||||
|
||||
t.Run("RegenerateAccessToken", func(t *testing.T) {
|
||||
const oldToken = "d2c6c1ba3890b309189a8e618c72a162e4efbf36"
|
||||
|
||||
// prime the successful-lookup cache with the old token value, as a real request would
|
||||
before, err := auth_model.GetAccessTokenBySHA(t.Context(), oldToken)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Token A", before.Name)
|
||||
|
||||
regenerated, err := auth_model.RegenerateAccessToken(t.Context(), before.ID, before.UID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, before.ID, regenerated.ID)
|
||||
assert.Equal(t, before.Name, regenerated.Name)
|
||||
assert.Equal(t, before.Scope, regenerated.Scope)
|
||||
assert.NotEqual(t, before.TokenHash, regenerated.TokenHash)
|
||||
assert.NotEmpty(t, regenerated.Token)
|
||||
|
||||
// the old token value must stop authenticating, even though it was cached as successful above
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), oldToken)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
// the new token value must authenticate
|
||||
found, err := auth_model.GetAccessTokenBySHA(t.Context(), regenerated.Token)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, before.ID, found.ID)
|
||||
assert.Equal(t, before.UpdatedUnix, found.UpdatedUnix)
|
||||
|
||||
// wrong owner
|
||||
_, err = auth_model.RegenerateAccessToken(t.Context(), before.ID, before.UID+1)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
// nonexistent token
|
||||
_, err = auth_model.RegenerateAccessToken(t.Context(), 100, 100)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
})
|
||||
|
||||
t.Run("DeleteAccessTokenByID", func(t *testing.T) {
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "4c6f36e6cf498e2a448662f915d932c09c5a146c")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), token.UID)
|
||||
|
||||
assert.NoError(t, auth_model.DeleteAccessTokenByID(t.Context(), token.ID, 1))
|
||||
unittest.AssertNotExistsBean(t, token)
|
||||
|
||||
err = auth_model.DeleteAccessTokenByID(t.Context(), 100, 100)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateAccessToken(t *testing.T) {
|
||||
@@ -116,58 +167,3 @@ func TestUpdateAccessToken(t *testing.T) {
|
||||
assert.NoError(t, auth_model.UpdateAccessToken(t.Context(), token))
|
||||
unittest.AssertExistsAndLoadBean(t, token)
|
||||
}
|
||||
|
||||
func TestRegenerateAccessToken(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
const oldToken = "d2c6c1ba3890b309189a8e618c72a162e4efbf36"
|
||||
|
||||
// prime the successful-lookup cache with the old token value, as a real request would
|
||||
before, err := auth_model.GetAccessTokenBySHA(t.Context(), oldToken)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Token A", before.Name)
|
||||
|
||||
regenerated, err := auth_model.RegenerateAccessToken(t.Context(), before.ID, before.UID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, before.ID, regenerated.ID)
|
||||
assert.Equal(t, before.Name, regenerated.Name)
|
||||
assert.Equal(t, before.Scope, regenerated.Scope)
|
||||
assert.NotEqual(t, before.TokenHash, regenerated.TokenHash)
|
||||
assert.NotEmpty(t, regenerated.Token)
|
||||
|
||||
// the old token value must stop authenticating, even though it was cached as successful above
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), oldToken)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
// the new token value must authenticate
|
||||
found, err := auth_model.GetAccessTokenBySHA(t.Context(), regenerated.Token)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, before.ID, found.ID)
|
||||
assert.Equal(t, before.UpdatedUnix, found.UpdatedUnix)
|
||||
|
||||
// wrong owner
|
||||
_, err = auth_model.RegenerateAccessToken(t.Context(), before.ID, before.UID+1)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
// nonexistent token
|
||||
_, err = auth_model.RegenerateAccessToken(t.Context(), 100, 100)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestDeleteAccessTokenByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "4c6f36e6cf498e2a448662f915d932c09c5a146c")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), token.UID)
|
||||
|
||||
assert.NoError(t, auth_model.DeleteAccessTokenByID(t.Context(), token.ID, 1))
|
||||
unittest.AssertNotExistsBean(t, token)
|
||||
|
||||
err = auth_model.DeleteAccessTokenByID(t.Context(), 100, 100)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
}
|
||||
+104
-127
@@ -57,13 +57,105 @@ func TestOAuth2AuthorizationCode(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestOAuth2Application_GenerateClientSecret(t *testing.T) {
|
||||
func TestOAuth2ApplicationAndGrant(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
secret, err := app.GenerateClientSecret(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, secret)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret})
|
||||
|
||||
t.Run("GetOAuth2ApplicationByClientID", func(t *testing.T) {
|
||||
app, err := auth_model.GetOAuth2ApplicationByClientID(t.Context(), "da7da3ba-9a13-4167-856f-3899de0b0138")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID)
|
||||
|
||||
app, err = auth_model.GetOAuth2ApplicationByClientID(t.Context(), "invalid client id")
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, app)
|
||||
})
|
||||
|
||||
t.Run("OAuth2Application_GetGrantByUserID", func(t *testing.T) {
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
grant, err := app.GetGrantByUserID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), grant.UserID)
|
||||
|
||||
grant, err = app.GetGrantByUserID(t.Context(), 34923458)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, grant)
|
||||
})
|
||||
|
||||
t.Run("GetOAuth2GrantByID", func(t *testing.T) {
|
||||
grant, err := auth_model.GetOAuth2GrantByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), grant.ID)
|
||||
|
||||
grant, err = auth_model.GetOAuth2GrantByID(t.Context(), 34923458)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, grant)
|
||||
})
|
||||
|
||||
t.Run("OAuth2Grant_ScopeContains", func(t *testing.T) {
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Scope: "openid profile"})
|
||||
assert.True(t, grant.ScopeContains("openid"))
|
||||
assert.True(t, grant.ScopeContains("profile"))
|
||||
assert.False(t, grant.ScopeContains("profil"))
|
||||
assert.False(t, grant.ScopeContains("profile2"))
|
||||
})
|
||||
|
||||
t.Run("GetOAuth2GrantsByUserID", func(t *testing.T) {
|
||||
result, err := auth_model.GetOAuth2GrantsByUserID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, result, 1)
|
||||
assert.Equal(t, int64(1), result[0].ID)
|
||||
assert.Equal(t, result[0].ApplicationID, result[0].Application.ID)
|
||||
|
||||
result, err = auth_model.GetOAuth2GrantsByUserID(t.Context(), 34134)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, result)
|
||||
})
|
||||
|
||||
t.Run("OAuth2Grant_GenerateNewAuthorizationCode", func(t *testing.T) {
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1})
|
||||
code, err := grant.GenerateNewAuthorizationCode(t.Context(), "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, code)
|
||||
assert.Greater(t, len(code.Code), 32) // secret length > 32
|
||||
})
|
||||
|
||||
t.Run("OAuth2Application_CreateGrant", func(t *testing.T) {
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
grant, err := app.CreateGrant(t.Context(), 2, "")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, grant)
|
||||
assert.Equal(t, int64(2), grant.UserID)
|
||||
assert.Equal(t, int64(1), grant.ApplicationID)
|
||||
assert.Empty(t, grant.Scope)
|
||||
})
|
||||
|
||||
t.Run("OAuth2Grant_IncreaseCounter", func(t *testing.T) {
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 1})
|
||||
stale := *grant
|
||||
assert.NoError(t, grant.IncreaseCounter(t.Context()))
|
||||
assert.Equal(t, int64(2), grant.Counter)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 2})
|
||||
err := stale.IncreaseCounter(t.Context())
|
||||
assert.ErrorIs(t, err, auth_model.ErrOAuth2GrantStaleCounter)
|
||||
})
|
||||
|
||||
t.Run("OAuth2Application_GenerateClientSecret", func(t *testing.T) {
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
secret, err := app.GenerateClientSecret(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, secret)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret})
|
||||
assert.True(t, app.ValidateClientSecret([]byte(secret)))
|
||||
assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew")))
|
||||
})
|
||||
|
||||
t.Run("CreateOAuth2Application", func(t *testing.T) {
|
||||
app, err := auth_model.CreateOAuth2Application(t.Context(), auth_model.CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "newapp", app.Name)
|
||||
assert.Len(t, app.ClientID, 36)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{Name: "newapp"})
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) {
|
||||
@@ -106,15 +198,12 @@ func TestOAuth2Application_ContainsRedirectURI_WithPort(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) {
|
||||
app := &auth_model.OAuth2Application{RedirectURIs: []string{"http://127.0.0.1"}}
|
||||
assert.True(t, app.ContainsRedirectURI("http://127.0.0.1"))
|
||||
assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))
|
||||
assert.False(t, app.ContainsRedirectURI("http://127.0.0.1/other"))
|
||||
|
||||
app = &auth_model.OAuth2Application{RedirectURIs: []string{"http://127.0.0.1/"}}
|
||||
assert.True(t, app.ContainsRedirectURI("http://127.0.0.1"))
|
||||
assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))
|
||||
assert.False(t, app.ContainsRedirectURI("http://127.0.0.1/other"))
|
||||
for _, redirectURI := range []string{"http://127.0.0.1", "http://127.0.0.1/"} {
|
||||
app := &auth_model.OAuth2Application{RedirectURIs: []string{redirectURI}}
|
||||
assert.True(t, app.ContainsRedirectURI("http://127.0.0.1"))
|
||||
assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))
|
||||
assert.False(t, app.ContainsRedirectURI("http://127.0.0.1/other"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuth2Application_ContainsRedirectURI_ASCIIOnlyNormalization(t *testing.T) {
|
||||
@@ -158,128 +247,16 @@ func TestOAuth2Application_ContainsRedirectURI_ASCIIOnlyNormalization(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuth2Application_ValidateClientSecret(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
secret, err := app.GenerateClientSecret(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, app.ValidateClientSecret([]byte(secret)))
|
||||
assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew")))
|
||||
}
|
||||
|
||||
func TestGetOAuth2ApplicationByClientID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
app, err := auth_model.GetOAuth2ApplicationByClientID(t.Context(), "da7da3ba-9a13-4167-856f-3899de0b0138")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID)
|
||||
|
||||
app, err = auth_model.GetOAuth2ApplicationByClientID(t.Context(), "invalid client id")
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, app)
|
||||
}
|
||||
|
||||
func TestCreateOAuth2Application(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
app, err := auth_model.CreateOAuth2Application(t.Context(), auth_model.CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "newapp", app.Name)
|
||||
assert.Len(t, app.ClientID, 36)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{Name: "newapp"})
|
||||
}
|
||||
|
||||
func TestOAuth2Application_TableName(t *testing.T) {
|
||||
assert.Equal(t, "oauth2_application", new(auth_model.OAuth2Application).TableName())
|
||||
}
|
||||
|
||||
func TestOAuth2Application_GetGrantByUserID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
grant, err := app.GetGrantByUserID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), grant.UserID)
|
||||
|
||||
grant, err = app.GetGrantByUserID(t.Context(), 34923458)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, grant)
|
||||
}
|
||||
|
||||
func TestOAuth2Application_CreateGrant(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
|
||||
grant, err := app.CreateGrant(t.Context(), 2, "")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, grant)
|
||||
assert.Equal(t, int64(2), grant.UserID)
|
||||
assert.Equal(t, int64(1), grant.ApplicationID)
|
||||
assert.Empty(t, grant.Scope)
|
||||
}
|
||||
|
||||
//////////////////// Grant
|
||||
|
||||
func TestGetOAuth2GrantByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
grant, err := auth_model.GetOAuth2GrantByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), grant.ID)
|
||||
|
||||
grant, err = auth_model.GetOAuth2GrantByID(t.Context(), 34923458)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, grant)
|
||||
}
|
||||
|
||||
func TestOAuth2Grant_IncreaseCounter(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 1})
|
||||
assert.NoError(t, grant.IncreaseCounter(t.Context()))
|
||||
assert.Equal(t, int64(2), grant.Counter)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 2})
|
||||
}
|
||||
|
||||
func TestOAuth2Grant_IncreaseCounterRejectsStaleCounter(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 1})
|
||||
stale := *grant
|
||||
|
||||
assert.NoError(t, grant.IncreaseCounter(t.Context()))
|
||||
err := stale.IncreaseCounter(t.Context())
|
||||
assert.ErrorIs(t, err, auth_model.ErrOAuth2GrantStaleCounter)
|
||||
}
|
||||
|
||||
func TestOAuth2Grant_ScopeContains(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Scope: "openid profile"})
|
||||
assert.True(t, grant.ScopeContains("openid"))
|
||||
assert.True(t, grant.ScopeContains("profile"))
|
||||
assert.False(t, grant.ScopeContains("profil"))
|
||||
assert.False(t, grant.ScopeContains("profile2"))
|
||||
}
|
||||
|
||||
func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1})
|
||||
code, err := grant.GenerateNewAuthorizationCode(t.Context(), "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, code)
|
||||
assert.Greater(t, len(code.Code), 32) // secret length > 32
|
||||
}
|
||||
|
||||
func TestOAuth2Grant_TableName(t *testing.T) {
|
||||
assert.Equal(t, "oauth2_grant", new(auth_model.OAuth2Grant).TableName())
|
||||
}
|
||||
|
||||
func TestGetOAuth2GrantsByUserID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
result, err := auth_model.GetOAuth2GrantsByUserID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, result, 1)
|
||||
assert.Equal(t, int64(1), result[0].ID)
|
||||
assert.Equal(t, result[0].ApplicationID, result[0].Application.ID)
|
||||
|
||||
result, err = auth_model.GetOAuth2GrantsByUserID(t.Context(), 34134)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, result)
|
||||
}
|
||||
|
||||
func TestRevokeOAuth2Grant(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
assert.NoError(t, auth_model.RevokeOAuth2Grant(t.Context(), 1, 1))
|
||||
|
||||
@@ -16,67 +16,68 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTwoFactorValidateAndConsumeTOTP(t *testing.T) {
|
||||
func TestTwoFactorLifecycle(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
key, err := totp.Generate(totp.GenerateOpts{SecretSize: 40, Issuer: "gitea-test", AccountName: "consume"})
|
||||
require.NoError(t, err)
|
||||
t.Run("TwoFactorValidateAndConsumeTOTP", func(t *testing.T) {
|
||||
key, err := totp.Generate(totp.GenerateOpts{SecretSize: 40, Issuer: "gitea-test", AccountName: "consume"})
|
||||
require.NoError(t, err)
|
||||
|
||||
tfa := &auth_model.TwoFactor{UID: 1}
|
||||
require.NoError(t, tfa.SetSecret(key.Secret()))
|
||||
require.NoError(t, auth_model.NewTwoFactor(t.Context(), tfa))
|
||||
tfa := &auth_model.TwoFactor{UID: 1}
|
||||
require.NoError(t, tfa.SetSecret(key.Secret()))
|
||||
require.NoError(t, auth_model.NewTwoFactor(t.Context(), tfa))
|
||||
|
||||
passcode, err := totp.GenerateCode(key.Secret(), time.Now())
|
||||
require.NoError(t, err)
|
||||
passcode, err := totp.GenerateCode(key.Secret(), time.Now())
|
||||
require.NoError(t, err)
|
||||
|
||||
// first use of a valid passcode succeeds
|
||||
ok, err := tfa.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ok)
|
||||
// first use of a valid passcode succeeds
|
||||
ok, err := tfa.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ok)
|
||||
|
||||
// replaying the same passcode is refused, even when still inside the TOTP validity window
|
||||
reloaded, err := auth_model.GetTwoFactorByUID(t.Context(), tfa.UID)
|
||||
require.NoError(t, err)
|
||||
ok, err = reloaded.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
// replaying the same passcode is refused, even when still inside the TOTP validity window
|
||||
reloaded, err := auth_model.GetTwoFactorByUID(t.Context(), tfa.UID)
|
||||
require.NoError(t, err)
|
||||
ok, err = reloaded.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
|
||||
// an invalid passcode is rejected without consuming anything
|
||||
ok, err = reloaded.ValidateAndConsumeTOTP(t.Context(), "000000")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
// an invalid passcode is rejected without consuming anything
|
||||
ok, err = reloaded.ValidateAndConsumeTOTP(t.Context(), "000000")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
})
|
||||
|
||||
func TestDisableTwoFactor(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
t.Run("DisableTwoFactor", func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
const uid = 1000 // a uid with no user/2FA fixtures
|
||||
const uid = 1000 // a uid with no user/2FA fixtures
|
||||
|
||||
// Enroll TOTP and register a WebAuthn credential.
|
||||
tfa := &auth_model.TwoFactor{UID: uid}
|
||||
require.NoError(t, tfa.SetSecret("test-secret"))
|
||||
require.NoError(t, auth_model.NewTwoFactor(ctx, tfa))
|
||||
_, err := auth_model.CreateCredential(ctx, uid, "test-key", &webauthn.Credential{ID: []byte("test-cred-id")})
|
||||
require.NoError(t, err)
|
||||
// Enroll TOTP and register a WebAuthn credential.
|
||||
tfa := &auth_model.TwoFactor{UID: uid}
|
||||
require.NoError(t, tfa.SetSecret("test-secret"))
|
||||
require.NoError(t, auth_model.NewTwoFactor(ctx, tfa))
|
||||
_, err := auth_model.CreateCredential(ctx, uid, "test-key", &webauthn.Credential{ID: []byte("test-cred-id")})
|
||||
require.NoError(t, err)
|
||||
|
||||
has, err := auth_model.HasTwoFactorOrWebAuthn(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
require.True(t, has)
|
||||
has, err := auth_model.HasTwoFactorOrWebAuthn(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
require.True(t, has)
|
||||
|
||||
// Both records are removed and counted separately.
|
||||
totp, webAuthn, err := auth_model.DisableTwoFactor(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, totp)
|
||||
assert.EqualValues(t, 1, webAuthn)
|
||||
// Both records are removed and counted separately.
|
||||
totp, webAuthn, err := auth_model.DisableTwoFactor(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 1, totp)
|
||||
assert.EqualValues(t, 1, webAuthn)
|
||||
|
||||
has, err = auth_model.HasTwoFactorOrWebAuthn(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, has)
|
||||
has, err = auth_model.HasTwoFactorOrWebAuthn(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, has)
|
||||
|
||||
// A second call on a user without 2FA is a no-op.
|
||||
totp, webAuthn, err = auth_model.DisableTwoFactor(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 0, totp)
|
||||
assert.EqualValues(t, 0, webAuthn)
|
||||
// A second call on a user without 2FA is a no-op.
|
||||
totp, webAuthn, err = auth_model.DisableTwoFactor(ctx, uid)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, 0, totp)
|
||||
assert.EqualValues(t, 0, webAuthn)
|
||||
})
|
||||
}
|
||||
@@ -13,29 +13,38 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetWebAuthnCredentialByID(t *testing.T) {
|
||||
func TestWebAuthnCredentials(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
res, err := auth_model.GetWebAuthnCredentialByID(t.Context(), 32, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "WebAuthn credential", res.Name)
|
||||
t.Run("GetWebAuthnCredentialByID", func(t *testing.T) {
|
||||
res, err := auth_model.GetWebAuthnCredentialByID(t.Context(), 32, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "WebAuthn credential", res.Name)
|
||||
|
||||
_, err = auth_model.GetWebAuthnCredentialByID(t.Context(), 99999, 1)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err))
|
||||
_, err = auth_model.GetWebAuthnCredentialByID(t.Context(), 99999, 1)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err))
|
||||
|
||||
_, err = auth_model.GetWebAuthnCredentialByID(t.Context(), 32, 99999)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err))
|
||||
}
|
||||
_, err = auth_model.GetWebAuthnCredentialByID(t.Context(), 32, 99999)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err))
|
||||
})
|
||||
|
||||
func TestGetWebAuthnCredentialsByUID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("GetWebAuthnCredentialsByUID", func(t *testing.T) {
|
||||
res, err := auth_model.GetWebAuthnCredentialsByUID(t.Context(), 32)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, res, 1)
|
||||
assert.Equal(t, "WebAuthn credential", res[0].Name)
|
||||
})
|
||||
|
||||
res, err := auth_model.GetWebAuthnCredentialsByUID(t.Context(), 32)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, res, 1)
|
||||
assert.Equal(t, "WebAuthn credential", res[0].Name)
|
||||
t.Run("CreateCredential", func(t *testing.T) {
|
||||
res, err := auth_model.CreateCredential(t.Context(), 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "WebAuthn Created Credential", res.Name)
|
||||
assert.Equal(t, []byte("Test"), res.CredentialID)
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{Name: "WebAuthn Created Credential", UserID: 1})
|
||||
})
|
||||
}
|
||||
|
||||
func TestWebAuthnCredential_TableName(t *testing.T) {
|
||||
@@ -43,28 +52,11 @@ func TestWebAuthnCredential_TableName(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWebAuthnCredential_UpdateSignCount(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
|
||||
cred.SignCount = 1
|
||||
assert.NoError(t, cred.UpdateSignCount(t.Context()))
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1, SignCount: 1})
|
||||
}
|
||||
|
||||
func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
|
||||
cred.SignCount = 0xffffffff
|
||||
assert.NoError(t, cred.UpdateSignCount(t.Context()))
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1, SignCount: 0xffffffff})
|
||||
}
|
||||
|
||||
func TestCreateCredential(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
res, err := auth_model.CreateCredential(t.Context(), 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "WebAuthn Created Credential", res.Name)
|
||||
assert.Equal(t, []byte("Test"), res.CredentialID)
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{Name: "WebAuthn Created Credential", UserID: 1})
|
||||
for _, signCount := range []uint32{1, 0xffffffff} {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
|
||||
cred.SignCount = signCount
|
||||
assert.NoError(t, cred.UpdateSignCount(t.Context()))
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1, SignCount: signCount})
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,10 @@ func TestTxContext(t *testing.T) {
|
||||
assert.NoError(t, committer.Commit())
|
||||
}
|
||||
|
||||
{ // reuse the transaction created by TxContext and commit it
|
||||
for _, finish := range []func(db.Committer) error{
|
||||
db.Committer.Commit, // reuse the transaction created by TxContext and commit it
|
||||
db.Committer.Close, // reuse the transaction created by TxContext and close it
|
||||
} {
|
||||
ctx, committer, err := db.TxContext(t.Context())
|
||||
engine := db.GetEngine(ctx)
|
||||
assert.NoError(t, err)
|
||||
@@ -52,24 +55,9 @@ func TestTxContext(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, db.InTransaction(ctx))
|
||||
assert.Equal(t, engine, db.GetEngine(ctx))
|
||||
assert.NoError(t, committer.Commit())
|
||||
assert.NoError(t, finish(committer))
|
||||
}
|
||||
assert.NoError(t, committer.Commit())
|
||||
}
|
||||
|
||||
{ // reuse the transaction created by TxContext and close it
|
||||
ctx, committer, err := db.TxContext(t.Context())
|
||||
engine := db.GetEngine(ctx)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, db.InTransaction(ctx))
|
||||
{
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, db.InTransaction(ctx))
|
||||
assert.Equal(t, engine, db.GetEngine(ctx))
|
||||
assert.NoError(t, committer.Close())
|
||||
}
|
||||
assert.NoError(t, committer.Close())
|
||||
assert.NoError(t, finish(committer))
|
||||
}
|
||||
|
||||
{ // reuse the transaction created by WithTx
|
||||
|
||||
+16
-21
@@ -35,27 +35,22 @@ func TestSyncMaxResourceIndex(t *testing.T) {
|
||||
xe := unittest.GetXORMEngine()
|
||||
assert.NoError(t, xe.Sync(&TestIndex{}))
|
||||
|
||||
err := db.SyncMaxResourceIndex(t.Context(), "test_index", 10, 51)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// sync new max index
|
||||
maxIndex, err := getCurrentResourceIndex(t.Context(), "test_index", 10)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 51, maxIndex)
|
||||
|
||||
// smaller index doesn't change
|
||||
err = db.SyncMaxResourceIndex(t.Context(), "test_index", 10, 30)
|
||||
assert.NoError(t, err)
|
||||
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 51, maxIndex)
|
||||
|
||||
// larger index changes
|
||||
err = db.SyncMaxResourceIndex(t.Context(), "test_index", 10, 62)
|
||||
assert.NoError(t, err)
|
||||
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 62, maxIndex)
|
||||
var maxIndex int64
|
||||
var err error
|
||||
for _, test := range []struct {
|
||||
index int64
|
||||
expected int
|
||||
}{
|
||||
{51, 51}, // sync new max index
|
||||
{30, 51}, // smaller index doesn't change
|
||||
{62, 62}, // larger index changes
|
||||
} {
|
||||
err = db.SyncMaxResourceIndex(t.Context(), "test_index", 10, test.index)
|
||||
assert.NoError(t, err)
|
||||
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, test.expected, maxIndex)
|
||||
}
|
||||
|
||||
// commit transaction
|
||||
err = db.WithTx(t.Context(), func(ctx context.Context) error {
|
||||
|
||||
+34
-54
@@ -54,38 +54,29 @@ func TestDbfsBasic(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "0bcdefghi9", string(buf))
|
||||
|
||||
// write to new size
|
||||
_, err = f.Seek(-1, io.SeekEnd)
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Write([]byte("JKLMNOP")) // blocks: 0bcd efgh iJKL MNOP
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Seek(0, io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
buf, err = io.ReadAll(f)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "0bcdefghiJKLMNOP", string(buf))
|
||||
|
||||
// write beyond EOF and fill with zero
|
||||
_, err = f.Seek(5, io.SeekCurrent)
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Write([]byte("xyzu")) // blocks: 0bcd efgh iJKL MNOP 0000 0xyz u
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Seek(0, io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
buf, err = io.ReadAll(f)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "0bcdefghiJKLMNOP\x00\x00\x00\x00\x00xyzu", string(buf))
|
||||
|
||||
// write to the block with zeros
|
||||
_, err = f.Seek(-6, io.SeekCurrent)
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Write([]byte("ABCD")) // blocks: 0bcd efgh iJKL MNOP 000A BCDz u
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Seek(0, io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
buf, err = io.ReadAll(f)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "0bcdefghiJKLMNOP\x00\x00\x00ABCDzu", string(buf))
|
||||
for _, write := range []struct {
|
||||
offset int64
|
||||
whence int
|
||||
content string
|
||||
expected string
|
||||
}{
|
||||
// write to new size
|
||||
{-1, io.SeekEnd, "JKLMNOP", "0bcdefghiJKLMNOP"}, // blocks: 0bcd efgh iJKL MNOP
|
||||
// write beyond EOF and fill with zero
|
||||
{5, io.SeekCurrent, "xyzu", "0bcdefghiJKLMNOP\x00\x00\x00\x00\x00xyzu"}, // blocks: 0bcd efgh iJKL MNOP 0000 0xyz u
|
||||
// write to the block with zeros
|
||||
{-6, io.SeekCurrent, "ABCD", "0bcdefghiJKLMNOP\x00\x00\x00ABCDzu"}, // blocks: 0bcd efgh iJKL MNOP 000A BCDz u
|
||||
} {
|
||||
_, err = f.Seek(write.offset, write.whence)
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Write([]byte(write.content))
|
||||
assert.NoError(t, err)
|
||||
_, err = f.Seek(0, io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
buf, err = io.ReadAll(f)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, write.expected, string(buf))
|
||||
}
|
||||
|
||||
assert.NoError(t, f.Close())
|
||||
|
||||
@@ -121,17 +112,11 @@ func TestDbfsBasic(t *testing.T) {
|
||||
assert.EqualValues(t, 10, stat.Size())
|
||||
|
||||
t.Run("NonExisting", func(t *testing.T) {
|
||||
f, err := OpenFile(t.Context(), "non-existing.txt", os.O_RDONLY)
|
||||
assert.ErrorIs(t, err, os.ErrNotExist)
|
||||
assert.Nil(t, f)
|
||||
|
||||
f, err = OpenFile(t.Context(), "non-existing.txt", os.O_WRONLY)
|
||||
assert.ErrorIs(t, err, os.ErrNotExist)
|
||||
assert.Nil(t, f)
|
||||
|
||||
f, err = OpenFile(t.Context(), "non-existing.txt", os.O_WRONLY|os.O_APPEND|os.O_TRUNC)
|
||||
assert.ErrorIs(t, err, os.ErrNotExist)
|
||||
assert.Nil(t, f)
|
||||
for _, flags := range []int{os.O_RDONLY, os.O_WRONLY, os.O_WRONLY | os.O_APPEND | os.O_TRUNC} {
|
||||
f, err := OpenFile(t.Context(), "non-existing.txt", flags)
|
||||
assert.ErrorIs(t, err, os.ErrNotExist)
|
||||
assert.Nil(t, f)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Existing", func(t *testing.T) {
|
||||
@@ -211,17 +196,12 @@ func TestDbfsSeekWrite(t *testing.T) {
|
||||
n, err := fw.Write([]byte("111"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = fw.Seek(int64(n), io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = fw.Write([]byte("222"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = fw.Seek(int64(n), io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = fw.Write([]byte("333"))
|
||||
assert.NoError(t, err)
|
||||
for _, content := range []string{"222", "333"} {
|
||||
_, err = fw.Seek(int64(n), io.SeekStart)
|
||||
assert.NoError(t, err)
|
||||
_, err = fw.Write([]byte(content))
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
// then read it
|
||||
fr, err := OpenFile(t.Context(), "test2.log", os.O_RDONLY)
|
||||
|
||||
@@ -92,116 +92,45 @@ func TestGetCommitStatuses(t *testing.T) {
|
||||
|
||||
func Test_CalcCommitStatus(t *testing.T) {
|
||||
kases := []struct {
|
||||
statuses []*git_model.CommitStatus
|
||||
expected *git_model.CommitStatus
|
||||
statuses commitstatus.CommitStatusStates
|
||||
expected commitstatus.CommitStatusState
|
||||
}{
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusPending},
|
||||
expected: commitstatus.CommitStatusPending,
|
||||
},
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusSuccess, commitstatus.CommitStatusPending},
|
||||
expected: commitstatus.CommitStatusPending,
|
||||
},
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusSuccess, commitstatus.CommitStatusPending, commitstatus.CommitStatusSuccess},
|
||||
expected: commitstatus.CommitStatusPending,
|
||||
},
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusError,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusError, commitstatus.CommitStatusPending, commitstatus.CommitStatusSuccess},
|
||||
expected: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusWarning,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusPending,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusWarning, commitstatus.CommitStatusPending, commitstatus.CommitStatusSuccess},
|
||||
expected: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusSuccess, commitstatus.CommitStatusSuccess, commitstatus.CommitStatusSuccess},
|
||||
expected: commitstatus.CommitStatusSuccess,
|
||||
},
|
||||
{
|
||||
statuses: []*git_model.CommitStatus{
|
||||
{
|
||||
State: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusError,
|
||||
},
|
||||
{
|
||||
State: commitstatus.CommitStatusWarning,
|
||||
},
|
||||
},
|
||||
expected: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
statuses: commitstatus.CommitStatusStates{commitstatus.CommitStatusFailure, commitstatus.CommitStatusError, commitstatus.CommitStatusWarning},
|
||||
expected: commitstatus.CommitStatusFailure,
|
||||
},
|
||||
}
|
||||
|
||||
for _, kase := range kases {
|
||||
assert.Equal(t, kase.expected, git_model.CalcCommitStatus(kase.statuses), "statuses: %v", kase.statuses)
|
||||
statuses := make([]*git_model.CommitStatus, len(kase.statuses))
|
||||
for i, state := range kase.statuses {
|
||||
statuses[i] = &git_model.CommitStatus{State: state}
|
||||
}
|
||||
assert.Equal(t, &git_model.CommitStatus{State: kase.expected}, git_model.CalcCommitStatus(statuses), "statuses: %v", statuses)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,29 +155,19 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
|
||||
err = git_model.NewCommitStatus(t.Context(), git_model.NewCommitStatusOptions{
|
||||
Repo: repo2,
|
||||
Creator: user2,
|
||||
SHA: commit.ID,
|
||||
CommitStatus: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusFailure,
|
||||
TargetURL: "https://example.com/tests/",
|
||||
Context: "compliance/lint-backend",
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = git_model.NewCommitStatus(t.Context(), git_model.NewCommitStatusOptions{
|
||||
Repo: repo2,
|
||||
Creator: user2,
|
||||
SHA: commit.ID,
|
||||
CommitStatus: &git_model.CommitStatus{
|
||||
State: commitstatus.CommitStatusSuccess,
|
||||
TargetURL: "https://example.com/tests/",
|
||||
Context: "compliance/lint-backend",
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
for _, state := range []commitstatus.CommitStatusState{commitstatus.CommitStatusFailure, commitstatus.CommitStatusSuccess} {
|
||||
err = git_model.NewCommitStatus(t.Context(), git_model.NewCommitStatusOptions{
|
||||
Repo: repo2,
|
||||
Creator: user2,
|
||||
SHA: commit.ID,
|
||||
CommitStatus: &git_model.CommitStatus{
|
||||
State: state,
|
||||
TargetURL: "https://example.com/tests/",
|
||||
Context: "compliance/lint-backend",
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
contexts, err := git_model.FindRepoRecentCommitStatusContexts(t.Context(), repo2.ID, time.Hour)
|
||||
assert.NoError(t, err)
|
||||
|
||||
@@ -75,65 +75,34 @@ func TestBranchRuleMatchPriority(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchRuleSortLegacy(t *testing.T) {
|
||||
in := []*ProtectedBranch{{
|
||||
RuleName: "b",
|
||||
CreatedUnix: 1,
|
||||
}, {
|
||||
RuleName: "b/*",
|
||||
CreatedUnix: 3,
|
||||
}, {
|
||||
RuleName: "a/*",
|
||||
CreatedUnix: 2,
|
||||
}, {
|
||||
RuleName: "c",
|
||||
CreatedUnix: 0,
|
||||
}, {
|
||||
RuleName: "a",
|
||||
CreatedUnix: 4,
|
||||
}}
|
||||
expect := []string{"c", "b", "a", "a/*", "b/*"}
|
||||
|
||||
pbr := ProtectedBranchRules(in)
|
||||
pbr.sort()
|
||||
|
||||
var got []string
|
||||
for i := range pbr {
|
||||
got = append(got, pbr[i].RuleName)
|
||||
func TestBranchRuleSort(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rules ProtectedBranchRules
|
||||
expected []string
|
||||
}{
|
||||
{"Legacy", ProtectedBranchRules{
|
||||
{RuleName: "b", CreatedUnix: 1},
|
||||
{RuleName: "b/*", CreatedUnix: 3},
|
||||
{RuleName: "a/*", CreatedUnix: 2},
|
||||
{RuleName: "c", CreatedUnix: 0},
|
||||
{RuleName: "a", CreatedUnix: 4},
|
||||
}, []string{"c", "b", "a", "a/*", "b/*"}},
|
||||
{"Priority", ProtectedBranchRules{
|
||||
{RuleName: "b", CreatedUnix: 1, Priority: 4},
|
||||
{RuleName: "b/*", CreatedUnix: 3, Priority: 2},
|
||||
{RuleName: "a/*", CreatedUnix: 2, Priority: 1},
|
||||
{RuleName: "c", CreatedUnix: 0, Priority: 0},
|
||||
{RuleName: "a", CreatedUnix: 4, Priority: 3},
|
||||
}, []string{"c", "a/*", "b/*", "a", "b"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
tc.rules.sort()
|
||||
var got []string
|
||||
for i := range tc.rules {
|
||||
got = append(got, tc.rules[i].RuleName)
|
||||
}
|
||||
assert.Equal(t, tc.expected, got)
|
||||
})
|
||||
}
|
||||
assert.Equal(t, expect, got)
|
||||
}
|
||||
|
||||
func TestBranchRuleSortPriority(t *testing.T) {
|
||||
in := []*ProtectedBranch{{
|
||||
RuleName: "b",
|
||||
CreatedUnix: 1,
|
||||
Priority: 4,
|
||||
}, {
|
||||
RuleName: "b/*",
|
||||
CreatedUnix: 3,
|
||||
Priority: 2,
|
||||
}, {
|
||||
RuleName: "a/*",
|
||||
CreatedUnix: 2,
|
||||
Priority: 1,
|
||||
}, {
|
||||
RuleName: "c",
|
||||
CreatedUnix: 0,
|
||||
Priority: 0,
|
||||
}, {
|
||||
RuleName: "a",
|
||||
CreatedUnix: 4,
|
||||
Priority: 3,
|
||||
}}
|
||||
expect := []string{"c", "a/*", "b/*", "a", "b"}
|
||||
|
||||
pbr := ProtectedBranchRules(in)
|
||||
pbr.sort()
|
||||
|
||||
var got []string
|
||||
for i := range pbr {
|
||||
got = append(got, pbr[i].RuleName)
|
||||
}
|
||||
assert.Equal(t, expect, got)
|
||||
}
|
||||
+184
-176
@@ -85,194 +85,202 @@ func TestBranchRuleMatch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateProtectBranchPriorities(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
func TestProtectedBranchPermissionsAndPriorities(t *testing.T) {
|
||||
setupErr := unittest.PrepareTestDatabase()
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
t.Run("CanBypassBranchProtection", func(t *testing.T) {
|
||||
assert.NoError(t, setupErr)
|
||||
|
||||
// Create some test protected branches with initial priorities
|
||||
protectedBranches := []*ProtectedBranch{
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "master",
|
||||
Priority: 1,
|
||||
},
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "develop",
|
||||
Priority: 2,
|
||||
},
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "feature/*",
|
||||
Priority: 3,
|
||||
},
|
||||
}
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) // not in team 1
|
||||
teamMember := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
|
||||
for _, pb := range protectedBranches {
|
||||
_, err := db.GetEngine(t.Context()).Insert(pb)
|
||||
pb := &ProtectedBranch{
|
||||
EnableBypassAllowlist: true,
|
||||
BypassAllowlistUserIDs: []int64{user.ID},
|
||||
}
|
||||
|
||||
testBypass := func(t *testing.T, expected bool, pb *ProtectedBranch, doer *user_model.User, isAdmin bool) {
|
||||
assert.Equal(t, expected, CanBypassBranchProtection(t.Context(), pb, doer, isAdmin))
|
||||
}
|
||||
// User bypasses via explicit allowlist.
|
||||
testBypass(t, true, pb, user, false)
|
||||
|
||||
// Non-admin cannot bypass when allowlist is disabled.
|
||||
pb.EnableBypassAllowlist = false
|
||||
testBypass(t, false, pb, user, false)
|
||||
|
||||
// Repo admin can bypass independently of allowlist when not blocked.
|
||||
testBypass(t, true, pb, user, true)
|
||||
|
||||
// Admin override block still allows bypass for allowlisted users.
|
||||
pb.EnableBypassAllowlist = true
|
||||
pb.BlockAdminMergeOverride = true
|
||||
testBypass(t, true, pb, user, false)
|
||||
|
||||
// admin cannot bypass without allowlist membership.
|
||||
pb.BypassAllowlistUserIDs = nil
|
||||
testBypass(t, false, pb, user, true)
|
||||
|
||||
// admin can bypass when allowlisted.
|
||||
pb.BypassAllowlistUserIDs = []int64{user.ID}
|
||||
testBypass(t, true, pb, user, true)
|
||||
|
||||
// User bypasses via team allowlist membership.
|
||||
pb.EnableBypassAllowlist = true
|
||||
pb.BlockAdminMergeOverride = false
|
||||
pb.BypassAllowlistUserIDs = nil
|
||||
pb.BypassAllowlistTeamIDs = []int64{1} // team 1 contains user 2 in test fixtures
|
||||
testBypass(t, true, pb, teamMember, false)
|
||||
|
||||
// User does not bypass when not in allowlisted teams.
|
||||
testBypass(t, false, pb, user, false)
|
||||
})
|
||||
|
||||
t.Run("ProtectedBranchCanUserDelete", func(t *testing.T) {
|
||||
require.NoError(t, setupErr)
|
||||
writePermission := access_model.Permission{}
|
||||
writePermission.SetUnitsWithDefaultAccessMode([]*repo_model.RepoUnit{{Type: unit.TypeCode}}, perm.AccessModeWrite)
|
||||
readPermission := access_model.Permission{}
|
||||
readPermission.SetUnitsWithDefaultAccessMode([]*repo_model.RepoUnit{{Type: unit.TypeCode}}, perm.AccessModeRead)
|
||||
|
||||
for _, user := range []*user_model.User{{ID: 2, Name: "user2"}, user_model.NewActionsUser(), user_model.NewDeployKeyUser()} {
|
||||
t.Run(user.GetDisplayName(), func(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
config ProtectedBranchConfig
|
||||
want bool
|
||||
}{
|
||||
{name: "disabled by default", config: ProtectedBranchConfig{CanPush: true}},
|
||||
{name: "push disabled", config: ProtectedBranchConfig{CanDelete: true}},
|
||||
{name: "unrestricted", config: ProtectedBranchConfig{CanPush: true, CanDelete: true}, want: true},
|
||||
{name: "empty push allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true}},
|
||||
{name: "not in push allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, WhitelistUserIDs: []int64{1}}},
|
||||
{name: "empty deletion allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true}},
|
||||
{name: "not in deletion allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{1}}},
|
||||
{name: "in both allowlists", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, WhitelistUserIDs: []int64{user.ID}, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{user.ID}}, want: true},
|
||||
{name: "deletion allowlist does not grant push", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{user.ID}}},
|
||||
{name: "team member", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistTeamIDs: []int64{1}}, want: user.ID == 2},
|
||||
{name: "push team member", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, WhitelistTeamIDs: []int64{1}}, want: user.ID == 2},
|
||||
{name: "not in team", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistTeamIDs: []int64{3}}},
|
||||
{name: "user or team", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{user.ID}, DeletionAllowlistTeamIDs: []int64{3}}, want: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pb := &ProtectedBranch{ProtectedBranchConfig: tt.config}
|
||||
assert.Equal(t, tt.want, pb.CanUserDelete(t.Context(), user, writePermission))
|
||||
assert.False(t, pb.CanUserDelete(t.Context(), user, readPermission))
|
||||
assert.False(t, pb.CanUserDelete(t.Context(), nil, writePermission))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("UpdateProtectBranchPriorities", func(t *testing.T) {
|
||||
assert.NoError(t, setupErr)
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
// Create some test protected branches with initial priorities
|
||||
protectedBranches := []*ProtectedBranch{
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "master",
|
||||
Priority: 1,
|
||||
},
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "develop",
|
||||
Priority: 2,
|
||||
},
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "feature/*",
|
||||
Priority: 3,
|
||||
},
|
||||
}
|
||||
|
||||
for _, pb := range protectedBranches {
|
||||
_, err := db.GetEngine(t.Context()).Insert(pb)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
// Test updating priorities
|
||||
newPriorities := []int64{protectedBranches[2].ID, protectedBranches[0].ID, protectedBranches[1].ID}
|
||||
err := UpdateProtectBranchPriorities(t.Context(), repo, newPriorities)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
// Test updating priorities
|
||||
newPriorities := []int64{protectedBranches[2].ID, protectedBranches[0].ID, protectedBranches[1].ID}
|
||||
err := UpdateProtectBranchPriorities(t.Context(), repo, newPriorities)
|
||||
assert.NoError(t, err)
|
||||
// Verify new priorities
|
||||
pbs, err := FindRepoProtectedBranchRules(t.Context(), repo.ID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify new priorities
|
||||
pbs, err := FindRepoProtectedBranchRules(t.Context(), repo.ID)
|
||||
assert.NoError(t, err)
|
||||
expectedPriorities := map[string]int64{
|
||||
"feature/*": 1,
|
||||
"master": 2,
|
||||
"develop": 3,
|
||||
}
|
||||
|
||||
expectedPriorities := map[string]int64{
|
||||
"feature/*": 1,
|
||||
"master": 2,
|
||||
"develop": 3,
|
||||
}
|
||||
|
||||
for _, pb := range pbs {
|
||||
assert.Equal(t, expectedPriorities[pb.RuleName], pb.Priority)
|
||||
}
|
||||
for _, pb := range pbs {
|
||||
assert.Equal(t, expectedPriorities[pb.RuleName], pb.Priority)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewProtectBranchPriority(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
setupErr := unittest.PrepareTestDatabase()
|
||||
|
||||
err := UpdateProtectBranch(t.Context(), repo, &ProtectedBranch{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "branch-1",
|
||||
Priority: 1,
|
||||
}, WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
t.Run("NewProtectBranchPriority", func(t *testing.T) {
|
||||
assert.NoError(t, setupErr)
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
newPB := &ProtectedBranch{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "branch-2",
|
||||
// Priority intentionally omitted
|
||||
}
|
||||
err := UpdateProtectBranch(t.Context(), repo, &ProtectedBranch{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "branch-1",
|
||||
Priority: 1,
|
||||
}, WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = UpdateProtectBranch(t.Context(), repo, newPB, WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
newPB := &ProtectedBranch{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "branch-2",
|
||||
// Priority intentionally omitted
|
||||
}
|
||||
|
||||
savedPB2, err := GetFirstMatchProtectedBranchRule(t.Context(), repo.ID, "branch-2")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), savedPB2.Priority)
|
||||
}
|
||||
|
||||
func TestCanBypassBranchProtection(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) // not in team 1
|
||||
teamMember := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
|
||||
pb := &ProtectedBranch{
|
||||
EnableBypassAllowlist: true,
|
||||
BypassAllowlistUserIDs: []int64{user.ID},
|
||||
}
|
||||
|
||||
testBypass := func(t *testing.T, expected bool, pb *ProtectedBranch, doer *user_model.User, isAdmin bool) {
|
||||
assert.Equal(t, expected, CanBypassBranchProtection(t.Context(), pb, doer, isAdmin))
|
||||
}
|
||||
// User bypasses via explicit allowlist.
|
||||
testBypass(t, true, pb, user, false)
|
||||
|
||||
// Non-admin cannot bypass when allowlist is disabled.
|
||||
pb.EnableBypassAllowlist = false
|
||||
testBypass(t, false, pb, user, false)
|
||||
|
||||
// Repo admin can bypass independently of allowlist when not blocked.
|
||||
testBypass(t, true, pb, user, true)
|
||||
|
||||
// Admin override block still allows bypass for allowlisted users.
|
||||
pb.EnableBypassAllowlist = true
|
||||
pb.BlockAdminMergeOverride = true
|
||||
testBypass(t, true, pb, user, false)
|
||||
|
||||
// admin cannot bypass without allowlist membership.
|
||||
pb.BypassAllowlistUserIDs = nil
|
||||
testBypass(t, false, pb, user, true)
|
||||
|
||||
// admin can bypass when allowlisted.
|
||||
pb.BypassAllowlistUserIDs = []int64{user.ID}
|
||||
testBypass(t, true, pb, user, true)
|
||||
|
||||
// User bypasses via team allowlist membership.
|
||||
pb.EnableBypassAllowlist = true
|
||||
pb.BlockAdminMergeOverride = false
|
||||
pb.BypassAllowlistUserIDs = nil
|
||||
pb.BypassAllowlistTeamIDs = []int64{1} // team 1 contains user 2 in test fixtures
|
||||
testBypass(t, true, pb, teamMember, false)
|
||||
|
||||
// User does not bypass when not in allowlisted teams.
|
||||
testBypass(t, false, pb, user, false)
|
||||
}
|
||||
|
||||
func TestProtectedBranchConfig(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
pb := &ProtectedBranch{
|
||||
RepoID: 1, RuleName: "config-test",
|
||||
ProtectedBranchConfig: ProtectedBranchConfig{
|
||||
CanDelete: true, EnableDeletionAllowlist: true,
|
||||
DeletionAllowlistUserIDs: []int64{2, 4, user_model.ActionsUserID, user_model.DeployKeyUserID}, DeletionAllowlistTeamIDs: []int64{1, 2},
|
||||
CanPush: true, WhitelistUserIDs: []int64{2, 4}, WhitelistTeamIDs: []int64{1, 2}, StatusCheckContexts: []string{},
|
||||
},
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, pb))
|
||||
loaded := unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ID: pb.ID})
|
||||
assert.Equal(t, pb.ProtectedBranchConfig, loaded.ProtectedBranchConfig)
|
||||
require.NoError(t, RemoveUserIDFromProtectedBranch(ctx, loaded, 2))
|
||||
require.NoError(t, RemoveTeamIDFromProtectedBranch(ctx, loaded, 1))
|
||||
loaded = unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ID: pb.ID})
|
||||
assert.Equal(t, []int64{4}, loaded.WhitelistUserIDs)
|
||||
assert.Equal(t, []int64{2}, loaded.WhitelistTeamIDs)
|
||||
assert.True(t, loaded.CanPush)
|
||||
assert.True(t, loaded.CanDelete)
|
||||
assert.True(t, loaded.EnableDeletionAllowlist)
|
||||
assert.Equal(t, []int64{4, user_model.ActionsUserID, user_model.DeployKeyUserID}, loaded.DeletionAllowlistUserIDs)
|
||||
assert.Equal(t, []int64{2}, loaded.DeletionAllowlistTeamIDs)
|
||||
loaded.ProtectedBranchConfig = ProtectedBranchConfig{}
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
require.NoError(t, UpdateProtectBranch(ctx, repo, loaded, WhitelistOptions{}))
|
||||
loaded = unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ID: pb.ID})
|
||||
assert.Equal(t, ProtectedBranchConfig{}, loaded.ProtectedBranchConfig)
|
||||
}
|
||||
|
||||
func TestProtectedBranchCanUserDelete(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
writePermission := access_model.Permission{}
|
||||
writePermission.SetUnitsWithDefaultAccessMode([]*repo_model.RepoUnit{{Type: unit.TypeCode}}, perm.AccessModeWrite)
|
||||
readPermission := access_model.Permission{}
|
||||
readPermission.SetUnitsWithDefaultAccessMode([]*repo_model.RepoUnit{{Type: unit.TypeCode}}, perm.AccessModeRead)
|
||||
|
||||
for _, user := range []*user_model.User{{ID: 2, Name: "user2"}, user_model.NewActionsUser(), user_model.NewDeployKeyUser()} {
|
||||
t.Run(user.GetDisplayName(), func(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
config ProtectedBranchConfig
|
||||
want bool
|
||||
}{
|
||||
{name: "disabled by default", config: ProtectedBranchConfig{CanPush: true}},
|
||||
{name: "push disabled", config: ProtectedBranchConfig{CanDelete: true}},
|
||||
{name: "unrestricted", config: ProtectedBranchConfig{CanPush: true, CanDelete: true}, want: true},
|
||||
{name: "empty push allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true}},
|
||||
{name: "not in push allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, WhitelistUserIDs: []int64{1}}},
|
||||
{name: "empty deletion allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true}},
|
||||
{name: "not in deletion allowlist", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{1}}},
|
||||
{name: "in both allowlists", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, WhitelistUserIDs: []int64{user.ID}, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{user.ID}}, want: true},
|
||||
{name: "deletion allowlist does not grant push", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{user.ID}}},
|
||||
{name: "team member", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistTeamIDs: []int64{1}}, want: user.ID == 2},
|
||||
{name: "push team member", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableWhitelist: true, WhitelistTeamIDs: []int64{1}}, want: user.ID == 2},
|
||||
{name: "not in team", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistTeamIDs: []int64{3}}},
|
||||
{name: "user or team", config: ProtectedBranchConfig{CanPush: true, CanDelete: true, EnableDeletionAllowlist: true, DeletionAllowlistUserIDs: []int64{user.ID}, DeletionAllowlistTeamIDs: []int64{3}}, want: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
pb := &ProtectedBranch{ProtectedBranchConfig: tt.config}
|
||||
assert.Equal(t, tt.want, pb.CanUserDelete(t.Context(), user, writePermission))
|
||||
assert.False(t, pb.CanUserDelete(t.Context(), user, readPermission))
|
||||
assert.False(t, pb.CanUserDelete(t.Context(), nil, writePermission))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
err = UpdateProtectBranch(t.Context(), repo, newPB, WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
savedPB2, err := GetFirstMatchProtectedBranchRule(t.Context(), repo.ID, "branch-2")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), savedPB2.Priority)
|
||||
})
|
||||
|
||||
t.Run("ProtectedBranchConfig", func(t *testing.T) {
|
||||
require.NoError(t, setupErr)
|
||||
ctx := t.Context()
|
||||
pb := &ProtectedBranch{
|
||||
RepoID: 1, RuleName: "config-test",
|
||||
ProtectedBranchConfig: ProtectedBranchConfig{
|
||||
CanDelete: true, EnableDeletionAllowlist: true,
|
||||
DeletionAllowlistUserIDs: []int64{2, 4, user_model.ActionsUserID, user_model.DeployKeyUserID}, DeletionAllowlistTeamIDs: []int64{1, 2},
|
||||
CanPush: true, WhitelistUserIDs: []int64{2, 4}, WhitelistTeamIDs: []int64{1, 2}, StatusCheckContexts: []string{},
|
||||
},
|
||||
}
|
||||
require.NoError(t, db.Insert(ctx, pb))
|
||||
loaded := unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ID: pb.ID})
|
||||
assert.Equal(t, pb.ProtectedBranchConfig, loaded.ProtectedBranchConfig)
|
||||
require.NoError(t, RemoveUserIDFromProtectedBranch(ctx, loaded, 2))
|
||||
require.NoError(t, RemoveTeamIDFromProtectedBranch(ctx, loaded, 1))
|
||||
loaded = unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ID: pb.ID})
|
||||
assert.Equal(t, []int64{4}, loaded.WhitelistUserIDs)
|
||||
assert.Equal(t, []int64{2}, loaded.WhitelistTeamIDs)
|
||||
assert.True(t, loaded.CanPush)
|
||||
assert.True(t, loaded.CanDelete)
|
||||
assert.True(t, loaded.EnableDeletionAllowlist)
|
||||
assert.Equal(t, []int64{4, user_model.ActionsUserID, user_model.DeployKeyUserID}, loaded.DeletionAllowlistUserIDs)
|
||||
assert.Equal(t, []int64{2}, loaded.DeletionAllowlistTeamIDs)
|
||||
loaded.ProtectedBranchConfig = ProtectedBranchConfig{}
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
require.NoError(t, UpdateProtectBranch(ctx, repo, loaded, WhitelistOptions{}))
|
||||
loaded = unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ID: pb.ID})
|
||||
assert.Equal(t, ProtectedBranchConfig{}, loaded.ProtectedBranchConfig)
|
||||
})
|
||||
}
|
||||
@@ -15,44 +15,31 @@ import (
|
||||
func TestIsUserAllowed(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
pt := &git_model.ProtectedTag{}
|
||||
allowed, err := git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, allowed)
|
||||
checkAllowed := func(pt *git_model.ProtectedTag, userID int64, check assert.BoolAssertionFunc) {
|
||||
allowed, err := git_model.IsUserAllowedModifyTag(t.Context(), pt, userID)
|
||||
assert.NoError(t, err)
|
||||
check(t, allowed)
|
||||
}
|
||||
checkAllowed(&git_model.ProtectedTag{}, 1, assert.False)
|
||||
|
||||
pt = &git_model.ProtectedTag{
|
||||
pt := &git_model.ProtectedTag{
|
||||
AllowlistUserIDs: []int64{1},
|
||||
}
|
||||
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, allowed)
|
||||
|
||||
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, allowed)
|
||||
checkAllowed(pt, 1, assert.True)
|
||||
checkAllowed(pt, 2, assert.False)
|
||||
|
||||
pt = &git_model.ProtectedTag{
|
||||
AllowlistTeamIDs: []int64{1},
|
||||
}
|
||||
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, allowed)
|
||||
|
||||
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, allowed)
|
||||
checkAllowed(pt, 1, assert.False)
|
||||
checkAllowed(pt, 2, assert.True)
|
||||
|
||||
pt = &git_model.ProtectedTag{
|
||||
AllowlistUserIDs: []int64{1},
|
||||
AllowlistTeamIDs: []int64{1},
|
||||
}
|
||||
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, allowed)
|
||||
|
||||
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, allowed)
|
||||
checkAllowed(pt, 1, assert.True)
|
||||
checkAllowed(pt, 2, assert.True)
|
||||
}
|
||||
|
||||
func TestIsUserAllowedToControlTag(t *testing.T) {
|
||||
@@ -118,47 +105,33 @@ func TestIsUserAllowedToControlTag(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("Glob", func(t *testing.T) {
|
||||
protectedTags := []*git_model.ProtectedTag{
|
||||
{
|
||||
NamePattern: `*gitea`,
|
||||
AllowlistUserIDs: []int64{1},
|
||||
},
|
||||
{
|
||||
NamePattern: `v-*`,
|
||||
AllowlistUserIDs: []int64{2},
|
||||
},
|
||||
{
|
||||
NamePattern: "release",
|
||||
},
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
patterns []string
|
||||
}{
|
||||
{"Glob", []string{`*gitea`, `v-*`, "release"}},
|
||||
{"Regex", []string{`/gitea\z/`, `/\Av-/`, "/release/"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
protectedTags := []*git_model.ProtectedTag{
|
||||
{
|
||||
NamePattern: tc.patterns[0],
|
||||
AllowlistUserIDs: []int64{1},
|
||||
},
|
||||
{
|
||||
NamePattern: tc.patterns[1],
|
||||
AllowlistUserIDs: []int64{2},
|
||||
},
|
||||
{
|
||||
NamePattern: tc.patterns[2],
|
||||
},
|
||||
}
|
||||
|
||||
for n, c := range cases {
|
||||
isAllowed, err := git_model.IsUserAllowedToControlTag(t.Context(), protectedTags, c.name, c.userid)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Regex", func(t *testing.T) {
|
||||
protectedTags := []*git_model.ProtectedTag{
|
||||
{
|
||||
NamePattern: `/gitea\z/`,
|
||||
AllowlistUserIDs: []int64{1},
|
||||
},
|
||||
{
|
||||
NamePattern: `/\Av-/`,
|
||||
AllowlistUserIDs: []int64{2},
|
||||
},
|
||||
{
|
||||
NamePattern: "/release/",
|
||||
},
|
||||
}
|
||||
|
||||
for n, c := range cases {
|
||||
isAllowed, err := git_model.IsUserAllowedToControlTag(t.Context(), protectedTags, c.name, c.userid)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
|
||||
}
|
||||
})
|
||||
for n, c := range cases {
|
||||
isAllowed, err := git_model.IsUserAllowedToControlTag(t.Context(), protectedTags, c.name, c.userid)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+161
-155
@@ -19,162 +19,177 @@ import (
|
||||
)
|
||||
|
||||
func TestCreateComment(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
prepareErr := unittest.PrepareTestDatabase()
|
||||
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
|
||||
t.Run("LoadAssigneeUserAndTeam_DeletedTeamBecomesGhostTeam", func(t *testing.T) {
|
||||
assert.NoError(t, prepareErr)
|
||||
|
||||
now := time.Now().Unix()
|
||||
comment, err := issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypeComment,
|
||||
Doer: doer,
|
||||
Repo: repo,
|
||||
Issue: issue,
|
||||
Content: "Hello",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
then := time.Now().Unix()
|
||||
|
||||
assert.Equal(t, issues_model.CommentTypeComment, comment.Type)
|
||||
assert.Equal(t, "Hello", comment.Content)
|
||||
assert.Equal(t, issue.ID, comment.IssueID)
|
||||
assert.Equal(t, doer.ID, comment.PosterID)
|
||||
unittest.AssertInt64InRange(t, now, then, int64(comment.CreatedUnix))
|
||||
unittest.AssertExistsAndLoadBean(t, comment) // assert actually added to DB
|
||||
|
||||
updatedIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue.ID})
|
||||
unittest.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix))
|
||||
assert.Nil(t, comment.CommentMetaData)
|
||||
|
||||
ctx := issues_model.WithProjectWorkflow(t.Context(), project_model.WorkflowEventItemClosed)
|
||||
comment, err = issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypeProjectColumn,
|
||||
Doer: doer,
|
||||
Repo: repo,
|
||||
Issue: issue,
|
||||
ProjectColumnID: 5,
|
||||
ProjectColumnTitle: "Done",
|
||||
ProjectTitle: "Board",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, &issues_model.CommentMetaData{
|
||||
ProjectColumnID: 5,
|
||||
ProjectColumnTitle: "Done",
|
||||
ProjectTitle: "Board",
|
||||
ProjectWorkflowEvent: project_model.WorkflowEventItemClosed,
|
||||
SpecialDoerName: issues_model.SpecialDoerNameProjectWorkflow,
|
||||
}, unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: comment.ID}).CommentMetaData)
|
||||
}
|
||||
|
||||
func TestLoadAssigneeUserAndTeam_DeletedTeamBecomesGhostTeam(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 15})
|
||||
comment := &issues_model.Comment{
|
||||
Type: issues_model.CommentTypeAssignees,
|
||||
IssueID: issue.ID,
|
||||
AssigneeTeamID: 999999, // non-existing team ID
|
||||
}
|
||||
assert.NoError(t, comment.LoadAssigneeUserAndTeam(t.Context()))
|
||||
assert.NotNil(t, comment.AssigneeTeam)
|
||||
assert.EqualValues(t, -1, comment.AssigneeTeam.ID)
|
||||
}
|
||||
|
||||
func TestCommentListLoadAttributesMixedAssignees(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
first := &issues_model.Comment{
|
||||
ID: 1, PosterID: 1, IssueID: 1, LabelID: 1, MilestoneID: 1, OldMilestoneID: 1, AssigneeID: 1, DependentIssueID: 2,
|
||||
}
|
||||
last := &issues_model.Comment{
|
||||
ID: 2, PosterID: 2, IssueID: 4, LabelID: 2, MilestoneID: 3, OldMilestoneID: 3, AssigneeID: 2, DependentIssueID: 1,
|
||||
}
|
||||
comments := issues_model.CommentList{
|
||||
{AssigneeTeamID: 8},
|
||||
{AssigneeID: 999999},
|
||||
first,
|
||||
}
|
||||
for i := range db.DefaultMaxInSize {
|
||||
id := unittest.NonexistentID - int64(i)
|
||||
comments = append(comments, &issues_model.Comment{
|
||||
ID: id, PosterID: id, IssueID: id, LabelID: id, MilestoneID: id, OldMilestoneID: id, AssigneeID: id, DependentIssueID: id,
|
||||
})
|
||||
}
|
||||
comments = append(comments, last)
|
||||
|
||||
require.NoError(t, comments.LoadAttributes(t.Context()))
|
||||
assert.Nil(t, comments[0].Assignee)
|
||||
assert.Zero(t, comments[0].AssigneeID)
|
||||
assert.Equal(t, user_model.GhostUserID, comments[1].AssigneeID)
|
||||
assert.Equal(t, user_model.GhostUserID, comments[1].Assignee.ID)
|
||||
for _, comment := range []*issues_model.Comment{first, last} {
|
||||
require.NotNil(t, comment.Poster)
|
||||
assert.Equal(t, comment.PosterID, comment.Poster.ID)
|
||||
require.NotNil(t, comment.Issue)
|
||||
assert.Equal(t, comment.IssueID, comment.Issue.ID)
|
||||
require.NotNil(t, comment.Label)
|
||||
assert.Equal(t, comment.LabelID, comment.Label.ID)
|
||||
require.NotNil(t, comment.Milestone)
|
||||
assert.Equal(t, comment.MilestoneID, comment.Milestone.ID)
|
||||
require.NotNil(t, comment.OldMilestone)
|
||||
assert.Equal(t, comment.OldMilestoneID, comment.OldMilestone.ID)
|
||||
require.NotNil(t, comment.Assignee)
|
||||
assert.Equal(t, comment.AssigneeID, comment.Assignee.ID)
|
||||
require.NotNil(t, comment.DependentIssue)
|
||||
assert.Equal(t, comment.DependentIssueID, comment.DependentIssue.ID)
|
||||
require.NotNil(t, comment.DependentIssue.Repo)
|
||||
assert.Equal(t, comment.DependentIssue.RepoID, comment.DependentIssue.Repo.ID)
|
||||
require.Len(t, comment.Attachments, 2)
|
||||
for _, attachment := range comment.Attachments {
|
||||
assert.Equal(t, comment.ID, attachment.CommentID)
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 15})
|
||||
comment := &issues_model.Comment{
|
||||
Type: issues_model.CommentTypeAssignees,
|
||||
IssueID: issue.ID,
|
||||
AssigneeTeamID: 999999, // non-existing team ID
|
||||
}
|
||||
}
|
||||
missing := comments[3]
|
||||
assert.Equal(t, user_model.GhostUserID, missing.Poster.ID)
|
||||
assert.Equal(t, user_model.GhostUserID, missing.Assignee.ID)
|
||||
assert.Nil(t, missing.Issue)
|
||||
assert.Nil(t, missing.Label)
|
||||
assert.Nil(t, missing.Milestone)
|
||||
assert.Nil(t, missing.OldMilestone)
|
||||
assert.Nil(t, missing.DependentIssue)
|
||||
assert.Empty(t, missing.Attachments)
|
||||
}
|
||||
assert.NoError(t, comment.LoadAssigneeUserAndTeam(t.Context()))
|
||||
assert.NotNil(t, comment.AssigneeTeam)
|
||||
assert.EqualValues(t, -1, comment.AssigneeTeam.ID)
|
||||
})
|
||||
|
||||
func Test_UpdateCommentAttachment(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("CommentListLoadAttributesMixedAssignees", func(t *testing.T) {
|
||||
require.NoError(t, prepareErr)
|
||||
|
||||
comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 1})
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: comment.IssueID})
|
||||
attachment := repo_model.Attachment{
|
||||
RepoID: issue.RepoID, // must match the comment's repo, else the cross-repo guard rejects it
|
||||
Name: "test.txt",
|
||||
}
|
||||
assert.NoError(t, db.Insert(t.Context(), &attachment))
|
||||
first := &issues_model.Comment{
|
||||
ID: 1, PosterID: 1, IssueID: 1, LabelID: 1, MilestoneID: 1, OldMilestoneID: 1, AssigneeID: 1, DependentIssueID: 2,
|
||||
}
|
||||
last := &issues_model.Comment{
|
||||
ID: 2, PosterID: 2, IssueID: 4, LabelID: 2, MilestoneID: 3, OldMilestoneID: 3, AssigneeID: 2, DependentIssueID: 1,
|
||||
}
|
||||
comments := issues_model.CommentList{
|
||||
{AssigneeTeamID: 8},
|
||||
{AssigneeID: 999999},
|
||||
first,
|
||||
}
|
||||
for i := range db.DefaultMaxInSize {
|
||||
id := unittest.NonexistentID - int64(i)
|
||||
comments = append(comments, &issues_model.Comment{
|
||||
ID: id, PosterID: id, IssueID: id, LabelID: id, MilestoneID: id, OldMilestoneID: id, AssigneeID: id, DependentIssueID: id,
|
||||
})
|
||||
}
|
||||
comments = append(comments, last)
|
||||
|
||||
err := issues_model.UpdateCommentAttachments(t.Context(), comment, []string{attachment.UUID})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, comments.LoadAttributes(t.Context()))
|
||||
assert.Nil(t, comments[0].Assignee)
|
||||
assert.Zero(t, comments[0].AssigneeID)
|
||||
assert.Equal(t, user_model.GhostUserID, comments[1].AssigneeID)
|
||||
assert.Equal(t, user_model.GhostUserID, comments[1].Assignee.ID)
|
||||
for _, comment := range []*issues_model.Comment{first, last} {
|
||||
require.NotNil(t, comment.Poster)
|
||||
assert.Equal(t, comment.PosterID, comment.Poster.ID)
|
||||
require.NotNil(t, comment.Issue)
|
||||
assert.Equal(t, comment.IssueID, comment.Issue.ID)
|
||||
require.NotNil(t, comment.Label)
|
||||
assert.Equal(t, comment.LabelID, comment.Label.ID)
|
||||
require.NotNil(t, comment.Milestone)
|
||||
assert.Equal(t, comment.MilestoneID, comment.Milestone.ID)
|
||||
require.NotNil(t, comment.OldMilestone)
|
||||
assert.Equal(t, comment.OldMilestoneID, comment.OldMilestone.ID)
|
||||
require.NotNil(t, comment.Assignee)
|
||||
assert.Equal(t, comment.AssigneeID, comment.Assignee.ID)
|
||||
require.NotNil(t, comment.DependentIssue)
|
||||
assert.Equal(t, comment.DependentIssueID, comment.DependentIssue.ID)
|
||||
require.NotNil(t, comment.DependentIssue.Repo)
|
||||
assert.Equal(t, comment.DependentIssue.RepoID, comment.DependentIssue.Repo.ID)
|
||||
require.Len(t, comment.Attachments, 2)
|
||||
for _, attachment := range comment.Attachments {
|
||||
assert.Equal(t, comment.ID, attachment.CommentID)
|
||||
}
|
||||
}
|
||||
missing := comments[3]
|
||||
assert.Equal(t, user_model.GhostUserID, missing.Poster.ID)
|
||||
assert.Equal(t, user_model.GhostUserID, missing.Assignee.ID)
|
||||
assert.Nil(t, missing.Issue)
|
||||
assert.Nil(t, missing.Label)
|
||||
assert.Nil(t, missing.Milestone)
|
||||
assert.Nil(t, missing.OldMilestone)
|
||||
assert.Nil(t, missing.DependentIssue)
|
||||
assert.Empty(t, missing.Attachments)
|
||||
})
|
||||
|
||||
attachment2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{ID: attachment.ID})
|
||||
assert.Equal(t, attachment.Name, attachment2.Name)
|
||||
assert.Equal(t, comment.ID, attachment2.CommentID)
|
||||
assert.Equal(t, comment.IssueID, attachment2.IssueID)
|
||||
}
|
||||
t.Run("FetchCodeComments", func(t *testing.T) {
|
||||
assert.NoError(t, prepareErr)
|
||||
|
||||
func TestFetchCodeComments(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
res, err := issues_model.FetchCodeComments(t.Context(), issue, user, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Contains(t, res, "README.md")
|
||||
assert.Contains(t, res["README.md"], int64(4))
|
||||
assert.Len(t, res["README.md"][4], 1)
|
||||
assert.Equal(t, int64(4), res["README.md"][4][0].ID)
|
||||
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
res, err := issues_model.FetchCodeComments(t.Context(), issue, user, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Contains(t, res, "README.md")
|
||||
assert.Contains(t, res["README.md"], int64(4))
|
||||
assert.Len(t, res["README.md"][4], 1)
|
||||
assert.Equal(t, int64(4), res["README.md"][4][0].ID)
|
||||
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
res, err = issues_model.FetchCodeComments(t.Context(), issue, user2, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, res, 1)
|
||||
})
|
||||
|
||||
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
res, err = issues_model.FetchCodeComments(t.Context(), issue, user2, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, res, 1)
|
||||
t.Run("UpdateCommentAttachment", func(t *testing.T) {
|
||||
assert.NoError(t, prepareErr)
|
||||
|
||||
comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 1})
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: comment.IssueID})
|
||||
attachment := repo_model.Attachment{
|
||||
RepoID: issue.RepoID, // must match the comment's repo, else the cross-repo guard rejects it
|
||||
Name: "test.txt",
|
||||
}
|
||||
assert.NoError(t, db.Insert(t.Context(), &attachment))
|
||||
|
||||
err := issues_model.UpdateCommentAttachments(t.Context(), comment, []string{attachment.UUID})
|
||||
assert.NoError(t, err)
|
||||
|
||||
attachment2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{ID: attachment.ID})
|
||||
assert.Equal(t, attachment.Name, attachment2.Name)
|
||||
assert.Equal(t, comment.ID, attachment2.CommentID)
|
||||
assert.Equal(t, comment.IssueID, attachment2.IssueID)
|
||||
})
|
||||
|
||||
t.Run("UpdateIssueNumComments", func(t *testing.T) {
|
||||
assert.NoError(t, prepareErr)
|
||||
issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
|
||||
assert.NoError(t, issues_model.UpdateIssueNumComments(t.Context(), issue2.ID))
|
||||
issue2 = unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
assert.Equal(t, 1, issue2.NumComments)
|
||||
})
|
||||
|
||||
t.Run("CreateComment", func(t *testing.T) {
|
||||
assert.NoError(t, prepareErr)
|
||||
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
|
||||
|
||||
now := time.Now().Unix()
|
||||
comment, err := issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypeComment,
|
||||
Doer: doer,
|
||||
Repo: repo,
|
||||
Issue: issue,
|
||||
Content: "Hello",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
then := time.Now().Unix()
|
||||
|
||||
assert.Equal(t, issues_model.CommentTypeComment, comment.Type)
|
||||
assert.Equal(t, "Hello", comment.Content)
|
||||
assert.Equal(t, issue.ID, comment.IssueID)
|
||||
assert.Equal(t, doer.ID, comment.PosterID)
|
||||
unittest.AssertInt64InRange(t, now, then, int64(comment.CreatedUnix))
|
||||
unittest.AssertExistsAndLoadBean(t, comment) // assert actually added to DB
|
||||
|
||||
updatedIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue.ID})
|
||||
unittest.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix))
|
||||
assert.Nil(t, comment.CommentMetaData)
|
||||
|
||||
ctx := issues_model.WithProjectWorkflow(t.Context(), project_model.WorkflowEventItemClosed)
|
||||
comment, err = issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{
|
||||
Type: issues_model.CommentTypeProjectColumn,
|
||||
Doer: doer,
|
||||
Repo: repo,
|
||||
Issue: issue,
|
||||
ProjectColumnID: 5,
|
||||
ProjectColumnTitle: "Done",
|
||||
ProjectTitle: "Board",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, &issues_model.CommentMetaData{
|
||||
ProjectColumnID: 5,
|
||||
ProjectColumnTitle: "Done",
|
||||
ProjectTitle: "Board",
|
||||
ProjectWorkflowEvent: project_model.WorkflowEventItemClosed,
|
||||
SpecialDoerName: issues_model.SpecialDoerNameProjectWorkflow,
|
||||
}, unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: comment.ID}).CommentMetaData)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAsCommentType(t *testing.T) {
|
||||
@@ -211,12 +226,3 @@ func TestMigrate_InsertIssueComments(t *testing.T) {
|
||||
|
||||
unittest.CheckConsistencyFor(t, &issues_model.Issue{})
|
||||
}
|
||||
|
||||
func Test_UpdateIssueNumComments(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
|
||||
assert.NoError(t, issues_model.UpdateIssueNumComments(t.Context(), issue2.ID))
|
||||
issue2 = unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
assert.Equal(t, 1, issue2.NumComments)
|
||||
}
|
||||
@@ -17,111 +17,117 @@ import (
|
||||
)
|
||||
|
||||
func TestIssueList_LoadRepositories(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
prepareErr := unittest.PrepareTestDatabase()
|
||||
|
||||
issueList := issues_model.IssueList{
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
|
||||
}
|
||||
t.Run("LoadRepositories", func(t *testing.T) {
|
||||
assert.NoError(t, prepareErr)
|
||||
|
||||
repos, err := issueList.LoadRepositories(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, repos, 2)
|
||||
for _, issue := range issueList {
|
||||
assert.Equal(t, issue.RepoID, issue.Repo.ID)
|
||||
}
|
||||
}
|
||||
issueList := issues_model.IssueList{
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
|
||||
}
|
||||
|
||||
func TestIssueList_LoadIsRead(t *testing.T) {
|
||||
// Regression: In("issue_id") was missing the issueIDs argument, causing
|
||||
// xorm to generate "0=1" and never mark any issue as read.
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
repos, err := issueList.LoadRepositories(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, repos, 2)
|
||||
for _, issue := range issueList {
|
||||
assert.Equal(t, issue.RepoID, issue.Repo.ID)
|
||||
}
|
||||
})
|
||||
|
||||
issue1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
t.Run("LoadIsRead", func(t *testing.T) {
|
||||
require.NoError(t, prepareErr)
|
||||
|
||||
// Fixture: uid=1 has is_read=true on issue 1 only.
|
||||
issueList := issues_model.IssueList{issue1, issue2}
|
||||
require.NoError(t, issueList.LoadIsRead(t.Context(), 1))
|
||||
// Regression: In("issue_id") was missing the issueIDs argument, causing
|
||||
// xorm to generate "0=1" and never mark any issue as read.
|
||||
|
||||
assert.True(t, issue1.IsRead, "issue 1 should be marked read for user 1")
|
||||
assert.False(t, issue2.IsRead, "issue 2 should not be marked read for user 1")
|
||||
}
|
||||
issue1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
|
||||
|
||||
func TestIssueList_LoadAttributes(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
defer test.MockVariableValue(&setting.Service.EnableTimetracking, true)()
|
||||
fixtureIssues := issues_model.IssueList{
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
|
||||
}
|
||||
issueList := issues_model.IssueList{fixtureIssues[0]}
|
||||
for i := range db.DefaultMaxInSize {
|
||||
issueList = append(issueList, &issues_model.Issue{ID: int64(1000 + i), RepoID: 1, IsPull: true})
|
||||
}
|
||||
issueList = append(issueList, fixtureIssues[1:]...)
|
||||
// Fixture: uid=1 has is_read=true on issue 1 only.
|
||||
issueList := issues_model.IssueList{issue1, issue2}
|
||||
require.NoError(t, issueList.LoadIsRead(t.Context(), 1))
|
||||
|
||||
require.NoError(t, issueList.LoadAttributes(t.Context()))
|
||||
require.NoError(t, issueList.LoadAttachments(t.Context()))
|
||||
require.NoError(t, issueList.LoadComments(t.Context()))
|
||||
assert.Len(t, fixtureIssues[0].Labels, 1)
|
||||
assert.Len(t, fixtureIssues[1].Labels, 2)
|
||||
assert.Len(t, fixtureIssues[0].Assignees, 1)
|
||||
assert.Empty(t, fixtureIssues[1].Assignees)
|
||||
assert.Len(t, fixtureIssues[0].Attachments, 1)
|
||||
assert.Len(t, fixtureIssues[1].Attachments, 1)
|
||||
assert.Len(t, fixtureIssues[2].Attachments, 2)
|
||||
assert.Len(t, fixtureIssues[0].Comments, 3)
|
||||
assert.Len(t, fixtureIssues[1].Comments, 4)
|
||||
assert.Len(t, fixtureIssues[2].Comments, 1)
|
||||
for _, issue := range fixtureIssues {
|
||||
assert.Equal(t, issue.RepoID, issue.Repo.ID)
|
||||
for _, label := range issue.Labels {
|
||||
assert.Equal(t, unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: label.ID}), label)
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
|
||||
}
|
||||
if issue.PosterID > 0 {
|
||||
assert.Equal(t, issue.PosterID, issue.Poster.ID)
|
||||
}
|
||||
if issue.AssigneeID > 0 {
|
||||
assert.Equal(t, issue.AssigneeID, issue.Assignee.ID)
|
||||
}
|
||||
if issue.MilestoneID > 0 {
|
||||
assert.Equal(t, issue.MilestoneID, issue.Milestone.ID)
|
||||
}
|
||||
if issue.IsPull {
|
||||
require.NotNil(t, issue.PullRequest)
|
||||
assert.Equal(t, issue.ID, issue.PullRequest.IssueID)
|
||||
assert.Same(t, issue, issue.PullRequest.Issue)
|
||||
}
|
||||
for _, attachment := range issue.Attachments {
|
||||
assert.Equal(t, issue.ID, attachment.IssueID)
|
||||
}
|
||||
for _, comment := range issue.Comments {
|
||||
assert.Equal(t, issue.ID, comment.IssueID)
|
||||
assert.True(t, issue1.IsRead, "issue 1 should be marked read for user 1")
|
||||
assert.False(t, issue2.IsRead, "issue 2 should not be marked read for user 1")
|
||||
})
|
||||
|
||||
t.Run("LoadAttributes", func(t *testing.T) {
|
||||
require.NoError(t, prepareErr)
|
||||
|
||||
defer test.MockVariableValue(&setting.Service.EnableTimetracking, true)()
|
||||
fixtureIssues := issues_model.IssueList{
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}),
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
|
||||
}
|
||||
if issue.ID == int64(1) {
|
||||
assert.Equal(t, int64(400), issue.TotalTrackedTime)
|
||||
issueList := issues_model.IssueList{fixtureIssues[0]}
|
||||
for i := range db.DefaultMaxInSize {
|
||||
issueList = append(issueList, &issues_model.Issue{ID: int64(1000 + i), RepoID: 1, IsPull: true})
|
||||
}
|
||||
if issue.ID == 1 || issue.ID == 2 {
|
||||
require.Len(t, issue.Projects, 1)
|
||||
assert.Equal(t, int64(1), issue.Projects[0].ID)
|
||||
} else {
|
||||
assert.Empty(t, issue.Projects)
|
||||
issueList = append(issueList, fixtureIssues[1:]...)
|
||||
|
||||
require.NoError(t, issueList.LoadAttributes(t.Context()))
|
||||
require.NoError(t, issueList.LoadAttachments(t.Context()))
|
||||
require.NoError(t, issueList.LoadComments(t.Context()))
|
||||
assert.Len(t, fixtureIssues[0].Labels, 1)
|
||||
assert.Len(t, fixtureIssues[1].Labels, 2)
|
||||
assert.Len(t, fixtureIssues[0].Assignees, 1)
|
||||
assert.Empty(t, fixtureIssues[1].Assignees)
|
||||
assert.Len(t, fixtureIssues[0].Attachments, 1)
|
||||
assert.Len(t, fixtureIssues[1].Attachments, 1)
|
||||
assert.Len(t, fixtureIssues[2].Attachments, 2)
|
||||
assert.Len(t, fixtureIssues[0].Comments, 3)
|
||||
assert.Len(t, fixtureIssues[1].Comments, 4)
|
||||
assert.Len(t, fixtureIssues[2].Comments, 1)
|
||||
for _, issue := range fixtureIssues {
|
||||
assert.Equal(t, issue.RepoID, issue.Repo.ID)
|
||||
for _, label := range issue.Labels {
|
||||
assert.Equal(t, unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: label.ID}), label)
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
|
||||
}
|
||||
if issue.PosterID > 0 {
|
||||
assert.Equal(t, issue.PosterID, issue.Poster.ID)
|
||||
}
|
||||
if issue.AssigneeID > 0 {
|
||||
assert.Equal(t, issue.AssigneeID, issue.Assignee.ID)
|
||||
}
|
||||
if issue.MilestoneID > 0 {
|
||||
assert.Equal(t, issue.MilestoneID, issue.Milestone.ID)
|
||||
}
|
||||
if issue.IsPull {
|
||||
require.NotNil(t, issue.PullRequest)
|
||||
assert.Equal(t, issue.ID, issue.PullRequest.IssueID)
|
||||
assert.Same(t, issue, issue.PullRequest.Issue)
|
||||
}
|
||||
for _, attachment := range issue.Attachments {
|
||||
assert.Equal(t, issue.ID, attachment.IssueID)
|
||||
}
|
||||
for _, comment := range issue.Comments {
|
||||
assert.Equal(t, issue.ID, comment.IssueID)
|
||||
}
|
||||
if issue.ID == int64(1) {
|
||||
assert.Equal(t, int64(400), issue.TotalTrackedTime)
|
||||
}
|
||||
if issue.ID == 1 || issue.ID == 2 {
|
||||
require.Len(t, issue.Projects, 1)
|
||||
assert.Equal(t, int64(1), issue.Projects[0].ID)
|
||||
} else {
|
||||
assert.Empty(t, issue.Projects)
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.Equal(t, int64(3682), fixtureIssues[1].TotalTrackedTime)
|
||||
assert.Equal(t, int64(3682), fixtureIssues[1].TotalTrackedTime)
|
||||
|
||||
require.NoError(t, issueList.LoadDiscussComments(t.Context()))
|
||||
assert.Len(t, fixtureIssues[0].Comments, 2)
|
||||
assert.Empty(t, fixtureIssues[1].Comments)
|
||||
assert.Len(t, fixtureIssues[2].Comments, 1)
|
||||
for _, issue := range fixtureIssues {
|
||||
for _, comment := range issue.Comments {
|
||||
assert.Equal(t, issue.ID, comment.IssueID)
|
||||
assert.Equal(t, issues_model.CommentTypeComment, comment.Type)
|
||||
require.NoError(t, issueList.LoadDiscussComments(t.Context()))
|
||||
assert.Len(t, fixtureIssues[0].Comments, 2)
|
||||
assert.Empty(t, fixtureIssues[1].Comments)
|
||||
assert.Len(t, fixtureIssues[2].Comments, 1)
|
||||
for _, issue := range fixtureIssues {
|
||||
for _, comment := range issue.Comments {
|
||||
assert.Equal(t, issue.ID, comment.IssueID)
|
||||
assert.Equal(t, issues_model.CommentTypeComment, comment.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -44,19 +44,14 @@ func TestIssueMultipleProjects(t *testing.T) {
|
||||
require.Empty(t, issue1.Projects)
|
||||
|
||||
// assign issue to both projects (each project uses its own default column)
|
||||
_, _, err = issues_model.IssueAssignOrRemoveProject(t.Context(), issue1, user2, []int64{project1.ID})
|
||||
require.NoError(t, err)
|
||||
assert.Nilf(t, issue1.Projects, "Issue's Projects should be nil after IssueAssignOrRemoveProject to ensure it reloads fresh data")
|
||||
err = issue1.LoadProjects(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, issue1.Projects, 1)
|
||||
|
||||
_, _, err = issues_model.IssueAssignOrRemoveProject(t.Context(), issue1, user2, []int64{project1.ID, project2.ID})
|
||||
require.NoError(t, err)
|
||||
assert.Nilf(t, issue1.Projects, "Issue's Projects should be nil after IssueAssignOrRemoveProject to ensure it reloads fresh data")
|
||||
err = issue1.LoadProjects(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, issue1.Projects, 2)
|
||||
for _, projectIDs := range [][]int64{{project1.ID}, {project1.ID, project2.ID}} {
|
||||
_, _, err = issues_model.IssueAssignOrRemoveProject(t.Context(), issue1, user2, projectIDs)
|
||||
require.NoError(t, err)
|
||||
assert.Nilf(t, issue1.Projects, "Issue's Projects should be nil after IssueAssignOrRemoveProject to ensure it reloads fresh data")
|
||||
err = issue1.LoadProjects(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, issue1.Projects, len(projectIDs))
|
||||
}
|
||||
assert.ElementsMatch(t, []int64{project1.ID, project2.ID}, []int64{issue1.Projects[0].ID, issue1.Projects[1].ID}, "Issue should be in both projects")
|
||||
|
||||
// test issue's project column map
|
||||
|
||||
+191
-204
@@ -53,79 +53,211 @@ func TestIssue_ReplaceLabels(t *testing.T) {
|
||||
testSuccess(18, []int64{6, 8, 7}, []int64{6, 7})
|
||||
}
|
||||
|
||||
func Test_GetIssueIDsByRepoID(t *testing.T) {
|
||||
func TestIssueQueries(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
ids, err := issues_model.GetIssueIDsByRepoID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, ids, 5)
|
||||
}
|
||||
|
||||
func TestIssueAPIURL(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
err := issue.LoadAttributes(t.Context())
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(t.Context()))
|
||||
}
|
||||
|
||||
func TestGetIssuesByIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) {
|
||||
issues, err := issues_model.GetIssuesByIDs(t.Context(), append(expectedIssueIDs, nonExistentIssueIDs...), true)
|
||||
t.Run("GetIssueIDsByRepoID", func(t *testing.T) {
|
||||
ids, err := issues_model.GetIssueIDsByRepoID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
actualIssueIDs := make([]int64, len(issues))
|
||||
for i, issue := range issues {
|
||||
actualIssueIDs[i] = issue.ID
|
||||
}
|
||||
assert.Equal(t, expectedIssueIDs, actualIssueIDs)
|
||||
}
|
||||
testSuccess([]int64{1, 2, 3}, []int64{})
|
||||
testSuccess([]int64{1, 2, 3}, []int64{unittest.NonexistentID})
|
||||
testSuccess([]int64{3, 2, 1}, []int64{})
|
||||
}
|
||||
assert.Len(t, ids, 5)
|
||||
})
|
||||
|
||||
func TestGetParticipantIDsByIssue(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("IssueAPIURL", func(t *testing.T) {
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
err := issue.LoadAttributes(t.Context())
|
||||
|
||||
checkParticipants := func(issueID int64, userIDs []int) {
|
||||
issue, err := issues_model.GetIssueByID(t.Context(), issueID)
|
||||
assert.NoError(t, err)
|
||||
participants, err := issue.GetParticipantIDsByIssue(t.Context())
|
||||
if assert.NoError(t, err) {
|
||||
participantsIDs := make([]int, len(participants))
|
||||
for i, uid := range participants {
|
||||
participantsIDs[i] = int(uid)
|
||||
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(t.Context()))
|
||||
})
|
||||
|
||||
t.Run("GetIssuesByIDs", func(t *testing.T) {
|
||||
testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) {
|
||||
issues, err := issues_model.GetIssuesByIDs(t.Context(), append(expectedIssueIDs, nonExistentIssueIDs...), true)
|
||||
assert.NoError(t, err)
|
||||
actualIssueIDs := make([]int64, len(issues))
|
||||
for i, issue := range issues {
|
||||
actualIssueIDs[i] = issue.ID
|
||||
}
|
||||
sort.Ints(participantsIDs)
|
||||
sort.Ints(userIDs)
|
||||
assert.Equal(t, userIDs, participantsIDs)
|
||||
assert.Equal(t, expectedIssueIDs, actualIssueIDs)
|
||||
}
|
||||
}
|
||||
testSuccess([]int64{1, 2, 3}, []int64{})
|
||||
testSuccess([]int64{1, 2, 3}, []int64{unittest.NonexistentID})
|
||||
testSuccess([]int64{3, 2, 1}, []int64{})
|
||||
})
|
||||
|
||||
// User 1 is issue1 poster (see fixtures/issue.yml)
|
||||
// User 2 only labeled issue1 (see fixtures/comment.yml)
|
||||
// Users 3 and 5 made actual comments (see fixtures/comment.yml)
|
||||
// User 3 is inactive, thus not active participant
|
||||
checkParticipants(1, []int{1, 5})
|
||||
t.Run("GetParticipantIDsByIssue", func(t *testing.T) {
|
||||
checkParticipants := func(issueID int64, userIDs []int) {
|
||||
issue, err := issues_model.GetIssueByID(t.Context(), issueID)
|
||||
assert.NoError(t, err)
|
||||
participants, err := issue.GetParticipantIDsByIssue(t.Context())
|
||||
if assert.NoError(t, err) {
|
||||
participantsIDs := make([]int, len(participants))
|
||||
for i, uid := range participants {
|
||||
participantsIDs[i] = int(uid)
|
||||
}
|
||||
sort.Ints(participantsIDs)
|
||||
sort.Ints(userIDs)
|
||||
assert.Equal(t, userIDs, participantsIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// User 1 is issue1 poster (see fixtures/issue.yml)
|
||||
// User 2 only labeled issue1 (see fixtures/comment.yml)
|
||||
// Users 3 and 5 made actual comments (see fixtures/comment.yml)
|
||||
// User 3 is inactive, thus not active participant
|
||||
checkParticipants(1, []int{1, 5})
|
||||
})
|
||||
|
||||
t.Run("Issues", func(t *testing.T) {
|
||||
publicOnlyUser2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
publicOnlyUser2.ExtDoerData = user_model.NewTokenExtDoerData(user_model.CredentialAccessToken, 1, "public-only,read:issue")
|
||||
for _, test := range []struct {
|
||||
Opts issues_model.IssuesOptions
|
||||
ExpectedIssueIDs []int64
|
||||
}{
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
AssigneeID: "1",
|
||||
SortType: "oldest",
|
||||
},
|
||||
[]int64{1, 6},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
RepoCond: builder.In("repo_id", 1, 3),
|
||||
SortType: "oldest",
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 4,
|
||||
},
|
||||
},
|
||||
[]int64{1, 2, 3, 5},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
LabelIDs: []int64{1},
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 4,
|
||||
},
|
||||
},
|
||||
[]int64{2, 1},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
LabelIDs: []int64{1, 2},
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 4,
|
||||
},
|
||||
},
|
||||
[]int64{}, // issues with **both** label 1 and 2, none of these issues matches, TODO: add more tests
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
MilestoneIDs: []int64{1},
|
||||
},
|
||||
[]int64{2},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
SubscriberID: 11,
|
||||
},
|
||||
[]int64{11, 5, 9, 8, 3, 2, 1},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
RepoCond: builder.In("repo_id", 1, 2),
|
||||
Doer: publicOnlyUser2,
|
||||
IsPull: optional.Some(false),
|
||||
SortType: "oldest",
|
||||
},
|
||||
[]int64{1, 5},
|
||||
},
|
||||
} {
|
||||
issues, err := issues_model.Issues(t.Context(), &test.Opts)
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, issues, len(test.ExpectedIssueIDs)) {
|
||||
for i, issue := range issues {
|
||||
assert.Equal(t, test.ExpectedIssueIDs[i], issue.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Issue_loadTotalTimes", func(t *testing.T) {
|
||||
ms, err := issues_model.GetIssueByID(t.Context(), 2)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, ms.LoadTotalTimes(t.Context()))
|
||||
assert.Equal(t, int64(3682), ms.TotalTrackedTime)
|
||||
})
|
||||
|
||||
t.Run("Issue_ResolveMentions", func(t *testing.T) {
|
||||
testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) {
|
||||
o := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: owner})
|
||||
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: o.ID, LowerName: repo})
|
||||
issue := &issues_model.Issue{RepoID: r.ID}
|
||||
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer})
|
||||
resolved, err := issues_model.ResolveIssueMentionsByVisibility(t.Context(), issue, d, mentions)
|
||||
assert.NoError(t, err)
|
||||
ids := make([]int64, len(resolved))
|
||||
for i, user := range resolved {
|
||||
ids[i] = user.ID
|
||||
}
|
||||
slices.Sort(ids)
|
||||
assert.Equal(t, expected, ids)
|
||||
}
|
||||
|
||||
// Public repo, existing user
|
||||
testSuccess("user2", "repo1", "user1", []string{"user5"}, []int64{5})
|
||||
// Public repo, non-existing user
|
||||
testSuccess("user2", "repo1", "user1", []string{"nonexisting"}, []int64{})
|
||||
// Public repo, doer
|
||||
testSuccess("user2", "repo1", "user1", []string{"user1"}, []int64{})
|
||||
// Private repo, team member
|
||||
testSuccess("org17", "big_test_private_4", "user20", []string{"user2"}, []int64{2})
|
||||
// Private repo, not a team member
|
||||
testSuccess("org17", "big_test_private_4", "user20", []string{"user5"}, []int64{})
|
||||
// Private repo, whole team
|
||||
testSuccess("org17", "big_test_private_4", "user15", []string{"org17/owners"}, []int64{18})
|
||||
})
|
||||
|
||||
t.Run("MilestoneList_LoadTotalTrackedTimes", func(t *testing.T) {
|
||||
miles := issues_model.MilestoneList{
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}),
|
||||
}
|
||||
|
||||
assert.NoError(t, miles.LoadTotalTrackedTimes(t.Context()))
|
||||
|
||||
assert.Equal(t, int64(3682), miles[0].TotalTrackedTime)
|
||||
})
|
||||
|
||||
t.Run("LoadTotalTrackedTime", func(t *testing.T) {
|
||||
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
|
||||
|
||||
assert.NoError(t, milestone.LoadTotalTrackedTime(t.Context()))
|
||||
|
||||
assert.Equal(t, int64(3682), milestone.TotalTrackedTime)
|
||||
})
|
||||
|
||||
t.Run("CountIssues", func(t *testing.T) {
|
||||
count, err := issues_model.CountIssues(t.Context(), &issues_model.IssuesOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 22, count)
|
||||
})
|
||||
}
|
||||
|
||||
func TestIssue_ClearLabels(t *testing.T) {
|
||||
tests := []struct {
|
||||
issueID int64
|
||||
doerID int64
|
||||
}{
|
||||
{1, 2}, // non-pull-request, has labels
|
||||
{2, 2}, // pull-request, has labels
|
||||
{3, 2}, // pull-request, has no labels
|
||||
}
|
||||
for _, test := range tests {
|
||||
for _, issueID := range []int64{
|
||||
1, // non-pull-request, has labels
|
||||
2, // pull-request, has labels
|
||||
3, // pull-request, has no labels
|
||||
} {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID})
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issueID})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
assert.NoError(t, issues_model.ClearIssueLabels(t.Context(), issue, doer))
|
||||
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID})
|
||||
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issueID})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,92 +281,6 @@ func TestUpdateIssueCols(t *testing.T) {
|
||||
unittest.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix))
|
||||
}
|
||||
|
||||
func TestIssues(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
publicOnlyUser2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
publicOnlyUser2.ExtDoerData = user_model.NewTokenExtDoerData(user_model.CredentialAccessToken, 1, "public-only,read:issue")
|
||||
for _, test := range []struct {
|
||||
Opts issues_model.IssuesOptions
|
||||
ExpectedIssueIDs []int64
|
||||
}{
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
AssigneeID: "1",
|
||||
SortType: "oldest",
|
||||
},
|
||||
[]int64{1, 6},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
RepoCond: builder.In("repo_id", 1, 3),
|
||||
SortType: "oldest",
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 4,
|
||||
},
|
||||
},
|
||||
[]int64{1, 2, 3, 5},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
LabelIDs: []int64{1},
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 4,
|
||||
},
|
||||
},
|
||||
[]int64{2, 1},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
LabelIDs: []int64{1, 2},
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 4,
|
||||
},
|
||||
},
|
||||
[]int64{}, // issues with **both** label 1 and 2, none of these issues matches, TODO: add more tests
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
MilestoneIDs: []int64{1},
|
||||
},
|
||||
[]int64{2},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
SubscriberID: 11,
|
||||
},
|
||||
[]int64{11, 5, 9, 8, 3, 2, 1},
|
||||
},
|
||||
{
|
||||
issues_model.IssuesOptions{
|
||||
RepoCond: builder.In("repo_id", 1, 2),
|
||||
Doer: publicOnlyUser2,
|
||||
IsPull: optional.Some(false),
|
||||
SortType: "oldest",
|
||||
},
|
||||
[]int64{1, 5},
|
||||
},
|
||||
} {
|
||||
issues, err := issues_model.Issues(t.Context(), &test.Opts)
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, issues, len(test.ExpectedIssueIDs)) {
|
||||
for i, issue := range issues {
|
||||
assert.Equal(t, test.ExpectedIssueIDs[i], issue.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssue_loadTotalTimes(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
ms, err := issues_model.GetIssueByID(t.Context(), 2)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, ms.LoadTotalTimes(t.Context()))
|
||||
assert.Equal(t, int64(3682), ms.TotalTrackedTime)
|
||||
}
|
||||
|
||||
func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *issues_model.Issue {
|
||||
var newIssue issues_model.Issue
|
||||
t.Run(title, func(t *testing.T) {
|
||||
@@ -276,38 +322,6 @@ func TestIssue_InsertIssue(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestIssue_ResolveMentions(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) {
|
||||
o := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: owner})
|
||||
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: o.ID, LowerName: repo})
|
||||
issue := &issues_model.Issue{RepoID: r.ID}
|
||||
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer})
|
||||
resolved, err := issues_model.ResolveIssueMentionsByVisibility(t.Context(), issue, d, mentions)
|
||||
assert.NoError(t, err)
|
||||
ids := make([]int64, len(resolved))
|
||||
for i, user := range resolved {
|
||||
ids[i] = user.ID
|
||||
}
|
||||
slices.Sort(ids)
|
||||
assert.Equal(t, expected, ids)
|
||||
}
|
||||
|
||||
// Public repo, existing user
|
||||
testSuccess("user2", "repo1", "user1", []string{"user5"}, []int64{5})
|
||||
// Public repo, non-existing user
|
||||
testSuccess("user2", "repo1", "user1", []string{"nonexisting"}, []int64{})
|
||||
// Public repo, doer
|
||||
testSuccess("user2", "repo1", "user1", []string{"user1"}, []int64{})
|
||||
// Private repo, team member
|
||||
testSuccess("org17", "big_test_private_4", "user20", []string{"user2"}, []int64{2})
|
||||
// Private repo, not a team member
|
||||
testSuccess("org17", "big_test_private_4", "user20", []string{"user5"}, []int64{})
|
||||
// Private repo, whole team
|
||||
testSuccess("org17", "big_test_private_4", "user15", []string{"org17/owners"}, []int64{18})
|
||||
}
|
||||
|
||||
func TestResourceIndex(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
var wg sync.WaitGroup
|
||||
@@ -365,33 +379,6 @@ func TestCorrectIssueStats(t *testing.T) {
|
||||
assert.EqualValues(t, issueStats.OpenCount, issueAmount)
|
||||
}
|
||||
|
||||
func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
miles := issues_model.MilestoneList{
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}),
|
||||
}
|
||||
|
||||
assert.NoError(t, miles.LoadTotalTrackedTimes(t.Context()))
|
||||
|
||||
assert.Equal(t, int64(3682), miles[0].TotalTrackedTime)
|
||||
}
|
||||
|
||||
func TestLoadTotalTrackedTime(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
|
||||
|
||||
assert.NoError(t, milestone.LoadTotalTrackedTime(t.Context()))
|
||||
|
||||
assert.Equal(t, int64(3682), milestone.TotalTrackedTime)
|
||||
}
|
||||
|
||||
func TestCountIssues(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
count, err := issues_model.CountIssues(t.Context(), &issues_model.IssuesOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 22, count)
|
||||
}
|
||||
|
||||
func TestIssueLoadAttributes(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
setting.Service.EnableTimetracking = true
|
||||
|
||||
@@ -15,47 +15,47 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_NewIssueUsers(t *testing.T) {
|
||||
func TestIssueUsers(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
newIssue := &issues_model.Issue{
|
||||
RepoID: repo.ID,
|
||||
PosterID: 4,
|
||||
Index: 6,
|
||||
Title: "newTestIssueTitle",
|
||||
Content: "newTestIssueContent",
|
||||
}
|
||||
t.Run("NewIssueUsers", func(t *testing.T) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
newIssue := &issues_model.Issue{
|
||||
RepoID: repo.ID,
|
||||
PosterID: 4,
|
||||
Index: 6,
|
||||
Title: "newTestIssueTitle",
|
||||
Content: "newTestIssueContent",
|
||||
}
|
||||
|
||||
// artificially insert new issue
|
||||
require.NoError(t, db.Insert(t.Context(), newIssue))
|
||||
require.NoError(t, issues_model.NewIssueUsers(t.Context(), repo, newIssue))
|
||||
// artificially insert new issue
|
||||
require.NoError(t, db.Insert(t.Context(), newIssue))
|
||||
require.NoError(t, issues_model.NewIssueUsers(t.Context(), repo, newIssue))
|
||||
|
||||
// issue_user table should now have entries for new issue
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: repo.OwnerID})
|
||||
}
|
||||
// issue_user table should now have entries for new issue
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: repo.OwnerID})
|
||||
})
|
||||
|
||||
func TestUpdateIssueUserByRead(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
t.Run("UpdateIssueUserByRead", func(t *testing.T) {
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
|
||||
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), 4, issue.ID))
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1")
|
||||
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), 4, issue.ID))
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1")
|
||||
|
||||
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), 4, issue.ID))
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1")
|
||||
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), 4, issue.ID))
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1")
|
||||
|
||||
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
|
||||
}
|
||||
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
|
||||
})
|
||||
|
||||
func TestUpdateIssueUsersByMentions(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
t.Run("UpdateIssueUsersByMentions", func(t *testing.T) {
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
|
||||
|
||||
uids := []int64{2, 5}
|
||||
assert.NoError(t, issues_model.UpdateIssueUsersByMentions(t.Context(), issue.ID, uids))
|
||||
for _, uid := range uids {
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1")
|
||||
}
|
||||
uids := []int64{2, 5}
|
||||
assert.NoError(t, issues_model.UpdateIssueUsersByMentions(t.Context(), issue.ID, uids))
|
||||
for _, uid := range uids {
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -13,55 +13,48 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCreateOrUpdateIssueWatch(t *testing.T) {
|
||||
func TestIssueWatch(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(t.Context(), 3, 1, true))
|
||||
iw := unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 3, IssueID: 1})
|
||||
assert.True(t, iw.IsWatching)
|
||||
t.Run("GetIssueWatch", func(t *testing.T) {
|
||||
_, exists, err := issues_model.GetIssueWatch(t.Context(), 9, 1)
|
||||
assert.True(t, exists)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(t.Context(), 1, 1, false))
|
||||
iw = unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 1, IssueID: 1})
|
||||
assert.False(t, iw.IsWatching)
|
||||
}
|
||||
|
||||
func TestGetIssueWatch(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
_, exists, err := issues_model.GetIssueWatch(t.Context(), 9, 1)
|
||||
assert.True(t, exists)
|
||||
assert.NoError(t, err)
|
||||
|
||||
iw, exists, err := issues_model.GetIssueWatch(t.Context(), 2, 2)
|
||||
assert.True(t, exists)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, iw.IsWatching)
|
||||
|
||||
_, exists, err = issues_model.GetIssueWatch(t.Context(), 3, 1)
|
||||
assert.False(t, exists)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestGetIssueWatchers(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
iws, err := issues_model.GetIssueWatchers(t.Context(), 1, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
// Watcher is inactive, thus 0
|
||||
assert.Empty(t, iws)
|
||||
|
||||
iws, err = issues_model.GetIssueWatchers(t.Context(), 2, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
// Watcher is explicit not watching
|
||||
assert.Empty(t, iws)
|
||||
|
||||
iws, err = issues_model.GetIssueWatchers(t.Context(), 5, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
// Issue has no Watchers
|
||||
assert.Empty(t, iws)
|
||||
|
||||
iws, err = issues_model.GetIssueWatchers(t.Context(), 7, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
// Issue has one watcher
|
||||
assert.Len(t, iws, 1)
|
||||
iw, exists, err := issues_model.GetIssueWatch(t.Context(), 2, 2)
|
||||
assert.True(t, exists)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, iw.IsWatching)
|
||||
|
||||
_, exists, err = issues_model.GetIssueWatch(t.Context(), 3, 1)
|
||||
assert.False(t, exists)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("GetIssueWatchers", func(t *testing.T) {
|
||||
for _, issueID := range []int64{
|
||||
1, // Watcher is inactive, thus 0
|
||||
2, // Watcher is explicit not watching
|
||||
5, // Issue has no Watchers
|
||||
} {
|
||||
iws, err := issues_model.GetIssueWatchers(t.Context(), issueID, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, iws)
|
||||
}
|
||||
|
||||
iws, err := issues_model.GetIssueWatchers(t.Context(), 7, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
// Issue has one watcher
|
||||
assert.Len(t, iws, 1)
|
||||
})
|
||||
|
||||
t.Run("CreateOrUpdateIssueWatch", func(t *testing.T) {
|
||||
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(t.Context(), 3, 1, true))
|
||||
iw := unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 3, IssueID: 1})
|
||||
assert.True(t, iw.IsWatching)
|
||||
|
||||
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(t.Context(), 1, 1, false))
|
||||
iw = unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 1, IssueID: 1})
|
||||
assert.False(t, iw.IsWatching)
|
||||
})
|
||||
}
|
||||
+177
-214
@@ -17,41 +17,190 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLabel_CalOpenIssues(t *testing.T) {
|
||||
func TestLabelQueries(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
|
||||
label.CalOpenIssues()
|
||||
assert.Equal(t, 2, label.NumOpenIssues)
|
||||
}
|
||||
t.Run("Label_CalOpenIssues", func(t *testing.T) {
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
|
||||
label.CalOpenIssues()
|
||||
assert.Equal(t, 2, label.NumOpenIssues)
|
||||
})
|
||||
t.Run("Label_LoadSelectedLabelsAfterClick", func(t *testing.T) {
|
||||
// Loading the label id:8 which have a scope and an exclusivity
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
|
||||
|
||||
func TestLabel_LoadSelectedLabelsAfterClick(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
// Loading the label id:8 which have a scope and an exclusivity
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
|
||||
// First test : with negative and scope
|
||||
label.LoadSelectedLabelsAfterClick([]int64{1, -8}, []string{"", "scope"})
|
||||
assert.Equal(t, "1", label.QueryString)
|
||||
assert.True(t, label.IsSelected)
|
||||
|
||||
// First test : with negative and scope
|
||||
label.LoadSelectedLabelsAfterClick([]int64{1, -8}, []string{"", "scope"})
|
||||
assert.Equal(t, "1", label.QueryString)
|
||||
assert.True(t, label.IsSelected)
|
||||
// Second test : with duplicates
|
||||
label.LoadSelectedLabelsAfterClick([]int64{1, 7, 1, 7, 7}, []string{"", "scope", "", "scope", "scope"})
|
||||
assert.Equal(t, "1,8", label.QueryString)
|
||||
assert.False(t, label.IsSelected)
|
||||
|
||||
// Second test : with duplicates
|
||||
label.LoadSelectedLabelsAfterClick([]int64{1, 7, 1, 7, 7}, []string{"", "scope", "", "scope", "scope"})
|
||||
assert.Equal(t, "1,8", label.QueryString)
|
||||
assert.False(t, label.IsSelected)
|
||||
// Third test : empty set
|
||||
label.LoadSelectedLabelsAfterClick([]int64{}, []string{})
|
||||
assert.False(t, label.IsSelected)
|
||||
assert.Equal(t, "8", label.QueryString)
|
||||
})
|
||||
t.Run("Label_ExclusiveScope", func(t *testing.T) {
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7})
|
||||
assert.Equal(t, "scope", label.ExclusiveScope())
|
||||
|
||||
// Third test : empty set
|
||||
label.LoadSelectedLabelsAfterClick([]int64{}, []string{})
|
||||
assert.False(t, label.IsSelected)
|
||||
assert.Equal(t, "8", label.QueryString)
|
||||
}
|
||||
label = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 9})
|
||||
assert.Equal(t, "scope/subscope", label.ExclusiveScope())
|
||||
})
|
||||
t.Run("GetLabelByID", func(t *testing.T) {
|
||||
label, err := issues_model.GetLabelByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, label.ID)
|
||||
|
||||
func TestLabel_ExclusiveScope(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7})
|
||||
assert.Equal(t, "scope", label.ExclusiveScope())
|
||||
_, err = issues_model.GetLabelByID(t.Context(), unittest.NonexistentID)
|
||||
assert.True(t, issues_model.IsErrLabelNotExist(err))
|
||||
})
|
||||
t.Run("GetLabelInRepoByName", func(t *testing.T) {
|
||||
label, err := issues_model.GetLabelInRepoByName(t.Context(), 1, "label1")
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, label.ID)
|
||||
assert.Equal(t, "label1", label.Name)
|
||||
|
||||
label = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 9})
|
||||
assert.Equal(t, "scope/subscope", label.ExclusiveScope())
|
||||
_, err = issues_model.GetLabelInRepoByName(t.Context(), 1, "")
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByName(t.Context(), unittest.NonexistentID, "nonexistent")
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
})
|
||||
t.Run("GetLabelInRepoByNames", func(t *testing.T) {
|
||||
for _, names := range [][]string{
|
||||
{"label1", "label2"},
|
||||
// label3 doesn't exists.. See labels.yml
|
||||
{"label1", "label2", "label3"},
|
||||
} {
|
||||
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(t.Context(), 1, names)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, labelIDs, 2)
|
||||
assert.Equal(t, int64(1), labelIDs[0])
|
||||
assert.Equal(t, int64(2), labelIDs[1])
|
||||
}
|
||||
})
|
||||
t.Run("GetLabelInRepoByID", func(t *testing.T) {
|
||||
label, err := issues_model.GetLabelInRepoByID(t.Context(), 1, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, label.ID)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByID(t.Context(), 1, -1)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
})
|
||||
t.Run("GetLabelsInRepoByIDs", func(t *testing.T) {
|
||||
labels, err := issues_model.GetLabelsInRepoByIDs(t.Context(), 1, []int64{1, 2, unittest.NonexistentID})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, labels, 2) {
|
||||
assert.EqualValues(t, 1, labels[0].ID)
|
||||
assert.EqualValues(t, 2, labels[1].ID)
|
||||
}
|
||||
})
|
||||
|
||||
// Org versions
|
||||
t.Run("GetLabelInOrgByName", func(t *testing.T) {
|
||||
label, err := issues_model.GetLabelInOrgByName(t.Context(), 3, "orglabel3")
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 3, label.ID)
|
||||
assert.Equal(t, "orglabel3", label.Name)
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), 3, "")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), 0, "orglabel3")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), -1, "orglabel3")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), unittest.NonexistentID, "nonexistent")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
})
|
||||
t.Run("GetLabelInOrgByID", func(t *testing.T) {
|
||||
label, err := issues_model.GetLabelInOrgByID(t.Context(), 3, 3)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 3, label.ID)
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), 3, -1)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), 0, 3)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), -1, 3)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
})
|
||||
t.Run("GetLabelsInOrgByIDs", func(t *testing.T) {
|
||||
labels, err := issues_model.GetLabelsInOrgByIDs(t.Context(), 3, []int64{3, 4, unittest.NonexistentID})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, labels, 2) {
|
||||
assert.EqualValues(t, 3, labels[0].ID)
|
||||
assert.EqualValues(t, 4, labels[1].ID)
|
||||
}
|
||||
})
|
||||
t.Run("GetLabelsByIssueID", func(t *testing.T) {
|
||||
labels, err := issues_model.GetLabelsByIssueID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, labels, 1) {
|
||||
assert.EqualValues(t, 1, labels[0].ID)
|
||||
}
|
||||
|
||||
labels, err = issues_model.GetLabelsByIssueID(t.Context(), unittest.NonexistentID)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, labels)
|
||||
})
|
||||
t.Run("HasIssueLabel", func(t *testing.T) {
|
||||
assert.True(t, issues_model.HasIssueLabel(t.Context(), 1, 1))
|
||||
assert.False(t, issues_model.HasIssueLabel(t.Context(), 1, 2))
|
||||
assert.False(t, issues_model.HasIssueLabel(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
|
||||
})
|
||||
t.Run("GetLabelsByRepoID", func(t *testing.T) {
|
||||
_, err := db.GetEngine(t.Context()).ID(2).Cols("num_issues", "num_closed_issues").Update(&issues_model.Label{NumIssues: 3, NumClosedIssues: 3})
|
||||
assert.NoError(t, err)
|
||||
testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) {
|
||||
labels, err := issues_model.GetLabelsByRepoID(t.Context(), repoID, sortType, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, labels, len(expectedIssueIDs))
|
||||
for i, label := range labels {
|
||||
assert.Equal(t, expectedIssueIDs[i], label.ID)
|
||||
}
|
||||
}
|
||||
testSuccess(1, "leastissues", []int64{2, 1})
|
||||
testSuccess(1, "mostissues", []int64{1, 2})
|
||||
testSuccess(1, "reversealphabetically", []int64{2, 1})
|
||||
testSuccess(1, "default", []int64{1, 2})
|
||||
})
|
||||
t.Run("GetLabelsByOrgID", func(t *testing.T) {
|
||||
_, err := db.GetEngine(t.Context()).ID(3).Cols("num_issues", "num_closed_issues").Update(&issues_model.Label{NumIssues: 3, NumClosedIssues: 3})
|
||||
assert.NoError(t, err)
|
||||
testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) {
|
||||
labels, err := issues_model.GetLabelsByOrgID(t.Context(), orgID, sortType, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, labels, len(expectedIssueIDs))
|
||||
for i, label := range labels {
|
||||
assert.Equal(t, expectedIssueIDs[i], label.ID)
|
||||
}
|
||||
}
|
||||
testSuccess(3, "leastissues", []int64{3, 4})
|
||||
testSuccess(3, "mostissues", []int64{4, 3})
|
||||
testSuccess(3, "reversealphabetically", []int64{4, 3})
|
||||
testSuccess(3, "default", []int64{3, 4})
|
||||
|
||||
_, err = issues_model.GetLabelsByOrgID(t.Context(), 0, "leastissues", db.ListOptions{})
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelsByOrgID(t.Context(), -1, "leastissues", db.ListOptions{})
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
})
|
||||
}
|
||||
|
||||
func TestSortLabelsForDisplay(t *testing.T) {
|
||||
@@ -118,185 +267,6 @@ func TestNewLabels(t *testing.T) {
|
||||
unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{})
|
||||
}
|
||||
|
||||
func TestGetLabelByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label, err := issues_model.GetLabelByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, label.ID)
|
||||
|
||||
_, err = issues_model.GetLabelByID(t.Context(), unittest.NonexistentID)
|
||||
assert.True(t, issues_model.IsErrLabelNotExist(err))
|
||||
}
|
||||
|
||||
func TestGetLabelInRepoByName(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label, err := issues_model.GetLabelInRepoByName(t.Context(), 1, "label1")
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, label.ID)
|
||||
assert.Equal(t, "label1", label.Name)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByName(t.Context(), 1, "")
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByName(t.Context(), unittest.NonexistentID, "nonexistent")
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestGetLabelInRepoByNames(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(t.Context(), 1, []string{"label1", "label2"})
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Len(t, labelIDs, 2)
|
||||
|
||||
assert.Equal(t, int64(1), labelIDs[0])
|
||||
assert.Equal(t, int64(2), labelIDs[1])
|
||||
}
|
||||
|
||||
func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
// label3 doesn't exists.. See labels.yml
|
||||
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(t.Context(), 1, []string{"label1", "label2", "label3"})
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Len(t, labelIDs, 2)
|
||||
|
||||
assert.Equal(t, int64(1), labelIDs[0])
|
||||
assert.Equal(t, int64(2), labelIDs[1])
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestGetLabelInRepoByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label, err := issues_model.GetLabelInRepoByID(t.Context(), 1, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, label.ID)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByID(t.Context(), 1, -1)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
_, err = issues_model.GetLabelInRepoByID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestGetLabelsInRepoByIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
labels, err := issues_model.GetLabelsInRepoByIDs(t.Context(), 1, []int64{1, 2, unittest.NonexistentID})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, labels, 2) {
|
||||
assert.EqualValues(t, 1, labels[0].ID)
|
||||
assert.EqualValues(t, 2, labels[1].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLabelsByRepoID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
_, err := db.GetEngine(t.Context()).ID(2).Cols("num_issues", "num_closed_issues").Update(&issues_model.Label{NumIssues: 3, NumClosedIssues: 3})
|
||||
assert.NoError(t, err)
|
||||
testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) {
|
||||
labels, err := issues_model.GetLabelsByRepoID(t.Context(), repoID, sortType, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, labels, len(expectedIssueIDs))
|
||||
for i, label := range labels {
|
||||
assert.Equal(t, expectedIssueIDs[i], label.ID)
|
||||
}
|
||||
}
|
||||
testSuccess(1, "leastissues", []int64{2, 1})
|
||||
testSuccess(1, "mostissues", []int64{1, 2})
|
||||
testSuccess(1, "reversealphabetically", []int64{2, 1})
|
||||
testSuccess(1, "default", []int64{1, 2})
|
||||
}
|
||||
|
||||
// Org versions
|
||||
|
||||
func TestGetLabelInOrgByName(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label, err := issues_model.GetLabelInOrgByName(t.Context(), 3, "orglabel3")
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 3, label.ID)
|
||||
assert.Equal(t, "orglabel3", label.Name)
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), 3, "")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), 0, "orglabel3")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), -1, "orglabel3")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByName(t.Context(), unittest.NonexistentID, "nonexistent")
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
}
|
||||
|
||||
func TestGetLabelInOrgByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label, err := issues_model.GetLabelInOrgByID(t.Context(), 3, 3)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 3, label.ID)
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), 3, -1)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), 0, 3)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), -1, 3)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelInOrgByID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
}
|
||||
|
||||
func TestGetLabelsInOrgByIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
labels, err := issues_model.GetLabelsInOrgByIDs(t.Context(), 3, []int64{3, 4, unittest.NonexistentID})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, labels, 2) {
|
||||
assert.EqualValues(t, 3, labels[0].ID)
|
||||
assert.EqualValues(t, 4, labels[1].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLabelsByOrgID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
_, err := db.GetEngine(t.Context()).ID(3).Cols("num_issues", "num_closed_issues").Update(&issues_model.Label{NumIssues: 3, NumClosedIssues: 3})
|
||||
assert.NoError(t, err)
|
||||
testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) {
|
||||
labels, err := issues_model.GetLabelsByOrgID(t.Context(), orgID, sortType, db.ListOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, labels, len(expectedIssueIDs))
|
||||
for i, label := range labels {
|
||||
assert.Equal(t, expectedIssueIDs[i], label.ID)
|
||||
}
|
||||
}
|
||||
testSuccess(3, "leastissues", []int64{3, 4})
|
||||
testSuccess(3, "mostissues", []int64{4, 3})
|
||||
testSuccess(3, "reversealphabetically", []int64{4, 3})
|
||||
testSuccess(3, "default", []int64{3, 4})
|
||||
|
||||
_, err = issues_model.GetLabelsByOrgID(t.Context(), 0, "leastissues", db.ListOptions{})
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
|
||||
_, err = issues_model.GetLabelsByOrgID(t.Context(), -1, "leastissues", db.ListOptions{})
|
||||
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
func TestGetLabelsByIssueID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
labels, err := issues_model.GetLabelsByIssueID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, labels, 1) {
|
||||
assert.EqualValues(t, 1, labels[0].ID)
|
||||
}
|
||||
|
||||
labels, err = issues_model.GetLabelsByIssueID(t.Context(), unittest.NonexistentID)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, labels)
|
||||
}
|
||||
|
||||
func TestUpdateLabel(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
|
||||
@@ -350,13 +320,6 @@ func TestDeleteLabel(t *testing.T) {
|
||||
unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{})
|
||||
}
|
||||
|
||||
func TestHasIssueLabel(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
assert.True(t, issues_model.HasIssueLabel(t.Context(), 1, 1))
|
||||
assert.False(t, issues_model.HasIssueLabel(t.Context(), 1, 2))
|
||||
assert.False(t, issues_model.HasIssueLabel(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
|
||||
}
|
||||
|
||||
func TestNewIssueLabel(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2})
|
||||
|
||||
+159
-233
@@ -24,263 +24,189 @@ func TestMilestone_State(t *testing.T) {
|
||||
assert.Equal(t, api.StateClosed, (&issues_model.Milestone{IsClosed: true}).State())
|
||||
}
|
||||
|
||||
func TestGetMilestoneByRepoID(t *testing.T) {
|
||||
func TestMilestoneQueries(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
milestone, err := issues_model.GetMilestoneByRepoID(t.Context(), 1, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, milestone.ID)
|
||||
assert.EqualValues(t, 1, milestone.RepoID)
|
||||
|
||||
_, err = issues_model.GetMilestoneByRepoID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
|
||||
assert.True(t, issues_model.IsErrMilestoneNotExist(err))
|
||||
}
|
||||
|
||||
func TestGetMilestonesByRepoID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
test := func(repoID int64, state api.StateType) {
|
||||
var isClosed optional.Option[bool]
|
||||
switch state {
|
||||
case api.StateClosed, api.StateOpen:
|
||||
isClosed = optional.Some(state == api.StateClosed)
|
||||
}
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: repo.ID,
|
||||
IsClosed: isClosed,
|
||||
})
|
||||
t.Run("GetMilestoneByRepoID", func(t *testing.T) {
|
||||
milestone, err := issues_model.GetMilestoneByRepoID(t.Context(), 1, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, milestone.ID)
|
||||
assert.EqualValues(t, 1, milestone.RepoID)
|
||||
|
||||
var n int
|
||||
|
||||
switch state {
|
||||
case api.StateClosed:
|
||||
n = repo.NumClosedMilestones
|
||||
|
||||
case api.StateAll:
|
||||
n = repo.NumMilestones
|
||||
|
||||
case api.StateOpen:
|
||||
fallthrough
|
||||
|
||||
default:
|
||||
n = repo.NumOpenMilestones
|
||||
}
|
||||
|
||||
assert.Len(t, milestones, n)
|
||||
for _, milestone := range milestones {
|
||||
assert.Equal(t, repoID, milestone.RepoID)
|
||||
}
|
||||
}
|
||||
test(1, api.StateOpen)
|
||||
test(1, api.StateAll)
|
||||
test(1, api.StateClosed)
|
||||
test(2, api.StateOpen)
|
||||
test(2, api.StateAll)
|
||||
test(2, api.StateClosed)
|
||||
test(3, api.StateOpen)
|
||||
test(3, api.StateClosed)
|
||||
test(3, api.StateAll)
|
||||
|
||||
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: unittest.NonexistentID,
|
||||
IsClosed: optional.Some(false),
|
||||
_, err = issues_model.GetMilestoneByRepoID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
|
||||
assert.True(t, issues_model.IsErrMilestoneNotExist(err))
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, milestones)
|
||||
}
|
||||
|
||||
func TestGetMilestones(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
|
||||
for _, page := range []int{0, 1} {
|
||||
t.Run("GetMilestonesByRepoID", func(t *testing.T) {
|
||||
test := func(repoID int64, state api.StateType) {
|
||||
var isClosed optional.Option[bool]
|
||||
switch state {
|
||||
case api.StateClosed, api.StateOpen:
|
||||
isClosed = optional.Some(state == api.StateClosed)
|
||||
}
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.IssuePagingNum,
|
||||
},
|
||||
RepoID: repo.ID,
|
||||
IsClosed: optional.Some(false),
|
||||
SortType: sortType,
|
||||
IsClosed: isClosed,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, milestones, repo.NumMilestones-repo.NumClosedMilestones)
|
||||
values := make([]int, len(milestones))
|
||||
for i, milestone := range milestones {
|
||||
values[i] = sortCond(milestone)
|
||||
}
|
||||
assert.True(t, sort.IntsAreSorted(values))
|
||||
|
||||
milestones, err = db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.IssuePagingNum,
|
||||
},
|
||||
RepoID: repo.ID,
|
||||
var n int
|
||||
|
||||
switch state {
|
||||
case api.StateClosed:
|
||||
n = repo.NumClosedMilestones
|
||||
|
||||
case api.StateAll:
|
||||
n = repo.NumMilestones
|
||||
|
||||
case api.StateOpen:
|
||||
fallthrough
|
||||
|
||||
default:
|
||||
n = repo.NumOpenMilestones
|
||||
}
|
||||
|
||||
assert.Len(t, milestones, n)
|
||||
for _, milestone := range milestones {
|
||||
assert.Equal(t, repoID, milestone.RepoID)
|
||||
}
|
||||
}
|
||||
test(1, api.StateOpen)
|
||||
test(1, api.StateAll)
|
||||
test(1, api.StateClosed)
|
||||
test(2, api.StateOpen)
|
||||
test(2, api.StateAll)
|
||||
test(2, api.StateClosed)
|
||||
test(3, api.StateOpen)
|
||||
test(3, api.StateClosed)
|
||||
test(3, api.StateAll)
|
||||
|
||||
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: unittest.NonexistentID,
|
||||
IsClosed: optional.Some(false),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, milestones)
|
||||
})
|
||||
t.Run("GetMilestones", func(t *testing.T) {
|
||||
test := func(t *testing.T, options issues_model.FindMilestoneOptions, numOpen, numClosed int) {
|
||||
testSort := func(sortType string, sortCond func(*issues_model.Milestone) int) {
|
||||
for _, page := range []int{0, 1} {
|
||||
for _, isClosed := range []bool{false, true} {
|
||||
options.ListOptions = db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.IssuePagingNum,
|
||||
}
|
||||
options.IsClosed = optional.Some(isClosed)
|
||||
options.SortType = sortType
|
||||
milestones, err := db.Find[issues_model.Milestone](t.Context(), options)
|
||||
assert.NoError(t, err)
|
||||
expectedCount := numOpen
|
||||
if isClosed {
|
||||
expectedCount = numClosed
|
||||
}
|
||||
assert.Len(t, milestones, expectedCount)
|
||||
values := make([]int, len(milestones))
|
||||
for i, milestone := range milestones {
|
||||
values[i] = sortCond(milestone)
|
||||
}
|
||||
assert.True(t, sort.IntsAreSorted(values))
|
||||
}
|
||||
}
|
||||
}
|
||||
testSort("furthestduedate", func(milestone *issues_model.Milestone) int {
|
||||
return -int(milestone.DeadlineUnix)
|
||||
})
|
||||
testSort("leastcomplete", func(milestone *issues_model.Milestone) int {
|
||||
return milestone.Completeness
|
||||
})
|
||||
testSort("mostcomplete", func(milestone *issues_model.Milestone) int {
|
||||
return -milestone.Completeness
|
||||
})
|
||||
testSort("leastissues", func(milestone *issues_model.Milestone) int {
|
||||
return milestone.NumIssues
|
||||
})
|
||||
testSort("mostissues", func(milestone *issues_model.Milestone) int {
|
||||
return -milestone.NumIssues
|
||||
})
|
||||
testSort("soonestduedate", func(milestone *issues_model.Milestone) int {
|
||||
return int(milestone.DeadlineUnix)
|
||||
})
|
||||
}
|
||||
t.Run("repo", func(t *testing.T) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
test(t, issues_model.FindMilestoneOptions{RepoID: repo.ID}, repo.NumMilestones-repo.NumClosedMilestones, repo.NumClosedMilestones)
|
||||
})
|
||||
t.Run("repos", func(t *testing.T) {
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
|
||||
test(t, issues_model.FindMilestoneOptions{RepoIDs: []int64{repo1.ID, repo2.ID}},
|
||||
repo1.NumOpenMilestones+repo2.NumOpenMilestones, repo1.NumClosedMilestones+repo2.NumClosedMilestones)
|
||||
})
|
||||
})
|
||||
t.Run("CountRepoMilestones", func(t *testing.T) {
|
||||
test := func(repoID int64) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: repoID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo.NumMilestones, count)
|
||||
}
|
||||
test(1)
|
||||
test(2)
|
||||
test(3)
|
||||
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: unittest.NonexistentID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
})
|
||||
t.Run("CountRepoClosedMilestones", func(t *testing.T) {
|
||||
test := func(repoID int64) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: repoID,
|
||||
IsClosed: optional.Some(true),
|
||||
Name: "",
|
||||
SortType: sortType,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, milestones, repo.NumClosedMilestones)
|
||||
values = make([]int, len(milestones))
|
||||
for i, milestone := range milestones {
|
||||
values[i] = sortCond(milestone)
|
||||
}
|
||||
assert.True(t, sort.IntsAreSorted(values))
|
||||
assert.EqualValues(t, repo.NumClosedMilestones, count)
|
||||
}
|
||||
}
|
||||
test("furthestduedate", func(milestone *issues_model.Milestone) int {
|
||||
return -int(milestone.DeadlineUnix)
|
||||
})
|
||||
test("leastcomplete", func(milestone *issues_model.Milestone) int {
|
||||
return milestone.Completeness
|
||||
})
|
||||
test("mostcomplete", func(milestone *issues_model.Milestone) int {
|
||||
return -milestone.Completeness
|
||||
})
|
||||
test("leastissues", func(milestone *issues_model.Milestone) int {
|
||||
return milestone.NumIssues
|
||||
})
|
||||
test("mostissues", func(milestone *issues_model.Milestone) int {
|
||||
return -milestone.NumIssues
|
||||
})
|
||||
test("soonestduedate", func(milestone *issues_model.Milestone) int {
|
||||
return int(milestone.DeadlineUnix)
|
||||
})
|
||||
}
|
||||
test(1)
|
||||
test(2)
|
||||
test(3)
|
||||
|
||||
func TestCountRepoMilestones(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
test := func(repoID int64) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: repoID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo.NumMilestones, count)
|
||||
}
|
||||
test(1)
|
||||
test(2)
|
||||
test(3)
|
||||
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: unittest.NonexistentID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
}
|
||||
|
||||
func TestCountRepoClosedMilestones(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
test := func(repoID int64) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: repoID,
|
||||
RepoID: unittest.NonexistentID,
|
||||
IsClosed: optional.Some(true),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo.NumClosedMilestones, count)
|
||||
}
|
||||
test(1)
|
||||
test(2)
|
||||
test(3)
|
||||
|
||||
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoID: unittest.NonexistentID,
|
||||
IsClosed: optional.Some(true),
|
||||
assert.EqualValues(t, 0, count)
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
}
|
||||
t.Run("CountMilestonesByRepoIDs", func(t *testing.T) {
|
||||
milestonesCount := func(repoID int64) (int, int) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
return repo.NumOpenMilestones, repo.NumClosedMilestones
|
||||
}
|
||||
repo1OpenCount, repo1ClosedCount := milestonesCount(1)
|
||||
repo2OpenCount, repo2ClosedCount := milestonesCount(2)
|
||||
|
||||
func TestCountMilestonesByRepoIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
milestonesCount := func(repoID int64) (int, int) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
return repo.NumOpenMilestones, repo.NumClosedMilestones
|
||||
}
|
||||
repo1OpenCount, repo1ClosedCount := milestonesCount(1)
|
||||
repo2OpenCount, repo2ClosedCount := milestonesCount(2)
|
||||
|
||||
openCounts, err := issues_model.CountMilestonesMap(t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoIDs: []int64{1, 2},
|
||||
IsClosed: optional.Some(false),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo1OpenCount, openCounts[1])
|
||||
assert.EqualValues(t, repo2OpenCount, openCounts[2])
|
||||
|
||||
closedCounts, err := issues_model.CountMilestonesMap(t.Context(),
|
||||
issues_model.FindMilestoneOptions{
|
||||
openCounts, err := issues_model.CountMilestonesMap(t.Context(), issues_model.FindMilestoneOptions{
|
||||
RepoIDs: []int64{1, 2},
|
||||
IsClosed: optional.Some(true),
|
||||
IsClosed: optional.Some(false),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo1ClosedCount, closedCounts[1])
|
||||
assert.EqualValues(t, repo2ClosedCount, closedCounts[2])
|
||||
}
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo1OpenCount, openCounts[1])
|
||||
assert.EqualValues(t, repo2OpenCount, openCounts[2])
|
||||
|
||||
func TestGetMilestonesByRepoIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
|
||||
test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
|
||||
for _, page := range []int{0, 1} {
|
||||
openMilestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.IssuePagingNum,
|
||||
},
|
||||
RepoIDs: []int64{repo1.ID, repo2.ID},
|
||||
IsClosed: optional.Some(false),
|
||||
SortType: sortType,
|
||||
closedCounts, err := issues_model.CountMilestonesMap(t.Context(),
|
||||
issues_model.FindMilestoneOptions{
|
||||
RepoIDs: []int64{1, 2},
|
||||
IsClosed: optional.Some(true),
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, openMilestones, repo1.NumOpenMilestones+repo2.NumOpenMilestones)
|
||||
values := make([]int, len(openMilestones))
|
||||
for i, milestone := range openMilestones {
|
||||
values[i] = sortCond(milestone)
|
||||
}
|
||||
assert.True(t, sort.IntsAreSorted(values))
|
||||
|
||||
closedMilestones, err := db.Find[issues_model.Milestone](t.Context(),
|
||||
issues_model.FindMilestoneOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.IssuePagingNum,
|
||||
},
|
||||
RepoIDs: []int64{repo1.ID, repo2.ID},
|
||||
IsClosed: optional.Some(true),
|
||||
SortType: sortType,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, closedMilestones, repo1.NumClosedMilestones+repo2.NumClosedMilestones)
|
||||
values = make([]int, len(closedMilestones))
|
||||
for i, milestone := range closedMilestones {
|
||||
values[i] = sortCond(milestone)
|
||||
}
|
||||
assert.True(t, sort.IntsAreSorted(values))
|
||||
}
|
||||
}
|
||||
test("furthestduedate", func(milestone *issues_model.Milestone) int {
|
||||
return -int(milestone.DeadlineUnix)
|
||||
})
|
||||
test("leastcomplete", func(milestone *issues_model.Milestone) int {
|
||||
return milestone.Completeness
|
||||
})
|
||||
test("mostcomplete", func(milestone *issues_model.Milestone) int {
|
||||
return -milestone.Completeness
|
||||
})
|
||||
test("leastissues", func(milestone *issues_model.Milestone) int {
|
||||
return milestone.NumIssues
|
||||
})
|
||||
test("mostissues", func(milestone *issues_model.Milestone) int {
|
||||
return -milestone.NumIssues
|
||||
})
|
||||
test("soonestduedate", func(milestone *issues_model.Milestone) int {
|
||||
return int(milestone.DeadlineUnix)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, repo1ClosedCount, closedCounts[1])
|
||||
assert.EqualValues(t, repo2ClosedCount, closedCounts[2])
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -225,33 +225,14 @@ func TestDismissReview(t *testing.T) {
|
||||
assert.True(t, rejectReviewExample.Dismissed)
|
||||
assert.False(t, requestReviewExample.Dismissed)
|
||||
|
||||
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, true))
|
||||
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
|
||||
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
|
||||
assert.True(t, rejectReviewExample.Dismissed)
|
||||
assert.False(t, requestReviewExample.Dismissed)
|
||||
assert.False(t, approveReviewExample.Dismissed)
|
||||
|
||||
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, true))
|
||||
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
|
||||
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
|
||||
assert.True(t, rejectReviewExample.Dismissed)
|
||||
assert.False(t, requestReviewExample.Dismissed)
|
||||
assert.False(t, approveReviewExample.Dismissed)
|
||||
|
||||
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, false))
|
||||
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
|
||||
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
|
||||
assert.True(t, rejectReviewExample.Dismissed)
|
||||
assert.False(t, requestReviewExample.Dismissed)
|
||||
assert.False(t, approveReviewExample.Dismissed)
|
||||
|
||||
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, false))
|
||||
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
|
||||
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
|
||||
assert.True(t, rejectReviewExample.Dismissed)
|
||||
assert.False(t, requestReviewExample.Dismissed)
|
||||
assert.False(t, approveReviewExample.Dismissed)
|
||||
for _, dismissed := range []bool{true, true, false, false} {
|
||||
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, dismissed))
|
||||
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
|
||||
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
|
||||
assert.True(t, rejectReviewExample.Dismissed)
|
||||
assert.False(t, requestReviewExample.Dismissed)
|
||||
assert.False(t, approveReviewExample.Dismissed)
|
||||
}
|
||||
|
||||
assert.NoError(t, issues_model.DismissReview(t.Context(), rejectReviewExample, false))
|
||||
assert.False(t, rejectReviewExample.Dismissed)
|
||||
|
||||
+113
-112
@@ -435,79 +435,80 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) {
|
||||
testSuccess(4, []int64{})
|
||||
}
|
||||
|
||||
func TestHasOrgVisibleTypePublic(t *testing.T) {
|
||||
func TestHasOrgVisibleType(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
|
||||
const newOrgName = "test-org-public"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
Visibility: structs.VisibleTypePublic,
|
||||
}
|
||||
t.Run("Public", func(t *testing.T) {
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
|
||||
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
|
||||
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
|
||||
assert.True(t, test1) // owner of org
|
||||
assert.True(t, test2) // user not a part of org
|
||||
assert.True(t, test3) // logged out user
|
||||
const newOrgName = "test-org-public"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
Visibility: structs.VisibleTypePublic,
|
||||
}
|
||||
|
||||
restrictedUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29, IsRestricted: true})
|
||||
require.True(t, restrictedUser.IsRestricted)
|
||||
assert.True(t, organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), restrictedUser))
|
||||
defer test.MockVariableValue(&setting.Service.RequireSignInViewStrict, true)()
|
||||
assert.False(t, organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), restrictedUser))
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
|
||||
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
|
||||
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
|
||||
assert.True(t, test1) // owner of org
|
||||
assert.True(t, test2) // user not a part of org
|
||||
assert.True(t, test3) // logged out user
|
||||
|
||||
func TestHasOrgVisibleTypeLimited(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
restrictedUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29, IsRestricted: true})
|
||||
require.True(t, restrictedUser.IsRestricted)
|
||||
assert.True(t, organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), restrictedUser))
|
||||
defer test.MockVariableValue(&setting.Service.RequireSignInViewStrict, true)()
|
||||
assert.False(t, organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), restrictedUser))
|
||||
})
|
||||
|
||||
const newOrgName = "test-org-limited"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
Visibility: structs.VisibleTypeLimited,
|
||||
}
|
||||
t.Run("Limited", func(t *testing.T) {
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
|
||||
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
|
||||
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
|
||||
assert.True(t, test1) // owner of org
|
||||
assert.True(t, test2) // user not a part of org
|
||||
assert.False(t, test3) // logged out user
|
||||
}
|
||||
const newOrgName = "test-org-limited"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
Visibility: structs.VisibleTypeLimited,
|
||||
}
|
||||
|
||||
func TestHasOrgVisibleTypePrivate(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
|
||||
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
|
||||
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
|
||||
assert.True(t, test1) // owner of org
|
||||
assert.True(t, test2) // user not a part of org
|
||||
assert.False(t, test3) // logged out user
|
||||
})
|
||||
|
||||
const newOrgName = "test-org-private"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
Visibility: structs.VisibleTypePrivate,
|
||||
}
|
||||
t.Run("Private", func(t *testing.T) {
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
|
||||
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
|
||||
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
|
||||
assert.True(t, test1) // owner of org
|
||||
assert.False(t, test2) // user not a part of org
|
||||
assert.False(t, test3) // logged out user
|
||||
const newOrgName = "test-org-private"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
Visibility: structs.VisibleTypePrivate,
|
||||
}
|
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
|
||||
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
|
||||
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
|
||||
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
|
||||
assert.True(t, test1) // owner of org
|
||||
assert.False(t, test2) // user not a part of org
|
||||
assert.False(t, test3) // logged out user
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) {
|
||||
@@ -568,65 +569,65 @@ func TestUser_RemoveOrgRepo(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCreateOrganization(t *testing.T) {
|
||||
// successful creation of org
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
const newOrgName = "neworg"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
}
|
||||
t.Run("Unauthorized", func(t *testing.T) {
|
||||
// unauthorized creation of org
|
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
ownerTeam := unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Team{Name: organization.OwnerTeamName, OrgID: org.ID})
|
||||
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: owner.ID, TeamID: ownerTeam.ID})
|
||||
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
|
||||
}
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5})
|
||||
const newOrgName = "neworg"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
}
|
||||
|
||||
func TestCreateOrganization2(t *testing.T) {
|
||||
// unauthorized creation of org
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
err := organization.CreateOrganization(t.Context(), org, owner)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err))
|
||||
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})
|
||||
})
|
||||
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5})
|
||||
const newOrgName = "neworg"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
}
|
||||
t.Run("ExistingName", func(t *testing.T) {
|
||||
// create org with same name as existent org
|
||||
|
||||
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
err := organization.CreateOrganization(t.Context(), org, owner)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err))
|
||||
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})
|
||||
}
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org := &organization.Organization{Name: "org3"} // should already exist
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check
|
||||
err := organization.CreateOrganization(t.Context(), org, owner)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, user_model.IsErrUserAlreadyExist(err))
|
||||
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
|
||||
})
|
||||
|
||||
func TestCreateOrganization3(t *testing.T) {
|
||||
// create org with same name as existent org
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("ReservedName", func(t *testing.T) {
|
||||
// create org with unusable name
|
||||
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org := &organization.Organization{Name: "org3"} // should already exist
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check
|
||||
err := organization.CreateOrganization(t.Context(), org, owner)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, user_model.IsErrUserAlreadyExist(err))
|
||||
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
|
||||
}
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
err := organization.CreateOrganization(t.Context(), &organization.Organization{Name: "assets"}, owner)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, db.IsErrNameReserved(err))
|
||||
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})
|
||||
})
|
||||
|
||||
func TestCreateOrganization4(t *testing.T) {
|
||||
// create org with unusable name
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("Success", func(t *testing.T) {
|
||||
// successful creation of org
|
||||
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
err := organization.CreateOrganization(t.Context(), &organization.Organization{Name: "assets"}, owner)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, db.IsErrNameReserved(err))
|
||||
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
const newOrgName = "neworg"
|
||||
org := &organization.Organization{
|
||||
Name: newOrgName,
|
||||
}
|
||||
|
||||
unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
|
||||
org = unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
|
||||
ownerTeam := unittest.AssertExistsAndLoadBean(t,
|
||||
&organization.Team{Name: organization.OwnerTeamName, OrgID: org.ID})
|
||||
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: owner.ID, TeamID: ownerTeam.ID})
|
||||
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
|
||||
})
|
||||
}
|
||||
|
||||
func TestOrAnyRepoUnitPermission(t *testing.T) {
|
||||
|
||||
@@ -82,7 +82,7 @@ func TestTeam_CanNonMemberReadMeta(t *testing.T) {
|
||||
func TestTeam_GetRepositories(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
test := func(teamID int64) {
|
||||
for _, teamID := range []int64{1, 3} {
|
||||
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
|
||||
repos, err := repo_model.GetTeamRepositories(t.Context(), &repo_model.SearchTeamRepoOptions{
|
||||
TeamID: team.ID,
|
||||
@@ -93,14 +93,12 @@ func TestTeam_GetRepositories(t *testing.T) {
|
||||
unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID})
|
||||
}
|
||||
}
|
||||
test(1)
|
||||
test(3)
|
||||
}
|
||||
|
||||
func TestTeam_GetMembers(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
test := func(teamID int64) {
|
||||
for _, teamID := range []int64{1, 3} {
|
||||
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
|
||||
assert.NoError(t, team.LoadMembers(t.Context()))
|
||||
assert.Len(t, team.Members, team.NumMembers)
|
||||
@@ -108,8 +106,6 @@ func TestTeam_GetMembers(t *testing.T) {
|
||||
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID})
|
||||
}
|
||||
}
|
||||
test(1)
|
||||
test(3)
|
||||
}
|
||||
|
||||
func TestGetTeam(t *testing.T) {
|
||||
@@ -133,15 +129,11 @@ func TestGetTeam(t *testing.T) {
|
||||
func TestGetTeamByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
testSuccess := func(teamID int64) {
|
||||
for _, teamID := range []int64{1, 2, 3, 4} {
|
||||
team, err := organization.GetTeamByID(t.Context(), teamID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, teamID, team.ID)
|
||||
}
|
||||
testSuccess(1)
|
||||
testSuccess(2)
|
||||
testSuccess(3)
|
||||
testSuccess(4)
|
||||
|
||||
_, err := organization.GetTeamByID(t.Context(), unittest.NonexistentID)
|
||||
assert.Error(t, err)
|
||||
@@ -169,7 +161,7 @@ func TestIsTeamMember(t *testing.T) {
|
||||
func TestGetTeamMembers(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
test := func(teamID int64) {
|
||||
for _, teamID := range []int64{1, 3} {
|
||||
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
|
||||
members, err := organization.GetTeamMembers(t.Context(), &organization.SearchMembersOptions{
|
||||
TeamID: teamID,
|
||||
@@ -180,22 +172,17 @@ func TestGetTeamMembers(t *testing.T) {
|
||||
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID})
|
||||
}
|
||||
}
|
||||
test(1)
|
||||
test(3)
|
||||
}
|
||||
|
||||
func TestGetUserTeams(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
test := func(userID int64) {
|
||||
for _, userID := range []int64{2, 5, unittest.NonexistentID} {
|
||||
teams, _, err := organization.SearchTeam(t.Context(), &organization.SearchTeamOptions{UserID: userID})
|
||||
assert.NoError(t, err)
|
||||
for _, team := range teams {
|
||||
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID})
|
||||
}
|
||||
}
|
||||
test(2)
|
||||
test(5)
|
||||
test(unittest.NonexistentID)
|
||||
}
|
||||
|
||||
func TestGetUserOrgTeams(t *testing.T) {
|
||||
|
||||
@@ -38,29 +38,21 @@ func TestHasOwnerPackages(t *testing.T) {
|
||||
assert.False(t, has)
|
||||
assert.NoError(t, err)
|
||||
|
||||
pv, err := packages_model.GetOrInsertVersion(t.Context(), &packages_model.PackageVersion{
|
||||
PackageID: p.ID,
|
||||
LowerVersion: "internal",
|
||||
IsInternal: true,
|
||||
})
|
||||
assert.NotNil(t, pv)
|
||||
assert.NoError(t, err)
|
||||
for _, testCase := range []struct {
|
||||
version packages_model.PackageVersion
|
||||
assertHasPackages assert.BoolAssertionFunc
|
||||
}{
|
||||
// A package with an internal package version gets automatically cleaned up and should return false
|
||||
{packages_model.PackageVersion{PackageID: p.ID, LowerVersion: "internal", IsInternal: true}, assert.False},
|
||||
// A package with a normal package version should return true
|
||||
{packages_model.PackageVersion{PackageID: p.ID, LowerVersion: "normal", IsInternal: false}, assert.True},
|
||||
} {
|
||||
pv, err := packages_model.GetOrInsertVersion(t.Context(), &testCase.version)
|
||||
assert.NotNil(t, pv)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// A package with an internal package version gets automatically cleaned up and should return false
|
||||
has, err = packages_model.HasOwnerPackages(t.Context(), owner.ID)
|
||||
assert.False(t, has)
|
||||
assert.NoError(t, err)
|
||||
|
||||
pv, err = packages_model.GetOrInsertVersion(t.Context(), &packages_model.PackageVersion{
|
||||
PackageID: p.ID,
|
||||
LowerVersion: "normal",
|
||||
IsInternal: false,
|
||||
})
|
||||
assert.NotNil(t, pv)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// A package with a normal package version should return true
|
||||
has, err = packages_model.HasOwnerPackages(t.Context(), owner.ID)
|
||||
assert.True(t, has)
|
||||
assert.NoError(t, err)
|
||||
has, err = packages_model.HasOwnerPackages(t.Context(), owner.ID)
|
||||
testCase.assertHasPackages(t, has)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
}
|
||||
@@ -56,43 +56,25 @@ func TestHasAnyUnitAccess(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApplyPublicAccessRepoPermission(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
user *user_model.User
|
||||
repoUnit *repo_model.RepoUnit
|
||||
assertRead assert.BoolAssertionFunc
|
||||
}{
|
||||
{nil, &repo_model.RepoUnit{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead}, assert.False},
|
||||
{nil, &repo_model.RepoUnit{Type: unit.TypeWiki, AnonymousAccessMode: perm_model.AccessModeRead}, assert.True},
|
||||
{&user_model.User{ID: 0}, &repo_model.RepoUnit{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead}, assert.False},
|
||||
{&user_model.User{ID: 1}, &repo_model.RepoUnit{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead}, assert.True},
|
||||
} {
|
||||
perm := Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
units: []*repo_model.RepoUnit{test.repoUnit},
|
||||
}
|
||||
finalProcessRepoUnitPermission(test.user, &perm)
|
||||
test.assertRead(t, perm.CanRead(unit.TypeWiki))
|
||||
}
|
||||
|
||||
perm := Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead},
|
||||
},
|
||||
}
|
||||
finalProcessRepoUnitPermission(nil, &perm)
|
||||
assert.False(t, perm.CanRead(unit.TypeWiki))
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki, AnonymousAccessMode: perm_model.AccessModeRead},
|
||||
},
|
||||
}
|
||||
finalProcessRepoUnitPermission(nil, &perm)
|
||||
assert.True(t, perm.CanRead(unit.TypeWiki))
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead},
|
||||
},
|
||||
}
|
||||
finalProcessRepoUnitPermission(&user_model.User{ID: 0}, &perm)
|
||||
assert.False(t, perm.CanRead(unit.TypeWiki))
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead},
|
||||
},
|
||||
}
|
||||
finalProcessRepoUnitPermission(&user_model.User{ID: 1}, &perm)
|
||||
assert.True(t, perm.CanRead(unit.TypeWiki))
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeWrite,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki, EveryoneAccessMode: perm_model.AccessModeRead},
|
||||
@@ -117,45 +99,27 @@ func TestApplyPublicAccessRepoPermission(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUnitAccessMode(t *testing.T) {
|
||||
perm := Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
for _, test := range []struct {
|
||||
accessMode perm_model.AccessMode
|
||||
hasUnit, hasMap bool
|
||||
expected perm_model.AccessMode
|
||||
message string
|
||||
}{
|
||||
{perm_model.AccessModeNone, false, false, perm_model.AccessModeNone, "no unit, no map, use AccessMode"},
|
||||
{perm_model.AccessModeRead, true, false, perm_model.AccessModeRead, "only unit, no map, use AccessMode"},
|
||||
{perm_model.AccessModeAdmin, false, true, perm_model.AccessModeAdmin, "no unit, only map, admin overrides map"},
|
||||
{perm_model.AccessModeNone, false, true, perm_model.AccessModeRead, "no unit, only map, use map"},
|
||||
{perm_model.AccessModeNone, true, true, perm_model.AccessModeRead, "has unit, and map, use map"},
|
||||
} {
|
||||
perm := Permission{AccessMode: test.accessMode}
|
||||
if test.hasUnit {
|
||||
perm.units = []*repo_model.RepoUnit{{Type: unit.TypeWiki}}
|
||||
}
|
||||
if test.hasMap {
|
||||
perm.unitsMode = map[unit.Type]perm_model.AccessMode{unit.TypeWiki: perm_model.AccessModeRead}
|
||||
}
|
||||
assert.Equal(t, test.expected, perm.UnitAccessMode(unit.TypeWiki), test.message)
|
||||
}
|
||||
assert.Equal(t, perm_model.AccessModeNone, perm.UnitAccessMode(unit.TypeWiki), "no unit, no map, use AccessMode")
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeRead,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki},
|
||||
},
|
||||
}
|
||||
assert.Equal(t, perm_model.AccessModeRead, perm.UnitAccessMode(unit.TypeWiki), "only unit, no map, use AccessMode")
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeAdmin,
|
||||
unitsMode: map[unit.Type]perm_model.AccessMode{
|
||||
unit.TypeWiki: perm_model.AccessModeRead,
|
||||
},
|
||||
}
|
||||
assert.Equal(t, perm_model.AccessModeAdmin, perm.UnitAccessMode(unit.TypeWiki), "no unit, only map, admin overrides map")
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
unitsMode: map[unit.Type]perm_model.AccessMode{
|
||||
unit.TypeWiki: perm_model.AccessModeRead,
|
||||
},
|
||||
}
|
||||
assert.Equal(t, perm_model.AccessModeRead, perm.UnitAccessMode(unit.TypeWiki), "no unit, only map, use map")
|
||||
|
||||
perm = Permission{
|
||||
AccessMode: perm_model.AccessModeNone,
|
||||
units: []*repo_model.RepoUnit{
|
||||
{Type: unit.TypeWiki},
|
||||
},
|
||||
unitsMode: map[unit.Type]perm_model.AccessMode{
|
||||
unit.TypeWiki: perm_model.AccessModeRead,
|
||||
},
|
||||
}
|
||||
assert.Equal(t, perm_model.AccessModeRead, perm.UnitAccessMode(unit.TypeWiki), "has unit, and map, use map")
|
||||
}
|
||||
|
||||
func TestGetRepoPermission(t *testing.T) {
|
||||
|
||||
@@ -34,17 +34,13 @@ func TestIsProjectTypeValid(t *testing.T) {
|
||||
func TestGetProjects(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
projects, err := db.Find[Project](t.Context(), SearchOptions{RepoID: 1})
|
||||
assert.NoError(t, err)
|
||||
for _, repoID := range []int64{1, 3} {
|
||||
projects, err := db.Find[Project](t.Context(), SearchOptions{RepoID: repoID})
|
||||
assert.NoError(t, err)
|
||||
|
||||
// 1 value for this repo exists in the fixtures
|
||||
assert.Len(t, projects, 1)
|
||||
|
||||
projects, err = db.Find[Project](t.Context(), SearchOptions{RepoID: 3})
|
||||
assert.NoError(t, err)
|
||||
|
||||
// 1 value for this repo exists in the fixtures
|
||||
assert.Len(t, projects, 1)
|
||||
// 1 value for this repo exists in the fixtures
|
||||
assert.Len(t, projects, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProject(t *testing.T) {
|
||||
|
||||
@@ -98,41 +98,40 @@ func TestRepoFile(t *testing.T) {
|
||||
</p>
|
||||
`), test.NormalizeHTMLSpaces(rendered))
|
||||
})
|
||||
}
|
||||
|
||||
func TestRepoFileOrgMode(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
t.Run("OrgMode", func(t *testing.T) {
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
t.Run("Links", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(t.Context(), repo1, RepoFileOptions{
|
||||
CurrentRefSubURL: "/commit/1234",
|
||||
CurrentTreePath: "my dir",
|
||||
}).WithRelativePath("my dir/a.org")
|
||||
t.Run("Links", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(t.Context(), repo1, RepoFileOptions{
|
||||
CurrentRefSubURL: "/commit/1234",
|
||||
CurrentTreePath: "my dir",
|
||||
}).WithRelativePath("my dir/a.org")
|
||||
|
||||
rendered, err := testRenderString(rctx, `
|
||||
rendered, err := testRenderString(rctx, `
|
||||
[[https://google.com/]]
|
||||
[[ImageLink.svg][The Image Desc]]
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<p>
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<p>
|
||||
<a href="https://google.com/" rel="nofollow">https://google.com/</a>
|
||||
<a href="/user2/repo1/src/commit/1234/my%20dir/ImageLink.svg" rel="nofollow">The Image Desc</a></p>
|
||||
`, rendered)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("CodeHighlight", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(t.Context(), repo1, RepoFileOptions{}).WithRelativePath("my-dir/a.org")
|
||||
t.Run("CodeHighlight", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(t.Context(), repo1, RepoFileOptions{}).WithRelativePath("my-dir/a.org")
|
||||
|
||||
rendered, err := testRenderString(rctx, `
|
||||
rendered, err := testRenderString(rctx, `
|
||||
#+begin_src c
|
||||
int a = 1;
|
||||
#+end_src
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<div>
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<div>
|
||||
<pre class="code-block"><code class="chroma language-c"><span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span></code></pre>
|
||||
</div>
|
||||
`, rendered)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -6,14 +6,12 @@ package renderhelper
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/markup/markdown"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSimpleDocument(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
rctx := NewRenderContextSimpleDocument(t.Context(), "/base").WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := testRenderString(rctx, `
|
||||
65f1bf27bc3bf70f64657658635e66094edbcb4d
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package repo
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestArchiveType(t *testing.T) {
|
||||
name, archiveType := SplitArchiveNameType("test.tar.gz")
|
||||
assert.Equal(t, "test", name)
|
||||
assert.Equal(t, "tar.gz", archiveType.String())
|
||||
|
||||
name, archiveType = SplitArchiveNameType("a/b/test.zip")
|
||||
assert.Equal(t, "a/b/test", name)
|
||||
assert.Equal(t, "zip", archiveType.String())
|
||||
|
||||
name, archiveType = SplitArchiveNameType("1234.bundle")
|
||||
assert.Equal(t, "1234", name)
|
||||
assert.Equal(t, "bundle", archiveType.String())
|
||||
|
||||
name, archiveType = SplitArchiveNameType("test")
|
||||
assert.Equal(t, "test", name)
|
||||
assert.Equal(t, "unknown", archiveType.String())
|
||||
|
||||
name, archiveType = SplitArchiveNameType("test.xz")
|
||||
assert.Equal(t, "test.xz", name)
|
||||
assert.Equal(t, "unknown", archiveType.String())
|
||||
}
|
||||
@@ -34,46 +34,73 @@ func TestIncreaseDownloadCount(t *testing.T) {
|
||||
func TestGetByCommentOrIssueID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
// count of attachments from issue ID
|
||||
attachments, err := repo_model.GetAttachmentsByIssueID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachments, 1)
|
||||
t.Run("GetByCommentOrIssueID", func(t *testing.T) {
|
||||
// count of attachments from issue ID
|
||||
attachments, err := repo_model.GetAttachmentsByIssueID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachments, 1)
|
||||
|
||||
attachments, err = repo_model.GetAttachmentsByIssueID(t.Context(), 0)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, attachments)
|
||||
attachments, err = repo_model.GetAttachmentsByIssueID(t.Context(), 0)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, attachments)
|
||||
|
||||
attachments, err = repo_model.GetAttachmentsByCommentID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachments, 2)
|
||||
}
|
||||
attachments, err = repo_model.GetAttachmentsByCommentID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachments, 2)
|
||||
})
|
||||
|
||||
func TestDeleteAttachments(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("GetAttachmentsByUUIDs", func(t *testing.T) {
|
||||
attachList, err := repo_model.GetAttachmentsByUUIDs(t.Context(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachList, 2)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", attachList[1].UUID)
|
||||
assert.Equal(t, int64(1), attachList[0].IssueID)
|
||||
assert.Equal(t, int64(5), attachList[1].IssueID)
|
||||
})
|
||||
|
||||
count, err := repo_model.DeleteAttachmentsByIssue(t.Context(), 4, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 2, count)
|
||||
t.Run("GetUnlinkedAttachmentsByUserID", func(t *testing.T) {
|
||||
attachments, err := repo_model.GetUnlinkedAttachmentsByUserID(t.Context(), 8)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachments, 1)
|
||||
assert.Equal(t, int64(10), attachments[0].ID)
|
||||
assert.Zero(t, attachments[0].IssueID)
|
||||
assert.Zero(t, attachments[0].ReleaseID)
|
||||
assert.Zero(t, attachments[0].CommentID)
|
||||
|
||||
count, err = repo_model.DeleteAttachmentsByComment(t.Context(), 2, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 2, count)
|
||||
attachments, err = repo_model.GetUnlinkedAttachmentsByUserID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, attachments)
|
||||
})
|
||||
|
||||
err = repo_model.DeleteAttachment(t.Context(), &repo_model.Attachment{ID: 8}, false)
|
||||
assert.NoError(t, err)
|
||||
t.Run("DeleteAttachments", func(t *testing.T) {
|
||||
count, err := repo_model.DeleteAttachmentsByIssue(t.Context(), 4, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 2, count)
|
||||
|
||||
attachment, err := repo_model.GetAttachmentByUUID(t.Context(), "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18")
|
||||
assert.Error(t, err)
|
||||
assert.True(t, repo_model.IsErrAttachmentNotExist(err))
|
||||
assert.Nil(t, attachment)
|
||||
}
|
||||
count, err = repo_model.DeleteAttachmentsByComment(t.Context(), 2, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 2, count)
|
||||
|
||||
func TestGetAttachmentByID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
err = repo_model.DeleteAttachment(t.Context(), &repo_model.Attachment{ID: 8}, false)
|
||||
assert.NoError(t, err)
|
||||
|
||||
attach, err := repo_model.GetAttachmentByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
|
||||
attachment, err := repo_model.GetAttachmentByUUID(t.Context(), "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18")
|
||||
assert.Error(t, err)
|
||||
assert.True(t, repo_model.IsErrAttachmentNotExist(err))
|
||||
assert.Nil(t, attachment)
|
||||
})
|
||||
|
||||
t.Run("UpdateAttachment", func(t *testing.T) {
|
||||
attach, err := repo_model.GetAttachmentByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
|
||||
|
||||
attach.Name = "new_name"
|
||||
assert.NoError(t, repo_model.UpdateAttachment(t.Context(), attach))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{Name: "new_name"})
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteOrphanedAttachments(t *testing.T) {
|
||||
@@ -111,44 +138,3 @@ func TestAttachment_DownloadURL(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, "https://try.gitea.io/attachments/a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.DownloadURL(t.Context()))
|
||||
}
|
||||
|
||||
func TestUpdateAttachment(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
attach, err := repo_model.GetAttachmentByID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
|
||||
|
||||
attach.Name = "new_name"
|
||||
assert.NoError(t, repo_model.UpdateAttachment(t.Context(), attach))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{Name: "new_name"})
|
||||
}
|
||||
|
||||
func TestGetAttachmentsByUUIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
attachList, err := repo_model.GetAttachmentsByUUIDs(t.Context(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachList, 2)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID)
|
||||
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", attachList[1].UUID)
|
||||
assert.Equal(t, int64(1), attachList[0].IssueID)
|
||||
assert.Equal(t, int64(5), attachList[1].IssueID)
|
||||
}
|
||||
|
||||
func TestGetUnlinkedAttachmentsByUserID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
attachments, err := repo_model.GetUnlinkedAttachmentsByUserID(t.Context(), 8)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, attachments, 1)
|
||||
assert.Equal(t, int64(10), attachments[0].ID)
|
||||
assert.Zero(t, attachments[0].IssueID)
|
||||
assert.Zero(t, attachments[0].ReleaseID)
|
||||
assert.Zero(t, attachments[0].CommentID)
|
||||
|
||||
attachments, err = repo_model.GetUnlinkedAttachmentsByUserID(t.Context(), 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, attachments)
|
||||
}
|
||||
@@ -25,3 +25,19 @@ func TestRepoAvatarLink(t *testing.T) {
|
||||
link = repo.AvatarLink(t.Context())
|
||||
assert.Equal(t, "https://localhost/sub-path/repo-avatars/avatar.png", link)
|
||||
}
|
||||
|
||||
func TestArchiveType(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
input, name, archiveType string
|
||||
}{
|
||||
{"test.tar.gz", "test", "tar.gz"},
|
||||
{"a/b/test.zip", "a/b/test", "zip"},
|
||||
{"1234.bundle", "1234", "bundle"},
|
||||
{"test", "test", "unknown"},
|
||||
{"test.xz", "test.xz", "unknown"},
|
||||
} {
|
||||
name, archiveType := SplitArchiveNameType(tc.input)
|
||||
assert.Equal(t, tc.name, name)
|
||||
assert.Equal(t, tc.archiveType, archiveType.String())
|
||||
}
|
||||
}
|
||||
@@ -15,107 +15,100 @@ import (
|
||||
|
||||
func TestRepository_GetCollaborators(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
test := func(repoID int64) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
collaborators, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{RepoID: repo.ID})
|
||||
assert.NoError(t, err)
|
||||
expectedLen, err := db.GetEngine(t.Context()).Count(&repo_model.Collaboration{RepoID: repoID})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, collaborators, int(expectedLen))
|
||||
for _, collaborator := range collaborators {
|
||||
assert.Equal(t, collaborator.User.ID, collaborator.Collaboration.UserID)
|
||||
assert.Equal(t, repoID, collaborator.Collaboration.RepoID)
|
||||
|
||||
t.Run("Repository_GetCollaborators", func(t *testing.T) {
|
||||
for _, repoID := range []int64{1, 2, 3, 4} {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
collaborators, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{RepoID: repo.ID})
|
||||
assert.NoError(t, err)
|
||||
expectedLen, err := db.GetEngine(t.Context()).Count(&repo_model.Collaboration{RepoID: repoID})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, collaborators, int(expectedLen))
|
||||
for _, collaborator := range collaborators {
|
||||
assert.Equal(t, collaborator.User.ID, collaborator.Collaboration.UserID)
|
||||
assert.Equal(t, repoID, collaborator.Collaboration.RepoID)
|
||||
}
|
||||
}
|
||||
}
|
||||
test(1)
|
||||
test(2)
|
||||
test(3)
|
||||
test(4)
|
||||
|
||||
// Test db.ListOptions
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22})
|
||||
// Test db.ListOptions
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22})
|
||||
|
||||
collaborators1, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{
|
||||
ListOptions: db.ListOptions{PageSize: 1, Page: 1},
|
||||
RepoID: repo.ID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, collaborators1, 1)
|
||||
|
||||
collaborators2, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{
|
||||
ListOptions: db.ListOptions{PageSize: 1, Page: 2},
|
||||
RepoID: repo.ID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, collaborators2, 1)
|
||||
|
||||
assert.NotEqual(t, collaborators1[0].ID, collaborators2[0].ID)
|
||||
}
|
||||
|
||||
func TestRepository_IsCollaborator(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
test := func(repoID, userID int64, expected bool) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
actual, err := repo_model.IsCollaborator(t.Context(), repo.ID, userID)
|
||||
collaborators1, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{
|
||||
ListOptions: db.ListOptions{PageSize: 1, Page: 1},
|
||||
RepoID: repo.ID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
test(3, 2, true)
|
||||
test(3, unittest.NonexistentID, false)
|
||||
test(4, 2, false)
|
||||
test(4, 4, true)
|
||||
}
|
||||
|
||||
func TestRepository_IsOwnerMemberCollaborator(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
|
||||
// Organisation owner.
|
||||
actual, err := repo_model.HasAccessToRepoCodeUnit(t.Context(), repo1, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
|
||||
// Team member.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo1, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
|
||||
// Normal user.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo1, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, actual)
|
||||
|
||||
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
|
||||
|
||||
// Collaborator.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo2, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
|
||||
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15})
|
||||
|
||||
// Repository owner.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo3, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
}
|
||||
|
||||
func TestRepo_GetCollaboration(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
|
||||
|
||||
// Existing collaboration.
|
||||
collab, err := repo_model.GetCollaboration(t.Context(), repo.ID, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, collab)
|
||||
assert.EqualValues(t, 4, collab.UserID)
|
||||
assert.EqualValues(t, 4, collab.RepoID)
|
||||
|
||||
// Non-existing collaboration.
|
||||
collab, err = repo_model.GetCollaboration(t.Context(), repo.ID, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, collab)
|
||||
assert.Len(t, collaborators1, 1)
|
||||
|
||||
collaborators2, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{
|
||||
ListOptions: db.ListOptions{PageSize: 1, Page: 2},
|
||||
RepoID: repo.ID,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, collaborators2, 1)
|
||||
|
||||
assert.NotEqual(t, collaborators1[0].ID, collaborators2[0].ID)
|
||||
})
|
||||
|
||||
t.Run("Repository_IsCollaborator", func(t *testing.T) {
|
||||
test := func(repoID, userID int64, expected bool) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
|
||||
actual, err := repo_model.IsCollaborator(t.Context(), repo.ID, userID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
test(3, 2, true)
|
||||
test(3, unittest.NonexistentID, false)
|
||||
test(4, 2, false)
|
||||
test(4, 4, true)
|
||||
})
|
||||
|
||||
t.Run("Repository_IsOwnerMemberCollaborator", func(t *testing.T) {
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
|
||||
// Organisation owner.
|
||||
actual, err := repo_model.HasAccessToRepoCodeUnit(t.Context(), repo1, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
|
||||
// Team member.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo1, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
|
||||
// Normal user.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo1, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, actual)
|
||||
|
||||
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
|
||||
|
||||
// Collaborator.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo2, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
|
||||
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15})
|
||||
|
||||
// Repository owner.
|
||||
actual, err = repo_model.HasAccessToRepoCodeUnit(t.Context(), repo3, 2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, actual)
|
||||
})
|
||||
|
||||
t.Run("Repo_GetCollaboration", func(t *testing.T) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
|
||||
|
||||
// Existing collaboration.
|
||||
collab, err := repo_model.GetCollaboration(t.Context(), repo.ID, 4)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, collab)
|
||||
assert.EqualValues(t, 4, collab.UserID)
|
||||
assert.EqualValues(t, 4, collab.RepoID)
|
||||
|
||||
// Non-existing collaboration.
|
||||
collab, err = repo_model.GetCollaboration(t.Context(), repo.ID, 1)
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, collab)
|
||||
})
|
||||
}
|
||||
@@ -33,46 +33,37 @@ func TestDefaultTargetBranchSelection(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPullRequestConfigFromDB(t *testing.T) {
|
||||
cases := []struct {
|
||||
for _, tc := range []struct {
|
||||
// name describes the row shape under test; the comments capture why each row matters.
|
||||
name string
|
||||
json string
|
||||
wantMergeUpdate bool
|
||||
wantRebaseUpdate bool
|
||||
wantDefaultStyle UpdateStyle
|
||||
wantValidatesPass bool
|
||||
name string
|
||||
json string
|
||||
wantRebaseUpdate bool
|
||||
}{
|
||||
{
|
||||
// Empty object exercises the all-defaults path (e.g. fresh repos created via low-level paths).
|
||||
name: "defaults", json: "{}",
|
||||
wantMergeUpdate: true, wantRebaseUpdate: true,
|
||||
wantDefaultStyle: UpdateStyleMerge, wantValidatesPass: true,
|
||||
wantRebaseUpdate: true,
|
||||
},
|
||||
{
|
||||
// Realistic upgrade case: pre-PR JSON lacks the new fields and has AllowRebaseUpdate=false.
|
||||
// Historical setting must be preserved while new fields take safe defaults.
|
||||
name: "legacy without new fields",
|
||||
json: `{"AllowMerge":true,"AllowRebase":true,"AllowRebaseMerge":true,"AllowSquash":true,"AllowRebaseUpdate":false}`,
|
||||
wantMergeUpdate: true, wantRebaseUpdate: false,
|
||||
wantDefaultStyle: UpdateStyleMerge, wantValidatesPass: true,
|
||||
name: "legacy without new fields",
|
||||
json: `{"AllowMerge":true,"AllowRebase":true,"AllowRebaseMerge":true,"AllowSquash":true,"AllowRebaseUpdate":false}`,
|
||||
wantRebaseUpdate: false,
|
||||
},
|
||||
{
|
||||
// Partially-migrated row with explicit empty string must normalize so ValidateUpdateSettings passes.
|
||||
name: "empty default style", json: `{"DefaultUpdateStyle":""}`,
|
||||
wantMergeUpdate: true, wantRebaseUpdate: true,
|
||||
wantDefaultStyle: UpdateStyleMerge, wantValidatesPass: true,
|
||||
wantRebaseUpdate: true,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := new(PullRequestsConfig)
|
||||
assert.NoError(t, cfg.FromDB([]byte(tc.json)))
|
||||
assert.Equal(t, tc.wantMergeUpdate, cfg.AllowMergeUpdate)
|
||||
assert.True(t, cfg.AllowMergeUpdate)
|
||||
assert.Equal(t, tc.wantRebaseUpdate, cfg.AllowRebaseUpdate)
|
||||
assert.Equal(t, tc.wantDefaultStyle, cfg.DefaultUpdateStyle)
|
||||
if tc.wantValidatesPass {
|
||||
assert.NoError(t, cfg.ValidateUpdateSettings())
|
||||
}
|
||||
assert.Equal(t, UpdateStyleMerge, cfg.DefaultUpdateStyle)
|
||||
assert.NoError(t, cfg.ValidateUpdateSettings())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,17 +27,12 @@ func TestPushMirrorsIterate(t *testing.T) {
|
||||
})
|
||||
|
||||
long, _ := time.ParseDuration("24h")
|
||||
db.Insert(t.Context(), &repo_model.PushMirror{
|
||||
RemoteName: "test-2",
|
||||
LastUpdateUnix: now,
|
||||
Interval: long,
|
||||
})
|
||||
|
||||
db.Insert(t.Context(), &repo_model.PushMirror{
|
||||
RemoteName: "test-3",
|
||||
LastUpdateUnix: now,
|
||||
Interval: 0,
|
||||
})
|
||||
for _, mirror := range []*repo_model.PushMirror{
|
||||
{RemoteName: "test-2", LastUpdateUnix: now, Interval: long},
|
||||
{RemoteName: "test-3", LastUpdateUnix: now, Interval: 0},
|
||||
} {
|
||||
db.Insert(t.Context(), mirror)
|
||||
}
|
||||
|
||||
repo_model.PushMirrorsIterate(t.Context(), 1, func(idx int, bean any) error {
|
||||
m, ok := bean.(*repo_model.PushMirror)
|
||||
|
||||
@@ -24,53 +24,37 @@ func TestLookupRedirect(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNewRedirect(t *testing.T) {
|
||||
// redirect to a completely new name
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
for _, tc := range []struct {
|
||||
repoID int64
|
||||
newName string
|
||||
}{
|
||||
{1, "newreponame"}, // redirect to a completely new name
|
||||
{1, "oldrepo1"}, // redirect to previously used name
|
||||
{2, "newreponame"}, // redirect for a previously-unredirected repo
|
||||
} {
|
||||
t.Run(tc.newName, func(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, "newreponame"))
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: tc.repoID})
|
||||
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, tc.newName))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: repo.LowerName,
|
||||
RedirectRepoID: repo.ID,
|
||||
})
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: "oldrepo1",
|
||||
RedirectRepoID: repo.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewRedirect2(t *testing.T) {
|
||||
// redirect to previously used name
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, "oldrepo1"))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: repo.LowerName,
|
||||
RedirectRepoID: repo.ID,
|
||||
})
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: "oldrepo1",
|
||||
RedirectRepoID: repo.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewRedirect3(t *testing.T) {
|
||||
// redirect for a previously-unredirected repo
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
|
||||
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, "newreponame"))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: repo.LowerName,
|
||||
RedirectRepoID: repo.ID,
|
||||
})
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: repo.LowerName,
|
||||
RedirectRepoID: repo.ID,
|
||||
})
|
||||
if tc.repoID == 1 {
|
||||
redirect := &repo_model.Redirect{
|
||||
OwnerID: repo.OwnerID,
|
||||
LowerName: "oldrepo1",
|
||||
RedirectRepoID: repo.ID,
|
||||
}
|
||||
if tc.newName == "oldrepo1" {
|
||||
unittest.AssertNotExistsBean(t, redirect)
|
||||
} else {
|
||||
unittest.AssertExistsAndLoadBean(t, redirect)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+56
-62
@@ -30,75 +30,69 @@ func TestMigrate_InsertReleases(t *testing.T) {
|
||||
func Test_FindTagsByCommitIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
sha1Rels, err := FindTagsByCommitIDs(t.Context(), 1, "65f1bf27bc3bf70f64657658635e66094edbcb4d")
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, sha1Rels, 1)
|
||||
rels := sha1Rels["65f1bf27bc3bf70f64657658635e66094edbcb4d"]
|
||||
assert.Len(t, rels, 3)
|
||||
assert.Equal(t, "v1.1", rels[0].TagName)
|
||||
assert.Equal(t, "delete-tag", rels[1].TagName)
|
||||
assert.Equal(t, "v1.0", rels[2].TagName)
|
||||
}
|
||||
t.Run("_FindTagsByCommitIDs", func(t *testing.T) {
|
||||
sha1Rels, err := FindTagsByCommitIDs(t.Context(), 1, "65f1bf27bc3bf70f64657658635e66094edbcb4d")
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, sha1Rels, 1)
|
||||
rels := sha1Rels["65f1bf27bc3bf70f64657658635e66094edbcb4d"]
|
||||
assert.Len(t, rels, 3)
|
||||
assert.Equal(t, "v1.1", rels[0].TagName)
|
||||
assert.Equal(t, "delete-tag", rels[1].TagName)
|
||||
assert.Equal(t, "v1.0", rels[2].TagName)
|
||||
})
|
||||
|
||||
func TestAddReleaseAttachmentsRejectsDifferentRepo(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
t.Run("AddReleaseAttachmentsRejectsDifferentRepo", func(t *testing.T) {
|
||||
uuid := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a12" // attachment 2 belongs to repo 2
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{uuid})
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrPermissionDenied)
|
||||
|
||||
uuid := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a12" // attachment 2 belongs to repo 2
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{uuid})
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrPermissionDenied)
|
||||
attach, err := GetAttachmentByUUID(t.Context(), uuid)
|
||||
assert.NoError(t, err)
|
||||
assert.Zero(t, attach.ReleaseID, "attachment should not be linked to release on failure")
|
||||
})
|
||||
|
||||
attach, err := GetAttachmentByUUID(t.Context(), uuid)
|
||||
assert.NoError(t, err)
|
||||
assert.Zero(t, attach.ReleaseID, "attachment should not be linked to release on failure")
|
||||
}
|
||||
t.Run("AddReleaseAttachmentsRejectsIssueAttachment", func(t *testing.T) {
|
||||
uuid := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{uuid})
|
||||
assert.ErrorIs(t, err, util.ErrPermissionDenied)
|
||||
|
||||
func TestAddReleaseAttachmentsRejectsIssueAttachment(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
attach, err := GetAttachmentByUUID(t.Context(), uuid)
|
||||
assert.NoError(t, err)
|
||||
assert.Zero(t, attach.ReleaseID)
|
||||
})
|
||||
|
||||
uuid := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{uuid})
|
||||
assert.ErrorIs(t, err, util.ErrPermissionDenied)
|
||||
t.Run("AddReleaseAttachmentsRejectsRecentZeroRepoID", func(t *testing.T) {
|
||||
recentUUID := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd3800aa"
|
||||
attachment := &Attachment{
|
||||
UUID: recentUUID,
|
||||
RepoID: 0,
|
||||
IssueID: 0,
|
||||
ReleaseID: 0,
|
||||
CommentID: 0,
|
||||
Name: "recent-zero",
|
||||
CreatedUnix: LegacyAttachmentMissingRepoIDCutoff + 1,
|
||||
}
|
||||
assert.NoError(t, db.Insert(t.Context(), attachment))
|
||||
|
||||
attach, err := GetAttachmentByUUID(t.Context(), uuid)
|
||||
assert.NoError(t, err)
|
||||
assert.Zero(t, attach.ReleaseID)
|
||||
}
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{recentUUID})
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrPermissionDenied)
|
||||
|
||||
func TestAddReleaseAttachmentsAllowsLegacyMissingRepoID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
attach, err := GetAttachmentByUUID(t.Context(), recentUUID)
|
||||
assert.NoError(t, err)
|
||||
assert.Zero(t, attach.ReleaseID)
|
||||
assert.Zero(t, attach.RepoID)
|
||||
})
|
||||
|
||||
legacyUUID := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a20" // attachment 10 has repo_id 0
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{legacyUUID})
|
||||
assert.NoError(t, err)
|
||||
t.Run("AddReleaseAttachmentsAllowsLegacyMissingRepoID", func(t *testing.T) {
|
||||
legacyUUID := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a20" // attachment 10 has repo_id 0
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{legacyUUID})
|
||||
assert.NoError(t, err)
|
||||
|
||||
attach, err := GetAttachmentByUUID(t.Context(), legacyUUID)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, attach.RepoID)
|
||||
assert.EqualValues(t, 1, attach.ReleaseID)
|
||||
}
|
||||
|
||||
func TestAddReleaseAttachmentsRejectsRecentZeroRepoID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
recentUUID := "a0eebc99-9c0b-4ef8-bb6d-6bb9bd3800aa"
|
||||
attachment := &Attachment{
|
||||
UUID: recentUUID,
|
||||
RepoID: 0,
|
||||
IssueID: 0,
|
||||
ReleaseID: 0,
|
||||
CommentID: 0,
|
||||
Name: "recent-zero",
|
||||
CreatedUnix: LegacyAttachmentMissingRepoIDCutoff + 1,
|
||||
}
|
||||
assert.NoError(t, db.Insert(t.Context(), attachment))
|
||||
|
||||
err := AddReleaseAttachments(t.Context(), 1, []string{recentUUID})
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrPermissionDenied)
|
||||
|
||||
attach, err := GetAttachmentByUUID(t.Context(), recentUUID)
|
||||
assert.NoError(t, err)
|
||||
assert.Zero(t, attach.ReleaseID)
|
||||
assert.Zero(t, attach.RepoID)
|
||||
attach, err := GetAttachmentByUUID(t.Context(), legacyUUID)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, attach.RepoID)
|
||||
assert.EqualValues(t, 1, attach.ReleaseID)
|
||||
})
|
||||
}
|
||||
+18
-33
@@ -96,27 +96,20 @@ func TestMetas(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
testSuccess := func(expectedStyle string) {
|
||||
for _, style := range []string{"", markup.IssueNameStyleAlphanumeric, markup.IssueNameStyleNumeric, markup.IssueNameStyleRegexp} {
|
||||
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = style
|
||||
repo.Units = []*RepoUnit{&externalTracker}
|
||||
repo.commonRenderingMetas = nil
|
||||
metas := repo.ComposeCommentMetas(t.Context())
|
||||
assert.Equal(t, expectedStyle, metas["style"])
|
||||
if style == "" {
|
||||
style = markup.IssueNameStyleNumeric
|
||||
}
|
||||
assert.Equal(t, style, metas["style"])
|
||||
assert.Equal(t, "testRepo", metas["repo"])
|
||||
assert.Equal(t, "testOwner", metas["user"])
|
||||
assert.Equal(t, "https://someurl.com/{user}/{repo}/{issue}", metas["externalTrackerLinkFormat"])
|
||||
}
|
||||
|
||||
testSuccess(markup.IssueNameStyleNumeric)
|
||||
|
||||
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleAlphanumeric
|
||||
testSuccess(markup.IssueNameStyleAlphanumeric)
|
||||
|
||||
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleNumeric
|
||||
testSuccess(markup.IssueNameStyleNumeric)
|
||||
|
||||
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp
|
||||
testSuccess(markup.IssueNameStyleRegexp)
|
||||
|
||||
repo, err := GetRepositoryByID(t.Context(), 3)
|
||||
assert.NoError(t, err)
|
||||
|
||||
@@ -211,29 +204,21 @@ func TestComposeSSHCloneURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestIsUsableRepoName(t *testing.T) {
|
||||
assert.NoError(t, IsUsableRepoName("a"))
|
||||
assert.NoError(t, IsUsableRepoName("-1_."))
|
||||
assert.NoError(t, IsUsableRepoName(".profile"))
|
||||
for _, name := range []string{"a", "-1_.", ".profile"} {
|
||||
assert.NoError(t, IsUsableRepoName(name))
|
||||
}
|
||||
|
||||
assert.Error(t, IsUsableRepoName("-"))
|
||||
assert.Error(t, IsUsableRepoName("🌞"))
|
||||
assert.Error(t, IsUsableRepoName("the/repo"))
|
||||
assert.Error(t, IsUsableRepoName("the..repo"))
|
||||
assert.Error(t, IsUsableRepoName("foo.wiki"))
|
||||
assert.Error(t, IsUsableRepoName("foo.git"))
|
||||
assert.Error(t, IsUsableRepoName("foo.RSS"))
|
||||
for _, name := range []string{"-", "🌞", "the/repo", "the..repo", "foo.wiki", "foo.git", "foo.RSS"} {
|
||||
assert.Error(t, IsUsableRepoName(name))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidSSHAccessRepoName(t *testing.T) {
|
||||
assert.True(t, IsValidSSHAccessRepoName("a"))
|
||||
assert.True(t, IsValidSSHAccessRepoName("-1_."))
|
||||
assert.True(t, IsValidSSHAccessRepoName(".profile"))
|
||||
assert.True(t, IsValidSSHAccessRepoName("foo.wiki"))
|
||||
for _, name := range []string{"a", "-1_.", ".profile", "foo.wiki"} {
|
||||
assert.True(t, IsValidSSHAccessRepoName(name))
|
||||
}
|
||||
|
||||
assert.False(t, IsValidSSHAccessRepoName("-"))
|
||||
assert.False(t, IsValidSSHAccessRepoName("🌞"))
|
||||
assert.False(t, IsValidSSHAccessRepoName("the/repo"))
|
||||
assert.False(t, IsValidSSHAccessRepoName("the..repo"))
|
||||
assert.False(t, IsValidSSHAccessRepoName("foo.git"))
|
||||
assert.False(t, IsValidSSHAccessRepoName("foo.RSS"))
|
||||
for _, name := range []string{"-", "🌞", "the/repo", "the..repo", "foo.git", "foo.RSS"} {
|
||||
assert.False(t, IsValidSSHAccessRepoName(name))
|
||||
}
|
||||
}
|
||||
+37
-42
@@ -17,6 +17,29 @@ import (
|
||||
func TestStarRepo(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
t.Run("IsStaring", func(t *testing.T) {
|
||||
assert.True(t, repo_model.IsStaring(t.Context(), 2, 4))
|
||||
assert.False(t, repo_model.IsStaring(t.Context(), 3, 4))
|
||||
})
|
||||
|
||||
t.Run("Repository_GetStargazers", func(t *testing.T) {
|
||||
// repo with stargazers
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
|
||||
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, gazers, 1) {
|
||||
assert.Equal(t, int64(2), gazers[0].ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Repository_GetStargazers2", func(t *testing.T) {
|
||||
// repo with stargazers
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, gazers)
|
||||
})
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
@@ -27,49 +50,21 @@ func TestStarRepo(t *testing.T) {
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, false))
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
}
|
||||
|
||||
func TestIsStaring(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
assert.True(t, repo_model.IsStaring(t.Context(), 2, 4))
|
||||
assert.False(t, repo_model.IsStaring(t.Context(), 3, 4))
|
||||
}
|
||||
t.Run("ClearRepoStars", func(t *testing.T) {
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
func TestRepository_GetStargazers(t *testing.T) {
|
||||
// repo with stargazers
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
|
||||
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, gazers, 1) {
|
||||
assert.Equal(t, int64(2), gazers[0].ID)
|
||||
}
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, true))
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, false))
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.ClearRepoStars(t.Context(), repo.ID))
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
|
||||
func TestRepository_GetStargazers2(t *testing.T) {
|
||||
// repo with stargazers
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, gazers)
|
||||
}
|
||||
|
||||
func TestClearRepoStars(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, true))
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, false))
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
assert.NoError(t, repo_model.ClearRepoStars(t.Context(), repo.ID))
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
|
||||
|
||||
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, gazers)
|
||||
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, gazers)
|
||||
})
|
||||
}
|
||||
+19
-40
@@ -72,47 +72,26 @@ func TestWatchIfAuto(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, repo.NumWatches)
|
||||
|
||||
setting.Service.AutoWatchOnChanges = false
|
||||
|
||||
prevCount := repo.NumWatches
|
||||
|
||||
// Must not add watch
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 8, 1, true))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, prevCount)
|
||||
|
||||
// Should not add watch
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 10, 1, true))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, prevCount)
|
||||
|
||||
setting.Service.AutoWatchOnChanges = true
|
||||
|
||||
// Must not add watch (user 8 has "don't watch" set)
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 8, 1, true))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, prevCount)
|
||||
|
||||
// Should not add watch (read operation)
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 12, 1, false))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, prevCount)
|
||||
|
||||
// Should add watch (write operation)
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 12, 1, true))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, prevCount+1)
|
||||
|
||||
// Should not add watch (system user should not be able to watch)
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), user_model.ActionsUserID, 1, true))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, prevCount+1)
|
||||
for _, test := range []struct {
|
||||
autoWatch bool
|
||||
userID int64
|
||||
isWrite bool
|
||||
count int
|
||||
}{
|
||||
{false, 8, true, prevCount}, // Must not add watch
|
||||
{false, 10, true, prevCount}, // Should not add watch
|
||||
{true, 8, true, prevCount}, // Must not add watch (user 8 has "don't watch" set)
|
||||
{true, 12, false, prevCount}, // Should not add watch (read operation)
|
||||
{true, 12, true, prevCount + 1}, // Should add watch (write operation)
|
||||
{true, user_model.ActionsUserID, true, prevCount + 1}, // Should not add watch (system user should not be able to watch)
|
||||
} {
|
||||
setting.Service.AutoWatchOnChanges = test.autoWatch
|
||||
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), test.userID, 1, test.isWrite))
|
||||
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, watchers, test.count)
|
||||
}
|
||||
|
||||
// Should remove watch, inhibit from adding auto
|
||||
assert.NoError(t, repo_model.WatchRepoAuto(t.Context(), user12, repo, false))
|
||||
|
||||
+71
-126
@@ -40,135 +40,80 @@ func TestGetScopedSecretsForJob(t *testing.T) {
|
||||
return job
|
||||
}
|
||||
|
||||
t.Run("TopLevelJob_ReturnsBaseUnchanged", func(t *testing.T) {
|
||||
const runID = 9001
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: 0}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, base, got, "top-level jobs should see the full base scope")
|
||||
})
|
||||
|
||||
t.Run("CallerInherit_PassesParentScopeThrough", func(t *testing.T) {
|
||||
const runID = 9002
|
||||
caller := insertCaller(t, runID, 0, "inherit")
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: caller.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, base, got, "secrets: inherit forwards everything from parent scope")
|
||||
})
|
||||
|
||||
t.Run("CallerEmptySecrets_ExposesOnlyAutoTokens", func(t *testing.T) {
|
||||
const runID = 9003
|
||||
caller := insertCaller(t, runID, 0, "")
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: caller.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
}, got)
|
||||
})
|
||||
|
||||
t.Run("CallerMapping_OnlyMappedAliasesPlusTokens", func(t *testing.T) {
|
||||
const runID = 9004
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
runID int64
|
||||
callSecrets []string
|
||||
check func(*testing.T, map[string]string)
|
||||
}{
|
||||
{"TopLevelJob_ReturnsBaseUnchanged", 9001, nil, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, base, got, "top-level jobs should see the full base scope")
|
||||
}},
|
||||
{"CallerInherit_PassesParentScopeThrough", 9002, []string{"inherit"}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, base, got, "secrets: inherit forwards everything from parent scope")
|
||||
}},
|
||||
{"CallerEmptySecrets_ExposesOnlyAutoTokens", 9003, []string{""}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
}, got)
|
||||
}},
|
||||
// {alias: source} - the called workflow sees `secrets.MY_KEY` resolved to PROD_API_KEY's value.
|
||||
caller := insertCaller(t, runID, 0, `{"MY_KEY":"PROD_API_KEY"}`)
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: caller.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"MY_KEY": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
})
|
||||
|
||||
t.Run("CallerMapping_CaseInsensitiveSource", func(t *testing.T) {
|
||||
const runID = 9005
|
||||
caller := insertCaller(t, runID, 0, `{"alias":"prod_api_key"}`)
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: caller.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "prod-secret", got["alias"])
|
||||
})
|
||||
|
||||
t.Run("CallerMapping_UnknownSourceDropsAlias", func(t *testing.T) {
|
||||
const runID = 9006
|
||||
{"CallerMapping_OnlyMappedAliasesPlusTokens", 9004, []string{`{"MY_KEY":"PROD_API_KEY"}`}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"MY_KEY": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
}},
|
||||
{"CallerMapping_CaseInsensitiveSource", 9005, []string{`{"alias":"prod_api_key"}`}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, "prod-secret", got["alias"])
|
||||
}},
|
||||
// alias points at a non-existent secret name, so it must be dropped.
|
||||
caller := insertCaller(t, runID, 0, `{"MAPPED_ALIAS":"DOES_NOT_EXIST"}`)
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: caller.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
_, present := got["MAPPED_ALIAS"]
|
||||
assert.False(t, present)
|
||||
})
|
||||
|
||||
t.Run("Nested_InheritThenInherit_FullScope", func(t *testing.T) {
|
||||
const runID = 9007
|
||||
outer := insertCaller(t, runID, 0, "inherit")
|
||||
inner := insertCaller(t, runID, outer.ID, "inherit")
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: inner.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, base, got, "inherit-then-inherit should pass the full base scope through")
|
||||
})
|
||||
|
||||
t.Run("Nested_InheritThenMapping_InnerNarrows", func(t *testing.T) {
|
||||
const runID = 9008
|
||||
{"CallerMapping_UnknownSourceDropsAlias", 9006, []string{`{"MAPPED_ALIAS":"DOES_NOT_EXIST"}`}, func(t *testing.T, got map[string]string) {
|
||||
_, present := got["MAPPED_ALIAS"]
|
||||
assert.False(t, present)
|
||||
}},
|
||||
{"Nested_InheritThenInherit_FullScope", 9007, []string{"inherit", "inherit"}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, base, got, "inherit-then-inherit should pass the full base scope through")
|
||||
}},
|
||||
// inner mapping narrows the full scope it inherited from outer.
|
||||
outer := insertCaller(t, runID, 0, "inherit")
|
||||
inner := insertCaller(t, runID, outer.ID, `{"ALIAS_OUT":"PROD_API_KEY"}`)
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: inner.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"ALIAS_OUT": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
})
|
||||
|
||||
t.Run("Nested_MappingThenInherit_OuterNarrows", func(t *testing.T) {
|
||||
const runID = 9009
|
||||
{"Nested_InheritThenMapping_InnerNarrows", 9008, []string{"inherit", `{"ALIAS_OUT":"PROD_API_KEY"}`}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"ALIAS_OUT": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
}},
|
||||
// inner inherits outer's already-narrowed scope, so leaf sees only auto-tokens + OUTER_ALIAS.
|
||||
outer := insertCaller(t, runID, 0, `{"OUTER_ALIAS":"PROD_API_KEY"}`)
|
||||
inner := insertCaller(t, runID, outer.ID, "inherit")
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: inner.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"OUTER_ALIAS": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
})
|
||||
|
||||
t.Run("Nested_MappingThenMapping_InnerSourceMustExistInOuterScope", func(t *testing.T) {
|
||||
const runID = 9010
|
||||
{"Nested_MappingThenInherit_OuterNarrows", 9009, []string{`{"OUTER_ALIAS":"PROD_API_KEY"}`, "inherit"}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"OUTER_ALIAS": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
}},
|
||||
// inner can rename ALIAS_A (in outer's scope) to ALIAS_C, but cannot forward DEV_API_KEY, which outer dropped.
|
||||
outer := insertCaller(t, runID, 0, `{"ALIAS_A":"PROD_API_KEY"}`)
|
||||
inner := insertCaller(t, runID, outer.ID, `{"ALIAS_B":"DEV_API_KEY","ALIAS_C":"ALIAS_A"}`)
|
||||
leaf := &actions_model.ActionRunJob{RunID: runID, ParentJobID: inner.ID}
|
||||
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"ALIAS_C": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
})
|
||||
{"Nested_MappingThenMapping_InnerSourceMustExistInOuterScope", 9010, []string{`{"ALIAS_A":"PROD_API_KEY"}`, `{"ALIAS_B":"DEV_API_KEY","ALIAS_C":"ALIAS_A"}`}, func(t *testing.T, got map[string]string) {
|
||||
assert.Equal(t, map[string]string{
|
||||
"GITHUB_TOKEN": "tok",
|
||||
"GITEA_TOKEN": "tok",
|
||||
"ALIAS_C": "prod-secret",
|
||||
// no "dev-secret"
|
||||
}, got)
|
||||
}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
leaf := &actions_model.ActionRunJob{RunID: testCase.runID, ParentJobID: 0}
|
||||
for _, callSecrets := range testCase.callSecrets {
|
||||
leaf.ParentJobID = insertCaller(t, testCase.runID, leaf.ParentJobID, callSecrets).ID
|
||||
}
|
||||
got, err := getScopedSecretsForJob(ctx, leaf, base)
|
||||
require.NoError(t, err)
|
||||
testCase.check(t, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -24,21 +24,15 @@ func TestSettings(t *testing.T) {
|
||||
assert.Equal(t, 1, rev)
|
||||
assert.Len(t, settings, 1) // there is only one "revision" key
|
||||
|
||||
err = system.SetSettings(t.Context(), map[string]string{keyName: "true"})
|
||||
assert.NoError(t, err)
|
||||
rev, settings, err = system.GetAllSettings(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 2, rev)
|
||||
assert.Len(t, settings, 2)
|
||||
assert.Equal(t, "true", settings[keyName])
|
||||
|
||||
err = system.SetSettings(t.Context(), map[string]string{keyName: "false"})
|
||||
assert.NoError(t, err)
|
||||
rev, settings, err = system.GetAllSettings(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 3, rev)
|
||||
assert.Len(t, settings, 2)
|
||||
assert.Equal(t, "false", settings[keyName])
|
||||
for index, value := range []string{"true", "false"} {
|
||||
err = system.SetSettings(t.Context(), map[string]string{keyName: value})
|
||||
assert.NoError(t, err)
|
||||
rev, settings, err = system.GetAllSettings(t.Context())
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, index+2, rev)
|
||||
assert.Len(t, settings, 2)
|
||||
assert.Equal(t, value, settings[keyName])
|
||||
}
|
||||
|
||||
// setting the same value should not trigger DuplicateKey error, and the "version" should be increased
|
||||
err = system.SetSettings(t.Context(), map[string]string{keyName: "false"})
|
||||
|
||||
+19
-32
@@ -24,39 +24,26 @@ func mockUnitConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestLoadUnitConfig(t *testing.T) {
|
||||
t.Run("regular", func(t *testing.T) {
|
||||
mockUnitConfig(t)
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
disabled, defaults, forks []string
|
||||
}{
|
||||
{"regular", []string{"repo.issues"}, []string{"repo.code", "repo.releases", "repo.issues", "repo.pulls"}, []string{"repo.releases"}},
|
||||
{"invalid", []string{"repo.issues", "invalid.1"}, []string{"repo.code", "invalid.2", "repo.releases", "repo.issues", "repo.pulls"}, []string{"invalid.3", "repo.releases"}},
|
||||
{"duplicate", []string{"repo.issues", "repo.issues"}, []string{"repo.code", "repo.releases", "repo.issues", "repo.pulls", "repo.code"}, []string{"repo.releases", "repo.releases"}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
mockUnitConfig(t)
|
||||
|
||||
setting.Repository.DisabledRepoUnits = []string{"repo.issues"}
|
||||
setting.Repository.DefaultRepoUnits = []string{"repo.code", "repo.releases", "repo.issues", "repo.pulls"}
|
||||
setting.Repository.DefaultForkRepoUnits = []string{"repo.releases"}
|
||||
assert.NoError(t, LoadUnitConfig())
|
||||
assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet())
|
||||
assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits)
|
||||
assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits)
|
||||
})
|
||||
t.Run("invalid", func(t *testing.T) {
|
||||
mockUnitConfig(t)
|
||||
|
||||
setting.Repository.DisabledRepoUnits = []string{"repo.issues", "invalid.1"}
|
||||
setting.Repository.DefaultRepoUnits = []string{"repo.code", "invalid.2", "repo.releases", "repo.issues", "repo.pulls"}
|
||||
setting.Repository.DefaultForkRepoUnits = []string{"invalid.3", "repo.releases"}
|
||||
assert.NoError(t, LoadUnitConfig())
|
||||
assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet())
|
||||
assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits)
|
||||
assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits)
|
||||
})
|
||||
t.Run("duplicate", func(t *testing.T) {
|
||||
mockUnitConfig(t)
|
||||
|
||||
setting.Repository.DisabledRepoUnits = []string{"repo.issues", "repo.issues"}
|
||||
setting.Repository.DefaultRepoUnits = []string{"repo.code", "repo.releases", "repo.issues", "repo.pulls", "repo.code"}
|
||||
setting.Repository.DefaultForkRepoUnits = []string{"repo.releases", "repo.releases"}
|
||||
assert.NoError(t, LoadUnitConfig())
|
||||
assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet())
|
||||
assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits)
|
||||
assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits)
|
||||
})
|
||||
setting.Repository.DisabledRepoUnits = testCase.disabled
|
||||
setting.Repository.DefaultRepoUnits = testCase.defaults
|
||||
setting.Repository.DefaultForkRepoUnits = testCase.forks
|
||||
assert.NoError(t, LoadUnitConfig())
|
||||
assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet())
|
||||
assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits)
|
||||
assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits)
|
||||
})
|
||||
}
|
||||
t.Run("empty_default", func(t *testing.T) {
|
||||
mockUnitConfig(t)
|
||||
|
||||
|
||||
+106
-127
@@ -15,138 +15,117 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetEmailAddresses(t *testing.T) {
|
||||
func TestEmailAddresses(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
emails, _ := user_model.GetEmailAddresses(t.Context(), int64(1))
|
||||
if assert.Len(t, emails, 3) {
|
||||
t.Run("GetEmailAddresses", func(t *testing.T) {
|
||||
emails, _ := user_model.GetEmailAddresses(t.Context(), int64(1))
|
||||
if assert.Len(t, emails, 3) {
|
||||
assert.True(t, emails[0].IsPrimary)
|
||||
assert.True(t, emails[2].IsActivated)
|
||||
assert.False(t, emails[2].IsPrimary)
|
||||
}
|
||||
|
||||
emails, _ = user_model.GetEmailAddresses(t.Context(), int64(2))
|
||||
if assert.Len(t, emails, 2) {
|
||||
assert.True(t, emails[0].IsPrimary)
|
||||
assert.True(t, emails[0].IsActivated)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("IsEmailUsed", func(t *testing.T) {
|
||||
isExist, _ := user_model.IsEmailUsed(t.Context(), "")
|
||||
assert.True(t, isExist)
|
||||
isExist, _ = user_model.IsEmailUsed(t.Context(), "user11@example.com")
|
||||
assert.True(t, isExist)
|
||||
isExist, _ = user_model.IsEmailUsed(t.Context(), "user1234567890@example.com")
|
||||
assert.False(t, isExist)
|
||||
})
|
||||
|
||||
t.Run("ListEmails", func(t *testing.T) {
|
||||
search := func(opts *user_model.SearchEmailOptions) ([]*user_model.SearchEmailResult, int64) {
|
||||
emails, count, err := user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
return emails, count
|
||||
}
|
||||
|
||||
// Must find all users and their emails
|
||||
emails, count := search(&user_model.SearchEmailOptions{ListOptions: db.ListOptions{PageSize: 10000}})
|
||||
assert.Greater(t, count, int64(5))
|
||||
|
||||
contains := func(match func(s *user_model.SearchEmailResult) bool) bool {
|
||||
return slices.ContainsFunc(emails, match)
|
||||
}
|
||||
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 18 }))
|
||||
// 'org3' is an organization
|
||||
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 3 }))
|
||||
|
||||
// Must find no records
|
||||
emails, count = search(&user_model.SearchEmailOptions{Keyword: "NOTFOUND"})
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
// Must find users 'user2', 'user28', etc.
|
||||
emails, count = search(&user_model.SearchEmailOptions{Keyword: "user2"})
|
||||
assert.NotEqual(t, int64(0), count)
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 2 }))
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 27 }))
|
||||
|
||||
// Must find only primary addresses (i.e. from the `user` table)
|
||||
emails, _ = search(&user_model.SearchEmailOptions{IsPrimary: optional.Some(true)})
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsPrimary }))
|
||||
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsPrimary }))
|
||||
|
||||
// Must find only inactive addresses (i.e. not validated)
|
||||
emails, _ = search(&user_model.SearchEmailOptions{IsActivated: optional.Some(false)})
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsActivated }))
|
||||
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsActivated }))
|
||||
|
||||
// Must find more than one page, but retrieve only one
|
||||
emails, count = search(&user_model.SearchEmailOptions{ListOptions: db.ListOptions{PageSize: 5, Page: 1}})
|
||||
assert.Len(t, emails, 5)
|
||||
assert.Greater(t, count, int64(len(emails)))
|
||||
})
|
||||
|
||||
t.Run("MakeEmailPrimary", func(t *testing.T) {
|
||||
err := user_model.MakeActiveEmailPrimary(t.Context(), 1, 9999999)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, user_model.ErrEmailAddressNotExist{})
|
||||
|
||||
email := unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user11@example.com"})
|
||||
err = user_model.MakeActiveEmailPrimary(t.Context(), email.UID, email.ID)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, user_model.ErrEmailAddressNotExist{}) // inactive email is considered as not exist for "MakeActiveEmailPrimary"
|
||||
|
||||
email = unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user9999999@example.com"})
|
||||
err = user_model.MakeActiveEmailPrimary(t.Context(), email.UID, email.ID)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, user_model.IsErrUserNotExist(err))
|
||||
|
||||
email = unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user101@example.com"})
|
||||
err = user_model.MakeActiveEmailPrimary(t.Context(), email.UID, email.ID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
user, _ := user_model.GetUserByID(t.Context(), int64(10))
|
||||
assert.Equal(t, "user101@example.com", user.Email)
|
||||
})
|
||||
|
||||
t.Run("Activate", func(t *testing.T) {
|
||||
email := &user_model.EmailAddress{
|
||||
ID: int64(1),
|
||||
UID: int64(1),
|
||||
Email: "user11@example.com",
|
||||
}
|
||||
assert.NoError(t, user_model.ActivateEmail(t.Context(), email))
|
||||
|
||||
emails, _ := user_model.GetEmailAddresses(t.Context(), int64(1))
|
||||
assert.Len(t, emails, 3)
|
||||
assert.True(t, emails[0].IsActivated)
|
||||
assert.True(t, emails[0].IsPrimary)
|
||||
assert.False(t, emails[1].IsPrimary)
|
||||
assert.True(t, emails[2].IsActivated)
|
||||
assert.False(t, emails[2].IsPrimary)
|
||||
}
|
||||
|
||||
emails, _ = user_model.GetEmailAddresses(t.Context(), int64(2))
|
||||
if assert.Len(t, emails, 2) {
|
||||
assert.True(t, emails[0].IsPrimary)
|
||||
assert.True(t, emails[0].IsActivated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmailUsed(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
isExist, _ := user_model.IsEmailUsed(t.Context(), "")
|
||||
assert.True(t, isExist)
|
||||
isExist, _ = user_model.IsEmailUsed(t.Context(), "user11@example.com")
|
||||
assert.True(t, isExist)
|
||||
isExist, _ = user_model.IsEmailUsed(t.Context(), "user1234567890@example.com")
|
||||
assert.False(t, isExist)
|
||||
}
|
||||
|
||||
func TestMakeEmailPrimary(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
err := user_model.MakeActiveEmailPrimary(t.Context(), 1, 9999999)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, user_model.ErrEmailAddressNotExist{})
|
||||
|
||||
email := unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user11@example.com"})
|
||||
err = user_model.MakeActiveEmailPrimary(t.Context(), email.UID, email.ID)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, user_model.ErrEmailAddressNotExist{}) // inactive email is considered as not exist for "MakeActiveEmailPrimary"
|
||||
|
||||
email = unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user9999999@example.com"})
|
||||
err = user_model.MakeActiveEmailPrimary(t.Context(), email.UID, email.ID)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, user_model.IsErrUserNotExist(err))
|
||||
|
||||
email = unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user101@example.com"})
|
||||
err = user_model.MakeActiveEmailPrimary(t.Context(), email.UID, email.ID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
user, _ := user_model.GetUserByID(t.Context(), int64(10))
|
||||
assert.Equal(t, "user101@example.com", user.Email)
|
||||
}
|
||||
|
||||
func TestActivate(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
email := &user_model.EmailAddress{
|
||||
ID: int64(1),
|
||||
UID: int64(1),
|
||||
Email: "user11@example.com",
|
||||
}
|
||||
assert.NoError(t, user_model.ActivateEmail(t.Context(), email))
|
||||
|
||||
emails, _ := user_model.GetEmailAddresses(t.Context(), int64(1))
|
||||
assert.Len(t, emails, 3)
|
||||
assert.True(t, emails[0].IsActivated)
|
||||
assert.True(t, emails[0].IsPrimary)
|
||||
assert.False(t, emails[1].IsPrimary)
|
||||
assert.True(t, emails[2].IsActivated)
|
||||
assert.False(t, emails[2].IsPrimary)
|
||||
}
|
||||
|
||||
func TestListEmails(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
// Must find all users and their emails
|
||||
opts := &user_model.SearchEmailOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
PageSize: 10000,
|
||||
},
|
||||
}
|
||||
emails, count, err := user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
assert.Greater(t, count, int64(5))
|
||||
|
||||
contains := func(match func(s *user_model.SearchEmailResult) bool) bool {
|
||||
return slices.ContainsFunc(emails, match)
|
||||
}
|
||||
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 18 }))
|
||||
// 'org3' is an organization
|
||||
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 3 }))
|
||||
|
||||
// Must find no records
|
||||
opts = &user_model.SearchEmailOptions{Keyword: "NOTFOUND"}
|
||||
emails, count, err = user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
// Must find users 'user2', 'user28', etc.
|
||||
opts = &user_model.SearchEmailOptions{Keyword: "user2"}
|
||||
emails, count, err = user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, int64(0), count)
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 2 }))
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 27 }))
|
||||
|
||||
// Must find only primary addresses (i.e. from the `user` table)
|
||||
opts = &user_model.SearchEmailOptions{IsPrimary: optional.Some(true)}
|
||||
emails, _, err = user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsPrimary }))
|
||||
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsPrimary }))
|
||||
|
||||
// Must find only inactive addresses (i.e. not validated)
|
||||
opts = &user_model.SearchEmailOptions{IsActivated: optional.Some(false)}
|
||||
emails, _, err = user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsActivated }))
|
||||
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsActivated }))
|
||||
|
||||
// Must find more than one page, but retrieve only one
|
||||
opts = &user_model.SearchEmailOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
PageSize: 5,
|
||||
Page: 1,
|
||||
},
|
||||
}
|
||||
emails, count, err = user_model.SearchEmails(t.Context(), opts)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, emails, 5)
|
||||
assert.Greater(t, count, int64(len(emails)))
|
||||
})
|
||||
}
|
||||
|
||||
func TestEmailAddressValidate(t *testing.T) {
|
||||
|
||||
+49
-49
@@ -14,57 +14,57 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetUserOpenIDs(t *testing.T) {
|
||||
func TestUserOpenIDs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
oids, err := user_model.GetUserOpenIDs(t.Context(), int64(1))
|
||||
if assert.NoError(t, err) && assert.Len(t, oids, 2) {
|
||||
assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI)
|
||||
t.Run("GetUserOpenIDs", func(t *testing.T) {
|
||||
oids, err := user_model.GetUserOpenIDs(t.Context(), int64(1))
|
||||
if assert.NoError(t, err) && assert.Len(t, oids, 2) {
|
||||
assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI)
|
||||
assert.False(t, oids[0].Show)
|
||||
assert.Equal(t, "http://user1.domain2.tld/", oids[1].URI)
|
||||
assert.True(t, oids[1].Show)
|
||||
}
|
||||
|
||||
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
if assert.NoError(t, err) && assert.Len(t, oids, 1) {
|
||||
assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI)
|
||||
assert.True(t, oids[0].Show)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ToggleUserOpenIDVisibilityRequiresOwnership", func(t *testing.T) {
|
||||
unauthorizedUser, err := user_model.GetUserByID(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
|
||||
err = user_model.ToggleUserOpenIDVisibility(t.Context(), int64(1), unauthorizedUser)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
})
|
||||
|
||||
t.Run("ToggleUserOpenIDVisibility", func(t *testing.T) {
|
||||
user, err := user_model.GetUserByID(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
oids, err := user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, oids, 1)
|
||||
assert.True(t, oids[0].Show)
|
||||
|
||||
err = user_model.ToggleUserOpenIDVisibility(t.Context(), oids[0].ID, user)
|
||||
require.NoError(t, err)
|
||||
|
||||
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, oids, 1)
|
||||
|
||||
assert.False(t, oids[0].Show)
|
||||
assert.Equal(t, "http://user1.domain2.tld/", oids[1].URI)
|
||||
assert.True(t, oids[1].Show)
|
||||
}
|
||||
err = user_model.ToggleUserOpenIDVisibility(t.Context(), oids[0].ID, user)
|
||||
require.NoError(t, err)
|
||||
|
||||
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
if assert.NoError(t, err) && assert.Len(t, oids, 1) {
|
||||
assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI)
|
||||
assert.True(t, oids[0].Show)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToggleUserOpenIDVisibility(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
user, err := user_model.GetUserByID(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
oids, err := user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, oids, 1)
|
||||
assert.True(t, oids[0].Show)
|
||||
|
||||
err = user_model.ToggleUserOpenIDVisibility(t.Context(), oids[0].ID, user)
|
||||
require.NoError(t, err)
|
||||
|
||||
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, oids, 1)
|
||||
|
||||
assert.False(t, oids[0].Show)
|
||||
err = user_model.ToggleUserOpenIDVisibility(t.Context(), oids[0].ID, user)
|
||||
require.NoError(t, err)
|
||||
|
||||
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
if assert.Len(t, oids, 1) {
|
||||
assert.True(t, oids[0].Show)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToggleUserOpenIDVisibilityRequiresOwnership(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
unauthorizedUser, err := user_model.GetUserByID(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
|
||||
err = user_model.ToggleUserOpenIDVisibility(t.Context(), int64(1), unauthorizedUser)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
|
||||
require.NoError(t, err)
|
||||
if assert.Len(t, oids, 1) {
|
||||
assert.True(t, oids[0].Show)
|
||||
}
|
||||
})
|
||||
}
|
||||
+42
-76
@@ -28,18 +28,13 @@ import (
|
||||
)
|
||||
|
||||
func TestIsUsableUsername(t *testing.T) {
|
||||
assert.NoError(t, user_model.IsUsableUsername("a"))
|
||||
assert.NoError(t, user_model.IsUsableUsername("foo.wiki"))
|
||||
assert.NoError(t, user_model.IsUsableUsername("foo.git"))
|
||||
for _, username := range []string{"a", "foo.wiki", "foo.git"} {
|
||||
assert.NoError(t, user_model.IsUsableUsername(username))
|
||||
}
|
||||
|
||||
assert.Error(t, user_model.IsUsableUsername("a--b"))
|
||||
assert.Error(t, user_model.IsUsableUsername("-1_."))
|
||||
assert.Error(t, user_model.IsUsableUsername(".profile"))
|
||||
assert.Error(t, user_model.IsUsableUsername("-"))
|
||||
assert.Error(t, user_model.IsUsableUsername("🌞"))
|
||||
assert.Error(t, user_model.IsUsableUsername("the..repo"))
|
||||
assert.Error(t, user_model.IsUsableUsername("foo.RSS"))
|
||||
assert.Error(t, user_model.IsUsableUsername("foo.PnG"))
|
||||
for _, username := range []string{"a--b", "-1_.", ".profile", "-", "🌞", "the..repo", "foo.RSS", "foo.PnG"} {
|
||||
assert.Error(t, user_model.IsUsableUsername(username))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuth2Application_LoadUser(t *testing.T) {
|
||||
@@ -161,28 +156,17 @@ func TestSearchUsers(t *testing.T) {
|
||||
}
|
||||
|
||||
// test orgs
|
||||
testOrgSuccess := func(opts user_model.SearchUserOptions, expectedOrgIDs []int64) {
|
||||
opts.Types = []user_model.UserType{user_model.UserTypeOrganization}
|
||||
testSuccess(opts, expectedOrgIDs)
|
||||
for page, expectedOrgIDs := range [][]int64{{3, 6}, {7, 17}, {19, 25}, {26, 41}, {42}} {
|
||||
testSuccess(user_model.SearchUserOptions{
|
||||
Types: []user_model.UserType{user_model.UserTypeOrganization},
|
||||
OrderBy: "id ASC",
|
||||
ListOptions: db.ListOptions{Page: page + 1, PageSize: 2},
|
||||
}, expectedOrgIDs)
|
||||
}
|
||||
|
||||
testOrgSuccess(user_model.SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 1, PageSize: 2}},
|
||||
[]int64{3, 6})
|
||||
|
||||
testOrgSuccess(user_model.SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 2, PageSize: 2}},
|
||||
[]int64{7, 17})
|
||||
|
||||
testOrgSuccess(user_model.SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 3, PageSize: 2}},
|
||||
[]int64{19, 25})
|
||||
|
||||
testOrgSuccess(user_model.SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 4, PageSize: 2}},
|
||||
[]int64{26, 41})
|
||||
|
||||
testOrgSuccess(user_model.SearchUserOptions{OrderBy: "id ASC", ListOptions: db.ListOptions{Page: 5, PageSize: 2}},
|
||||
[]int64{42})
|
||||
|
||||
testOrgSuccess(user_model.SearchUserOptions{ListOptions: db.ListOptions{Page: 6, PageSize: 2}},
|
||||
[]int64{})
|
||||
testSuccess(user_model.SearchUserOptions{
|
||||
Types: []user_model.UserType{user_model.UserTypeOrganization},
|
||||
ListOptions: db.ListOptions{Page: 6, PageSize: 2},
|
||||
}, []int64{})
|
||||
|
||||
// test users
|
||||
testUserSuccess := func(opts user_model.SearchUserOptions, expectedUserIDs []int64) {
|
||||
@@ -403,50 +387,34 @@ func TestGetMaileableUsersByIDs(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNewUserRedirect(t *testing.T) {
|
||||
// redirect to a completely new name
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
for _, testCase := range []struct {
|
||||
userID int64
|
||||
newName string
|
||||
}{
|
||||
{1, "newusername"}, // redirect to a completely new name
|
||||
{1, "olduser1"}, // redirect to previously used name
|
||||
{2, "newusername"}, // redirect for a previously-unredirected user
|
||||
} {
|
||||
t.Run(fmt.Sprintf("%d/%s", testCase.userID, testCase.newName), func(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, "newusername"))
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.userID})
|
||||
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, testCase.newName))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
|
||||
LowerName: user.LowerName,
|
||||
RedirectUserID: user.ID,
|
||||
})
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
|
||||
LowerName: "olduser1",
|
||||
RedirectUserID: user.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewUserRedirect2(t *testing.T) {
|
||||
// redirect to previously used name
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, "olduser1"))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
|
||||
LowerName: user.LowerName,
|
||||
RedirectUserID: user.ID,
|
||||
})
|
||||
unittest.AssertNotExistsBean(t, &user_model.Redirect{
|
||||
LowerName: "olduser1",
|
||||
RedirectUserID: user.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewUserRedirect3(t *testing.T) {
|
||||
// redirect for a previously-unredirected user
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, "newusername"))
|
||||
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
|
||||
LowerName: user.LowerName,
|
||||
RedirectUserID: user.ID,
|
||||
})
|
||||
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
|
||||
LowerName: user.LowerName,
|
||||
RedirectUserID: user.ID,
|
||||
})
|
||||
if testCase.userID == 1 {
|
||||
redirect := &user_model.Redirect{LowerName: "olduser1", RedirectUserID: user.ID}
|
||||
if testCase.newName == "olduser1" {
|
||||
unittest.AssertNotExistsBean(t, redirect)
|
||||
} else {
|
||||
unittest.AssertExistsAndLoadBean(t, redirect)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUserByOpenID(t *testing.T) {
|
||||
@@ -546,13 +514,11 @@ func TestIsUserVisibleToViewer(t *testing.T) {
|
||||
|
||||
// limited user
|
||||
test(user33, user33, true)
|
||||
test(user33, user4, true)
|
||||
test(user33, user29, false)
|
||||
test(user33, nil, false)
|
||||
|
||||
// private user
|
||||
test(user31, user31, true)
|
||||
test(user31, user4, false)
|
||||
test(user31, user20, true)
|
||||
test(user31, user29, false)
|
||||
test(user31, user33, true)
|
||||
|
||||
+45
-114
@@ -322,120 +322,51 @@ func TestUpdateHookTask(t *testing.T) {
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
}
|
||||
|
||||
func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
func TestCleanupHookTaskTable(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
url string
|
||||
cleanupType HookTaskCleanupType
|
||||
isDelivered bool
|
||||
delivered func() timeutil.TimeStampNano
|
||||
numberToKeep int
|
||||
deleted bool
|
||||
}{
|
||||
{"PerWebhook_DeletesDelivered", "https://www.example.com/cleanup1", PerWebhook, true, timeutil.TimeStampNanoNow, 0, true},
|
||||
{"PerWebhook_LeavesUndelivered", "https://www.example.com/cleanup2", PerWebhook, false, nil, 0, false},
|
||||
{"PerWebhook_LeavesMostRecentTask", "https://www.example.com/cleanup3", PerWebhook, true, timeutil.TimeStampNanoNow, 1, false},
|
||||
{"OlderThan_DeletesDelivered", "https://www.example.com/cleanup4", OlderThan, true, func() timeutil.TimeStampNano {
|
||||
return timeutil.TimeStampNano(time.Now().AddDate(0, 0, -8).UnixNano())
|
||||
}, 0, true},
|
||||
{"OlderThan_LeavesUndelivered", "https://www.example.com/cleanup5", OlderThan, false, nil, 0, false},
|
||||
{"OlderThan_LeavesTaskEarlierThanAgeToDelete", "https://www.example.com/cleanup6", OlderThan, true, func() timeutil.TimeStampNano {
|
||||
return timeutil.TimeStampNano(time.Now().AddDate(0, 0, -6).UnixNano())
|
||||
}, 0, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
hook := &Webhook{RepoID: 3, URL: "https://www.example.com/cleanup1", ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: true,
|
||||
Delivered: timeutil.TimeStampNanoNow(),
|
||||
PayloadVersion: 2,
|
||||
hook := &Webhook{RepoID: 3, URL: test.url, ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: test.isDelivered,
|
||||
PayloadVersion: 2,
|
||||
}
|
||||
if test.delivered != nil {
|
||||
hookTask.Delivered = test.delivered()
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), test.cleanupType, 168*time.Hour, test.numberToKeep))
|
||||
if test.deleted {
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
} else {
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
}
|
||||
})
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), PerWebhook, 168*time.Hour, 0))
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
}
|
||||
|
||||
func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
hook := &Webhook{RepoID: 3, URL: "https://www.example.com/cleanup2", ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: false,
|
||||
PayloadVersion: 2,
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), PerWebhook, 168*time.Hour, 0))
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
}
|
||||
|
||||
func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
hook := &Webhook{RepoID: 3, URL: "https://www.example.com/cleanup3", ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: true,
|
||||
Delivered: timeutil.TimeStampNanoNow(),
|
||||
PayloadVersion: 2,
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), PerWebhook, 168*time.Hour, 1))
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
}
|
||||
|
||||
func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
hook := &Webhook{RepoID: 3, URL: "https://www.example.com/cleanup4", ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: true,
|
||||
Delivered: timeutil.TimeStampNano(time.Now().AddDate(0, 0, -8).UnixNano()),
|
||||
PayloadVersion: 2,
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), OlderThan, 168*time.Hour, 0))
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
}
|
||||
|
||||
func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
hook := &Webhook{RepoID: 3, URL: "https://www.example.com/cleanup5", ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: false,
|
||||
PayloadVersion: 2,
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), OlderThan, 168*time.Hour, 0))
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
}
|
||||
|
||||
func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
hook := &Webhook{RepoID: 3, URL: "https://www.example.com/cleanup6", ContentType: ContentTypeJSON, Events: `{"push_only":true}`}
|
||||
require.NoError(t, db.Insert(t.Context(), hook))
|
||||
hookTask := &HookTask{
|
||||
HookID: hook.ID,
|
||||
IsDelivered: true,
|
||||
Delivered: timeutil.TimeStampNano(time.Now().AddDate(0, 0, -6).UnixNano()),
|
||||
PayloadVersion: 2,
|
||||
}
|
||||
unittest.AssertNotExistsBean(t, hookTask)
|
||||
_, err := CreateHookTask(t.Context(), hookTask)
|
||||
assert.NoError(t, err)
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
|
||||
assert.NoError(t, CleanupHookTaskTable(t.Context(), OlderThan, 168*time.Hour, 0))
|
||||
unittest.AssertExistsAndLoadBean(t, hookTask)
|
||||
}
|
||||
@@ -77,12 +77,6 @@ func TestCanGithubEventMatch(t *testing.T) {
|
||||
webhook_module.HookEventPullRequest,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"pull_request_target cannot match",
|
||||
GithubEventPullRequest,
|
||||
webhook_module.HookEventPullRequestComment,
|
||||
false,
|
||||
},
|
||||
// pull_request_review event
|
||||
{
|
||||
"pull_request_review matches",
|
||||
|
||||
@@ -18,72 +18,21 @@ import (
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
options []ParseOption
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "multiple_jobs",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "multiple_matrix",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "has_needs",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "has_with",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "has_secrets",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "empty_step",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "job_name_with_matrix",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "prefixed_newline",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "continue_on_error_expr",
|
||||
options: nil,
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
invalidFileTests := []struct {
|
||||
name string
|
||||
}{
|
||||
{name: "null_job_implicit"},
|
||||
{name: "null_job_explicit"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
content := ReadTestdata(t, tt.name+".in.yaml")
|
||||
want := ReadTestdata(t, tt.name+".out.yaml")
|
||||
got, err := Parse(content, append([]ParseOption{WithGitContext(&model.GithubContext{})}, tt.options...)...)
|
||||
if tt.wantErr {
|
||||
require.Error(t, err)
|
||||
}
|
||||
for _, name := range []string{
|
||||
"multiple_jobs",
|
||||
"multiple_matrix",
|
||||
"has_needs",
|
||||
"has_with",
|
||||
"has_secrets",
|
||||
"empty_step",
|
||||
"job_name_with_matrix",
|
||||
"prefixed_newline",
|
||||
"continue_on_error_expr",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
content := ReadTestdata(t, name+".in.yaml")
|
||||
want := ReadTestdata(t, name+".out.yaml")
|
||||
got, err := Parse(content, WithGitContext(&model.GithubContext{}))
|
||||
require.NoError(t, err)
|
||||
|
||||
builder := &strings.Builder{}
|
||||
@@ -102,9 +51,9 @@ func TestParse(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
for _, tt := range invalidFileTests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
content := ReadTestdata(t, tt.name+".in.yaml")
|
||||
for _, name := range []string{"null_job_implicit", "null_job_explicit"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
content := ReadTestdata(t, name+".in.yaml")
|
||||
require.NotPanics(t, func() {
|
||||
_, err := Parse(content)
|
||||
require.Error(t, err)
|
||||
@@ -460,6 +409,8 @@ func TestExpandMatrixWithNeeds(t *testing.T) {
|
||||
{"empty vector", "\n version: ${{ fromJson(needs.setup.outputs.empty) }}\n", `Matrix vector "version" does not contain any values`},
|
||||
{"empty include", "\n include: ${{ fromJson(needs.setup.outputs.empty) }}\n", "Matrix must define at least one vector"},
|
||||
{"whole matrix not a mapping", " ${{ fromJson(needs.setup.outputs.empty) }}\n", `Matrix "" is not a map of matrix keys to values`},
|
||||
{"unresolved need", "\n v: ${{ fromJson(needs.missing.outputs.v) }}\n", "evaluate matrix"},
|
||||
{"invalid strategy field", "\n os: [linux]\nmax-parallel: ${{ fromJSON('bad') }}\n", "evaluate strategy"},
|
||||
} {
|
||||
t.Run(tt.name+" errors", func(t *testing.T) {
|
||||
_, err := expand(t, tt.matrix)
|
||||
@@ -475,16 +426,6 @@ func TestExpandMatrixWithNeeds(t *testing.T) {
|
||||
assert.Equal(t, 1, got[0].Strategy.JobTotal)
|
||||
})
|
||||
|
||||
t.Run("unresolved need errors", func(t *testing.T) {
|
||||
_, err := expand(t, "\n v: ${{ fromJson(needs.missing.outputs.v) }}\n")
|
||||
require.ErrorContains(t, err, "evaluate matrix")
|
||||
})
|
||||
|
||||
t.Run("invalid strategy field errors", func(t *testing.T) {
|
||||
_, err := expand(t, "\n os: [linux]\nmax-parallel: ${{ fromJSON('bad') }}\n")
|
||||
require.ErrorContains(t, err, "evaluate strategy")
|
||||
})
|
||||
|
||||
// The combination count comes from a runtime output, so it must be rejected before one Job per
|
||||
// combination is built rather than after.
|
||||
t.Run("too many combinations errors", func(t *testing.T) {
|
||||
|
||||
@@ -332,29 +332,17 @@ func TestSingleWorkflow_SetJob(t *testing.T) {
|
||||
|
||||
func TestGetContinueOnError(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want bool
|
||||
name string
|
||||
continueOnError string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "absent",
|
||||
yaml: "name: test\non: push\njobs:\n job1:\n runs-on: ubuntu-22.04\n steps:\n - run: echo hi\n",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "static true",
|
||||
yaml: "name: test\non: push\njobs:\n job1:\n runs-on: ubuntu-22.04\n continue-on-error: true\n steps:\n - run: echo hi\n",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "static false",
|
||||
yaml: "name: test\non: push\njobs:\n job1:\n runs-on: ubuntu-22.04\n continue-on-error: false\n steps:\n - run: echo hi\n",
|
||||
want: false,
|
||||
},
|
||||
{name: "absent", want: false},
|
||||
{name: "static true", continueOnError: " continue-on-error: true\n", want: true},
|
||||
{name: "static false", continueOnError: " continue-on-error: false\n", want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := Parse([]byte(tt.yaml))
|
||||
got, err := Parse(fmt.Appendf(nil, "name: test\non: push\njobs:\n job1:\n runs-on: ubuntu-22.04\n%s steps:\n - run: echo hi\n", tt.continueOnError))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
_, job := got[0].Job()
|
||||
|
||||
@@ -13,404 +13,214 @@ import (
|
||||
|
||||
func TestMatchPattern(t *testing.T) {
|
||||
kases := []struct {
|
||||
inputs []string
|
||||
inputs [][]string
|
||||
patterns []string
|
||||
skipResult bool
|
||||
filterResult bool
|
||||
}{
|
||||
{
|
||||
patterns: []string{"*"},
|
||||
inputs: []string{"path/with/slash"},
|
||||
inputs: [][]string{{"path/with/slash"}},
|
||||
skipResult: true,
|
||||
filterResult: false,
|
||||
},
|
||||
{
|
||||
patterns: []string{"path/a", "path/b", "path/c"},
|
||||
inputs: []string{"meta", "path/b", "otherfile"},
|
||||
inputs: [][]string{{"meta", "path/b", "otherfile"}},
|
||||
skipResult: false,
|
||||
filterResult: false,
|
||||
},
|
||||
{
|
||||
patterns: []string{"path/a", "path/b", "path/c"},
|
||||
inputs: []string{"path/b"},
|
||||
inputs: [][]string{{"path/b"}, {"path/c", "path/b"}, {"path/c", "path/b", "path/a"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"path/a", "path/b", "path/c"},
|
||||
inputs: []string{"path/c", "path/b"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"path/a", "path/b", "path/c"},
|
||||
inputs: []string{"path/c", "path/b", "path/a"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"path/a", "path/b", "path/c"},
|
||||
inputs: []string{"path/c", "path/b", "path/d", "path/a"},
|
||||
inputs: [][]string{{"path/c", "path/b", "path/d", "path/a"}},
|
||||
skipResult: false,
|
||||
filterResult: false,
|
||||
},
|
||||
{
|
||||
patterns: []string{},
|
||||
inputs: []string{},
|
||||
inputs: [][]string{{}},
|
||||
skipResult: false,
|
||||
filterResult: false,
|
||||
},
|
||||
{
|
||||
patterns: []string{"\\!file"},
|
||||
inputs: []string{"!file"},
|
||||
inputs: [][]string{{"!file"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"escape\\\\backslash"},
|
||||
inputs: []string{"escape\\backslash"},
|
||||
inputs: [][]string{{"escape\\backslash"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{".yml"},
|
||||
inputs: []string{"fyml"},
|
||||
inputs: [][]string{{"fyml"}},
|
||||
skipResult: true,
|
||||
filterResult: false,
|
||||
},
|
||||
// https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#patterns-to-match-branches-and-tags
|
||||
{
|
||||
patterns: []string{"feature/*"},
|
||||
inputs: []string{"feature/my-branch"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"feature/*"},
|
||||
inputs: []string{"feature/your-branch"},
|
||||
inputs: [][]string{{"feature/my-branch"}, {"feature/your-branch"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"feature/**"},
|
||||
inputs: []string{"feature/beta-a/my-branch"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"feature/**"},
|
||||
inputs: []string{"feature/beta-a/my-branch"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"feature/**"},
|
||||
inputs: []string{"feature/mona/the/octocat"},
|
||||
inputs: [][]string{{"feature/beta-a/my-branch"}, {"feature/mona/the/octocat"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"main", "releases/mona-the-octocat"},
|
||||
inputs: []string{"main"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"main", "releases/mona-the-octocat"},
|
||||
inputs: []string{"releases/mona-the-octocat"},
|
||||
inputs: [][]string{{"main"}, {"releases/mona-the-octocat"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*"},
|
||||
inputs: []string{"main"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*"},
|
||||
inputs: []string{"releases"},
|
||||
inputs: [][]string{{"main"}, {"releases"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**"},
|
||||
inputs: []string{"all/the/branches"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**"},
|
||||
inputs: []string{"every/tag"},
|
||||
inputs: [][]string{{"all/the/branches"}, {"every/tag"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*feature"},
|
||||
inputs: []string{"mona-feature"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*feature"},
|
||||
inputs: []string{"feature"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*feature"},
|
||||
inputs: []string{"ver-10-feature"},
|
||||
inputs: [][]string{{"mona-feature"}, {"feature"}, {"ver-10-feature"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"v2*"},
|
||||
inputs: []string{"v2"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"v2*"},
|
||||
inputs: []string{"v2.0"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"v2*"},
|
||||
inputs: []string{"v2.9"},
|
||||
inputs: [][]string{{"v2"}, {"v2.0"}, {"v2.9"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"v[12].[0-9]+.[0-9]+"},
|
||||
inputs: []string{"v1.10.1"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"v[12].[0-9]+.[0-9]+"},
|
||||
inputs: []string{"v2.0.0"},
|
||||
inputs: [][]string{{"v1.10.1"}, {"v2.0.0"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
// https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#patterns-to-match-file-paths
|
||||
{
|
||||
patterns: []string{"*"},
|
||||
inputs: []string{"README.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*"},
|
||||
inputs: []string{"server.rb"},
|
||||
inputs: [][]string{{"README.md"}, {"server.rb"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.jsx?"},
|
||||
inputs: []string{"page.js"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.jsx?"},
|
||||
inputs: []string{"page.jsx"},
|
||||
inputs: [][]string{{"page.js"}, {"page.jsx"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**"},
|
||||
inputs: []string{"all/the/files.md"},
|
||||
inputs: [][]string{{"all/the/files.md"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.js"},
|
||||
inputs: []string{"app.js"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.js"},
|
||||
inputs: []string{"index.js"},
|
||||
inputs: [][]string{{"app.js"}, {"index.js"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**.js"},
|
||||
inputs: []string{"index.js"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**.js"},
|
||||
inputs: []string{"js/index.js"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**.js"},
|
||||
inputs: []string{"src/js/app.js"},
|
||||
inputs: [][]string{{"index.js"}, {"js/index.js"}, {"src/js/app.js"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/*"},
|
||||
inputs: []string{"docs/README.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/*"},
|
||||
inputs: []string{"docs/file.txt"},
|
||||
inputs: [][]string{{"docs/README.md"}, {"docs/file.txt"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/**"},
|
||||
inputs: []string{"docs/README.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/**"},
|
||||
inputs: []string{"docs/mona/octocat.txt"},
|
||||
inputs: [][]string{{"docs/README.md"}, {"docs/mona/octocat.txt"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/**/*.md"},
|
||||
inputs: []string{"docs/README.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/**/*.md"},
|
||||
inputs: []string{"docs/mona/hello-world.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"docs/**/*.md"},
|
||||
inputs: []string{"docs/a/markdown/file.md"},
|
||||
inputs: [][]string{{"docs/README.md"}, {"docs/mona/hello-world.md"}, {"docs/a/markdown/file.md"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/docs/**"},
|
||||
inputs: []string{"docs/hello.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/docs/**"},
|
||||
inputs: []string{"dir/docs/my-file.txt"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/docs/**"},
|
||||
inputs: []string{"space/docs/plan/space.doc"},
|
||||
inputs: [][]string{{"docs/hello.md"}, {"dir/docs/my-file.txt"}, {"space/docs/plan/space.doc"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/README.md"},
|
||||
inputs: []string{"README.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/README.md"},
|
||||
inputs: []string{"js/README.md"},
|
||||
inputs: [][]string{{"README.md"}, {"js/README.md"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/*src/**"},
|
||||
inputs: []string{"a/src/app.js"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/*src/**"},
|
||||
inputs: []string{"my-src/code/js/app.js"},
|
||||
inputs: [][]string{{"a/src/app.js"}, {"my-src/code/js/app.js"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/*-post.md"},
|
||||
inputs: []string{"my-post.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/*-post.md"},
|
||||
inputs: []string{"path/their-post.md"},
|
||||
inputs: [][]string{{"my-post.md"}, {"path/their-post.md"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/migrate-*.sql"},
|
||||
inputs: []string{"migrate-10909.sql"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/migrate-*.sql"},
|
||||
inputs: []string{"db/migrate-v1.0.sql"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"**/migrate-*.sql"},
|
||||
inputs: []string{"db/sept/migrate-v1.sql"},
|
||||
inputs: [][]string{{"migrate-10909.sql"}, {"db/migrate-v1.0.sql"}, {"db/sept/migrate-v1.sql"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.md", "!README.md"},
|
||||
inputs: []string{"hello.md"},
|
||||
inputs: [][]string{{"hello.md"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.md", "!README.md"},
|
||||
inputs: []string{"README.md"},
|
||||
skipResult: true,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.md", "!README.md"},
|
||||
inputs: []string{"docs/hello.md"},
|
||||
inputs: [][]string{{"README.md"}, {"docs/hello.md"}},
|
||||
skipResult: true,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.md", "!README.md", "README*"},
|
||||
inputs: []string{"hello.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.md", "!README.md", "README*"},
|
||||
inputs: []string{"README.md"},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
{
|
||||
patterns: []string{"*.md", "!README.md", "README*"},
|
||||
inputs: []string{"README.doc"},
|
||||
inputs: [][]string{{"hello.md"}, {"README.md"}, {"README.doc"}},
|
||||
skipResult: false,
|
||||
filterResult: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, kase := range kases {
|
||||
msg := fmt.Sprintf("patterns=%s, input=%s", strings.Join(kase.patterns, ","), strings.Join(kase.inputs, ","))
|
||||
patterns, err := CompilePatterns(kase.patterns...)
|
||||
assert.NoError(t, err, "compile error: %s", msg)
|
||||
assert.Equal(t, kase.skipResult, Skip(patterns, kase.inputs), "unexpected skip result: %s", msg)
|
||||
assert.Equal(t, kase.filterResult, Filter(patterns, kase.inputs), "unexpected filter result: %s", msg)
|
||||
for _, inputs := range kase.inputs {
|
||||
msg := fmt.Sprintf("patterns=%s, input=%s", strings.Join(kase.patterns, ","), strings.Join(inputs, ","))
|
||||
patterns, err := CompilePatterns(kase.patterns...)
|
||||
assert.NoError(t, err, "compile error: %s", msg)
|
||||
assert.Equal(t, kase.skipResult, Skip(patterns, inputs), "unexpected skip result: %s", msg)
|
||||
assert.Equal(t, kase.filterResult, Filter(patterns, inputs), "unexpected filter result: %s", msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -281,6 +281,24 @@ func TestDetectMatched(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMatchIssuesEvent(t *testing.T) {
|
||||
labelChangesPayload := func() *api.IssuePayload {
|
||||
return &api.IssuePayload{
|
||||
Action: api.HookIssueLabelUpdated,
|
||||
Issue: &api.Issue{
|
||||
Labels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
},
|
||||
Changes: &api.ChangesPayload{
|
||||
AddedLabels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
RemovedLabels: []*api.Label{
|
||||
{ID: 123, Name: "deleted-label"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
testCases := []struct {
|
||||
desc string
|
||||
payload *api.IssuePayload
|
||||
@@ -358,67 +376,22 @@ func TestMatchIssuesEvent(t *testing.T) {
|
||||
eventType: "unlabeled",
|
||||
},
|
||||
{
|
||||
desc: "Both adding and removing labels should trigger labeled event",
|
||||
payload: &api.IssuePayload{
|
||||
Action: api.HookIssueLabelUpdated,
|
||||
Issue: &api.Issue{
|
||||
Labels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
},
|
||||
Changes: &api.ChangesPayload{
|
||||
AddedLabels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
RemovedLabels: []*api.Label{
|
||||
{ID: 123, Name: "deleted-label"},
|
||||
},
|
||||
},
|
||||
},
|
||||
desc: "Both adding and removing labels should trigger labeled event",
|
||||
payload: labelChangesPayload(),
|
||||
yamlOn: "on:\n issues:\n types: [labeled]",
|
||||
expected: true,
|
||||
eventType: "labeled",
|
||||
},
|
||||
{
|
||||
desc: "Both adding and removing labels should trigger unlabeled event",
|
||||
payload: &api.IssuePayload{
|
||||
Action: api.HookIssueLabelUpdated,
|
||||
Issue: &api.Issue{
|
||||
Labels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
},
|
||||
Changes: &api.ChangesPayload{
|
||||
AddedLabels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
RemovedLabels: []*api.Label{
|
||||
{ID: 123, Name: "deleted-label"},
|
||||
},
|
||||
},
|
||||
},
|
||||
desc: "Both adding and removing labels should trigger unlabeled event",
|
||||
payload: labelChangesPayload(),
|
||||
yamlOn: "on:\n issues:\n types: [unlabeled]",
|
||||
expected: true,
|
||||
eventType: "unlabeled",
|
||||
},
|
||||
{
|
||||
desc: "Both adding and removing labels should trigger both events",
|
||||
payload: &api.IssuePayload{
|
||||
Action: api.HookIssueLabelUpdated,
|
||||
Issue: &api.Issue{
|
||||
Labels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
},
|
||||
Changes: &api.ChangesPayload{
|
||||
AddedLabels: []*api.Label{
|
||||
{ID: 789, Name: "new-label"},
|
||||
},
|
||||
RemovedLabels: []*api.Label{
|
||||
{ID: 123, Name: "deleted-label"},
|
||||
},
|
||||
},
|
||||
},
|
||||
desc: "Both adding and removing labels should trigger both events",
|
||||
payload: labelChangesPayload(),
|
||||
yamlOn: "on:\n issues:\n types: [labeled, unlabeled]",
|
||||
expected: true,
|
||||
eventType: "multiple",
|
||||
|
||||
@@ -74,34 +74,22 @@ func TestLayered(t *testing.T) {
|
||||
|
||||
assertRead("", fs.ErrNotExist, "no-such")
|
||||
|
||||
files, err := assets.ListFiles(".", true)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"f1", "f2", "fa"}, files)
|
||||
|
||||
files, err = assets.ListFiles(".", false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"d1", "d2", "da"}, files)
|
||||
|
||||
files, err = assets.ListFiles(".")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"d1", "d2", "da", "f1", "f2", "fa"}, files)
|
||||
|
||||
files, err = assets.ListAllFiles(".", true)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"d1/f", "d2/f", "da/f", "f1", "f2", "fa"}, files)
|
||||
|
||||
files, err = assets.ListAllFiles(".", false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{"d1", "d2", "da", "da/sub1", "da/sub2"}, files)
|
||||
|
||||
files, err = assets.ListAllFiles(".")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{
|
||||
assertList := func(listFiles func(string, ...bool) ([]string, error), expected []string, fileMode ...bool) {
|
||||
files, err := listFiles(".", fileMode...)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, files)
|
||||
}
|
||||
assertList(assets.ListFiles, []string{"f1", "f2", "fa"}, true)
|
||||
assertList(assets.ListFiles, []string{"d1", "d2", "da"}, false)
|
||||
assertList(assets.ListFiles, []string{"d1", "d2", "da", "f1", "f2", "fa"})
|
||||
assertList(assets.ListAllFiles, []string{"d1/f", "d2/f", "da/f", "f1", "f2", "fa"}, true)
|
||||
assertList(assets.ListAllFiles, []string{"d1", "d2", "da", "da/sub1", "da/sub2"}, false)
|
||||
assertList(assets.ListAllFiles, []string{
|
||||
"d1", "d1/f",
|
||||
"d2", "d2/f",
|
||||
"da", "da/f", "da/sub1", "da/sub2",
|
||||
"f1", "f2", "fa",
|
||||
}, files)
|
||||
})
|
||||
|
||||
assert.Empty(t, assets.GetFileLayerName("no-such"))
|
||||
assert.Equal(t, "l1", assets.GetFileLayerName("f1"))
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestComplexity_Generate(t *testing.T) {
|
||||
const maxCount = 50
|
||||
const pwdLen = 50
|
||||
|
||||
test := func(t *testing.T, modes []string) {
|
||||
for _, modes := range [][]string{{"lower"}, {"upper"}, {"lower", "upper", "spec"}, {"off"}, {""}} {
|
||||
testComplextity(modes)
|
||||
for range maxCount {
|
||||
pwd, err := Generate(pwdLen)
|
||||
@@ -58,12 +58,6 @@ func TestComplexity_Generate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
test(t, []string{"lower"})
|
||||
test(t, []string{"upper"})
|
||||
test(t, []string{"lower", "upper", "spec"})
|
||||
test(t, []string{"off"})
|
||||
test(t, []string{""})
|
||||
|
||||
// Remove settings for other tests
|
||||
testComplextity([]string{"off"})
|
||||
}
|
||||
|
||||
@@ -47,25 +47,21 @@ func TestPassword(t *testing.T) {
|
||||
assert.ErrorContains(t, err, "password cannot be empty")
|
||||
assert.EqualValues(t, -1, count)
|
||||
|
||||
count, err = client.CheckPassword(ctx, "pwned", false)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, count)
|
||||
|
||||
count, err = client.CheckPassword(ctx, "notpwned", false)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
|
||||
count, err = client.CheckPassword(ctx, "paddedpwned", true)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, count)
|
||||
|
||||
count, err = client.CheckPassword(ctx, "paddednotpwned", true)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
|
||||
count, err = client.CheckPassword(ctx, "paddednotpwnedzero", true)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 0, count)
|
||||
for _, test := range []struct {
|
||||
password string
|
||||
padding bool
|
||||
count int
|
||||
}{
|
||||
{"pwned", false, 1},
|
||||
{"notpwned", false, 0},
|
||||
{"paddedpwned", true, 1},
|
||||
{"paddednotpwned", true, 0},
|
||||
{"paddednotpwnedzero", true, 0},
|
||||
} {
|
||||
count, err = client.CheckPassword(ctx, test.password, test.padding)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, test.count, count)
|
||||
}
|
||||
|
||||
count, err = client.CheckPassword(ctx, "ratelimited", false)
|
||||
assert.Error(t, err)
|
||||
|
||||
@@ -16,26 +16,19 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_ProcessAvatarPNG(t *testing.T) {
|
||||
setting.Avatar.MaxWidth = 4096
|
||||
setting.Avatar.MaxHeight = 4096
|
||||
func Test_ProcessAvatarFormats(t *testing.T) {
|
||||
for _, format := range []string{"png", "jpeg"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
setting.Avatar.MaxWidth = 4096
|
||||
setting.Avatar.MaxHeight = 4096
|
||||
|
||||
data, err := os.ReadFile("testdata/avatar.png")
|
||||
assert.NoError(t, err)
|
||||
data, err := os.ReadFile("testdata/avatar." + format)
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = processAvatarImage(data, 262144)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func Test_ProcessAvatarJPEG(t *testing.T) {
|
||||
setting.Avatar.MaxWidth = 4096
|
||||
setting.Avatar.MaxHeight = 4096
|
||||
|
||||
data, err := os.ReadFile("testdata/avatar.jpeg")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = processAvatarImage(data, 262144)
|
||||
assert.NoError(t, err)
|
||||
_, err = processAvatarImage(data, 262144)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_ProcessAvatarInvalidData(t *testing.T) {
|
||||
|
||||
@@ -87,90 +87,64 @@ func TestToUTF8(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestToUTF8WithFallback(t *testing.T) {
|
||||
// "ABC"
|
||||
res := ToUTF8WithFallback([]byte{0x41, 0x42, 0x43}, ConvertOpts{})
|
||||
assert.Equal(t, []byte{0x41, 0x42, 0x43}, res)
|
||||
for _, converter := range []struct {
|
||||
name string
|
||||
convert func([]byte) []byte
|
||||
}{
|
||||
{"fallback", func(content []byte) []byte { return ToUTF8WithFallback(content, ConvertOpts{}) }},
|
||||
{"drop errors", ToUTF8DropErrors},
|
||||
} {
|
||||
t.Run(converter.name, func(t *testing.T) {
|
||||
// "ABC"
|
||||
res := converter.convert([]byte{0x41, 0x42, 0x43})
|
||||
assert.Equal(t, []byte{0x41, 0x42, 0x43}, res)
|
||||
|
||||
// "áéíóú"
|
||||
res = ToUTF8WithFallback([]byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, ConvertOpts{})
|
||||
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
|
||||
// "áéíóú"
|
||||
res = converter.convert([]byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba})
|
||||
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
|
||||
|
||||
// UTF8 BOM + "áéíóú"
|
||||
res = ToUTF8WithFallback([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, ConvertOpts{})
|
||||
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
|
||||
// UTF8 BOM + "áéíóú"
|
||||
res = converter.convert([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba})
|
||||
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
|
||||
|
||||
// "Hola, así cómo ños"
|
||||
res = ToUTF8WithFallback([]byte{
|
||||
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
|
||||
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73,
|
||||
}, ConvertOpts{})
|
||||
assert.Equal(t, []byte{
|
||||
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63,
|
||||
0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73,
|
||||
}, res)
|
||||
// "Hola, así cómo ños"
|
||||
res = converter.convert([]byte{
|
||||
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
|
||||
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73,
|
||||
})
|
||||
if converter.name == "fallback" {
|
||||
assert.Equal(t, []byte{
|
||||
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63,
|
||||
0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73,
|
||||
}, res)
|
||||
} else {
|
||||
assert.Equal(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73}, res[:8])
|
||||
assert.Equal(t, []byte{0x73}, res[len(res)-1:])
|
||||
}
|
||||
|
||||
// "Hola, así cómo "
|
||||
minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20}
|
||||
// "Hola, así cómo "
|
||||
minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20}
|
||||
|
||||
res = ToUTF8WithFallback([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73}, ConvertOpts{})
|
||||
// Do not fail for differences in invalid cases, as the library might change the conversion criteria for those
|
||||
assert.Equal(t, minmatch, res[0:len(minmatch)])
|
||||
res = converter.convert([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73})
|
||||
// Do not fail for differences in invalid cases, as the library might change the conversion criteria for those
|
||||
assert.Equal(t, minmatch, res[0:len(minmatch)])
|
||||
|
||||
res = ToUTF8WithFallback([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73}, ConvertOpts{})
|
||||
// Do not fail for differences in invalid cases, as the library might change the conversion criteria for those
|
||||
assert.Equal(t, minmatch, res[0:len(minmatch)])
|
||||
res = converter.convert([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73})
|
||||
// Do not fail for differences in invalid cases, as the library might change the conversion criteria for those
|
||||
assert.Equal(t, minmatch, res[0:len(minmatch)])
|
||||
|
||||
// Japanese (Shift-JIS)
|
||||
// "日属秘ぞしちゅ。"
|
||||
res = ToUTF8WithFallback([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}, ConvertOpts{})
|
||||
assert.Equal(t, []byte{
|
||||
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
|
||||
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
|
||||
}, res)
|
||||
// Japanese (Shift-JIS)
|
||||
// "日属秘ぞしちゅ。"
|
||||
res = converter.convert([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42})
|
||||
assert.Equal(t, []byte{
|
||||
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
|
||||
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
|
||||
}, res)
|
||||
|
||||
res = ToUTF8WithFallback([]byte{0x00, 0x00, 0x00, 0x00}, ConvertOpts{})
|
||||
assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res)
|
||||
}
|
||||
|
||||
func TestToUTF8DropErrors(t *testing.T) {
|
||||
// "ABC"
|
||||
res := ToUTF8DropErrors([]byte{0x41, 0x42, 0x43})
|
||||
assert.Equal(t, []byte{0x41, 0x42, 0x43}, res)
|
||||
|
||||
// "áéíóú"
|
||||
res = ToUTF8DropErrors([]byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba})
|
||||
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
|
||||
|
||||
// UTF8 BOM + "áéíóú"
|
||||
res = ToUTF8DropErrors([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba})
|
||||
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
|
||||
|
||||
// "Hola, así cómo ños"
|
||||
res = ToUTF8DropErrors([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73})
|
||||
assert.Equal(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73}, res[:8])
|
||||
assert.Equal(t, []byte{0x73}, res[len(res)-1:])
|
||||
|
||||
// "Hola, así cómo "
|
||||
minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20}
|
||||
|
||||
res = ToUTF8DropErrors([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73})
|
||||
// Do not fail for differences in invalid cases, as the library might change the conversion criteria for those
|
||||
assert.Equal(t, minmatch, res[0:len(minmatch)])
|
||||
|
||||
res = ToUTF8DropErrors([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73})
|
||||
// Do not fail for differences in invalid cases, as the library might change the conversion criteria for those
|
||||
assert.Equal(t, minmatch, res[0:len(minmatch)])
|
||||
|
||||
// Japanese (Shift-JIS)
|
||||
// "日属秘ぞしちゅ。"
|
||||
res = ToUTF8DropErrors([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42})
|
||||
assert.Equal(t, []byte{
|
||||
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
|
||||
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
|
||||
}, res)
|
||||
|
||||
res = ToUTF8DropErrors([]byte{0x00, 0x00, 0x00, 0x00})
|
||||
assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res)
|
||||
res = converter.convert([]byte{0x00, 0x00, 0x00, 0x00})
|
||||
assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res)
|
||||
})
|
||||
}
|
||||
|
||||
assert.Equal(t, "caf ", string(ToUTF8DropErrors([]byte("caf\xe9"))))
|
||||
}
|
||||
|
||||
@@ -173,11 +173,6 @@ func TestCombine(t *testing.T) {
|
||||
states: CommitStatusStates{CommitStatusSuccess, CommitStatusError, CommitStatusFailure, CommitStatusWarning},
|
||||
expected: CommitStatusFailure,
|
||||
},
|
||||
{
|
||||
name: "mixed states",
|
||||
states: CommitStatusStates{CommitStatusPending, CommitStatusSuccess, CommitStatusError, CommitStatusWarning},
|
||||
expected: CommitStatusFailure,
|
||||
},
|
||||
{
|
||||
name: "mixed states with all success",
|
||||
states: CommitStatusStates{CommitStatusSuccess, CommitStatusSuccess, CommitStatusPending, CommitStatusWarning},
|
||||
|
||||
+8
-33
@@ -307,6 +307,7 @@ func TestGuessDelimiter(t *testing.T) {
|
||||
cases := []struct {
|
||||
csv string
|
||||
expectedDelimiter rune
|
||||
checkQuotes bool
|
||||
}{
|
||||
// case 0 - single cell, comma delmited
|
||||
{
|
||||
@@ -373,12 +374,14 @@ quoted,
|
||||
quoted,
|
||||
text," d`,
|
||||
expectedDelimiter: '\t',
|
||||
checkQuotes: true,
|
||||
},
|
||||
// case 10 - semicolon delmited with quotes and semicolon in value
|
||||
{
|
||||
csv: `col1;col2
|
||||
"this has a literal "" in the text";"and an ; in the text"`,
|
||||
expectedDelimiter: ';',
|
||||
checkQuotes: true,
|
||||
},
|
||||
// case 11 - pipe delimited with quotes
|
||||
{
|
||||
@@ -389,6 +392,7 @@ World"|123
|
||||
|
|
||||
f" | 4.56 | 789`,
|
||||
expectedDelimiter: '|',
|
||||
checkQuotes: true,
|
||||
},
|
||||
// case 12 - a tab delimited 6 column CSV, but the values are not quoted and have lots of commas.
|
||||
// In the previous bestScore algorithm, this would have picked comma as the delimiter, but now it should guess tab
|
||||
@@ -455,6 +459,10 @@ jkl`,
|
||||
for n, c := range cases {
|
||||
delimiter := guessDelimiter([]byte(decodeSlashes(t, c.csv)))
|
||||
assert.Equal(t, c.expectedDelimiter, delimiter, "case %d: delimiter should be equal, expected '%c' got '%c'", n, c.expectedDelimiter, delimiter)
|
||||
if c.checkQuotes {
|
||||
delimiter = guessFromBeforeAfterQuotes([]byte(decodeSlashes(t, c.csv)))
|
||||
assert.Equal(t, c.expectedDelimiter, delimiter, "case %d: delimiter should be equal, expected '%c' got '%c'", n, c.expectedDelimiter, delimiter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,39 +471,6 @@ func TestGuessFromBeforeAfterQuotes(t *testing.T) {
|
||||
csv string
|
||||
expectedDelimiter rune
|
||||
}{
|
||||
// case 0 - tab delimited with new lines in values, commas in values
|
||||
{
|
||||
csv: `1 "some,""more
|
||||
""
|
||||
quoted,
|
||||
text," a
|
||||
2 "some,
|
||||
quoted,\t
|
||||
text," b
|
||||
3 "some,
|
||||
quoted,
|
||||
text" c
|
||||
4 "some,
|
||||
quoted,
|
||||
text," d`,
|
||||
expectedDelimiter: '\t',
|
||||
},
|
||||
// case 1 - semicolon delmited with quotes and semicolon in value
|
||||
{
|
||||
csv: `col1;col2
|
||||
"this has a literal "" in the text";"and an ; in the text"`,
|
||||
expectedDelimiter: ';',
|
||||
},
|
||||
// case 2 - pipe delimited with quotes
|
||||
{
|
||||
csv: `Col1 | Col2 | Col3
|
||||
abc | "Hello
|
||||
World"|123
|
||||
"de
|
||||
|
|
||||
f" | 4.56 | 789`,
|
||||
expectedDelimiter: '|',
|
||||
},
|
||||
// case 3 - a complicated quoted CSV that is semicolon delmiited
|
||||
{
|
||||
csv: `he; she
|
||||
|
||||
@@ -16,60 +16,36 @@ import (
|
||||
|
||||
func TestRenderEntryIconHTML_WithDifferentThemes(t *testing.T) {
|
||||
// Test that folder icons use the folder theme
|
||||
t.Run("FolderUsesBasicTheme", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.UI.FileIconTheme, "material")()
|
||||
defer test.MockVariableValue(&setting.UI.FolderIconTheme, "basic")()
|
||||
|
||||
folderEntry := &fileicon.EntryInfo{
|
||||
BaseName: "testfolder",
|
||||
EntryMode: git.EntryModeTree,
|
||||
}
|
||||
|
||||
html := fileicon.RenderEntryIconHTML(nil, folderEntry)
|
||||
for _, testCase := range []struct {
|
||||
name, folderTheme, expected string
|
||||
entry fileicon.EntryInfo
|
||||
}{
|
||||
// Basic theme renders octicon classes
|
||||
assert.Contains(t, string(html), "octicon-file-directory-fill")
|
||||
})
|
||||
|
||||
t.Run("FileUsesMaterialTheme", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.UI.FileIconTheme, "material")()
|
||||
defer test.MockVariableValue(&setting.UI.FolderIconTheme, "basic")()
|
||||
|
||||
fileEntry := &fileicon.EntryInfo{
|
||||
BaseName: "test.js",
|
||||
EntryMode: git.EntryModeBlob,
|
||||
}
|
||||
|
||||
html := fileicon.RenderEntryIconHTML(nil, fileEntry)
|
||||
{
|
||||
"FolderUsesBasicTheme", "basic", "octicon-file-directory-fill",
|
||||
fileicon.EntryInfo{BaseName: "testfolder", EntryMode: git.EntryModeTree},
|
||||
},
|
||||
// Material theme for files renders material icons
|
||||
assert.Contains(t, string(html), "svg-mfi-")
|
||||
})
|
||||
|
||||
t.Run("SymlinkToFolderUsesBasicTheme", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.UI.FileIconTheme, "material")()
|
||||
defer test.MockVariableValue(&setting.UI.FolderIconTheme, "basic")()
|
||||
|
||||
symlinkEntry := &fileicon.EntryInfo{
|
||||
BaseName: "link",
|
||||
EntryMode: git.EntryModeSymlink,
|
||||
SymlinkToMode: git.EntryModeTree,
|
||||
}
|
||||
|
||||
html := fileicon.RenderEntryIconHTML(nil, symlinkEntry)
|
||||
{
|
||||
"FileUsesMaterialTheme", "basic", "svg-mfi-",
|
||||
fileicon.EntryInfo{BaseName: "test.js", EntryMode: git.EntryModeBlob},
|
||||
},
|
||||
// Symlinks to folders should use folder theme
|
||||
assert.Contains(t, string(html), "octicon-file-directory-symlink")
|
||||
})
|
||||
|
||||
t.Run("BothMaterialTheme", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.UI.FileIconTheme, "material")()
|
||||
defer test.MockVariableValue(&setting.UI.FolderIconTheme, "material")()
|
||||
|
||||
folderEntry := &fileicon.EntryInfo{
|
||||
BaseName: "testfolder",
|
||||
EntryMode: git.EntryModeTree,
|
||||
}
|
||||
|
||||
html := fileicon.RenderEntryIconHTML(nil, folderEntry)
|
||||
{
|
||||
"SymlinkToFolderUsesBasicTheme", "basic", "octicon-file-directory-symlink",
|
||||
fileicon.EntryInfo{BaseName: "link", EntryMode: git.EntryModeSymlink, SymlinkToMode: git.EntryModeTree},
|
||||
},
|
||||
// Material theme for folders renders material folder icons
|
||||
assert.Contains(t, string(html), "svg-mfi-")
|
||||
})
|
||||
{
|
||||
"BothMaterialTheme", "material", "svg-mfi-",
|
||||
fileicon.EntryInfo{BaseName: "testfolder", EntryMode: git.EntryModeTree},
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.UI.FileIconTheme, "material")()
|
||||
defer test.MockVariableValue(&setting.UI.FolderIconTheme, testCase.folderTheme)()
|
||||
|
||||
assert.Contains(t, string(fileicon.RenderEntryIconHTML(nil, &testCase.entry)), testCase.expected)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -23,50 +23,31 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
|
||||
|
||||
testStr := ".gitignore\"\n\x00linguist-vendored\x00unspecified\x00"
|
||||
|
||||
n, err := wr.Write([]byte(testStr))
|
||||
|
||||
assert.Len(t, testStr, n)
|
||||
assert.NoError(t, err)
|
||||
select {
|
||||
case attr := <-wr.ReadAttribute():
|
||||
assert.Equal(t, ".gitignore\"\n", attr.Filename)
|
||||
assert.Equal(t, LinguistVendored, attr.Attribute)
|
||||
assert.Equal(t, "unspecified", attr.Value)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
assert.FailNow(t, "took too long to read an attribute from the list")
|
||||
}
|
||||
// Write a second attribute again
|
||||
n, err = wr.Write([]byte(testStr))
|
||||
|
||||
assert.Len(t, testStr, n)
|
||||
assert.NoError(t, err)
|
||||
|
||||
select {
|
||||
case attr := <-wr.ReadAttribute():
|
||||
assert.Equal(t, ".gitignore\"\n", attr.Filename)
|
||||
assert.Equal(t, LinguistVendored, attr.Attribute)
|
||||
assert.Equal(t, "unspecified", attr.Value)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
assert.FailNow(t, "took too long to read an attribute from the list")
|
||||
for range 2 {
|
||||
n, err := wr.Write([]byte(testStr))
|
||||
assert.Len(t, testStr, n)
|
||||
assert.NoError(t, err)
|
||||
select {
|
||||
case attr := <-wr.ReadAttribute():
|
||||
assert.Equal(t, ".gitignore\"\n", attr.Filename)
|
||||
assert.Equal(t, LinguistVendored, attr.Attribute)
|
||||
assert.Equal(t, "unspecified", attr.Value)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
assert.FailNow(t, "took too long to read an attribute from the list")
|
||||
}
|
||||
}
|
||||
|
||||
// Write a partial attribute
|
||||
_, err = wr.Write([]byte("incomplete-file"))
|
||||
_, err := wr.Write([]byte("incomplete-file"))
|
||||
assert.NoError(t, err)
|
||||
_, err = wr.Write([]byte("name\x00"))
|
||||
assert.NoError(t, err)
|
||||
|
||||
select {
|
||||
case <-wr.ReadAttribute():
|
||||
assert.FailNow(t, "There should not be an attribute ready to read")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
_, err = wr.Write([]byte("attribute\x00"))
|
||||
assert.NoError(t, err)
|
||||
select {
|
||||
case <-wr.ReadAttribute():
|
||||
assert.FailNow(t, "There should not be an attribute ready to read")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
for _, part := range []string{"name\x00", "attribute\x00"} {
|
||||
_, err = wr.Write([]byte(part))
|
||||
assert.NoError(t, err)
|
||||
select {
|
||||
case <-wr.ReadAttribute():
|
||||
assert.FailNow(t, "There should not be an attribute ready to read")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
_, err = wr.Write([]byte("value\x00"))
|
||||
@@ -79,27 +60,15 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
|
||||
|
||||
_, err = wr.Write([]byte("shouldbe.vendor\x00linguist-vendored\x00set\x00shouldbe.vendor\x00linguist-generated\x00unspecified\x00shouldbe.vendor\x00linguist-language\x00unspecified\x00"))
|
||||
assert.NoError(t, err)
|
||||
attr = <-wr.ReadAttribute()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, attributeTriple{
|
||||
Filename: "shouldbe.vendor",
|
||||
Attribute: LinguistVendored,
|
||||
Value: "set",
|
||||
}, attr)
|
||||
attr = <-wr.ReadAttribute()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, attributeTriple{
|
||||
Filename: "shouldbe.vendor",
|
||||
Attribute: LinguistGenerated,
|
||||
Value: "unspecified",
|
||||
}, attr)
|
||||
attr = <-wr.ReadAttribute()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, attributeTriple{
|
||||
Filename: "shouldbe.vendor",
|
||||
Attribute: LinguistLanguage,
|
||||
Value: "unspecified",
|
||||
}, attr)
|
||||
for _, expected := range []attributeTriple{
|
||||
{"shouldbe.vendor", LinguistVendored, "set"},
|
||||
{"shouldbe.vendor", LinguistGenerated, "unspecified"},
|
||||
{"shouldbe.vendor", LinguistLanguage, "unspecified"},
|
||||
} {
|
||||
attr = <-wr.ReadAttribute()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, attr)
|
||||
}
|
||||
}
|
||||
|
||||
func expectedAttrs() *Attributes {
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package git
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/setting"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestReadingBlameOutputSha256(t *testing.T) {
|
||||
setting.AppDataPath = t.TempDir()
|
||||
ctx := t.Context()
|
||||
|
||||
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := mockRepository("repo5_pulls_sha256")
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
commit, err := repo.GetCommit(t.Context(), "0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345")
|
||||
assert.NoError(t, err)
|
||||
|
||||
parts := []*BlamePart{
|
||||
{
|
||||
Sha: "1e35a51dc00fd7de730344c07061acfe80e8117e075ac979b6a29a3a045190ca",
|
||||
Lines: []string{
|
||||
"# test_repo",
|
||||
"Test repository for testing migration from github to gitea",
|
||||
},
|
||||
},
|
||||
{
|
||||
Sha: "0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345",
|
||||
Lines: []string{"", "Do not make any changes to this repo it is used for unit testing"},
|
||||
PreviousSha: "1e35a51dc00fd7de730344c07061acfe80e8117e075ac979b6a29a3a045190ca",
|
||||
PreviousPath: "README.md",
|
||||
},
|
||||
}
|
||||
|
||||
for _, bypass := range []bool{false, true} {
|
||||
blameReader, err := CreateBlameReader(ctx, Sha256ObjectFormat, storage, repo, commit, "README.md", bypass)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, blameReader)
|
||||
defer blameReader.Close()
|
||||
|
||||
assert.False(t, blameReader.UsesIgnoreRevs())
|
||||
|
||||
for _, part := range parts {
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, part, actualPart)
|
||||
}
|
||||
|
||||
// make sure all parts have been read
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.Nil(t, actualPart)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := mockRepository("repo6_blame_sha256")
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
full := []*BlamePart{
|
||||
{
|
||||
Sha: "ab2b57a4fa476fb2edb74dafa577caf918561abbaa8fba0c8dc63c412e17a7cc",
|
||||
Lines: []string{"line", "line"},
|
||||
},
|
||||
{
|
||||
Sha: "9347b0198cd1f25017579b79d0938fa89dba34ad2514f0dd92f6bc975ed1a2fe",
|
||||
Lines: []string{"changed line"},
|
||||
PreviousSha: "ab2b57a4fa476fb2edb74dafa577caf918561abbaa8fba0c8dc63c412e17a7cc",
|
||||
PreviousPath: "blame.txt",
|
||||
},
|
||||
{
|
||||
Sha: "ab2b57a4fa476fb2edb74dafa577caf918561abbaa8fba0c8dc63c412e17a7cc",
|
||||
Lines: []string{"line", "line", ""},
|
||||
},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
CommitID string
|
||||
UsesIgnoreRevs bool
|
||||
Bypass bool
|
||||
Parts []*BlamePart
|
||||
}{
|
||||
{
|
||||
CommitID: "e2f5660e15159082902960af0ed74fc144921d2b0c80e069361853b3ece29ba3",
|
||||
UsesIgnoreRevs: true,
|
||||
Bypass: false,
|
||||
Parts: []*BlamePart{
|
||||
{
|
||||
Sha: "ab2b57a4fa476fb2edb74dafa577caf918561abbaa8fba0c8dc63c412e17a7cc",
|
||||
Lines: []string{"line", "line", "changed line", "line", "line", ""},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
CommitID: "e2f5660e15159082902960af0ed74fc144921d2b0c80e069361853b3ece29ba3",
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: true,
|
||||
Parts: full,
|
||||
},
|
||||
{
|
||||
CommitID: "9347b0198cd1f25017579b79d0938fa89dba34ad2514f0dd92f6bc975ed1a2fe",
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: false,
|
||||
Parts: full,
|
||||
},
|
||||
{
|
||||
CommitID: "9347b0198cd1f25017579b79d0938fa89dba34ad2514f0dd92f6bc975ed1a2fe",
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: false,
|
||||
Parts: full,
|
||||
},
|
||||
}
|
||||
|
||||
objectFormat, err := repo.GetObjectFormat(t.Context())
|
||||
assert.NoError(t, err)
|
||||
for _, c := range cases {
|
||||
commit, err := repo.GetCommit(t.Context(), c.CommitID)
|
||||
assert.NoError(t, err)
|
||||
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, blameReader)
|
||||
defer blameReader.Close()
|
||||
|
||||
assert.Equal(t, c.UsesIgnoreRevs, blameReader.UsesIgnoreRevs())
|
||||
|
||||
for _, part := range c.Parts {
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, part, actualPart)
|
||||
}
|
||||
|
||||
// make sure all parts have been read
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.Nil(t, actualPart)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
+155
-122
@@ -24,137 +24,170 @@ func TestLineBlameCommitID(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestReadingBlameOutput(t *testing.T) {
|
||||
setting.AppDataPath = t.TempDir()
|
||||
ctx := t.Context()
|
||||
for _, scenario := range []struct {
|
||||
name string
|
||||
repositorySuffix string
|
||||
objectFormat ObjectFormat
|
||||
readmeCommit string
|
||||
readmePrevious string
|
||||
blameCommit string
|
||||
blameChanged string
|
||||
blameOriginal string
|
||||
}{
|
||||
{
|
||||
name: "sha1",
|
||||
objectFormat: Sha1ObjectFormat,
|
||||
readmeCommit: "f32b0a9dfd09a60f616f29158f772cedd89942d2",
|
||||
readmePrevious: "72866af952e98d02a73003501836074b286a78f6",
|
||||
blameCommit: "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7",
|
||||
blameChanged: "45fb6cbc12f970b04eacd5cd4165edd11c8d7376",
|
||||
blameOriginal: "af7486bd54cfc39eea97207ca666aa69c9d6df93",
|
||||
},
|
||||
{
|
||||
name: "sha256",
|
||||
repositorySuffix: "_sha256",
|
||||
objectFormat: Sha256ObjectFormat,
|
||||
readmeCommit: "0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345",
|
||||
readmePrevious: "1e35a51dc00fd7de730344c07061acfe80e8117e075ac979b6a29a3a045190ca",
|
||||
blameCommit: "e2f5660e15159082902960af0ed74fc144921d2b0c80e069361853b3ece29ba3",
|
||||
blameChanged: "9347b0198cd1f25017579b79d0938fa89dba34ad2514f0dd92f6bc975ed1a2fe",
|
||||
blameOriginal: "ab2b57a4fa476fb2edb74dafa577caf918561abbaa8fba0c8dc63c412e17a7cc",
|
||||
},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
setting.AppDataPath = t.TempDir()
|
||||
ctx := t.Context()
|
||||
|
||||
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := mockRepository("repo5_pulls")
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
commit, err := repo.GetCommit(t.Context(), "f32b0a9dfd09a60f616f29158f772cedd89942d2")
|
||||
assert.NoError(t, err)
|
||||
|
||||
parts := []*BlamePart{
|
||||
{
|
||||
Sha: "72866af952e98d02a73003501836074b286a78f6",
|
||||
Lines: []string{
|
||||
"# test_repo",
|
||||
"Test repository for testing migration from github to gitea",
|
||||
},
|
||||
},
|
||||
{
|
||||
Sha: "f32b0a9dfd09a60f616f29158f772cedd89942d2",
|
||||
Lines: []string{"", "Do not make any changes to this repo it is used for unit testing"},
|
||||
PreviousSha: "72866af952e98d02a73003501836074b286a78f6",
|
||||
PreviousPath: "README.md",
|
||||
},
|
||||
}
|
||||
|
||||
for _, bypass := range []bool{false, true} {
|
||||
blameReader, err := CreateBlameReader(ctx, Sha1ObjectFormat, storage, repo, commit, "README.md", bypass)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, blameReader)
|
||||
defer blameReader.Close()
|
||||
|
||||
assert.False(t, blameReader.UsesIgnoreRevs())
|
||||
|
||||
for _, part := range parts {
|
||||
actualPart, err := blameReader.NextPart()
|
||||
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := mockRepository("repo5_pulls" + scenario.repositorySuffix)
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
commit, err := repo.GetCommit(t.Context(), scenario.readmeCommit)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, part, actualPart)
|
||||
}
|
||||
|
||||
// make sure all parts have been read
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.Nil(t, actualPart)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := mockRepository("repo6_blame")
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
full := []*BlamePart{
|
||||
{
|
||||
Sha: "af7486bd54cfc39eea97207ca666aa69c9d6df93",
|
||||
Lines: []string{"line", "line"},
|
||||
},
|
||||
{
|
||||
Sha: "45fb6cbc12f970b04eacd5cd4165edd11c8d7376",
|
||||
Lines: []string{"changed line"},
|
||||
PreviousSha: "af7486bd54cfc39eea97207ca666aa69c9d6df93",
|
||||
PreviousPath: "blame.txt",
|
||||
},
|
||||
{
|
||||
Sha: "af7486bd54cfc39eea97207ca666aa69c9d6df93",
|
||||
Lines: []string{"line", "line", ""},
|
||||
},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
CommitID string
|
||||
UsesIgnoreRevs bool
|
||||
Bypass bool
|
||||
Parts []*BlamePart
|
||||
}{
|
||||
{
|
||||
CommitID: "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7",
|
||||
UsesIgnoreRevs: true,
|
||||
Bypass: false,
|
||||
Parts: []*BlamePart{
|
||||
parts := []*BlamePart{
|
||||
{
|
||||
Sha: "af7486bd54cfc39eea97207ca666aa69c9d6df93",
|
||||
Lines: []string{"line", "line", "changed line", "line", "line", ""},
|
||||
Sha: scenario.readmePrevious,
|
||||
Lines: []string{
|
||||
"# test_repo",
|
||||
"Test repository for testing migration from github to gitea",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
CommitID: "544d8f7a3b15927cddf2299b4b562d6ebd71b6a7",
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: true,
|
||||
Parts: full,
|
||||
},
|
||||
{
|
||||
CommitID: "45fb6cbc12f970b04eacd5cd4165edd11c8d7376",
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: false,
|
||||
Parts: full,
|
||||
},
|
||||
{
|
||||
CommitID: "45fb6cbc12f970b04eacd5cd4165edd11c8d7376",
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: false,
|
||||
Parts: full,
|
||||
},
|
||||
}
|
||||
{
|
||||
Sha: scenario.readmeCommit,
|
||||
Lines: []string{"", "Do not make any changes to this repo it is used for unit testing"},
|
||||
PreviousSha: scenario.readmePrevious,
|
||||
PreviousPath: "README.md",
|
||||
},
|
||||
}
|
||||
|
||||
objectFormat, err := repo.GetObjectFormat(t.Context())
|
||||
assert.NoError(t, err)
|
||||
for _, c := range cases {
|
||||
commit, err := repo.GetCommit(t.Context(), c.CommitID)
|
||||
assert.NoError(t, err)
|
||||
for _, bypass := range []bool{false, true} {
|
||||
blameReader, err := CreateBlameReader(ctx, scenario.objectFormat, storage, repo, commit, "README.md", bypass)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, blameReader)
|
||||
defer blameReader.Close()
|
||||
|
||||
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, blameReader)
|
||||
defer blameReader.Close()
|
||||
assert.False(t, blameReader.UsesIgnoreRevs())
|
||||
|
||||
assert.Equal(t, c.UsesIgnoreRevs, blameReader.UsesIgnoreRevs())
|
||||
for _, part := range parts {
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, part, actualPart)
|
||||
}
|
||||
|
||||
for _, part := range c.Parts {
|
||||
actualPart, err := blameReader.NextPart()
|
||||
// make sure all parts have been read
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.Nil(t, actualPart)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("With .git-blame-ignore-revs", func(t *testing.T) {
|
||||
storage := mockRepository("repo6_blame" + scenario.repositorySuffix)
|
||||
repo, err := OpenRepository(ctx, storage)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, part, actualPart)
|
||||
}
|
||||
defer repo.Close()
|
||||
|
||||
// make sure all parts have been read
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.Nil(t, actualPart)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
full := []*BlamePart{
|
||||
{
|
||||
Sha: scenario.blameOriginal,
|
||||
Lines: []string{"line", "line"},
|
||||
},
|
||||
{
|
||||
Sha: scenario.blameChanged,
|
||||
Lines: []string{"changed line"},
|
||||
PreviousSha: scenario.blameOriginal,
|
||||
PreviousPath: "blame.txt",
|
||||
},
|
||||
{
|
||||
Sha: scenario.blameOriginal,
|
||||
Lines: []string{"line", "line", ""},
|
||||
},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
CommitID string
|
||||
UsesIgnoreRevs bool
|
||||
Bypass bool
|
||||
Parts []*BlamePart
|
||||
}{
|
||||
{
|
||||
CommitID: scenario.blameCommit,
|
||||
UsesIgnoreRevs: true,
|
||||
Bypass: false,
|
||||
Parts: []*BlamePart{
|
||||
{
|
||||
Sha: scenario.blameOriginal,
|
||||
Lines: []string{"line", "line", "changed line", "line", "line", ""},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
CommitID: scenario.blameCommit,
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: true,
|
||||
Parts: full,
|
||||
},
|
||||
{
|
||||
CommitID: scenario.blameChanged,
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: false,
|
||||
Parts: full,
|
||||
},
|
||||
{
|
||||
CommitID: scenario.blameChanged,
|
||||
UsesIgnoreRevs: false,
|
||||
Bypass: false,
|
||||
Parts: full,
|
||||
},
|
||||
}
|
||||
|
||||
objectFormat, err := repo.GetObjectFormat(t.Context())
|
||||
assert.NoError(t, err)
|
||||
for _, c := range cases {
|
||||
commit, err := repo.GetCommit(t.Context(), c.CommitID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
blameReader, err := CreateBlameReader(ctx, objectFormat, storage, repo, commit, "blame.txt", c.Bypass)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, blameReader)
|
||||
defer blameReader.Close()
|
||||
|
||||
assert.Equal(t, c.UsesIgnoreRevs, blameReader.UsesIgnoreRevs())
|
||||
|
||||
for _, part := range c.Parts {
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, part, actualPart)
|
||||
}
|
||||
|
||||
// make sure all parts have been read
|
||||
actualPart, err := blameReader.NextPart()
|
||||
assert.Nil(t, actualPart)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
+10
-41
@@ -11,60 +11,29 @@ import (
|
||||
|
||||
func TestCommitsCount(t *testing.T) {
|
||||
bareRepo1 := mockRepository("repo1_bare")
|
||||
|
||||
commitsCount, err := CommitsCount(t.Context(), bareRepo1,
|
||||
CommitsCountOptions{
|
||||
Revision: []string{"8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"},
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(3), commitsCount)
|
||||
}
|
||||
|
||||
func TestCommitsCountWithSinceUntil(t *testing.T) {
|
||||
bareRepo1 := mockRepository("repo1_bare")
|
||||
revision := []string{"8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"}
|
||||
|
||||
// The three commits on this revision are dated 2018-04-18, 2017-12-19 and 2017-12-19.
|
||||
cases := []struct {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
since string
|
||||
until string
|
||||
options CommitsCountOptions
|
||||
expected int64
|
||||
}{
|
||||
{name: "no filter", expected: 3},
|
||||
{name: "since keeps newer commits", since: "2018-01-01", expected: 1},
|
||||
{name: "until keeps older commits", until: "2018-01-01", expected: 2},
|
||||
{name: "since and until bound the range", since: "2017-12-19T22:16:00-08:00", until: "2018-01-01", expected: 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
{"revision", CommitsCountOptions{Revision: revision}, 3},
|
||||
{"no filter", CommitsCountOptions{Revision: revision}, 3},
|
||||
{"since keeps newer commits", CommitsCountOptions{Revision: revision, Since: "2018-01-01"}, 1},
|
||||
{"until keeps older commits", CommitsCountOptions{Revision: revision, Until: "2018-01-01"}, 2},
|
||||
{"since and until bound the range", CommitsCountOptions{Revision: revision, Since: "2017-12-19T22:16:00-08:00", Until: "2018-01-01"}, 1},
|
||||
{"without base", CommitsCountOptions{Not: "master", Revision: []string{"branch1"}}, 2},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
commitsCount, err := CommitsCount(t.Context(), bareRepo1,
|
||||
CommitsCountOptions{
|
||||
Revision: revision,
|
||||
Since: tc.since,
|
||||
Until: tc.until,
|
||||
})
|
||||
|
||||
commitsCount, err := CommitsCount(t.Context(), bareRepo1, tc.options)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.expected, commitsCount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommitsCountWithoutBase(t *testing.T) {
|
||||
bareRepo1 := mockRepository("repo1_bare")
|
||||
|
||||
commitsCount, err := CommitsCount(t.Context(), bareRepo1,
|
||||
CommitsCountOptions{
|
||||
Not: "master",
|
||||
Revision: []string{"branch1"},
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), commitsCount)
|
||||
}
|
||||
|
||||
func TestGetLatestCommitTime(t *testing.T) {
|
||||
bareRepo1 := mockRepository("repo1_bare")
|
||||
lct, err := GetLatestCommitTime(t.Context(), bareRepo1)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
func TestParseCommitFileStatus(t *testing.T) {
|
||||
type testcase struct {
|
||||
output string
|
||||
outputs []string
|
||||
added []string
|
||||
removed []string
|
||||
modified []string
|
||||
@@ -21,7 +21,11 @@ func TestParseCommitFileStatus(t *testing.T) {
|
||||
kases := []testcase{
|
||||
{
|
||||
// Merge commit
|
||||
output: "MM\x00options/locale/locale_en-US.ini\x00",
|
||||
outputs: []string{
|
||||
"MM\x00options/locale/locale_en-US.ini\x00",
|
||||
// git 1.7.2 adds an unnecessary \x00 on merge commit
|
||||
"\x00MM\x00options/locale/locale_en-US.ini\x00",
|
||||
},
|
||||
modified: []string{
|
||||
"options/locale/locale_en-US.ini",
|
||||
},
|
||||
@@ -30,7 +34,11 @@ func TestParseCommitFileStatus(t *testing.T) {
|
||||
},
|
||||
{
|
||||
// Spaces commit
|
||||
output: "D\x00b\x00D\x00b b/b\x00A\x00b b/b b/b b/b\x00A\x00b b/b b/b b/b b/b\x00",
|
||||
outputs: []string{
|
||||
"D\x00b\x00D\x00b b/b\x00A\x00b b/b b/b b/b\x00A\x00b b/b b/b b/b b/b\x00",
|
||||
// git 1.7.2 adds an unnecessary \n on normal commit
|
||||
"\nD\x00b\x00D\x00b b/b\x00A\x00b b/b b/b b/b\x00A\x00b b/b b/b b/b b/b\x00",
|
||||
},
|
||||
removed: []string{
|
||||
"b",
|
||||
"b b/b",
|
||||
@@ -43,7 +51,7 @@ func TestParseCommitFileStatus(t *testing.T) {
|
||||
},
|
||||
{
|
||||
// larger commit
|
||||
output: "M\x00go.mod\x00M\x00go.sum\x00M\x00modules/ssh/ssh.go\x00M\x00vendor/github.com/gliderlabs/ssh/circle.yml\x00M\x00vendor/github.com/gliderlabs/ssh/context.go\x00A\x00vendor/github.com/gliderlabs/ssh/go.mod\x00A\x00vendor/github.com/gliderlabs/ssh/go.sum\x00M\x00vendor/github.com/gliderlabs/ssh/server.go\x00M\x00vendor/github.com/gliderlabs/ssh/session.go\x00M\x00vendor/github.com/gliderlabs/ssh/ssh.go\x00M\x00vendor/golang.org/x/sys/unix/mkerrors.sh\x00M\x00vendor/golang.org/x/sys/unix/syscall_darwin.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_linux.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go\x00M\x00vendor/modules.txt\x00",
|
||||
outputs: []string{"M\x00go.mod\x00M\x00go.sum\x00M\x00modules/ssh/ssh.go\x00M\x00vendor/github.com/gliderlabs/ssh/circle.yml\x00M\x00vendor/github.com/gliderlabs/ssh/context.go\x00A\x00vendor/github.com/gliderlabs/ssh/go.mod\x00A\x00vendor/github.com/gliderlabs/ssh/go.sum\x00M\x00vendor/github.com/gliderlabs/ssh/server.go\x00M\x00vendor/github.com/gliderlabs/ssh/session.go\x00M\x00vendor/github.com/gliderlabs/ssh/ssh.go\x00M\x00vendor/golang.org/x/sys/unix/mkerrors.sh\x00M\x00vendor/golang.org/x/sys/unix/syscall_darwin.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/zerrors_linux.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go\x00M\x00vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go\x00M\x00vendor/modules.txt\x00"},
|
||||
modified: []string{
|
||||
"go.mod",
|
||||
"go.sum",
|
||||
@@ -81,37 +89,17 @@ func TestParseCommitFileStatus(t *testing.T) {
|
||||
},
|
||||
removed: []string{},
|
||||
},
|
||||
{
|
||||
// git 1.7.2 adds an unnecessary \x00 on merge commit
|
||||
output: "\x00MM\x00options/locale/locale_en-US.ini\x00",
|
||||
modified: []string{
|
||||
"options/locale/locale_en-US.ini",
|
||||
},
|
||||
added: []string{},
|
||||
removed: []string{},
|
||||
},
|
||||
{
|
||||
// git 1.7.2 adds an unnecessary \n on normal commit
|
||||
output: "\nD\x00b\x00D\x00b b/b\x00A\x00b b/b b/b b/b\x00A\x00b b/b b/b b/b b/b\x00",
|
||||
removed: []string{
|
||||
"b",
|
||||
"b b/b",
|
||||
},
|
||||
modified: []string{},
|
||||
added: []string{
|
||||
"b b/b b/b b/b",
|
||||
"b b/b b/b b/b b/b",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, kase := range kases {
|
||||
fileStatus := NewCommitFileStatus()
|
||||
parseCommitFileStatus(fileStatus, strings.NewReader(kase.output))
|
||||
for _, output := range kase.outputs {
|
||||
fileStatus := NewCommitFileStatus()
|
||||
parseCommitFileStatus(fileStatus, strings.NewReader(output))
|
||||
|
||||
assert.Equal(t, kase.added, fileStatus.Added)
|
||||
assert.Equal(t, kase.removed, fileStatus.Removed)
|
||||
assert.Equal(t, kase.modified, fileStatus.Modified)
|
||||
assert.Equal(t, kase.added, fileStatus.Added)
|
||||
assert.Equal(t, kase.removed, fileStatus.Removed)
|
||||
assert.Equal(t, kase.modified, fileStatus.Modified)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,35 +129,23 @@ func TestGetCommitFileStatusMerges(t *testing.T) {
|
||||
func TestGetCommitFileStatusMergesSha256(t *testing.T) {
|
||||
bareRepo6Sha256 := mockRepository("repo6_merge_sha256")
|
||||
|
||||
commitFileStatus, err := GetCommitFileStatus(t.Context(), bareRepo6Sha256, "d2e5609f630dd8db500f5298d05d16def282412e3e66ed68cc7d0833b29129a1")
|
||||
assert.NoError(t, err)
|
||||
|
||||
expected := CommitFileStatus{
|
||||
[]string{
|
||||
"add_file.txt",
|
||||
for _, tc := range []struct {
|
||||
commitID string
|
||||
expected CommitFileStatus
|
||||
}{
|
||||
{
|
||||
"d2e5609f630dd8db500f5298d05d16def282412e3e66ed68cc7d0833b29129a1",
|
||||
CommitFileStatus{[]string{"add_file.txt"}, []string{}, []string{"to_modify.txt"}},
|
||||
},
|
||||
[]string{},
|
||||
[]string{
|
||||
"to_modify.txt",
|
||||
{
|
||||
"da1ded40dc8e5b7c564171f4bf2fc8370487decfb1cb6a99ef28f3ed73d09172",
|
||||
CommitFileStatus{[]string{}, []string{"to_remove.txt"}, []string{}},
|
||||
},
|
||||
} {
|
||||
commitFileStatus, err := GetCommitFileStatus(t.Context(), bareRepo6Sha256, tc.commitID)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.expected.Added, commitFileStatus.Added)
|
||||
assert.Equal(t, tc.expected.Removed, commitFileStatus.Removed)
|
||||
assert.Equal(t, tc.expected.Modified, commitFileStatus.Modified)
|
||||
}
|
||||
|
||||
assert.Equal(t, expected.Added, commitFileStatus.Added)
|
||||
assert.Equal(t, expected.Removed, commitFileStatus.Removed)
|
||||
assert.Equal(t, expected.Modified, commitFileStatus.Modified)
|
||||
|
||||
expected = CommitFileStatus{
|
||||
[]string{},
|
||||
[]string{
|
||||
"to_remove.txt",
|
||||
},
|
||||
[]string{},
|
||||
}
|
||||
|
||||
commitFileStatus, err = GetCommitFileStatus(t.Context(), bareRepo6Sha256, "da1ded40dc8e5b7c564171f4bf2fc8370487decfb1cb6a99ef28f3ed73d09172")
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, expected.Added, commitFileStatus.Added)
|
||||
assert.Equal(t, expected.Removed, commitFileStatus.Removed)
|
||||
assert.Equal(t, expected.Modified, commitFileStatus.Modified)
|
||||
}
|
||||
@@ -5,11 +5,9 @@ package git
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetFullCommitIDSha256(t *testing.T) {
|
||||
@@ -26,74 +24,6 @@ func TestGetFullCommitIDErrorSha256(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommitFromReaderSha256(t *testing.T) {
|
||||
commitString := `tree e7f9e96dd79c09b078cac8b303a7d3b9d65ff9b734e86060a4d20409fd379f9e
|
||||
parent 26e9ccc29fad747e9c5d9f4c9ddeb7eff61cc45ef6a8dc258cbeb181afc055e8
|
||||
author Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
committer Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
gpgsig-sha256 -----BEGIN PGP SIGNATURE-----
|
||||
` + " " + `
|
||||
iQIrBAABCgAtFiEES+fB08xlgTrzSdQvhkUIsBsmec8FAmU/wKoPHGFtYWplckBz
|
||||
dXNlLmRlAAoJEIZFCLAbJnnP4s4PQIJATa++WPzR6/H4etT7bsOGoMyguEJYyWOd
|
||||
aTybplzT7QAL7h2to0QszGabtzMJPIA39xSFZNYNN30voK5YyyYibXluPKgjemfK
|
||||
WNXwF+gkwgZI38gSvKf+vlqI+EYyIFe19wOhiju0m8SIlB5NEPiWHa17q2mqmqqx
|
||||
1FWa2JdqLPYjAtSLFXeSZegrY5V1FxdemyMUONkg8YO9OSIMZiE0GsnnOXQ3xcT4
|
||||
JTCnmlUxIKw689UiEY80JopUIq+Wl7+qq9507IYYSUCyB6JazL42AKMzVCbD+qBP
|
||||
oOzh/hafYgk9H9qCQXaLbmvs17zXRpicig1bAzqgAy1FDelvpERyRTydEajSLIG6
|
||||
U1cRCkgXCZ0NfsYNPPmBa8b3+rnstypXYTbyMwTln7FfUAaGo6o9JYiPMkzxlmsy
|
||||
zfp/tcaY8+LlBL9aOJjtv+a0p+HrpCGd6CCa4ARfphTLq8QRSSh8uzlB9N+6HnRI
|
||||
VAEUo6ecdDxSpyt2naeg9pKus/BRi7P6g4B1hkk/zZstUX/QP4IQuAJbXjkvsC+X
|
||||
HKRr3NlRM/DygzTyj0gN74uoa0goCIbyAQhiT42nm0cuhM7uN/W0ayrlZjGF1cbR
|
||||
8NCJUL2Nwj0ywKIavC99Ipkb8AsFwpVT6U6effs6
|
||||
=xybZ
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
signed commit`
|
||||
|
||||
sha := &Sha256Hash{
|
||||
0x94, 0x33, 0xb2, 0xa6, 0x2b, 0x96, 0x4c, 0x17, 0xa4, 0x48, 0x5a, 0xe1, 0x80, 0xf4, 0x5f, 0x59,
|
||||
0x5d, 0x3e, 0x69, 0xd3, 0x1b, 0x78, 0x60, 0x87, 0x77, 0x5e, 0x28, 0xc6, 0xb6, 0x39, 0x9d, 0xf0,
|
||||
}
|
||||
gitRepo, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "repo1_bare_sha256"))
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
|
||||
commitFromReader, err := CommitFromReader(sha, strings.NewReader(commitString))
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, commitFromReader)
|
||||
assert.EqualValues(t, sha, commitFromReader.ID)
|
||||
assert.Equal(t, `-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
iQIrBAABCgAtFiEES+fB08xlgTrzSdQvhkUIsBsmec8FAmU/wKoPHGFtYWplckBz
|
||||
dXNlLmRlAAoJEIZFCLAbJnnP4s4PQIJATa++WPzR6/H4etT7bsOGoMyguEJYyWOd
|
||||
aTybplzT7QAL7h2to0QszGabtzMJPIA39xSFZNYNN30voK5YyyYibXluPKgjemfK
|
||||
WNXwF+gkwgZI38gSvKf+vlqI+EYyIFe19wOhiju0m8SIlB5NEPiWHa17q2mqmqqx
|
||||
1FWa2JdqLPYjAtSLFXeSZegrY5V1FxdemyMUONkg8YO9OSIMZiE0GsnnOXQ3xcT4
|
||||
JTCnmlUxIKw689UiEY80JopUIq+Wl7+qq9507IYYSUCyB6JazL42AKMzVCbD+qBP
|
||||
oOzh/hafYgk9H9qCQXaLbmvs17zXRpicig1bAzqgAy1FDelvpERyRTydEajSLIG6
|
||||
U1cRCkgXCZ0NfsYNPPmBa8b3+rnstypXYTbyMwTln7FfUAaGo6o9JYiPMkzxlmsy
|
||||
zfp/tcaY8+LlBL9aOJjtv+a0p+HrpCGd6CCa4ARfphTLq8QRSSh8uzlB9N+6HnRI
|
||||
VAEUo6ecdDxSpyt2naeg9pKus/BRi7P6g4B1hkk/zZstUX/QP4IQuAJbXjkvsC+X
|
||||
HKRr3NlRM/DygzTyj0gN74uoa0goCIbyAQhiT42nm0cuhM7uN/W0ayrlZjGF1cbR
|
||||
8NCJUL2Nwj0ywKIavC99Ipkb8AsFwpVT6U6effs6
|
||||
=xybZ
|
||||
-----END PGP SIGNATURE-----`, commitFromReader.Signature.Signature)
|
||||
assert.Equal(t, `tree e7f9e96dd79c09b078cac8b303a7d3b9d65ff9b734e86060a4d20409fd379f9e
|
||||
parent 26e9ccc29fad747e9c5d9f4c9ddeb7eff61cc45ef6a8dc258cbeb181afc055e8
|
||||
author Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
committer Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
|
||||
signed commit`, commitFromReader.Signature.Payload)
|
||||
assert.Equal(t, "Adam Majer <amajer@suse.de>", commitFromReader.Author.String())
|
||||
|
||||
commitFromReader2, err := CommitFromReader(sha, strings.NewReader(commitString+"\n\n"))
|
||||
assert.NoError(t, err)
|
||||
commitFromReader.CommitMessage.MessageRaw += "\n\n"
|
||||
commitFromReader.Signature.Payload += "\n\n"
|
||||
assert.Equal(t, commitFromReader, commitFromReader2)
|
||||
}
|
||||
|
||||
func TestHasPreviousCommitSha256(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256")
|
||||
|
||||
|
||||
+100
-50
@@ -28,7 +28,15 @@ func TestGetFullCommitIDError(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCommitFromReader(t *testing.T) {
|
||||
commitString := `tree f1a6cb52b2d16773290cefe49ad0684b50a4f930
|
||||
for _, testCase := range []struct {
|
||||
name, repo string
|
||||
sha ObjectID
|
||||
commitString, signature, payload, author string
|
||||
}{
|
||||
{
|
||||
"TestCommitFromReader", "repo1_bare",
|
||||
&Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2},
|
||||
`tree f1a6cb52b2d16773290cefe49ad0684b50a4f930
|
||||
parent 37991dec2c8e592043f47155ce4808d4580f9123
|
||||
author silverwind <me@silverwind.io> 1563741793 +0200
|
||||
committer silverwind <me@silverwind.io> 1563741793 +0200
|
||||
@@ -49,19 +57,8 @@ gpgsig -----BEGIN PGP SIGNATURE-----
|
||||
=FRsO
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
empty commit`
|
||||
|
||||
sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2}
|
||||
gitRepo, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
|
||||
commitFromReader, err := CommitFromReader(sha, strings.NewReader(commitString))
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, commitFromReader)
|
||||
assert.EqualValues(t, sha, commitFromReader.ID)
|
||||
assert.Equal(t, `-----BEGIN PGP SIGNATURE-----
|
||||
empty commit`,
|
||||
`-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
iQIzBAABCAAdFiEEWPb2jX6FS2mqyJRQLmK0HJOGlEMFAl00zmEACgkQLmK0HJOG
|
||||
lEMDFBAAhQKKqLD1VICygJMEB8t1gBmNLgvziOLfpX4KPWdPtBk3v/QJ7OrfMrVK
|
||||
@@ -76,24 +73,19 @@ sD53z/f0J+We4VZjY+pidvA9BGZPFVdR3wd3xGs8/oH6UWaLJAMGkLG6dDb3qDLm
|
||||
mfeFhT57UbE4qukTDIQ0Y0WM40UYRTakRaDY7ubhXgLgx09Cnp9XTVMsHgT6j9/i
|
||||
1pxsB104XLWjQHTjr1JtiaBQEwFh9r2OKTcpvaLcbNtYpo7CzOs=
|
||||
=FRsO
|
||||
-----END PGP SIGNATURE-----`, commitFromReader.Signature.Signature)
|
||||
assert.Equal(t, `tree f1a6cb52b2d16773290cefe49ad0684b50a4f930
|
||||
-----END PGP SIGNATURE-----`,
|
||||
`tree f1a6cb52b2d16773290cefe49ad0684b50a4f930
|
||||
parent 37991dec2c8e592043f47155ce4808d4580f9123
|
||||
author silverwind <me@silverwind.io> 1563741793 +0200
|
||||
committer silverwind <me@silverwind.io> 1563741793 +0200
|
||||
|
||||
empty commit`, commitFromReader.Signature.Payload)
|
||||
assert.Equal(t, "silverwind <me@silverwind.io>", commitFromReader.Author.String())
|
||||
|
||||
commitFromReader2, err := CommitFromReader(sha, strings.NewReader(commitString+"\n\n"))
|
||||
assert.NoError(t, err)
|
||||
commitFromReader.CommitMessage.MessageRaw += "\n\n"
|
||||
commitFromReader.Signature.Payload += "\n\n"
|
||||
assert.Equal(t, commitFromReader, commitFromReader2)
|
||||
}
|
||||
|
||||
func TestCommitWithEncodingFromReader(t *testing.T) {
|
||||
commitString := `tree ca3fad42080dd1a6d291b75acdfc46e5b9b307e5
|
||||
empty commit`,
|
||||
"silverwind <me@silverwind.io>",
|
||||
},
|
||||
{
|
||||
"TestCommitWithEncodingFromReader", "repo1_bare",
|
||||
&Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2},
|
||||
strings.ReplaceAll(`tree ca3fad42080dd1a6d291b75acdfc46e5b9b307e5
|
||||
parent 47b24e7ab977ed31c5a39989d570847d6d0052af
|
||||
author KN4CK3R <admin@oldschoolhack.me> 1711702962 +0100
|
||||
committer KN4CK3R <admin@oldschoolhack.me> 1711702962 +0100
|
||||
@@ -113,19 +105,8 @@ gpgsig -----BEGIN PGP SIGNATURE-----
|
||||
=r3UU
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
ISO-8859-1`
|
||||
commitString = strings.ReplaceAll(commitString, "<SPACE>", " ")
|
||||
sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2}
|
||||
gitRepo, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
|
||||
commitFromReader, err := CommitFromReader(sha, strings.NewReader(commitString))
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, commitFromReader)
|
||||
assert.EqualValues(t, sha, commitFromReader.ID)
|
||||
assert.Equal(t, `-----BEGIN PGP SIGNATURE-----
|
||||
ISO-8859-1`, "<SPACE>", " "),
|
||||
`-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
iQGzBAABCgAdFiEE9HRrbqvYxPT8PXbefPSEkrowAa8FAmYGg7IACgkQfPSEkrow
|
||||
Aa9olwv+P0HhtCM6CRvlUmPaqswRsDPNR4i66xyXGiSxdI9V5oJL7HLiQIM7KrFR
|
||||
@@ -138,21 +119,90 @@ SONRzusmu5n3DgV956REL7x62h7JuqmBz/12HZkr0z0zgXkcZ04q08pSJATX5N1F
|
||||
yN+tWxTsWg+zhDk96d5Esdo9JMjcFvPv0eioo30GAERaz1hoD7zCMT4jgUFTQwgz
|
||||
jw4YcO5u
|
||||
=r3UU
|
||||
-----END PGP SIGNATURE-----`, commitFromReader.Signature.Signature)
|
||||
assert.Equal(t, `tree ca3fad42080dd1a6d291b75acdfc46e5b9b307e5
|
||||
-----END PGP SIGNATURE-----`,
|
||||
`tree ca3fad42080dd1a6d291b75acdfc46e5b9b307e5
|
||||
parent 47b24e7ab977ed31c5a39989d570847d6d0052af
|
||||
author KN4CK3R <admin@oldschoolhack.me> 1711702962 +0100
|
||||
committer KN4CK3R <admin@oldschoolhack.me> 1711702962 +0100
|
||||
encoding ISO-8859-1
|
||||
|
||||
ISO-8859-1`, commitFromReader.Signature.Payload)
|
||||
assert.Equal(t, "KN4CK3R <admin@oldschoolhack.me>", commitFromReader.Author.String())
|
||||
ISO-8859-1`,
|
||||
"KN4CK3R <admin@oldschoolhack.me>",
|
||||
},
|
||||
{
|
||||
"TestCommitFromReaderSha256", "repo1_bare_sha256",
|
||||
&Sha256Hash{
|
||||
0x94, 0x33, 0xb2, 0xa6, 0x2b, 0x96, 0x4c, 0x17, 0xa4, 0x48, 0x5a, 0xe1, 0x80, 0xf4, 0x5f, 0x59,
|
||||
0x5d, 0x3e, 0x69, 0xd3, 0x1b, 0x78, 0x60, 0x87, 0x77, 0x5e, 0x28, 0xc6, 0xb6, 0x39, 0x9d, 0xf0,
|
||||
},
|
||||
`tree e7f9e96dd79c09b078cac8b303a7d3b9d65ff9b734e86060a4d20409fd379f9e
|
||||
parent 26e9ccc29fad747e9c5d9f4c9ddeb7eff61cc45ef6a8dc258cbeb181afc055e8
|
||||
author Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
committer Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
gpgsig-sha256 -----BEGIN PGP SIGNATURE-----
|
||||
` + " " + `
|
||||
iQIrBAABCgAtFiEES+fB08xlgTrzSdQvhkUIsBsmec8FAmU/wKoPHGFtYWplckBz
|
||||
dXNlLmRlAAoJEIZFCLAbJnnP4s4PQIJATa++WPzR6/H4etT7bsOGoMyguEJYyWOd
|
||||
aTybplzT7QAL7h2to0QszGabtzMJPIA39xSFZNYNN30voK5YyyYibXluPKgjemfK
|
||||
WNXwF+gkwgZI38gSvKf+vlqI+EYyIFe19wOhiju0m8SIlB5NEPiWHa17q2mqmqqx
|
||||
1FWa2JdqLPYjAtSLFXeSZegrY5V1FxdemyMUONkg8YO9OSIMZiE0GsnnOXQ3xcT4
|
||||
JTCnmlUxIKw689UiEY80JopUIq+Wl7+qq9507IYYSUCyB6JazL42AKMzVCbD+qBP
|
||||
oOzh/hafYgk9H9qCQXaLbmvs17zXRpicig1bAzqgAy1FDelvpERyRTydEajSLIG6
|
||||
U1cRCkgXCZ0NfsYNPPmBa8b3+rnstypXYTbyMwTln7FfUAaGo6o9JYiPMkzxlmsy
|
||||
zfp/tcaY8+LlBL9aOJjtv+a0p+HrpCGd6CCa4ARfphTLq8QRSSh8uzlB9N+6HnRI
|
||||
VAEUo6ecdDxSpyt2naeg9pKus/BRi7P6g4B1hkk/zZstUX/QP4IQuAJbXjkvsC+X
|
||||
HKRr3NlRM/DygzTyj0gN74uoa0goCIbyAQhiT42nm0cuhM7uN/W0ayrlZjGF1cbR
|
||||
8NCJUL2Nwj0ywKIavC99Ipkb8AsFwpVT6U6effs6
|
||||
=xybZ
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
commitFromReader2, err := CommitFromReader(sha, strings.NewReader(commitString+"\n\n"))
|
||||
assert.NoError(t, err)
|
||||
commitFromReader.CommitMessage.MessageRaw += "\n\n"
|
||||
commitFromReader.Signature.Payload += "\n\n"
|
||||
assert.Equal(t, commitFromReader, commitFromReader2)
|
||||
signed commit`,
|
||||
`-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
iQIrBAABCgAtFiEES+fB08xlgTrzSdQvhkUIsBsmec8FAmU/wKoPHGFtYWplckBz
|
||||
dXNlLmRlAAoJEIZFCLAbJnnP4s4PQIJATa++WPzR6/H4etT7bsOGoMyguEJYyWOd
|
||||
aTybplzT7QAL7h2to0QszGabtzMJPIA39xSFZNYNN30voK5YyyYibXluPKgjemfK
|
||||
WNXwF+gkwgZI38gSvKf+vlqI+EYyIFe19wOhiju0m8SIlB5NEPiWHa17q2mqmqqx
|
||||
1FWa2JdqLPYjAtSLFXeSZegrY5V1FxdemyMUONkg8YO9OSIMZiE0GsnnOXQ3xcT4
|
||||
JTCnmlUxIKw689UiEY80JopUIq+Wl7+qq9507IYYSUCyB6JazL42AKMzVCbD+qBP
|
||||
oOzh/hafYgk9H9qCQXaLbmvs17zXRpicig1bAzqgAy1FDelvpERyRTydEajSLIG6
|
||||
U1cRCkgXCZ0NfsYNPPmBa8b3+rnstypXYTbyMwTln7FfUAaGo6o9JYiPMkzxlmsy
|
||||
zfp/tcaY8+LlBL9aOJjtv+a0p+HrpCGd6CCa4ARfphTLq8QRSSh8uzlB9N+6HnRI
|
||||
VAEUo6ecdDxSpyt2naeg9pKus/BRi7P6g4B1hkk/zZstUX/QP4IQuAJbXjkvsC+X
|
||||
HKRr3NlRM/DygzTyj0gN74uoa0goCIbyAQhiT42nm0cuhM7uN/W0ayrlZjGF1cbR
|
||||
8NCJUL2Nwj0ywKIavC99Ipkb8AsFwpVT6U6effs6
|
||||
=xybZ
|
||||
-----END PGP SIGNATURE-----`,
|
||||
`tree e7f9e96dd79c09b078cac8b303a7d3b9d65ff9b734e86060a4d20409fd379f9e
|
||||
parent 26e9ccc29fad747e9c5d9f4c9ddeb7eff61cc45ef6a8dc258cbeb181afc055e8
|
||||
author Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
committer Adam Majer <amajer@suse.de> 1698676906 +0100
|
||||
|
||||
signed commit`,
|
||||
"Adam Majer <amajer@suse.de>",
|
||||
},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
gitRepo, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, testCase.repo))
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, gitRepo)
|
||||
defer gitRepo.Close()
|
||||
|
||||
commitFromReader, err := CommitFromReader(testCase.sha, strings.NewReader(testCase.commitString))
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, commitFromReader)
|
||||
assert.Equal(t, testCase.sha, commitFromReader.ID)
|
||||
assert.Equal(t, testCase.signature, commitFromReader.Signature.Signature)
|
||||
assert.Equal(t, testCase.payload, commitFromReader.Signature.Payload)
|
||||
assert.Equal(t, testCase.author, commitFromReader.Author.String())
|
||||
|
||||
commitFromReader2, err := CommitFromReader(testCase.sha, strings.NewReader(testCase.commitString+"\n\n"))
|
||||
assert.NoError(t, err)
|
||||
commitFromReader.CommitMessage.MessageRaw += "\n\n"
|
||||
commitFromReader.Signature.Payload += "\n\n"
|
||||
assert.Equal(t, commitFromReader, commitFromReader2)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasPreviousCommit(t *testing.T) {
|
||||
|
||||
+34
-83
@@ -43,96 +43,47 @@ Hello from 2
|
||||
|
||||
func TestRepoGetDivergingCommits(t *testing.T) {
|
||||
repo := mockRepository("repo1_bare")
|
||||
do, err := GetDivergingCommits(t.Context(), repo, "master", "branch2")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, &DivergeObject{
|
||||
Ahead: 1,
|
||||
Behind: 5,
|
||||
}, do)
|
||||
|
||||
do, err = GetDivergingCommits(t.Context(), repo, "master", "master")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, &DivergeObject{
|
||||
Ahead: 0,
|
||||
Behind: 0,
|
||||
}, do)
|
||||
|
||||
do, err = GetDivergingCommits(t.Context(), repo, "master", "test")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, &DivergeObject{
|
||||
Ahead: 0,
|
||||
Behind: 2,
|
||||
}, do)
|
||||
for _, testcase := range []struct {
|
||||
branch string
|
||||
expected DivergeObject
|
||||
}{
|
||||
{"branch2", DivergeObject{Ahead: 1, Behind: 5}},
|
||||
{"master", DivergeObject{Ahead: 0, Behind: 0}},
|
||||
{"test", DivergeObject{Ahead: 0, Behind: 2}},
|
||||
} {
|
||||
do, err := GetDivergingCommits(t.Context(), repo, "master", testcase.branch)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, &testcase.expected, do)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCommitIDsBetweenReverse(t *testing.T) {
|
||||
repo := mockRepository("repo1_bare")
|
||||
|
||||
// tests raw commit IDs
|
||||
commitIDs, err := GetCommitIDsBetweenReverse(t.Context(), repo,
|
||||
"8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
"",
|
||||
100,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{
|
||||
startRef := "8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2"
|
||||
endRef := "ce064814f4a0d337b333e646ece456cd39fab612"
|
||||
expectedCommitIDs := []string{
|
||||
"8006ff9adbf0cb94da7dad9e537e53817f9fa5c0",
|
||||
"6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1",
|
||||
"37991dec2c8e592043f47155ce4808d4580f9123",
|
||||
"feaf4ba6bc635fec442f46ddd4512416ec43c2c2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
}, commitIDs)
|
||||
|
||||
commitIDs, err = GetCommitIDsBetweenReverse(t.Context(), repo,
|
||||
"8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
"6fbd69e9823458e6c4a2fc5c0f6bc022b2f2acd1",
|
||||
100,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{
|
||||
"37991dec2c8e592043f47155ce4808d4580f9123",
|
||||
"feaf4ba6bc635fec442f46ddd4512416ec43c2c2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
}, commitIDs)
|
||||
|
||||
commitIDs, err = GetCommitIDsBetweenReverse(t.Context(), repo,
|
||||
"8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
"",
|
||||
3,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{
|
||||
"37991dec2c8e592043f47155ce4808d4580f9123",
|
||||
"feaf4ba6bc635fec442f46ddd4512416ec43c2c2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
}, commitIDs)
|
||||
|
||||
// test branch names instead of raw commit IDs.
|
||||
commitIDs, err = GetCommitIDsBetweenReverse(t.Context(), repo,
|
||||
"test",
|
||||
"master",
|
||||
"",
|
||||
100,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{
|
||||
"feaf4ba6bc635fec442f46ddd4512416ec43c2c2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
}, commitIDs)
|
||||
|
||||
// add notref to exclude test
|
||||
commitIDs, err = GetCommitIDsBetweenReverse(t.Context(), repo,
|
||||
"test",
|
||||
"master",
|
||||
"test",
|
||||
100,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []string{
|
||||
"feaf4ba6bc635fec442f46ddd4512416ec43c2c2",
|
||||
"ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
}, commitIDs)
|
||||
}
|
||||
for _, testcase := range []struct {
|
||||
startRef, endRef, notRef string
|
||||
limit int
|
||||
expected []string
|
||||
}{
|
||||
// tests raw commit IDs
|
||||
{startRef, endRef, "", 100, expectedCommitIDs},
|
||||
{startRef, endRef, expectedCommitIDs[1], 100, expectedCommitIDs[2:]},
|
||||
{startRef, endRef, "", 3, expectedCommitIDs[2:]},
|
||||
// test branch names instead of raw commit IDs.
|
||||
{"test", "master", "", 100, expectedCommitIDs[3:]},
|
||||
// add notref to exclude test
|
||||
{"test", "master", "test", 100, expectedCommitIDs[3:]},
|
||||
} {
|
||||
commitIDs, err := GetCommitIDsBetweenReverse(t.Context(), repo, testcase.startRef, testcase.endRef, testcase.notRef, testcase.limit)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, testcase.expected, commitIDs)
|
||||
}
|
||||
}
|
||||
+23
-45
@@ -20,9 +20,7 @@ func TestGrepSearch(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
res, err := GrepSearch(t.Context(), repo, "void", GrepOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []*GrepResult{
|
||||
expectedResults := []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
@@ -33,49 +31,29 @@ func TestGrepSearch(t *testing.T) {
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] args)"},
|
||||
},
|
||||
}, res)
|
||||
}
|
||||
for _, testcase := range []struct {
|
||||
options GrepOptions
|
||||
expected []*GrepResult
|
||||
}{
|
||||
{GrepOptions{}, expectedResults},
|
||||
{GrepOptions{PathspecList: []string{":(glob)java-hello/*"}}, expectedResults[:1]},
|
||||
{GrepOptions{PathspecList: []string{":(glob,exclude)java-hello/*"}}, expectedResults[1:]},
|
||||
{GrepOptions{MaxResultLimit: 1}, expectedResults[:1]},
|
||||
{GrepOptions{MaxResultLimit: 1, MaxLineLength: 39}, []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] arg"},
|
||||
},
|
||||
}},
|
||||
} {
|
||||
res, err := GrepSearch(t.Context(), repo, "void", testcase.options)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, testcase.expected, res)
|
||||
}
|
||||
|
||||
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{PathspecList: []string{":(glob)java-hello/*"}})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] args)"},
|
||||
},
|
||||
}, res)
|
||||
|
||||
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{PathspecList: []string{":(glob,exclude)java-hello/*"}})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []*GrepResult{
|
||||
{
|
||||
Filename: "main.vendor.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] args)"},
|
||||
},
|
||||
}, res)
|
||||
|
||||
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{MaxResultLimit: 1})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] args)"},
|
||||
},
|
||||
}, res)
|
||||
|
||||
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{MaxResultLimit: 1, MaxLineLength: 39})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] arg"},
|
||||
},
|
||||
}, res)
|
||||
|
||||
res, err = GrepSearch(t.Context(), repo, "no-such-content", GrepOptions{})
|
||||
res, err := GrepSearch(t.Context(), repo, "no-such-content", GrepOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, res)
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseTreeEntriesLong(t *testing.T) {
|
||||
func TestParseTreeEntries(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Input string
|
||||
Expected []*TreeEntry
|
||||
@@ -53,22 +53,6 @@ func TestParseTreeEntriesLong(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
entries, err := ParseTreeEntries([]byte(testCase.Input))
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, entries, len(testCase.Expected))
|
||||
for i, entry := range entries {
|
||||
assert.Equal(t, testCase.Expected[i], entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTreeEntriesShort(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Input string
|
||||
Expected []*TreeEntry
|
||||
}{
|
||||
{
|
||||
Input: `100644 blob ea0d83c9081af9500ac9f804101b3fd0a5c293af README.md
|
||||
040000 tree 84b90550547016f73c5dd3f50dea662389e67b6d assets
|
||||
|
||||
@@ -40,30 +40,23 @@ func TestRepository_GetBlob_Found(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepository_GetBlob_NotExist(t *testing.T) {
|
||||
repoPath := filepath.Join(testReposDir, "repo1_bare")
|
||||
r, err := OpenRepositoryLocal(t.Context(), repoPath)
|
||||
assert.NoError(t, err)
|
||||
defer r.Close()
|
||||
func TestRepository_GetBlob_Errors(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
id string
|
||||
err error
|
||||
}{
|
||||
{"NotExist", "0000000000000000000000000000000000000000", ErrNotExist{"0000000000000000000000000000000000000000", ""}},
|
||||
{"NoId", "", fmt.Errorf("length %d has no matched object format: %s", len(""), "")},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
r, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
|
||||
assert.NoError(t, err)
|
||||
defer r.Close()
|
||||
|
||||
testCase := "0000000000000000000000000000000000000000"
|
||||
testError := ErrNotExist{testCase, ""}
|
||||
|
||||
blob, err := r.GetBlob(testCase)
|
||||
assert.Nil(t, blob)
|
||||
assert.EqualError(t, err, testError.Error())
|
||||
}
|
||||
|
||||
func TestRepository_GetBlob_NoId(t *testing.T) {
|
||||
repoPath := filepath.Join(testReposDir, "repo1_bare")
|
||||
r, err := OpenRepositoryLocal(t.Context(), repoPath)
|
||||
assert.NoError(t, err)
|
||||
defer r.Close()
|
||||
|
||||
testCase := ""
|
||||
testError := fmt.Errorf("length %d has no matched object format: %s", len(testCase), testCase)
|
||||
|
||||
blob, err := r.GetBlob(testCase)
|
||||
assert.Nil(t, blob)
|
||||
assert.EqualError(t, err, testError.Error())
|
||||
blob, err := r.GetBlob(testCase.id)
|
||||
assert.Nil(t, blob)
|
||||
assert.EqualError(t, err, testCase.err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
@@ -96,100 +97,37 @@ func BenchmarkGetRefsBySha(b *testing.B) {
|
||||
_, _ = bareRepo5.GetRefsBySha(b.Context(), "58a4bcc53ac13e7ff76127e0fb518b5262bf09af", "")
|
||||
}
|
||||
|
||||
func TestRepository_IsObjectExist(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
repo, err := OpenRepositoryLocal(ctx, filepath.Join(testReposDir, "repo1_bare"))
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
arg string
|
||||
want bool
|
||||
func TestRepository_Existence(t *testing.T) {
|
||||
for _, method := range []struct {
|
||||
name string
|
||||
exists func(*Repository, context.Context, string) bool
|
||||
branchExists bool
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
arg: "",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "branch",
|
||||
arg: "master",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "commit hash",
|
||||
arg: "ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "short commit hash",
|
||||
arg: "ce06481",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "blob hash",
|
||||
arg: "153f451b9ee7fa1da317ab17a127e9fd9d384310",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "short blob hash",
|
||||
arg: "153f451",
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, repo.IsObjectExist(ctx, tt.arg))
|
||||
})
|
||||
}
|
||||
}
|
||||
{"IsObjectExist", (*Repository).IsObjectExist, false},
|
||||
{"IsReferenceExist", (*Repository).IsReferenceExist, true},
|
||||
} {
|
||||
t.Run(method.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
repo, err := OpenRepositoryLocal(ctx, filepath.Join(testReposDir, "repo1_bare"))
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
func TestRepository_IsReferenceExist(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
repo, err := OpenRepositoryLocal(ctx, filepath.Join(testReposDir, "repo1_bare"))
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
arg string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
arg: "",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "branch",
|
||||
arg: "master",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "commit hash",
|
||||
arg: "ce064814f4a0d337b333e646ece456cd39fab612",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "short commit hash",
|
||||
arg: "ce06481",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "blob hash",
|
||||
arg: "153f451b9ee7fa1da317ab17a127e9fd9d384310",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "short blob hash",
|
||||
arg: "153f451",
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, repo.IsReferenceExist(ctx, tt.arg))
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
arg string
|
||||
want bool
|
||||
}{
|
||||
{"empty", "", false},
|
||||
{"branch", "master", method.branchExists},
|
||||
{"commit hash", "ce064814f4a0d337b333e646ece456cd39fab612", true},
|
||||
{"short commit hash", "ce06481", true},
|
||||
{"blob hash", "153f451b9ee7fa1da317ab17a127e9fd9d384310", true},
|
||||
{"short blob hash", "153f451", true},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
assert.Equal(t, testCase.want, method.exists(repo, ctx, testCase.arg))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+88
-108
@@ -16,91 +16,96 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRepository_GetCommitBranches(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
// these test case are specific to the repo1_bare test repo
|
||||
testCases := []struct {
|
||||
CommitID string
|
||||
ExpectedBranches []string
|
||||
func TestRepository_CommitQueries(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
run func(*testing.T, *Repository)
|
||||
}{
|
||||
{"2839944139e0de9737a044f78b0e4b40d989a9e3", []string{"branch1"}},
|
||||
{"5c80b0245c1c6f8343fa418ec374b13b5d4ee658", []string{"branch2"}},
|
||||
{"37991dec2c8e592043f47155ce4808d4580f9123", []string{"master"}},
|
||||
{"95bb4d39648ee7e325106df01a621c530863a653", []string{"branch1", "branch2"}},
|
||||
{"8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2", []string{"branch2", "master"}},
|
||||
{"master", []string{"master"}},
|
||||
{"TestRepository_GetCommitBranches", func(t *testing.T, bareRepo1 *Repository) {
|
||||
// these test case are specific to the repo1_bare test repo
|
||||
testCases := []struct {
|
||||
CommitID string
|
||||
ExpectedBranches []string
|
||||
}{
|
||||
{"2839944139e0de9737a044f78b0e4b40d989a9e3", []string{"branch1"}},
|
||||
{"5c80b0245c1c6f8343fa418ec374b13b5d4ee658", []string{"branch2"}},
|
||||
{"37991dec2c8e592043f47155ce4808d4580f9123", []string{"master"}},
|
||||
{"95bb4d39648ee7e325106df01a621c530863a653", []string{"branch1", "branch2"}},
|
||||
{"8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2", []string{"branch2", "master"}},
|
||||
{"master", []string{"master"}},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), testCase.CommitID)
|
||||
assert.NoError(t, err)
|
||||
branches, err := bareRepo1.getBranches(t.Context(), nil, commit.ID.String(), 2)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, testCase.ExpectedBranches, branches)
|
||||
}
|
||||
}},
|
||||
{"TestGetTagCommitWithSignature", func(t *testing.T, bareRepo1 *Repository) {
|
||||
// both the tag and the commit are signed here, this validates only the commit signature
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), "28b55526e7100924d864dd89e35c1ea62e7a5a32")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, commit)
|
||||
assert.NotNil(t, commit.Signature)
|
||||
// test that signature is not in message
|
||||
assert.Equal(t, "signed-commit\n", commit.CommitMessage.MessageRaw)
|
||||
}},
|
||||
{"TestGetCommitWithBadCommitID", func(t *testing.T, bareRepo1 *Repository) {
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), "bad_branch")
|
||||
assert.Nil(t, commit)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, IsErrNotExist(err))
|
||||
}},
|
||||
{"TestIsCommitInRepo", func(t *testing.T, bareRepo1 *Repository) {
|
||||
exist, err := IsCommitInRepo(t.Context(), bareRepo1, "2839944139e0de9737a044f78b0e4b40d989a9e3")
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exist)
|
||||
|
||||
exist, err = IsCommitInRepo(t.Context(), bareRepo1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exist)
|
||||
}},
|
||||
{"TestIsCommitInBranch", func(t *testing.T, bareRepo1 *Repository) {
|
||||
result, err := IsCommitInBranch(t.Context(), bareRepo1, "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1")
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, result)
|
||||
|
||||
result, err = IsCommitInBranch(t.Context(), bareRepo1, "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, result)
|
||||
|
||||
result, err = IsCommitInBranch(t.Context(), bareRepo1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "branch1")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, result)
|
||||
}},
|
||||
{"TestGetRefCommitID", func(t *testing.T, bareRepo1 *Repository) {
|
||||
// these test case are specific to the repo1_bare test repo
|
||||
testCases := []struct {
|
||||
Ref string
|
||||
ExpectedCommitID string
|
||||
}{
|
||||
{RefNameFromBranch("master").String(), "ce064814f4a0d337b333e646ece456cd39fab612"},
|
||||
{RefNameFromBranch("branch1").String(), "2839944139e0de9737a044f78b0e4b40d989a9e3"},
|
||||
{RefNameFromTag("test").String(), "3ad28a9149a2864384548f3d17ed7f38014c9e8a"},
|
||||
{"ce064814f4a0d337b333e646ece456cd39fab612", "ce064814f4a0d337b333e646ece456cd39fab612"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
commitID, err := bareRepo1.GetRefCommitID(t.Context(), testCase.Ref)
|
||||
if assert.NoError(t, err) {
|
||||
assert.Equal(t, testCase.ExpectedCommitID, commitID)
|
||||
}
|
||||
}
|
||||
}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
testCase.run(t, bareRepo1)
|
||||
})
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), testCase.CommitID)
|
||||
assert.NoError(t, err)
|
||||
branches, err := bareRepo1.getBranches(t.Context(), nil, commit.ID.String(), 2)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, testCase.ExpectedBranches, branches)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTagCommitWithSignature(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
// both the tag and the commit are signed here, this validates only the commit signature
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), "28b55526e7100924d864dd89e35c1ea62e7a5a32")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, commit)
|
||||
assert.NotNil(t, commit.Signature)
|
||||
// test that signature is not in message
|
||||
assert.Equal(t, "signed-commit\n", commit.CommitMessage.MessageRaw)
|
||||
}
|
||||
|
||||
func TestGetCommitWithBadCommitID(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
commit, err := bareRepo1.GetCommit(t.Context(), "bad_branch")
|
||||
assert.Nil(t, commit)
|
||||
assert.Error(t, err)
|
||||
assert.True(t, IsErrNotExist(err))
|
||||
}
|
||||
|
||||
func TestIsCommitInRepo(t *testing.T) {
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "repo1_bare"))
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
exist, err := IsCommitInRepo(t.Context(), bareRepo1, "2839944139e0de9737a044f78b0e4b40d989a9e3")
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exist)
|
||||
|
||||
exist, err = IsCommitInRepo(t.Context(), bareRepo1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exist)
|
||||
}
|
||||
|
||||
func TestIsCommitInBranch(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
result, err := IsCommitInBranch(t.Context(), bareRepo1, "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1")
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, result)
|
||||
|
||||
result, err = IsCommitInBranch(t.Context(), bareRepo1, "2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, result)
|
||||
|
||||
result, err = IsCommitInBranch(t.Context(), bareRepo1, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "branch1")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, result)
|
||||
}
|
||||
|
||||
func TestRepository_CommitsBetween(t *testing.T) {
|
||||
@@ -125,31 +130,6 @@ func TestRepository_CommitsBetween(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRefCommitID(t *testing.T) {
|
||||
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
|
||||
bareRepo1, err := OpenRepositoryLocal(t.Context(), bareRepo1Path)
|
||||
assert.NoError(t, err)
|
||||
defer bareRepo1.Close()
|
||||
|
||||
// these test case are specific to the repo1_bare test repo
|
||||
testCases := []struct {
|
||||
Ref string
|
||||
ExpectedCommitID string
|
||||
}{
|
||||
{RefNameFromBranch("master").String(), "ce064814f4a0d337b333e646ece456cd39fab612"},
|
||||
{RefNameFromBranch("branch1").String(), "2839944139e0de9737a044f78b0e4b40d989a9e3"},
|
||||
{RefNameFromTag("test").String(), "3ad28a9149a2864384548f3d17ed7f38014c9e8a"},
|
||||
{"ce064814f4a0d337b333e646ece456cd39fab612", "ce064814f4a0d337b333e646ece456cd39fab612"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
commitID, err := bareRepo1.GetRefCommitID(t.Context(), testCase.Ref)
|
||||
if assert.NoError(t, err) {
|
||||
assert.Equal(t, testCase.ExpectedCommitID, commitID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommitsByFileAndRange(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Git.CommitsRangeSize, 2)()
|
||||
|
||||
|
||||
@@ -185,6 +185,22 @@ func TestRepository_GetAnnotatedTag(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRepository_parseTagRef(t *testing.T) {
|
||||
signature := `-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
aBCGzBAABCgAdFiEEyWRwv/q1Q6IjSv+D4IPOwzt33PoFAmI8jbIACgkQ4IPOwzt3
|
||||
3PoRuAv9FVSbPBXvzECubls9KQd7urwEvcfG20Uf79iBwifQJUv+egNQojrs6APT
|
||||
T4CdIXeGRpwJZaGTUX9RWnoDO1SLXAWnc82CypWraNwrHq8Go2YeoVu0Iy3vb0EU
|
||||
REdob/tXYZecMuP8AjhUR0XfdYaERYAvJ2dYsH/UkFrqDjM3V4kPXWG+R5DCaZiE
|
||||
slB5U01i4Dwb/zm/ckzhUGEcOgcnpOKX8SnY5kYRVDY47dl/yJZ1u2XWir3mu60G
|
||||
1geIitH7StBddHi/8rz+sJwTfcVaLjn2p59p/Dr9aGbk17GIaKq1j0pZA2lKT0Xt
|
||||
f9jDqU+9vCxnKgjSDhrwN69LF2jT47ZFjEMGV/wFPOa1EBxVWpgQ/CfEolBlbUqx
|
||||
yVpbxi/6AOK2lmG130e9jEZJcu+WeZUeq851WgKSEkf2d5f/JpwtSTEOlOedu6V6
|
||||
kl845zu5oE2nKM4zMQ7XrYQn538I31ps+VGQ0H8R07WrZP8WKUWugL2cU8KmXFwg
|
||||
qbHDASXl
|
||||
=2yGi
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
`
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -273,38 +289,8 @@ func TestRepository_parseTagRef(t *testing.T) {
|
||||
* add changelog of v1.9.1
|
||||
* Update CHANGELOG.md
|
||||
|
||||
-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
aBCGzBAABCgAdFiEEyWRwv/q1Q6IjSv+D4IPOwzt33PoFAmI8jbIACgkQ4IPOwzt3
|
||||
3PoRuAv9FVSbPBXvzECubls9KQd7urwEvcfG20Uf79iBwifQJUv+egNQojrs6APT
|
||||
T4CdIXeGRpwJZaGTUX9RWnoDO1SLXAWnc82CypWraNwrHq8Go2YeoVu0Iy3vb0EU
|
||||
REdob/tXYZecMuP8AjhUR0XfdYaERYAvJ2dYsH/UkFrqDjM3V4kPXWG+R5DCaZiE
|
||||
slB5U01i4Dwb/zm/ckzhUGEcOgcnpOKX8SnY5kYRVDY47dl/yJZ1u2XWir3mu60G
|
||||
1geIitH7StBddHi/8rz+sJwTfcVaLjn2p59p/Dr9aGbk17GIaKq1j0pZA2lKT0Xt
|
||||
f9jDqU+9vCxnKgjSDhrwN69LF2jT47ZFjEMGV/wFPOa1EBxVWpgQ/CfEolBlbUqx
|
||||
yVpbxi/6AOK2lmG130e9jEZJcu+WeZUeq851WgKSEkf2d5f/JpwtSTEOlOedu6V6
|
||||
kl845zu5oE2nKM4zMQ7XrYQn538I31ps+VGQ0H8R07WrZP8WKUWugL2cU8KmXFwg
|
||||
qbHDASXl
|
||||
=2yGi
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
`,
|
||||
"contents:signature": `-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
aBCGzBAABCgAdFiEEyWRwv/q1Q6IjSv+D4IPOwzt33PoFAmI8jbIACgkQ4IPOwzt3
|
||||
3PoRuAv9FVSbPBXvzECubls9KQd7urwEvcfG20Uf79iBwifQJUv+egNQojrs6APT
|
||||
T4CdIXeGRpwJZaGTUX9RWnoDO1SLXAWnc82CypWraNwrHq8Go2YeoVu0Iy3vb0EU
|
||||
REdob/tXYZecMuP8AjhUR0XfdYaERYAvJ2dYsH/UkFrqDjM3V4kPXWG+R5DCaZiE
|
||||
slB5U01i4Dwb/zm/ckzhUGEcOgcnpOKX8SnY5kYRVDY47dl/yJZ1u2XWir3mu60G
|
||||
1geIitH7StBddHi/8rz+sJwTfcVaLjn2p59p/Dr9aGbk17GIaKq1j0pZA2lKT0Xt
|
||||
f9jDqU+9vCxnKgjSDhrwN69LF2jT47ZFjEMGV/wFPOa1EBxVWpgQ/CfEolBlbUqx
|
||||
yVpbxi/6AOK2lmG130e9jEZJcu+WeZUeq851WgKSEkf2d5f/JpwtSTEOlOedu6V6
|
||||
kl845zu5oE2nKM4zMQ7XrYQn538I31ps+VGQ0H8R07WrZP8WKUWugL2cU8KmXFwg
|
||||
qbHDASXl
|
||||
=2yGi
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
`,
|
||||
` + signature,
|
||||
"contents:signature": signature,
|
||||
},
|
||||
|
||||
want: &Tag{
|
||||
@@ -315,22 +301,7 @@ qbHDASXl
|
||||
Tagger: parseSignatureFromCommitLine("Foo Bar <foo@bar.com> 1565789218 +0300"),
|
||||
CommitMessage: CommitMessage{MessageRaw: "Add changelog of v1.9.1 (#7859)\n\n* add changelog of v1.9.1\n* Update CHANGELOG.md\n"},
|
||||
Signature: &CommitSignature{
|
||||
Signature: `-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
aBCGzBAABCgAdFiEEyWRwv/q1Q6IjSv+D4IPOwzt33PoFAmI8jbIACgkQ4IPOwzt3
|
||||
3PoRuAv9FVSbPBXvzECubls9KQd7urwEvcfG20Uf79iBwifQJUv+egNQojrs6APT
|
||||
T4CdIXeGRpwJZaGTUX9RWnoDO1SLXAWnc82CypWraNwrHq8Go2YeoVu0Iy3vb0EU
|
||||
REdob/tXYZecMuP8AjhUR0XfdYaERYAvJ2dYsH/UkFrqDjM3V4kPXWG+R5DCaZiE
|
||||
slB5U01i4Dwb/zm/ckzhUGEcOgcnpOKX8SnY5kYRVDY47dl/yJZ1u2XWir3mu60G
|
||||
1geIitH7StBddHi/8rz+sJwTfcVaLjn2p59p/Dr9aGbk17GIaKq1j0pZA2lKT0Xt
|
||||
f9jDqU+9vCxnKgjSDhrwN69LF2jT47ZFjEMGV/wFPOa1EBxVWpgQ/CfEolBlbUqx
|
||||
yVpbxi/6AOK2lmG130e9jEZJcu+WeZUeq851WgKSEkf2d5f/JpwtSTEOlOedu6V6
|
||||
kl845zu5oE2nKM4zMQ7XrYQn538I31ps+VGQ0H8R07WrZP8WKUWugL2cU8KmXFwg
|
||||
qbHDASXl
|
||||
=2yGi
|
||||
-----END PGP SIGNATURE-----
|
||||
|
||||
`,
|
||||
Signature: signature,
|
||||
Payload: `object 3325fd8a973321fd59455492976c042dde3fd1ca
|
||||
type commit
|
||||
tag v0.0.1
|
||||
|
||||
@@ -11,37 +11,18 @@ import (
|
||||
)
|
||||
|
||||
func TestParseSignatureFromCommitLine(t *testing.T) {
|
||||
tests := []struct {
|
||||
line string
|
||||
want *Signature
|
||||
}{
|
||||
{
|
||||
line: "a b <c@d.com> 12345 +0100",
|
||||
want: &Signature{
|
||||
Name: "a b",
|
||||
Email: "c@d.com",
|
||||
When: time.Unix(12345, 0).In(time.FixedZone("", 3600)),
|
||||
},
|
||||
},
|
||||
{
|
||||
line: "bad line",
|
||||
want: &Signature{Name: "bad line"},
|
||||
},
|
||||
{
|
||||
line: "bad < line",
|
||||
want: &Signature{Name: "bad < line"},
|
||||
},
|
||||
{
|
||||
line: "bad > line",
|
||||
want: &Signature{Name: "bad > line"},
|
||||
},
|
||||
{
|
||||
line: "bad-line <name@example.com>",
|
||||
want: &Signature{Name: "bad-line <name@example.com>"},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
got := parseSignatureFromCommitLine(test.line)
|
||||
assert.Equal(t, test.want, got)
|
||||
assert.Equal(t, &Signature{
|
||||
Name: "a b",
|
||||
Email: "c@d.com",
|
||||
When: time.Unix(12345, 0).In(time.FixedZone("", 3600)),
|
||||
}, parseSignatureFromCommitLine("a b <c@d.com> 12345 +0100"))
|
||||
|
||||
for _, line := range []string{
|
||||
"bad line",
|
||||
"bad < line",
|
||||
"bad > line",
|
||||
"bad-line <name@example.com>",
|
||||
} {
|
||||
assert.Equal(t, &Signature{Name: line}, parseSignatureFromCommitLine(line))
|
||||
}
|
||||
}
|
||||
@@ -46,32 +46,22 @@ func TestFollowLink(t *testing.T) {
|
||||
assert.Nil(t, res)
|
||||
}
|
||||
|
||||
{
|
||||
// should error for broken links
|
||||
entry, err := commit.Tree().GetTreeEntryByPath(t.Context(), r, "foo/broken_link")
|
||||
for _, test := range []struct {
|
||||
fullPath string
|
||||
symlinkContent string
|
||||
checkLink bool
|
||||
}{
|
||||
{"foo/broken_link", "nar/broken_link", true}, // should error for broken links
|
||||
{"foo/outside_repo", "../../outside_repo", true}, // should error for external links
|
||||
{"foo/link_short", "a", false}, // testing fix for short link bug
|
||||
} {
|
||||
entry, err := commit.Tree().GetTreeEntryByPath(t.Context(), r, test.fullPath)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, entry.IsLink())
|
||||
res, err := EntryFollowLink(t.Context(), r, commit, "foo/broken_link", entry)
|
||||
if test.checkLink {
|
||||
assert.True(t, entry.IsLink())
|
||||
}
|
||||
res, err := EntryFollowLink(t.Context(), r, commit, test.fullPath, entry)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
assert.Equal(t, "nar/broken_link", res.SymlinkContent)
|
||||
}
|
||||
|
||||
{
|
||||
// should error for external links
|
||||
entry, err := commit.Tree().GetTreeEntryByPath(t.Context(), r, "foo/outside_repo")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, entry.IsLink())
|
||||
res, err := EntryFollowLink(t.Context(), r, commit, "foo/outside_repo", entry)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
assert.Equal(t, "../../outside_repo", res.SymlinkContent)
|
||||
}
|
||||
|
||||
{
|
||||
// testing fix for short link bug
|
||||
entry, err := commit.Tree().GetTreeEntryByPath(t.Context(), r, "foo/link_short")
|
||||
require.NoError(t, err)
|
||||
res, err := EntryFollowLink(t.Context(), r, commit, "foo/link_short", entry)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
assert.Equal(t, "a", res.SymlinkContent)
|
||||
assert.Equal(t, test.symlinkContent, res.SymlinkContent)
|
||||
}
|
||||
}
|
||||
+41
-169
@@ -17,156 +17,37 @@ import (
|
||||
)
|
||||
|
||||
func TestParseGitURLs(t *testing.T) {
|
||||
kases := []struct {
|
||||
kase string
|
||||
expected *GitURL
|
||||
for _, kase := range []struct {
|
||||
kase, scheme, host, path string
|
||||
user *url.Userinfo
|
||||
extraMark int
|
||||
}{
|
||||
{
|
||||
kase: "git@127.0.0.1:go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "ssh",
|
||||
User: url.User("git"),
|
||||
Host: "127.0.0.1",
|
||||
Path: "go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "git@[fe80::14fc:cec5:c174:d88%2510]:go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "ssh",
|
||||
User: url.User("git"),
|
||||
Host: "[fe80::14fc:cec5:c174:d88%10]",
|
||||
Path: "go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "git@[::1]:go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "ssh",
|
||||
User: url.User("git"),
|
||||
Host: "[::1]",
|
||||
Path: "go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "git@github.com:go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "ssh",
|
||||
User: url.User("git"),
|
||||
Host: "github.com",
|
||||
Path: "go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "ssh://git@github.com/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "ssh",
|
||||
User: url.User("git"),
|
||||
Host: "github.com",
|
||||
Path: "/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "ssh://git@[::1]/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "ssh",
|
||||
User: url.User("git"),
|
||||
Host: "[::1]",
|
||||
Path: "/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "/repositories/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "file",
|
||||
Path: "/repositories/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "file:///repositories/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "file",
|
||||
Path: "/repositories/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "https://github.com/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "github.com",
|
||||
Path: "/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "https://git:git@github.com/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "github.com",
|
||||
User: url.UserPassword("git", "git"),
|
||||
Path: "/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
kase: "https://[fe80::14fc:cec5:c174:d88%2510]:20/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "[fe80::14fc:cec5:c174:d88%10]:20",
|
||||
Path: "/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
kase: "git://github.com/go-gitea/gitea.git",
|
||||
expected: &GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: "git",
|
||||
Host: "github.com",
|
||||
Path: "/go-gitea/gitea.git",
|
||||
},
|
||||
extraMark: 0,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, kase := range kases {
|
||||
{"git@127.0.0.1:go-gitea/gitea.git", "ssh", "127.0.0.1", "go-gitea/gitea.git", url.User("git"), 1},
|
||||
{"git@[fe80::14fc:cec5:c174:d88%2510]:go-gitea/gitea.git", "ssh", "[fe80::14fc:cec5:c174:d88%10]", "go-gitea/gitea.git", url.User("git"), 1},
|
||||
{"git@[::1]:go-gitea/gitea.git", "ssh", "[::1]", "go-gitea/gitea.git", url.User("git"), 1},
|
||||
{"git@github.com:go-gitea/gitea.git", "ssh", "github.com", "go-gitea/gitea.git", url.User("git"), 1},
|
||||
{"ssh://git@github.com/go-gitea/gitea.git", "ssh", "github.com", "/go-gitea/gitea.git", url.User("git"), 0},
|
||||
{"ssh://git@[::1]/go-gitea/gitea.git", "ssh", "[::1]", "/go-gitea/gitea.git", url.User("git"), 0},
|
||||
{"/repositories/go-gitea/gitea.git", "file", "", "/repositories/go-gitea/gitea.git", nil, 2},
|
||||
{"file:///repositories/go-gitea/gitea.git", "file", "", "/repositories/go-gitea/gitea.git", nil, 0},
|
||||
{"https://github.com/go-gitea/gitea.git", "https", "github.com", "/go-gitea/gitea.git", nil, 0},
|
||||
{"https://git:git@github.com/go-gitea/gitea.git", "https", "github.com", "/go-gitea/gitea.git", url.UserPassword("git", "git"), 0},
|
||||
{"https://[fe80::14fc:cec5:c174:d88%2510]:20/go-gitea/gitea.git", "https", "[fe80::14fc:cec5:c174:d88%10]:20", "/go-gitea/gitea.git", nil, 0},
|
||||
{"git://github.com/go-gitea/gitea.git", "git", "github.com", "/go-gitea/gitea.git", nil, 0},
|
||||
} {
|
||||
t.Run(kase.kase, func(t *testing.T) {
|
||||
u, err := ParseGitURL(kase.kase)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, kase.expected.extraMark, u.extraMark)
|
||||
assert.Equal(t, *kase.expected, *u)
|
||||
assert.Equal(t, kase.extraMark, u.extraMark)
|
||||
assert.Equal(t, GitURL{
|
||||
URL: &url.URL{
|
||||
Scheme: kase.scheme,
|
||||
User: kase.user,
|
||||
Host: kase.host,
|
||||
Path: kase.path,
|
||||
},
|
||||
extraMark: kase.extraMark,
|
||||
}, *u)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -251,27 +132,18 @@ func TestMakeRepositoryBaseLink(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.AppURL, "https://localhost:3000/subpath")()
|
||||
defer test.MockVariableValue(&setting.AppSubURL, "/subpath")()
|
||||
|
||||
u, err := ParseRepositoryURL(t.Context(), "https://localhost:3000/subpath/user/repo.git")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "/subpath/user/repo", MakeRepositoryWebLink(u))
|
||||
|
||||
u, err = ParseRepositoryURL(t.Context(), "https://github.com/owner/repo.git")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://github.com/owner/repo", MakeRepositoryWebLink(u))
|
||||
|
||||
u, err = ParseRepositoryURL(t.Context(), "git@github.com:owner/repo.git")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://github.com/owner/repo", MakeRepositoryWebLink(u))
|
||||
|
||||
u, err = ParseRepositoryURL(t.Context(), "git+ssh://other:123/owner/repo.git")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://other/owner/repo", MakeRepositoryWebLink(u))
|
||||
|
||||
u, err = ParseRepositoryURL(t.Context(), "git+ssh://[::1]/owner/repo.git")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://[::1]/owner/repo", MakeRepositoryWebLink(u))
|
||||
|
||||
u, err = ParseRepositoryURL(t.Context(), "git+ssh://[::1]:2222/owner/repo.git")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "https://[::1]/owner/repo", MakeRepositoryWebLink(u))
|
||||
for _, kase := range []struct {
|
||||
input, expected string
|
||||
}{
|
||||
{"https://localhost:3000/subpath/user/repo.git", "/subpath/user/repo"},
|
||||
{"https://github.com/owner/repo.git", "https://github.com/owner/repo"},
|
||||
{"git@github.com:owner/repo.git", "https://github.com/owner/repo"},
|
||||
{"git+ssh://other:123/owner/repo.git", "https://other/owner/repo"},
|
||||
{"git+ssh://[::1]/owner/repo.git", "https://[::1]/owner/repo"},
|
||||
{"git+ssh://[::1]:2222/owner/repo.git", "https://[::1]/owner/repo"},
|
||||
} {
|
||||
u, err := ParseRepositoryURL(t.Context(), kase.input)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, kase.expected, MakeRepositoryWebLink(u))
|
||||
}
|
||||
}
|
||||
@@ -34,12 +34,14 @@ func TestFile(t *testing.T) {
|
||||
name string
|
||||
code string
|
||||
want []template.HTML
|
||||
plainWant []template.HTML
|
||||
lexerName string
|
||||
}{
|
||||
{
|
||||
name: "empty.py",
|
||||
code: "",
|
||||
want: lines(""),
|
||||
plainWant: lines(""),
|
||||
lexerName: "Python",
|
||||
},
|
||||
{
|
||||
@@ -64,18 +66,21 @@ func TestFile(t *testing.T) {
|
||||
name: "tags.py",
|
||||
code: "<>",
|
||||
want: lines(`<span class="o"><></span>`),
|
||||
plainWant: lines("<>"),
|
||||
lexerName: "Python",
|
||||
},
|
||||
{
|
||||
name: "eol-no.py",
|
||||
code: "a=1",
|
||||
want: lines(`<span class="n">a</span><span class="o">=</span><span class="mi">1</span>`),
|
||||
plainWant: lines(`a=1`),
|
||||
lexerName: "Python",
|
||||
},
|
||||
{
|
||||
name: "eol-newline1.py",
|
||||
code: "a=1\n",
|
||||
want: lines(`<span class="n">a</span><span class="o">=</span><span class="mi">1</span>\n`),
|
||||
plainWant: lines(`a=1\n`),
|
||||
lexerName: "Python",
|
||||
},
|
||||
{
|
||||
@@ -86,6 +91,10 @@ func TestFile(t *testing.T) {
|
||||
\n
|
||||
`,
|
||||
),
|
||||
plainWant: lines(`
|
||||
a=1\n
|
||||
\n
|
||||
`),
|
||||
lexerName: "Python",
|
||||
},
|
||||
{
|
||||
@@ -106,6 +115,13 @@ c=2
|
||||
\n
|
||||
<span class="n">c</span><span class="o">=</span><span class="mi">2</span>`,
|
||||
),
|
||||
plainWant: lines(`
|
||||
def:\n
|
||||
a=1\n
|
||||
\n
|
||||
b=''\n
|
||||
\n
|
||||
c=2`),
|
||||
lexerName: "Python",
|
||||
},
|
||||
{
|
||||
@@ -135,67 +151,14 @@ Content-Type: text/html
|
||||
assert.Equal(t, tt.lexerName, lexerName)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlainText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
code string
|
||||
want []template.HTML
|
||||
}{
|
||||
{
|
||||
name: "empty.py",
|
||||
code: "",
|
||||
want: lines(""),
|
||||
},
|
||||
{
|
||||
name: "tags.py",
|
||||
code: "<>",
|
||||
want: lines("<>"),
|
||||
},
|
||||
{
|
||||
name: "eol-no.py",
|
||||
code: "a=1",
|
||||
want: lines(`a=1`),
|
||||
},
|
||||
{
|
||||
name: "eol-newline1.py",
|
||||
code: "a=1\n",
|
||||
want: lines(`a=1\n`),
|
||||
},
|
||||
{
|
||||
name: "eol-newline2.py",
|
||||
code: "a=1\n\n",
|
||||
want: lines(`
|
||||
a=1\n
|
||||
\n
|
||||
`),
|
||||
},
|
||||
{
|
||||
name: "empty-line-with-space.py",
|
||||
code: strings.ReplaceAll(strings.TrimSpace(`
|
||||
def:
|
||||
a=1
|
||||
|
||||
b=''
|
||||
{space}
|
||||
c=2
|
||||
`), "{space}", " "),
|
||||
want: lines(`
|
||||
def:\n
|
||||
a=1\n
|
||||
\n
|
||||
b=''\n
|
||||
\n
|
||||
c=2`),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
out := renderPlainText([]byte(tt.code))
|
||||
assert.Equal(t, tt.want, out)
|
||||
})
|
||||
if tt.plainWant != nil {
|
||||
t.Run("plaintext/"+tt.name, func(t *testing.T) {
|
||||
out := renderPlainText([]byte(tt.code))
|
||||
assert.Equal(t, tt.plainWant, out)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,76 +25,58 @@ func TestHandleGenericETagCache(t *testing.T) {
|
||||
respEtag string
|
||||
reqHeaders map[string]string
|
||||
wantHandled bool
|
||||
wantHeaders map[string]string
|
||||
wantStatus int
|
||||
}
|
||||
cases := []testCase{
|
||||
{
|
||||
name: "No If-None-Match",
|
||||
wantHandled: false,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": cacheControl, "Etag": matchedEtag},
|
||||
},
|
||||
{
|
||||
name: "Mismatched If-None-Match",
|
||||
reqHeaders: map[string]string{"If-None-Match": `"mismatched-etag"`},
|
||||
wantHandled: false,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": cacheControl, "Etag": matchedEtag},
|
||||
},
|
||||
{
|
||||
name: "Matched If-None-Match",
|
||||
reqHeaders: map[string]string{"If-None-Match": matchedEtag},
|
||||
wantHandled: true,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": "", "Etag": matchedEtag},
|
||||
wantStatus: http.StatusNotModified,
|
||||
},
|
||||
{
|
||||
name: "Multiple Mismatched If-None-Match",
|
||||
reqHeaders: map[string]string{"If-None-Match": `"mismatched-etag1", "mismatched-etag2"`},
|
||||
wantHandled: false,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": cacheControl, "Etag": matchedEtag},
|
||||
},
|
||||
{
|
||||
name: "Wildcard If-None-Match matches any current representation",
|
||||
reqHeaders: map[string]string{"If-None-Match": "*"},
|
||||
wantHandled: true,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": "", "Etag": matchedEtag},
|
||||
wantStatus: http.StatusNotModified,
|
||||
},
|
||||
{
|
||||
name: "Weak response tag matched by a strong request tag",
|
||||
respEtag: weakEtag,
|
||||
reqHeaders: map[string]string{"If-None-Match": matchedEtag},
|
||||
wantHandled: true,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": "", "Etag": weakEtag},
|
||||
wantStatus: http.StatusNotModified,
|
||||
},
|
||||
{
|
||||
name: "Weak response tag matched by a weak request tag",
|
||||
respEtag: weakEtag,
|
||||
reqHeaders: map[string]string{"If-None-Match": weakEtag},
|
||||
wantHandled: true,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": "", "Etag": weakEtag},
|
||||
wantStatus: http.StatusNotModified,
|
||||
},
|
||||
{
|
||||
name: "If-Modified-Since without If-None-Match",
|
||||
reqHeaders: map[string]string{"If-Modified-Since": lastModified},
|
||||
wantHandled: true,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": "", "Etag": matchedEtag},
|
||||
wantStatus: http.StatusNotModified,
|
||||
},
|
||||
{
|
||||
name: "Mismatched If-None-Match takes precedence over If-Modified-Since",
|
||||
reqHeaders: map[string]string{"If-None-Match": `"mismatched-etag"`, "If-Modified-Since": lastModified},
|
||||
wantHandled: false,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": cacheControl, "Etag": matchedEtag},
|
||||
},
|
||||
{
|
||||
name: "Multiple Matched If-None-Match",
|
||||
reqHeaders: map[string]string{"If-None-Match": `"mismatched-etag", ` + matchedEtag},
|
||||
wantHandled: true,
|
||||
wantHeaders: map[string]string{"Last-Modified": lastModified, "Cache-Control": "", "Etag": matchedEtag},
|
||||
wantStatus: http.StatusNotModified,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -107,10 +89,14 @@ func TestHandleGenericETagCache(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
assert.Equal(t, tc.wantHandled, HandleGenericETagPrivateCache(req, w, util.IfZero(tc.respEtag, matchedEtag), lastModifiedTime))
|
||||
resp := w.Result()
|
||||
for k, v := range tc.wantHeaders {
|
||||
for k, v := range map[string]string{
|
||||
"Last-Modified": lastModified,
|
||||
"Cache-Control": util.Iif(tc.wantHandled, "", cacheControl),
|
||||
"Etag": util.IfZero(tc.respEtag, matchedEtag),
|
||||
} {
|
||||
assert.Equal(t, v, resp.Header.Get(k))
|
||||
}
|
||||
assert.Equal(t, tc.wantStatus, util.Iif(resp.StatusCode == http.StatusOK, 0, resp.StatusCode))
|
||||
assert.Equal(t, util.Iif(tc.wantHandled, http.StatusNotModified, 0), util.Iif(resp.StatusCode == http.StatusOK, 0, resp.StatusCode))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -18,95 +18,51 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestServeUserContentByReader(t *testing.T) {
|
||||
func TestServeUserContent(t *testing.T) {
|
||||
data := "0123456789abcdef"
|
||||
|
||||
test := func(t *testing.T, expectedStatusCode int, expectedContent string) {
|
||||
_, rangeStr, _ := strings.Cut(t.Name(), "_range_")
|
||||
r := &http.Request{Header: http.Header{}, Form: url.Values{}}
|
||||
if rangeStr != "" {
|
||||
r.Header.Set("Range", "bytes="+rangeStr)
|
||||
}
|
||||
reader := strings.NewReader(data)
|
||||
w := httptest.NewRecorder()
|
||||
ServeUserContentByReader(r, w, int64(len(data)), reader, ServeHeaderOptions{})
|
||||
assert.Equal(t, expectedStatusCode, w.Code)
|
||||
if expectedStatusCode == http.StatusPartialContent || expectedStatusCode == http.StatusOK {
|
||||
assert.Equal(t, strconv.Itoa(len(expectedContent)), w.Header().Get("Content-Length"))
|
||||
assert.Equal(t, expectedContent, w.Body.String())
|
||||
}
|
||||
for _, source := range []string{"reader", "file"} {
|
||||
t.Run(source, func(t *testing.T) {
|
||||
var tmpFile string
|
||||
if source == "file" {
|
||||
tmpFile = t.TempDir() + "/test"
|
||||
assert.NoError(t, os.WriteFile(tmpFile, []byte(data), 0o644))
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
rangeStr string
|
||||
expectedStatusCode int
|
||||
expectedContent string
|
||||
}{
|
||||
{"", http.StatusOK, data},
|
||||
{"0-", http.StatusPartialContent, data},
|
||||
{"0-15", http.StatusPartialContent, data},
|
||||
{"1-", http.StatusPartialContent, data[1:]},
|
||||
{"1-3", http.StatusPartialContent, data[1 : 3+1]},
|
||||
{"16-", http.StatusRequestedRangeNotSatisfiable, ""},
|
||||
{"1-99999", http.StatusPartialContent, data[1:]},
|
||||
} {
|
||||
t.Run("_range_"+tc.rangeStr, func(t *testing.T) {
|
||||
r := &http.Request{Header: http.Header{}, Form: url.Values{}}
|
||||
if tc.rangeStr != "" {
|
||||
r.Header.Set("Range", "bytes="+tc.rangeStr)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
if source == "file" {
|
||||
seekReader, err := os.OpenFile(tmpFile, os.O_RDONLY, 0o644)
|
||||
require.NoError(t, err)
|
||||
defer seekReader.Close()
|
||||
ServeUserContentByFile(r, w, seekReader, ServeHeaderOptions{})
|
||||
} else {
|
||||
ServeUserContentByReader(r, w, int64(len(data)), strings.NewReader(data), ServeHeaderOptions{})
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatusCode, w.Code)
|
||||
if tc.expectedStatusCode == http.StatusPartialContent || tc.expectedStatusCode == http.StatusOK {
|
||||
assert.Equal(t, strconv.Itoa(len(tc.expectedContent)), w.Header().Get("Content-Length"))
|
||||
assert.Equal(t, tc.expectedContent, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("_range_", func(t *testing.T) {
|
||||
test(t, http.StatusOK, data)
|
||||
})
|
||||
t.Run("_range_0-", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data)
|
||||
})
|
||||
t.Run("_range_0-15", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data)
|
||||
})
|
||||
t.Run("_range_1-", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data[1:])
|
||||
})
|
||||
t.Run("_range_1-3", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data[1:3+1])
|
||||
})
|
||||
t.Run("_range_16-", func(t *testing.T) {
|
||||
test(t, http.StatusRequestedRangeNotSatisfiable, "")
|
||||
})
|
||||
t.Run("_range_1-99999", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data[1:])
|
||||
})
|
||||
}
|
||||
|
||||
func TestServeUserContentByFile(t *testing.T) {
|
||||
data := "0123456789abcdef"
|
||||
tmpFile := t.TempDir() + "/test"
|
||||
err := os.WriteFile(tmpFile, []byte(data), 0o644)
|
||||
assert.NoError(t, err)
|
||||
|
||||
test := func(t *testing.T, expectedStatusCode int, expectedContent string) {
|
||||
_, rangeStr, _ := strings.Cut(t.Name(), "_range_")
|
||||
r := &http.Request{Header: http.Header{}, Form: url.Values{}}
|
||||
if rangeStr != "" {
|
||||
r.Header.Set("Range", "bytes="+rangeStr)
|
||||
}
|
||||
|
||||
seekReader, err := os.OpenFile(tmpFile, os.O_RDONLY, 0o644)
|
||||
require.NoError(t, err)
|
||||
defer seekReader.Close()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
ServeUserContentByFile(r, w, seekReader, ServeHeaderOptions{})
|
||||
assert.Equal(t, expectedStatusCode, w.Code)
|
||||
if expectedStatusCode == http.StatusPartialContent || expectedStatusCode == http.StatusOK {
|
||||
assert.Equal(t, strconv.Itoa(len(expectedContent)), w.Header().Get("Content-Length"))
|
||||
assert.Equal(t, expectedContent, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("_range_", func(t *testing.T) {
|
||||
test(t, http.StatusOK, data)
|
||||
})
|
||||
t.Run("_range_0-", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data)
|
||||
})
|
||||
t.Run("_range_0-15", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data)
|
||||
})
|
||||
t.Run("_range_1-", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data[1:])
|
||||
})
|
||||
t.Run("_range_1-3", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data[1:3+1])
|
||||
})
|
||||
t.Run("_range_16-", func(t *testing.T) {
|
||||
test(t, http.StatusRequestedRangeNotSatisfiable, "")
|
||||
})
|
||||
t.Run("_range_1-99999", func(t *testing.T) {
|
||||
test(t, http.StatusPartialContent, data[1:])
|
||||
})
|
||||
}
|
||||
|
||||
func TestServeSetHeaderContentRelated(t *testing.T) {
|
||||
|
||||
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user