mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2026-05-13 22:40:24 +00:00
66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
// Copyright 2026 The Forgejo Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package forgery
|
|
|
|
import (
|
|
"math/rand/v2"
|
|
"regexp"
|
|
"strconv"
|
|
"testing"
|
|
|
|
org_model "forgejo.org/models/organization"
|
|
user_model "forgejo.org/models/user"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
var nameCleaner = regexp.MustCompile(`[^a-zA-Z0-9-]+`) // exclude "_", to prevent multiple consecutive dashes
|
|
|
|
// uniqueSafeName replaces specials chars with _ and appends a random hex suffix
|
|
func uniqueSafeName(testName string) string {
|
|
return nameCleaner.ReplaceAllLiteralString(testName, "_") + "-" + strconv.FormatUint(uint64(rand.Uint32()), 16)
|
|
}
|
|
|
|
type CreateUserOptions struct {
|
|
IsAdmin bool
|
|
}
|
|
|
|
const userPassword = "password"
|
|
|
|
func CreateUser(t testing.TB, opts *CreateUserOptions) *user_model.User {
|
|
t.Helper()
|
|
|
|
if opts == nil {
|
|
opts = &CreateUserOptions{}
|
|
}
|
|
u := &user_model.User{}
|
|
|
|
name := "user-" + uniqueSafeName(t.Name())
|
|
|
|
u.Name = name
|
|
u.Email = name + "@test.forgejo.org"
|
|
u.Passwd = userPassword
|
|
u.IsAdmin = opts.IsAdmin
|
|
|
|
err := user_model.CreateUser(t.Context(), u)
|
|
require.NoError(t, err)
|
|
return u
|
|
}
|
|
|
|
func CreateOrganisation(t testing.TB, owner *user_model.User) *org_model.Organization {
|
|
t.Helper()
|
|
|
|
if owner == nil {
|
|
owner = CreateUser(t, nil) // if specific options are needed, create the owner manually
|
|
}
|
|
o := &org_model.Organization{}
|
|
|
|
name := "org-" + uniqueSafeName(t.Name())
|
|
|
|
o.Name = name
|
|
|
|
err := org_model.CreateOrganization(t.Context(), o, owner)
|
|
require.NoError(t, err)
|
|
return o
|
|
}
|