diff options
author | Sami Hiltunen <shiltunen@gitlab.com> | 2020-03-18 17:01:14 +0300 |
---|---|---|
committer | Sami Hiltunen <shiltunen@gitlab.com> | 2020-03-20 16:58:23 +0300 |
commit | 3cd7f7b8dd786bb8d32077e1be77d3e1970f6e5e (patch) | |
tree | 41c09e6a5bfff191b7831f3ecfd599c6e6729b1a | |
parent | 2abaf625641391c3216fd66aeda183afb80cfa4e (diff) |
add TB interface to testhelpers package
Adds TB interface to the testhelpers package and modifies the existing
helpers to use the interface instead of `testing.TB`. This allows for
exporting test helpers from packages without bringing in the `testing`
package and the side effects importing it causes, such as additional
flag definitions in the default flag set.
-rw-r--r-- | internal/service/objectpool/fetch_into_object_pool_test.go | 4 | ||||
-rw-r--r-- | internal/service/repository/gc_test.go | 4 | ||||
-rw-r--r-- | internal/service/repository/repack_test.go | 8 | ||||
-rw-r--r-- | internal/testhelper/branch.go | 6 | ||||
-rw-r--r-- | internal/testhelper/commit.go | 9 | ||||
-rw-r--r-- | internal/testhelper/githttp.go | 3 | ||||
-rw-r--r-- | internal/testhelper/hook_env.go | 3 | ||||
-rw-r--r-- | internal/testhelper/interface.go | 25 | ||||
-rw-r--r-- | internal/testhelper/interface_test.go | 9 | ||||
-rw-r--r-- | internal/testhelper/remote.go | 3 | ||||
-rw-r--r-- | internal/testhelper/tag.go | 3 | ||||
-rw-r--r-- | internal/testhelper/test_hook.go | 5 | ||||
-rw-r--r-- | internal/testhelper/testhelper.go | 57 | ||||
-rw-r--r-- | internal/testhelper/testserver.go | 27 |
14 files changed, 94 insertions, 72 deletions
diff --git a/internal/service/objectpool/fetch_into_object_pool_test.go b/internal/service/objectpool/fetch_into_object_pool_test.go index 5f31a4159..280b60f20 100644 --- a/internal/service/objectpool/fetch_into_object_pool_test.go +++ b/internal/service/objectpool/fetch_into_object_pool_test.go @@ -65,12 +65,12 @@ func TestFetchIntoObjectPool_Success(t *testing.T) { } func TestFetchIntoObjectPool_CollectLogStatistics(t *testing.T) { - defer func(tl func(tb testing.TB) *logrus.Logger) { + defer func(tl func(tb testhelper.TB) *logrus.Logger) { testhelper.NewTestLogger = tl }(testhelper.NewTestLogger) logBuffer := &bytes.Buffer{} - testhelper.NewTestLogger = func(tb testing.TB) *logrus.Logger { + testhelper.NewTestLogger = func(tb testhelper.TB) *logrus.Logger { return &logrus.Logger{Out: logBuffer, Formatter: new(logrus.JSONFormatter), Level: logrus.InfoLevel} } diff --git a/internal/service/repository/gc_test.go b/internal/service/repository/gc_test.go index d8703e3b1..e16b70e84 100644 --- a/internal/service/repository/gc_test.go +++ b/internal/service/repository/gc_test.go @@ -124,12 +124,12 @@ func TestGarbageCollectSuccess(t *testing.T) { } func TestGarbageCollectLogStatistics(t *testing.T) { - defer func(tl func(tb testing.TB) *logrus.Logger) { + defer func(tl func(tb testhelper.TB) *logrus.Logger) { testhelper.NewTestLogger = tl }(testhelper.NewTestLogger) logBuffer := &bytes.Buffer{} - testhelper.NewTestLogger = func(tb testing.TB) *logrus.Logger { + testhelper.NewTestLogger = func(tb testhelper.TB) *logrus.Logger { return &logrus.Logger{Out: logBuffer, Formatter: new(logrus.JSONFormatter), Level: logrus.InfoLevel} } diff --git a/internal/service/repository/repack_test.go b/internal/service/repository/repack_test.go index 8865fc88e..037db1f59 100644 --- a/internal/service/repository/repack_test.go +++ b/internal/service/repository/repack_test.go @@ -50,12 +50,12 @@ func TestRepackIncrementalSuccess(t *testing.T) { } func TestRepackIncrementalCollectLogStatistics(t *testing.T) { - defer func(tl func(tb testing.TB) *logrus.Logger) { + defer func(tl func(tb testhelper.TB) *logrus.Logger) { testhelper.NewTestLogger = tl }(testhelper.NewTestLogger) logBuffer := &bytes.Buffer{} - testhelper.NewTestLogger = func(tb testing.TB) *logrus.Logger { + testhelper.NewTestLogger = func(tb testhelper.TB) *logrus.Logger { return &logrus.Logger{Out: logBuffer, Formatter: new(logrus.JSONFormatter), Level: logrus.InfoLevel} } @@ -199,12 +199,12 @@ func TestRepackFullSuccess(t *testing.T) { } func TestRepackFullCollectLogStatistics(t *testing.T) { - defer func(tl func(tb testing.TB) *logrus.Logger) { + defer func(tl func(tb testhelper.TB) *logrus.Logger) { testhelper.NewTestLogger = tl }(testhelper.NewTestLogger) logBuffer := &bytes.Buffer{} - testhelper.NewTestLogger = func(tb testing.TB) *logrus.Logger { + testhelper.NewTestLogger = func(tb testhelper.TB) *logrus.Logger { return &logrus.Logger{Out: logBuffer, Formatter: new(logrus.JSONFormatter), Level: logrus.InfoLevel} } diff --git a/internal/testhelper/branch.go b/internal/testhelper/branch.go index c4ac2e557..c8984e1a0 100644 --- a/internal/testhelper/branch.go +++ b/internal/testhelper/branch.go @@ -1,11 +1,7 @@ package testhelper -import ( - "testing" -) - // CreateRemoteBranch creates a new remote branch -func CreateRemoteBranch(t *testing.T, repoPath, remoteName, branchName, ref string) { +func CreateRemoteBranch(t TB, repoPath, remoteName, branchName, ref string) { MustRunCommand(t, nil, "git", "-C", repoPath, "update-ref", "refs/remotes/"+remoteName+"/"+branchName, ref) } diff --git a/internal/testhelper/commit.go b/internal/testhelper/commit.go index 4c4a567ba..a6b60131e 100644 --- a/internal/testhelper/commit.go +++ b/internal/testhelper/commit.go @@ -7,7 +7,6 @@ import ( "os/exec" "path" "strings" - "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/internal/helper/text" @@ -25,7 +24,7 @@ const ( ) // CreateCommit makes a new empty commit and updates the named branch to point to it. -func CreateCommit(t *testing.T, repoPath, branchName string, opts *CreateCommitOpts) string { +func CreateCommit(t TB, repoPath, branchName string, opts *CreateCommitOpts) string { message := "message" // The ID of an arbitrary commit known to exist in the test repository. parentID := "1a0b36b3cdad1d2ee32457c102a8c0b7056fa863" @@ -62,7 +61,7 @@ func CreateCommit(t *testing.T, repoPath, branchName string, opts *CreateCommitO // CreateCommitInAlternateObjectDirectory runs a command such that its created // objects will live in an alternate objects directory. It returns the current // head after the command is run and the alternate objects directory path -func CreateCommitInAlternateObjectDirectory(t *testing.T, repoPath, altObjectsDir string, cmd *exec.Cmd) (currentHead []byte) { +func CreateCommitInAlternateObjectDirectory(t TB, repoPath, altObjectsDir string, cmd *exec.Cmd) (currentHead []byte) { gitPath := path.Join(repoPath, ".git") altObjectsPath := path.Join(gitPath, altObjectsDir) @@ -92,7 +91,7 @@ func CreateCommitInAlternateObjectDirectory(t *testing.T, repoPath, altObjectsDi // specified name. This enables testing situations where the filepath is not // possible due to filesystem constraints (e.g. non-UTF characters). The commit // ID is returned. -func CommitBlobWithName(t *testing.T, testRepoPath, blobID, fileName, commitMessage string) string { +func CommitBlobWithName(t TB, testRepoPath, blobID, fileName, commitMessage string) string { mktreeIn := strings.NewReader(fmt.Sprintf("100644 blob %s\t%s", blobID, fileName)) treeID := text.ChompBytes(MustRunCommand(t, mktreeIn, "git", "-C", testRepoPath, "mktree")) @@ -105,7 +104,7 @@ func CommitBlobWithName(t *testing.T, testRepoPath, blobID, fileName, commitMess } // CreateCommitOnNewBranch creates a branch and a commit, returning the commit sha and the branch name respectivelyi -func CreateCommitOnNewBranch(t *testing.T, repoPath string) (string, string) { +func CreateCommitOnNewBranch(t TB, repoPath string) (string, string) { nonce, err := text.RandomHex(4) require.NoError(t, err) newBranch := "branch-" + nonce diff --git a/internal/testhelper/githttp.go b/internal/testhelper/githttp.go index 0c1416978..c694ed800 100644 --- a/internal/testhelper/githttp.go +++ b/internal/testhelper/githttp.go @@ -6,13 +6,12 @@ import ( "net/http" "net/http/cgi" "path/filepath" - "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/internal/config" ) -func GitServer(t testing.TB, repoPath string, middleware func(http.ResponseWriter, *http.Request, http.Handler)) (int, func() error) { +func GitServer(t TB, repoPath string, middleware func(http.ResponseWriter, *http.Request, http.Handler)) (int, func() error) { require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, "git-daemon-export-ok"), nil, 0644)) listener, err := net.Listen("tcp", "127.0.0.1:0") diff --git a/internal/testhelper/hook_env.go b/internal/testhelper/hook_env.go index 3efdeb078..8f5356d26 100644 --- a/internal/testhelper/hook_env.go +++ b/internal/testhelper/hook_env.go @@ -5,7 +5,6 @@ import ( "os" "path" "path/filepath" - "testing" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" @@ -15,7 +14,7 @@ import ( // CaptureHookEnv creates a bogus 'update' Git hook to sniff out what // environment variables get set for hooks. -func CaptureHookEnv(t *testing.T) (hookPath string, cleanup func()) { +func CaptureHookEnv(t TB) (hookPath string, cleanup func()) { var err error oldOverride := hooks.Override hooks.Override, err = filepath.Abs("testdata/scratch/hooks") diff --git a/internal/testhelper/interface.go b/internal/testhelper/interface.go new file mode 100644 index 000000000..c86ece6f3 --- /dev/null +++ b/internal/testhelper/interface.go @@ -0,0 +1,25 @@ +package testhelper + +// TB is an interface that matches that of testing.TB. +// Using TB rather than testing.TB prevents side effects from +// importing testing package such as extra flags being added to the default +// flag set. TB should be used in testing utilities that should be +// importable by tests in other packages, namely anything that is not in a +// *_test.go file. +type TB interface { + Error(args ...interface{}) + Errorf(format string, args ...interface{}) + Fail() + FailNow() + Failed() bool + Fatal(args ...interface{}) + Fatalf(format string, args ...interface{}) + Helper() + Log(args ...interface{}) + Logf(format string, args ...interface{}) + Name() string + Skip(args ...interface{}) + SkipNow() + Skipf(format string, args ...interface{}) + Skipped() bool +} diff --git a/internal/testhelper/interface_test.go b/internal/testhelper/interface_test.go new file mode 100644 index 000000000..24b3a1122 --- /dev/null +++ b/internal/testhelper/interface_test.go @@ -0,0 +1,9 @@ +package testhelper + +import ( + "testing" +) + +// test that TB interface is a subset of testing.TB, +// compiling fails if this is not the case. +var _ TB = (testing.TB)(nil) diff --git a/internal/testhelper/remote.go b/internal/testhelper/remote.go index ada387494..bdb483b2d 100644 --- a/internal/testhelper/remote.go +++ b/internal/testhelper/remote.go @@ -2,11 +2,10 @@ package testhelper import ( "strings" - "testing" ) // RemoteExists tests if the repository at repoPath has a Git remote named remoteName. -func RemoteExists(t *testing.T, repoPath string, remoteName string) bool { +func RemoteExists(t TB, repoPath string, remoteName string) bool { if remoteName == "" { t.Fatal("empty remote name") } diff --git a/internal/testhelper/tag.go b/internal/testhelper/tag.go index 2abfd9dcf..8d3fc72d6 100644 --- a/internal/testhelper/tag.go +++ b/internal/testhelper/tag.go @@ -3,7 +3,6 @@ package testhelper import ( "bytes" "fmt" - "testing" "gitlab.com/gitlab-org/gitaly/internal/helper/text" ) @@ -15,7 +14,7 @@ type CreateTagOpts struct { } // CreateTag creates a new tag. -func CreateTag(t *testing.T, repoPath, tagName, targetID string, opts *CreateTagOpts) string { +func CreateTag(t TB, repoPath, tagName, targetID string, opts *CreateTagOpts) string { var message string force := false diff --git a/internal/testhelper/test_hook.go b/internal/testhelper/test_hook.go index 8d0b0264c..e28eb5e35 100644 --- a/internal/testhelper/test_hook.go +++ b/internal/testhelper/test_hook.go @@ -2,7 +2,6 @@ package testhelper import ( "io/ioutil" - "testing" log "github.com/sirupsen/logrus" ) @@ -11,7 +10,7 @@ import ( var NewTestLogger = DiscardTestLogger // DiscardTestLogger created a logrus hook that discards everything. -func DiscardTestLogger(tb testing.TB) *log.Logger { +func DiscardTestLogger(tb TB) *log.Logger { logger := log.New() logger.Out = ioutil.Discard @@ -19,6 +18,6 @@ func DiscardTestLogger(tb testing.TB) *log.Logger { } // DiscardTestLogger created a logrus entry that discards everything. -func DiscardTestEntry(tb testing.TB) *log.Entry { +func DiscardTestEntry(tb TB) *log.Entry { return log.NewEntry(DiscardTestLogger(tb)) } diff --git a/internal/testhelper/testhelper.go b/internal/testhelper/testhelper.go index 0ba640434..9ead5bbee 100644 --- a/internal/testhelper/testhelper.go +++ b/internal/testhelper/testhelper.go @@ -18,7 +18,6 @@ import ( "strconv" "strings" "syscall" - "testing" "time" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" @@ -84,7 +83,7 @@ func configure() error { } // MustReadFile returns the content of a file or fails at once. -func MustReadFile(t *testing.T, filename string) []byte { +func MustReadFile(t TB, filename string) []byte { content, err := ioutil.ReadFile(filename) if err != nil { t.Fatal(err) @@ -104,7 +103,7 @@ func GitlabTestStoragePath() string { // GitalyServersMetadata returns a metadata pair for gitaly-servers to be used in // inter-gitaly operations. -func GitalyServersMetadata(t *testing.T, serverSocketPath string) metadata.MD { +func GitalyServersMetadata(t TB, serverSocketPath string) metadata.MD { gitalyServers := storage.GitalyServers{ "default": { "address": serverSocketPath, @@ -148,7 +147,7 @@ func TestRepository() *gitalypb.Repository { } // RequireGrpcError asserts the passed err is of the same code as expectedCode. -func RequireGrpcError(t *testing.T, err error, expectedCode codes.Code) { +func RequireGrpcError(t TB, err error, expectedCode codes.Code) { if err == nil { t.Fatal("Expected an error, got nil") } @@ -161,7 +160,7 @@ func RequireGrpcError(t *testing.T, err error, expectedCode codes.Code) { } // MustRunCommand runs a command with an optional standard input and returns the standard output, or fails. -func MustRunCommand(t testing.TB, stdin io.Reader, name string, args ...string) []byte { +func MustRunCommand(t TB, stdin io.Reader, name string, args ...string) []byte { cmd := exec.Command(name, args...) if name == "git" { @@ -273,7 +272,7 @@ func GetTemporaryGitalySocketFileName() string { // GetLocalhostListener listens on the next available TCP port and returns // the listener and the localhost address (host:port) string. -func GetLocalhostListener(t testing.TB) (net.Listener, string) { +func GetLocalhostListener(t TB) (net.Listener, string) { l, err := net.Listen("tcp", "localhost:0") require.NoError(t, err) @@ -314,7 +313,7 @@ func GetGitEnvData() (string, error) { } // NewTestGrpcServer creates a GRPC Server for testing purposes -func NewTestGrpcServer(tb testing.TB, streamInterceptors []grpc.StreamServerInterceptor, unaryInterceptors []grpc.UnaryServerInterceptor) *grpc.Server { +func NewTestGrpcServer(tb TB, streamInterceptors []grpc.StreamServerInterceptor, unaryInterceptors []grpc.UnaryServerInterceptor) *grpc.Server { logger := NewTestLogger(tb) logrusEntry := log.NewEntry(logger).WithField("test", tb.Name()) @@ -387,7 +386,7 @@ func Context() (context.Context, func()) { } // CreateRepo creates a temporary directory for a repo, without initializing it -func CreateRepo(t testing.TB, storagePath, relativePath string) *gitalypb.Repository { +func CreateRepo(t TB, storagePath, relativePath string) *gitalypb.Repository { require.NoError(t, os.MkdirAll(filepath.Dir(storagePath), 0755), "making repo parent dir") return &gitalypb.Repository{ StorageName: "default", @@ -397,16 +396,16 @@ func CreateRepo(t testing.TB, storagePath, relativePath string) *gitalypb.Reposi } // InitBareRepo creates a new bare repository -func InitBareRepo(t *testing.T) (*gitalypb.Repository, string, func()) { +func InitBareRepo(t TB) (*gitalypb.Repository, string, func()) { return initRepo(t, true) } // InitRepoWithWorktree creates a new repository with a worktree -func InitRepoWithWorktree(t *testing.T) (*gitalypb.Repository, string, func()) { +func InitRepoWithWorktree(t TB) (*gitalypb.Repository, string, func()) { return initRepo(t, false) } -func initRepo(t *testing.T, bare bool) (*gitalypb.Repository, string, func()) { +func initRepo(t TB, bare bool) (*gitalypb.Repository, string, func()) { storagePath := GitlabTestStoragePath() relativePath := NewRepositoryName(t) repoPath := filepath.Join(storagePath, relativePath) @@ -427,17 +426,17 @@ func initRepo(t *testing.T, bare bool) (*gitalypb.Repository, string, func()) { } // NewTestRepo creates a bare copy of the test repository. -func NewTestRepo(t testing.TB) (repo *gitalypb.Repository, repoPath string, cleanup func()) { +func NewTestRepo(t TB) (repo *gitalypb.Repository, repoPath string, cleanup func()) { return cloneTestRepo(t, true) } // NewTestRepoWithWorktree creates a copy of the test repository with a // worktree. This is allows you to run normal 'non-bare' Git commands. -func NewTestRepoWithWorktree(t testing.TB) (repo *gitalypb.Repository, repoPath string, cleanup func()) { +func NewTestRepoWithWorktree(t TB) (repo *gitalypb.Repository, repoPath string, cleanup func()) { return cloneTestRepo(t, false) } -func cloneTestRepo(t testing.TB, bare bool) (repo *gitalypb.Repository, repoPath string, cleanup func()) { +func cloneTestRepo(t TB, bare bool) (repo *gitalypb.Repository, repoPath string, cleanup func()) { storagePath := GitlabTestStoragePath() relativePath := NewRepositoryName(t) repoPath = filepath.Join(storagePath, relativePath) @@ -466,7 +465,7 @@ func AddWorktreeArgs(repoPath, worktreeName string) []string { } // AddWorktree creates a worktree in the repository path for tests -func AddWorktree(t *testing.T, repoPath string, worktreeName string) { +func AddWorktree(t TB, repoPath string, worktreeName string) { MustRunCommand(t, nil, "git", AddWorktreeArgs(repoPath, worktreeName)...) } @@ -489,14 +488,14 @@ func ConfigureGitalySSH() { } // GetRepositoryRefs gives a list of each repository ref as a string -func GetRepositoryRefs(t *testing.T, repoPath string) string { +func GetRepositoryRefs(t TB, repoPath string) string { refs := MustRunCommand(t, nil, "git", "-C", repoPath, "for-each-ref") return string(refs) } // AssertPathNotExists asserts true if the path doesn't exist, false otherwise -func AssertPathNotExists(t *testing.T, path string) { +func AssertPathNotExists(t TB, path string) { _, err := os.Stat(path) assert.True(t, os.IsNotExist(err), "file should not exist: %s", path) } @@ -504,7 +503,7 @@ func AssertPathNotExists(t *testing.T, path string) { // newDiskHash generates a random directory path following the Rails app's // approach in the hashed storage module, formatted as '[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{64}'. // https://gitlab.com/gitlab-org/gitlab/-/blob/f5c7d8eb1dd4eee5106123e04dec26d277ff6a83/app/models/storage/hashed.rb#L38-43 -func newDiskHash(t testing.TB) string { +func newDiskHash(t TB) string { // rails app calculates a sha256 and uses its hex representation // as the directory path b, err := text.RandomHex(sha256.Size) @@ -514,18 +513,18 @@ func newDiskHash(t testing.TB) string { // NewRepositoryName returns a random repository hash // in format '@hashed/[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{64}.git'. -func NewRepositoryName(t testing.TB) string { +func NewRepositoryName(t TB) string { return filepath.Join("@hashed", newDiskHash(t)) } // NewTestObjectPoolName returns a random pool repository name // in format '@pools/[0-9a-z]{2}/[0-9a-z]{2}/[0-9a-z]{64}.git'. -func NewTestObjectPoolName(t testing.TB) string { +func NewTestObjectPoolName(t TB) string { return filepath.Join("@pools", newDiskHash(t)) } // CreateLooseRef creates a ref that points to master -func CreateLooseRef(t *testing.T, repoPath, refName string) { +func CreateLooseRef(t TB, repoPath, refName string) { relRefPath := fmt.Sprintf("refs/heads/%s", refName) MustRunCommand(t, nil, "git", "-C", repoPath, "update-ref", relRefPath, "master") require.FileExists(t, filepath.Join(repoPath, relRefPath), "ref must be in loose file") @@ -535,7 +534,7 @@ func CreateLooseRef(t *testing.T, repoPath, refName string) { // The returned temp directory will be created in the directory specified by // environment variable TEST_TEMP_DIR_PATH. If that variable is unset, the // relative folder "./testdata/tmp" to this source file will be used. -func TempDir(t *testing.T, prefix string) (string, func() error) { +func TempDir(t TB, prefix string) (string, func() error) { _, currentFile, _, ok := runtime.Caller(0) if !ok { log.Fatal("Could not get caller info") @@ -550,16 +549,16 @@ func TempDir(t *testing.T, prefix string) (string, func() error) { } // GitObjectMustExist is a test assertion that fails unless the git repo in repoPath contains sha -func GitObjectMustExist(t testing.TB, repoPath, sha string) { +func GitObjectMustExist(t TB, repoPath, sha string) { gitObjectExists(t, repoPath, sha, true) } // GitObjectMustNotExist is a test assertion that fails unless the git repo in repoPath contains sha -func GitObjectMustNotExist(t testing.TB, repoPath, sha string) { +func GitObjectMustNotExist(t TB, repoPath, sha string) { gitObjectExists(t, repoPath, sha, false) } -func gitObjectExists(t testing.TB, repoPath, sha string, exists bool) { +func gitObjectExists(t TB, repoPath, sha string, exists bool) { cmd := exec.Command("git", "-C", repoPath, "cat-file", "-e", sha) if exists { require.NoError(t, cmd.Run(), "checking for object should succeed") @@ -573,16 +572,16 @@ func gitObjectExists(t testing.TB, repoPath, sha string, exists bool) { type Cleanup func() // GetGitObjectDirSize gets the number of 1k blocks of a git object directory -func GetGitObjectDirSize(t *testing.T, repoPath string) int64 { +func GetGitObjectDirSize(t TB, repoPath string) int64 { return getGitDirSize(t, repoPath, "objects") } // GetGitPackfileDirSize gets the number of 1k blocks of a git object directory -func GetGitPackfileDirSize(t *testing.T, repoPath string) int64 { +func GetGitPackfileDirSize(t TB, repoPath string) int64 { return getGitDirSize(t, repoPath, "objects", "pack") } -func getGitDirSize(t *testing.T, repoPath string, subdirs ...string) int64 { +func getGitDirSize(t TB, repoPath string, subdirs ...string) int64 { cmd := exec.Command("du", "-s", "-k", filepath.Join(append([]string{repoPath}, subdirs...)...)) output, err := cmd.Output() require.NoError(t, err) @@ -606,7 +605,7 @@ func GrpcErrorHasMessage(grpcError error, msg string) bool { } // dump the env vars that the custom hooks receives to a file -func WriteEnvToCustomHook(t *testing.T, repoPath, hookName string) (string, func()) { +func WriteEnvToCustomHook(t TB, repoPath, hookName string) (string, func()) { hookOutputTemp, err := ioutil.TempFile("", "") require.NoError(t, err) require.NoError(t, hookOutputTemp.Close()) diff --git a/internal/testhelper/testserver.go b/internal/testhelper/testserver.go index 38227789f..5d17e500a 100644 --- a/internal/testhelper/testserver.go +++ b/internal/testhelper/testserver.go @@ -13,7 +13,6 @@ import ( "path/filepath" "regexp" "strings" - "testing" "time" "github.com/BurntSushi/toml" @@ -75,7 +74,7 @@ func NewTestServer(srv *grpc.Server, opts ...TestServerOpt) *TestServer { } // NewServerWithAuth creates a new test server with authentication -func NewServerWithAuth(tb testing.TB, streamInterceptors []grpc.StreamServerInterceptor, unaryInterceptors []grpc.UnaryServerInterceptor, token string, opts ...TestServerOpt) *TestServer { +func NewServerWithAuth(tb TB, streamInterceptors []grpc.StreamServerInterceptor, unaryInterceptors []grpc.UnaryServerInterceptor, token string, opts ...TestServerOpt) *TestServer { if token != "" { if PraefectEnabled() { opts = append(opts, WithToken(token)) @@ -232,7 +231,7 @@ func waitForPraefectStartup(conn *grpc.ClientConn) error { } // NewServer creates a Server for testing purposes -func NewServer(tb testing.TB, streamInterceptors []grpc.StreamServerInterceptor, unaryInterceptors []grpc.UnaryServerInterceptor, opts ...TestServerOpt) *TestServer { +func NewServer(tb TB, streamInterceptors []grpc.StreamServerInterceptor, unaryInterceptors []grpc.UnaryServerInterceptor, opts ...TestServerOpt) *TestServer { logger := NewTestLogger(tb) logrusEntry := log.NewEntry(logger).WithField("test", tb.Name()) @@ -254,7 +253,7 @@ func NewServer(tb testing.TB, streamInterceptors []grpc.StreamServerInterceptor, var changeLineRegex = regexp.MustCompile("^[a-f0-9]{40} [a-f0-9]{40} refs/[^ ]+$") -func handleAllowed(t *testing.T, options GitlabTestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handleAllowed(t TB, options GitlabTestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { require.NoError(t, r.ParseForm()) require.Equal(t, http.MethodPost, r.Method, "expected http post") @@ -304,7 +303,7 @@ func handleAllowed(t *testing.T, options GitlabTestServerOptions) func(w http.Re } } -func handlePreReceive(t *testing.T, options GitlabTestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handlePreReceive(t TB, options GitlabTestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { require.NoError(t, r.ParseForm()) require.Equal(t, http.MethodPost, r.Method) @@ -321,7 +320,7 @@ func handlePreReceive(t *testing.T, options GitlabTestServerOptions) func(w http } } -func handlePostReceive(t *testing.T, options GitlabTestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handlePostReceive(t TB, options GitlabTestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { require.NoError(t, r.ParseForm()) require.Equal(t, http.MethodPost, r.Method) @@ -377,7 +376,7 @@ type GitlabTestServerOptions struct { } // NewGitlabTestServer returns a mock gitlab server that responds to the hook api endpoints -func NewGitlabTestServer(t *testing.T, options GitlabTestServerOptions) *httptest.Server { +func NewGitlabTestServer(t TB, options GitlabTestServerOptions) *httptest.Server { mux := http.NewServeMux() mux.Handle("/api/v4/internal/allowed", http.HandlerFunc(handleAllowed(t, options))) mux.Handle("/api/v4/internal/pre_receive", http.HandlerFunc(handlePreReceive(t, options))) @@ -389,7 +388,7 @@ func NewGitlabTestServer(t *testing.T, options GitlabTestServerOptions) *httptes // CreateTemporaryGitlabShellDir creates a temporary gitlab shell directory. It returns the path to the directory // and a cleanup function -func CreateTemporaryGitlabShellDir(t *testing.T) (string, func()) { +func CreateTemporaryGitlabShellDir(t TB) (string, func()) { tempDir, err := ioutil.TempDir("", "gitlab-shell") require.NoError(t, err) return tempDir, func() { @@ -399,7 +398,7 @@ func CreateTemporaryGitlabShellDir(t *testing.T) (string, func()) { // WriteTemporaryGitlabShellConfigFile writes a gitlab shell config.yml in a temporary directory. It returns the path // and a cleanup function -func WriteTemporaryGitlabShellConfigFile(t *testing.T, dir string, config GitlabShellConfig) (string, func()) { +func WriteTemporaryGitlabShellConfigFile(t TB, dir string, config GitlabShellConfig) (string, func()) { out, err := yaml.Marshal(&config) require.NoError(t, err) @@ -413,7 +412,7 @@ func WriteTemporaryGitlabShellConfigFile(t *testing.T, dir string, config Gitlab // WriteTemporaryGitalyConfigFile writes a gitaly toml file into a temporary directory. It returns the path to // the file as well as a cleanup function -func WriteTemporaryGitalyConfigFile(t *testing.T, tempDir string) (string, func()) { +func WriteTemporaryGitalyConfigFile(t TB, tempDir string) (string, func()) { path := filepath.Join(tempDir, "config.toml") contents := fmt.Sprintf(` [gitlab-shell] @@ -431,7 +430,7 @@ type GlHookValues struct { } // EnvForHooks generates a set of environment variables for gitaly hooks -func EnvForHooks(t *testing.T, gitlabShellDir string, glHookValues GlHookValues, gitPushOptions ...string) []string { +func EnvForHooks(t TB, gitlabShellDir string, glHookValues GlHookValues, gitPushOptions ...string) []string { rubyDir, err := filepath.Abs("../../ruby") require.NoError(t, err) @@ -450,7 +449,7 @@ func EnvForHooks(t *testing.T, gitlabShellDir string, glHookValues GlHookValues, } // WriteShellSecretFile writes a .gitlab_shell_secret file in the specified directory -func WriteShellSecretFile(t *testing.T, dir, secretToken string) { +func WriteShellSecretFile(t TB, dir, secretToken string) { require.NoError(t, ioutil.WriteFile(filepath.Join(dir, ".gitlab_shell_secret"), []byte(secretToken), 0644)) } @@ -466,7 +465,7 @@ type HTTPSettings struct { Password string `yaml:"password"` } -func NewServerWithHealth(t testing.TB, socketName string) (*grpc.Server, *health.Server) { +func NewServerWithHealth(t TB, socketName string) (*grpc.Server, *health.Server) { srv := NewTestGrpcServer(t, nil, nil) healthSrvr := health.NewServer() grpc_health_v1.RegisterHealthServer(srv, healthSrvr) @@ -480,7 +479,7 @@ func NewServerWithHealth(t testing.TB, socketName string) (*grpc.Server, *health return srv, healthSrvr } -func SetupAndStartGitlabServer(t *testing.T, c *GitlabTestServerOptions) func() { +func SetupAndStartGitlabServer(t TB, c *GitlabTestServerOptions) func() { ts := NewGitlabTestServer(t, *c) WriteTemporaryGitlabShellConfigFile(t, config.Config.GitlabShell.Dir, GitlabShellConfig{GitlabURL: ts.URL}) |