From 055f6d229672524e3933940f95aa28939d94961a Mon Sep 17 00:00:00 2001
From: zeripath <art27@cantab.net>
Date: Mon, 25 Nov 2019 23:21:37 +0000
Subject: [PATCH] Fix "data race" in testlogger (#9159)

* Fix data race in testlogger

* Update git_helper_for_declarative_test.go
---
 integrations/api_admin_org_test.go            |  2 +-
 integrations/api_admin_test.go                | 16 ++++++-------
 integrations/api_branch_test.go               |  2 +-
 integrations/api_comment_test.go              | 10 ++++----
 integrations/api_fork_test.go                 |  2 +-
 integrations/api_gpg_keys_test.go             |  2 +-
 integrations/api_issue_test.go                |  4 ++--
 integrations/api_keys_test.go                 | 14 +++++------
 integrations/api_pull_test.go                 |  8 +++----
 integrations/api_releases_test.go             |  6 ++---
 integrations/api_repo_git_blobs_test.go       |  2 +-
 integrations/api_repo_git_commits_test.go     |  8 +++----
 integrations/api_repo_git_hook_test.go        | 18 +++++++-------
 integrations/api_repo_git_ref_test.go         |  2 +-
 integrations/api_repo_git_tags_test.go        |  2 +-
 integrations/api_repo_git_trees_test.go       |  2 +-
 integrations/api_repo_lfs_locks_test.go       |  6 ++---
 integrations/api_repo_raw_test.go             |  2 +-
 integrations/api_repo_tags_test.go            |  2 +-
 integrations/api_repo_test.go                 | 14 +++++------
 integrations/api_repo_topic_test.go           |  2 +-
 integrations/api_team_test.go                 |  4 ++--
 integrations/api_team_user_test.go            |  2 +-
 integrations/api_token_test.go                |  4 ++--
 integrations/api_user_heatmap_test.go         |  2 +-
 integrations/api_user_orgs_test.go            |  4 ++--
 integrations/api_user_search_test.go          |  4 ++--
 integrations/auth_ldap_test.go                |  8 +++----
 integrations/branches_test.go                 |  6 ++---
 integrations/change_default_branch_test.go    |  2 +-
 integrations/cors_test.go                     |  2 +-
 integrations/create_no_session_test.go        |  6 ++---
 integrations/delete_user_test.go              |  6 ++---
 integrations/download_test.go                 |  4 ++--
 integrations/empty_repo_test.go               |  2 +-
 integrations/explore_repos_test.go            |  2 +-
 integrations/git_test.go                      | 22 ++++++++---------
 integrations/gpg_git_test.go                  | 24 +++++++++----------
 integrations/integration_test.go              |  5 ++--
 integrations/issue_test.go                    | 14 +++++------
 integrations/lfs_getobject_test.go            |  2 +-
 integrations/links_test.go                    |  6 ++---
 integrations/migration-test/migration_test.go |  9 +++----
 integrations/nonascii_branches_test.go        |  2 +-
 integrations/oauth_test.go                    | 20 ++++++++--------
 integrations/org_test.go                      |  6 ++---
 integrations/pull_compare_test.go             |  2 +-
 integrations/pull_merge_test.go               | 12 +++++-----
 integrations/pull_review_test.go              |  2 +-
 integrations/release_test.go                  | 12 +++++-----
 integrations/repo_branch_test.go              |  4 ++--
 integrations/repo_commits_search_test.go      |  2 +-
 integrations/repo_commits_test.go             |  4 ++--
 integrations/repo_fork_test.go                |  4 ++--
 integrations/repo_generate_test.go            |  4 ++--
 integrations/repo_migrate_test.go             |  2 +-
 integrations/repo_search_test.go              |  2 +-
 integrations/repo_test.go                     | 14 +++++------
 integrations/setting_test.go                  |  6 ++---
 integrations/signin_test.go                   |  2 +-
 integrations/signout_test.go                  |  2 +-
 integrations/signup_test.go                   |  2 +-
 integrations/testlogger.go                    | 23 +++++++++++++-----
 integrations/timetracking_test.go             |  6 ++---
 integrations/user_test.go                     | 10 ++++----
 integrations/version_test.go                  |  2 +-
 integrations/xss_test.go                      |  2 +-
 67 files changed, 213 insertions(+), 200 deletions(-)

diff --git a/integrations/api_admin_org_test.go b/integrations/api_admin_org_test.go
index 546ed861c25..b10f5607d30 100644
--- a/integrations/api_admin_org_test.go
+++ b/integrations/api_admin_org_test.go
@@ -69,7 +69,7 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) {
 }
 
 func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	nonAdminUsername := "user2"
 	session := loginUser(t, nonAdminUsername)
 	token := getTokenForLoggedInUser(t, session)
diff --git a/integrations/api_admin_test.go b/integrations/api_admin_test.go
index 825aed9d504..eda8f076c3e 100644
--- a/integrations/api_admin_test.go
+++ b/integrations/api_admin_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	// user1 is an admin user
 	session := loginUser(t, "user1")
 	keyOwner := models.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User)
@@ -46,7 +46,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) {
 }
 
 func TestAPIAdminDeleteMissingSSHKey(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	// user1 is an admin user
 	session := loginUser(t, "user1")
 
@@ -56,7 +56,7 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) {
 }
 
 func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	normalUsername := "user2"
 	session := loginUser(t, adminUsername)
@@ -79,7 +79,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) {
 }
 
 func TestAPISudoUser(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	normalUsername := "user2"
 	session := loginUser(t, adminUsername)
@@ -95,7 +95,7 @@ func TestAPISudoUser(t *testing.T) {
 }
 
 func TestAPISudoUserForbidden(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	normalUsername := "user2"
 
@@ -108,7 +108,7 @@ func TestAPISudoUserForbidden(t *testing.T) {
 }
 
 func TestAPIListUsers(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	session := loginUser(t, adminUsername)
 	token := getTokenForLoggedInUser(t, session)
@@ -131,13 +131,13 @@ func TestAPIListUsers(t *testing.T) {
 }
 
 func TestAPIListUsersNotLoggedIn(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", "/api/v1/admin/users")
 	MakeRequest(t, req, http.StatusUnauthorized)
 }
 
 func TestAPIListUsersNonAdmin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	nonAdminUsername := "user2"
 	session := loginUser(t, nonAdminUsername)
 	token := getTokenForLoggedInUser(t, session)
diff --git a/integrations/api_branch_test.go b/integrations/api_branch_test.go
index fddbe4e40ef..037a42deec6 100644
--- a/integrations/api_branch_test.go
+++ b/integrations/api_branch_test.go
@@ -14,7 +14,7 @@ import (
 )
 
 func testAPIGetBranch(t *testing.T, branchName string, exists bool) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	token := getTokenForLoggedInUser(t, session)
diff --git a/integrations/api_comment_test.go b/integrations/api_comment_test.go
index 7bd36449126..0716c5d8593 100644
--- a/integrations/api_comment_test.go
+++ b/integrations/api_comment_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestAPIListRepoComments(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
 		models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
@@ -40,7 +40,7 @@ func TestAPIListRepoComments(t *testing.T) {
 }
 
 func TestAPIListIssueComments(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
 		models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
@@ -61,7 +61,7 @@ func TestAPIListIssueComments(t *testing.T) {
 }
 
 func TestAPICreateComment(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	const commentBody = "Comment body"
 
 	issue := models.AssertExistsAndLoadBean(t, &models.Issue{}).(*models.Issue)
@@ -84,7 +84,7 @@ func TestAPICreateComment(t *testing.T) {
 }
 
 func TestAPIEditComment(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	const newCommentBody = "This is the new comment body"
 
 	comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
@@ -110,7 +110,7 @@ func TestAPIEditComment(t *testing.T) {
 }
 
 func TestAPIDeleteComment(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
 		models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
diff --git a/integrations/api_fork_test.go b/integrations/api_fork_test.go
index fec288d96fe..4f3b023312c 100644
--- a/integrations/api_fork_test.go
+++ b/integrations/api_fork_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestCreateForkNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/forks", &api.CreateForkOption{})
 	MakeRequest(t, req, http.StatusUnauthorized)
 }
diff --git a/integrations/api_gpg_keys_test.go b/integrations/api_gpg_keys_test.go
index 0384dcb22a0..edae22205e7 100644
--- a/integrations/api_gpg_keys_test.go
+++ b/integrations/api_gpg_keys_test.go
@@ -18,7 +18,7 @@ import (
 type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseRecorder
 
 func TestGPGKeys(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	token := getTokenForLoggedInUser(t, session)
 
diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go
index 24535057e24..f412f5af085 100644
--- a/integrations/api_issue_test.go
+++ b/integrations/api_issue_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestAPIListIssues(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -35,7 +35,7 @@ func TestAPIListIssues(t *testing.T) {
 }
 
 func TestAPICreateIssue(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	const body, title = "apiTestBody", "apiTestTitle"
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
diff --git a/integrations/api_keys_test.go b/integrations/api_keys_test.go
index d9686a063ce..6979480543b 100644
--- a/integrations/api_keys_test.go
+++ b/integrations/api_keys_test.go
@@ -17,13 +17,13 @@ import (
 )
 
 func TestViewDeployKeysNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/keys")
 	MakeRequest(t, req, http.StatusUnauthorized)
 }
 
 func TestCreateDeployKeyNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/keys", api.CreateKeyOption{
 		Title: "title",
 		Key:   "key",
@@ -32,19 +32,19 @@ func TestCreateDeployKeyNoLogin(t *testing.T) {
 }
 
 func TestGetDeployKeyNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/keys/1")
 	MakeRequest(t, req, http.StatusUnauthorized)
 }
 
 func TestDeleteDeployKeyNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "DELETE", "/api/v1/repos/user2/repo1/keys/1")
 	MakeRequest(t, req, http.StatusUnauthorized)
 }
 
 func TestCreateReadOnlyDeployKey(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
 	repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 
@@ -70,7 +70,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) {
 }
 
 func TestCreateReadWriteDeployKey(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
 	repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 
@@ -95,7 +95,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) {
 }
 
 func TestCreateUserKey(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
 
 	session := loginUser(t, "user1")
diff --git a/integrations/api_pull_test.go b/integrations/api_pull_test.go
index ed5a55a9db0..9e22be5755b 100644
--- a/integrations/api_pull_test.go
+++ b/integrations/api_pull_test.go
@@ -19,7 +19,7 @@ import (
 )
 
 func TestAPIViewPulls(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 
@@ -36,7 +36,7 @@ func TestAPIViewPulls(t *testing.T) {
 
 // TestAPIMergePullWIP ensures that we can't merge a WIP pull request
 func TestAPIMergePullWIP(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 	pr := models.AssertExistsAndLoadBean(t, &models.PullRequest{Status: models.PullRequestStatusMergeable}, models.Cond("has_merged = ?", false)).(*models.PullRequest)
@@ -59,7 +59,7 @@ func TestAPIMergePullWIP(t *testing.T) {
 }
 
 func TestAPICreatePullSuccess1(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo10 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
 	// repo10 have code, pulls units.
 	repo11 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
@@ -79,7 +79,7 @@ func TestAPICreatePullSuccess1(t *testing.T) {
 }
 
 func TestAPICreatePullSuccess2(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo10 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
 	owner10 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
 
diff --git a/integrations/api_releases_test.go b/integrations/api_releases_test.go
index 8025f1de5d5..9aef33d0689 100644
--- a/integrations/api_releases_test.go
+++ b/integrations/api_releases_test.go
@@ -42,7 +42,7 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string,
 }
 
 func TestAPICreateAndUpdateRelease(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -93,7 +93,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
 }
 
 func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -104,7 +104,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
 }
 
 func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
diff --git a/integrations/api_repo_git_blobs_test.go b/integrations/api_repo_git_blobs_test.go
index ad81299ba45..675916eeaaa 100644
--- a/integrations/api_repo_git_blobs_test.go
+++ b/integrations/api_repo_git_blobs_test.go
@@ -15,7 +15,7 @@ import (
 )
 
 func TestAPIReposGitBlobs(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)               // owner of the repo1 & repo16
 	user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)               // owner of the repo3
 	user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)               // owner of neither repos
diff --git a/integrations/api_repo_git_commits_test.go b/integrations/api_repo_git_commits_test.go
index 16db1e871c7..5291b8f4acb 100644
--- a/integrations/api_repo_git_commits_test.go
+++ b/integrations/api_repo_git_commits_test.go
@@ -15,7 +15,7 @@ import (
 )
 
 func TestAPIReposGitCommits(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
@@ -35,7 +35,7 @@ func TestAPIReposGitCommits(t *testing.T) {
 }
 
 func TestAPIReposGitCommitList(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
@@ -55,7 +55,7 @@ func TestAPIReposGitCommitList(t *testing.T) {
 }
 
 func TestAPIReposGitCommitListPage2Empty(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
@@ -72,7 +72,7 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) {
 }
 
 func TestAPIReposGitCommitListDifferentBranch(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
diff --git a/integrations/api_repo_git_hook_test.go b/integrations/api_repo_git_hook_test.go
index 1c6de786777..f7e55d92ae8 100644
--- a/integrations/api_repo_git_hook_test.go
+++ b/integrations/api_repo_git_hook_test.go
@@ -21,7 +21,7 @@ echo Hello, World!
 `
 
 func TestAPIListGitHooks(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -47,7 +47,7 @@ func TestAPIListGitHooks(t *testing.T) {
 }
 
 func TestAPIListGitHooksNoHooks(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -68,7 +68,7 @@ func TestAPIListGitHooksNoHooks(t *testing.T) {
 }
 
 func TestAPIListGitHooksNoAccess(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -81,7 +81,7 @@ func TestAPIListGitHooksNoAccess(t *testing.T) {
 }
 
 func TestAPIGetGitHook(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -99,7 +99,7 @@ func TestAPIGetGitHook(t *testing.T) {
 }
 
 func TestAPIGetGitHookNoAccess(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -112,7 +112,7 @@ func TestAPIGetGitHookNoAccess(t *testing.T) {
 }
 
 func TestAPIEditGitHook(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -142,7 +142,7 @@ func TestAPIEditGitHook(t *testing.T) {
 }
 
 func TestAPIEditGitHookNoAccess(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -158,7 +158,7 @@ func TestAPIEditGitHookNoAccess(t *testing.T) {
 }
 
 func TestAPIDeleteGitHook(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
@@ -181,7 +181,7 @@ func TestAPIDeleteGitHook(t *testing.T) {
 }
 
 func TestAPIDeleteGitHookNoAccess(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
diff --git a/integrations/api_repo_git_ref_test.go b/integrations/api_repo_git_ref_test.go
index 1a7864a7c10..39237f59a25 100644
--- a/integrations/api_repo_git_ref_test.go
+++ b/integrations/api_repo_git_ref_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestAPIReposGitRefs(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
diff --git a/integrations/api_repo_git_tags_test.go b/integrations/api_repo_git_tags_test.go
index d6ff08990a3..ef2e1ccd085 100644
--- a/integrations/api_repo_git_tags_test.go
+++ b/integrations/api_repo_git_tags_test.go
@@ -17,7 +17,7 @@ import (
 )
 
 func TestAPIGitTags(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	// Login as User2.
diff --git a/integrations/api_repo_git_trees_test.go b/integrations/api_repo_git_trees_test.go
index 95da7738f24..6b4e120dec1 100644
--- a/integrations/api_repo_git_trees_test.go
+++ b/integrations/api_repo_git_trees_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestAPIReposGitTrees(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)               // owner of the repo1 & repo16
 	user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)               // owner of the repo3
 	user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)               // owner of neither repos
diff --git a/integrations/api_repo_lfs_locks_test.go b/integrations/api_repo_lfs_locks_test.go
index 4fe92b33b5f..69981d1c420 100644
--- a/integrations/api_repo_lfs_locks_test.go
+++ b/integrations/api_repo_lfs_locks_test.go
@@ -18,7 +18,7 @@ import (
 )
 
 func TestAPILFSLocksNotStarted(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	setting.LFS.StartServer = false
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
@@ -34,7 +34,7 @@ func TestAPILFSLocksNotStarted(t *testing.T) {
 }
 
 func TestAPILFSLocksNotLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	setting.LFS.StartServer = true
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
@@ -48,7 +48,7 @@ func TestAPILFSLocksNotLogin(t *testing.T) {
 }
 
 func TestAPILFSLocksLogged(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	setting.LFS.StartServer = true
 	user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) //in org 3
 	user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) //in org 3
diff --git a/integrations/api_repo_raw_test.go b/integrations/api_repo_raw_test.go
index d8da9c831d5..62b734fa060 100644
--- a/integrations/api_repo_raw_test.go
+++ b/integrations/api_repo_raw_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestAPIReposRaw(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
diff --git a/integrations/api_repo_tags_test.go b/integrations/api_repo_tags_test.go
index 252037bd4a5..9988a483001 100644
--- a/integrations/api_repo_tags_test.go
+++ b/integrations/api_repo_tags_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestAPIReposGetTags(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	// Login as User2.
 	session := loginUser(t, user.Name)
diff --git a/integrations/api_repo_test.go b/integrations/api_repo_test.go
index e021911afdb..add546fb49a 100644
--- a/integrations/api_repo_test.go
+++ b/integrations/api_repo_test.go
@@ -19,7 +19,7 @@ import (
 )
 
 func TestAPIUserReposNotLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 
 	req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name)
@@ -37,7 +37,7 @@ func TestAPIUserReposNotLogin(t *testing.T) {
 }
 
 func TestAPISearchRepo(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	const keyword = "test"
 
 	req := NewRequestf(t, "GET", "/api/v1/repos/search?q=%s", keyword)
@@ -207,7 +207,7 @@ func getRepo(t *testing.T, repoID int64) *models.Repository {
 }
 
 func TestAPIViewRepo(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1")
 	resp := MakeRequest(t, req, http.StatusOK)
@@ -219,7 +219,7 @@ func TestAPIViewRepo(t *testing.T) {
 }
 
 func TestAPIOrgRepos(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 	user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
@@ -265,7 +265,7 @@ func TestAPIOrgRepos(t *testing.T) {
 }
 
 func TestAPIGetRepoByIDUnauthorized(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)
 	session := loginUser(t, user.Name)
 	token := getTokenForLoggedInUser(t, session)
@@ -286,7 +286,7 @@ func TestAPIRepoMigrate(t *testing.T) {
 		{ctxUserID: 2, userID: 6, cloneURL: "https://github.com/go-gitea/git.git", repoName: "git-bad-org", expectedStatus: http.StatusForbidden},
 	}
 
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	for _, testCase := range testCases {
 		user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
 		session := loginUser(t, user.Name)
@@ -351,7 +351,7 @@ func TestAPIOrgRepoCreate(t *testing.T) {
 		{ctxUserID: 28, orgName: "user6", repoName: "repo-not-creator", expectedStatus: http.StatusForbidden},
 	}
 
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	for _, testCase := range testCases {
 		user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
 		session := loginUser(t, user.Name)
diff --git a/integrations/api_repo_topic_test.go b/integrations/api_repo_topic_test.go
index 34c33d1b258..b96489ae221 100644
--- a/integrations/api_repo_topic_test.go
+++ b/integrations/api_repo_topic_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestAPIRepoTopic(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of repo2
 	user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of repo3
 	user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // write access to repo 3
diff --git a/integrations/api_team_test.go b/integrations/api_team_test.go
index 3a27cd48659..be56e37edfe 100644
--- a/integrations/api_team_test.go
+++ b/integrations/api_team_test.go
@@ -18,7 +18,7 @@ import (
 )
 
 func TestAPITeam(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	teamUser := models.AssertExistsAndLoadBean(t, &models.TeamUser{}).(*models.TeamUser)
 	team := models.AssertExistsAndLoadBean(t, &models.Team{ID: teamUser.TeamID}).(*models.Team)
@@ -122,7 +122,7 @@ type TeamSearchResults struct {
 }
 
 func TestAPITeamSearch(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	org := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
diff --git a/integrations/api_team_user_test.go b/integrations/api_team_user_test.go
index f847c789496..eec8634cb03 100644
--- a/integrations/api_team_user_test.go
+++ b/integrations/api_team_user_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestAPITeamUser(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	normalUsername := "user2"
 	session := loginUser(t, normalUsername)
diff --git a/integrations/api_token_test.go b/integrations/api_token_test.go
index 76660d160f3..05b9af7a266 100644
--- a/integrations/api_token_test.go
+++ b/integrations/api_token_test.go
@@ -14,7 +14,7 @@ import (
 
 // TestAPICreateAndDeleteToken tests that token that was just created can be deleted
 func TestAPICreateAndDeleteToken(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 
 	req := NewRequestWithJSON(t, "POST", "/api/v1/users/user1/tokens", map[string]string{
@@ -41,7 +41,7 @@ func TestAPICreateAndDeleteToken(t *testing.T) {
 
 // TestAPIDeleteMissingToken ensures that error is thrown when token not found
 func TestAPIDeleteMissingToken(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 
 	req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", models.NonexistentID)
diff --git a/integrations/api_user_heatmap_test.go b/integrations/api_user_heatmap_test.go
index 2e2636ce94d..159d70e8679 100644
--- a/integrations/api_user_heatmap_test.go
+++ b/integrations/api_user_heatmap_test.go
@@ -15,7 +15,7 @@ import (
 )
 
 func TestUserHeatmap(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	normalUsername := "user2"
 	session := loginUser(t, adminUsername)
diff --git a/integrations/api_user_orgs_test.go b/integrations/api_user_orgs_test.go
index 6611a429d1f..849cb74c46e 100644
--- a/integrations/api_user_orgs_test.go
+++ b/integrations/api_user_orgs_test.go
@@ -16,7 +16,7 @@ import (
 )
 
 func TestUserOrgs(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	normalUsername := "user2"
 	session := loginUser(t, adminUsername)
@@ -44,7 +44,7 @@ func TestUserOrgs(t *testing.T) {
 }
 
 func TestMyOrgs(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	normalUsername := "user2"
 	session := loginUser(t, normalUsername)
diff --git a/integrations/api_user_search_test.go b/integrations/api_user_search_test.go
index b4c95db2f31..66618622282 100644
--- a/integrations/api_user_search_test.go
+++ b/integrations/api_user_search_test.go
@@ -19,7 +19,7 @@ type SearchResults struct {
 }
 
 func TestAPIUserSearchLoggedIn(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	adminUsername := "user1"
 	session := loginUser(t, adminUsername)
 	token := getTokenForLoggedInUser(t, session)
@@ -37,7 +37,7 @@ func TestAPIUserSearchLoggedIn(t *testing.T) {
 }
 
 func TestAPIUserSearchNotLoggedIn(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	query := "user2"
 	req := NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query)
 	resp := MakeRequest(t, req, http.StatusOK)
diff --git a/integrations/auth_ldap_test.go b/integrations/auth_ldap_test.go
index 9ea3184ae79..5cb2bad57d2 100644
--- a/integrations/auth_ldap_test.go
+++ b/integrations/auth_ldap_test.go
@@ -124,7 +124,7 @@ func TestLDAPUserSignin(t *testing.T) {
 		t.Skip()
 		return
 	}
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	addAuthSourceLDAP(t, "")
 
 	u := gitLDAPUsers[0]
@@ -145,7 +145,7 @@ func TestLDAPUserSync(t *testing.T) {
 		t.Skip()
 		return
 	}
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	addAuthSourceLDAP(t, "")
 	models.SyncExternalUsers()
 
@@ -191,7 +191,7 @@ func TestLDAPUserSigninFailed(t *testing.T) {
 		t.Skip()
 		return
 	}
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	addAuthSourceLDAP(t, "")
 
 	u := otherLDAPUsers[0]
@@ -204,7 +204,7 @@ func TestLDAPUserSSHKeySync(t *testing.T) {
 		t.Skip()
 		return
 	}
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	addAuthSourceLDAP(t, "sshPublicKey")
 	models.SyncExternalUsers()
 
diff --git a/integrations/branches_test.go b/integrations/branches_test.go
index ea38821d218..ed6a73fdb43 100644
--- a/integrations/branches_test.go
+++ b/integrations/branches_test.go
@@ -15,7 +15,7 @@ import (
 )
 
 func TestViewBranches(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2/repo1/branches")
 	resp := MakeRequest(t, req, http.StatusOK)
@@ -26,13 +26,13 @@ func TestViewBranches(t *testing.T) {
 }
 
 func TestDeleteBranch(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	deleteBranch(t)
 }
 
 func TestUndoDeleteBranch(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	deleteBranch(t)
 	htmlDoc, name := branchAction(t, ".undo-button")
diff --git a/integrations/change_default_branch_test.go b/integrations/change_default_branch_test.go
index dbd189cd28a..dcd6d9b08b2 100644
--- a/integrations/change_default_branch_test.go
+++ b/integrations/change_default_branch_test.go
@@ -13,7 +13,7 @@ import (
 )
 
 func TestChangeDefaultBranch(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 
diff --git a/integrations/cors_test.go b/integrations/cors_test.go
index 02b6b9dbfca..466984c79a7 100644
--- a/integrations/cors_test.go
+++ b/integrations/cors_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestCORSNotSet(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestf(t, "GET", "/api/v1/version")
 	session := loginUser(t, "user2")
 	resp := session.MakeRequest(t, req, http.StatusOK)
diff --git a/integrations/create_no_session_test.go b/integrations/create_no_session_test.go
index 2d21f250051..8d5b6f2f7cb 100644
--- a/integrations/create_no_session_test.go
+++ b/integrations/create_no_session_test.go
@@ -52,7 +52,7 @@ func sessionFileExist(t *testing.T, tmpDir, sessionID string) bool {
 }
 
 func TestSessionFileCreation(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	oldSessionConfig := setting.SessionConfig.ProviderConfig
 	defer func() {
@@ -86,7 +86,7 @@ func TestSessionFileCreation(t *testing.T) {
 	routes.RegisterRoutes(mac)
 
 	t.Run("NoSessionOnViewIssue", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 
 		req := NewRequest(t, "GET", "/user2/repo1/issues/1")
 		resp := MakeRequest(t, req, http.StatusOK)
@@ -96,7 +96,7 @@ func TestSessionFileCreation(t *testing.T) {
 		assert.False(t, sessionFileExist(t, tmpDir, sessionID))
 	})
 	t.Run("CreateSessionOnLogin", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 
 		req := NewRequest(t, "GET", "/user/login")
 		resp := MakeRequest(t, req, http.StatusOK)
diff --git a/integrations/delete_user_test.go b/integrations/delete_user_test.go
index 2a5ca89860f..32032b3ddf4 100644
--- a/integrations/delete_user_test.go
+++ b/integrations/delete_user_test.go
@@ -25,7 +25,7 @@ func assertUserDeleted(t *testing.T, userID int64) {
 }
 
 func TestAdminDeleteUser(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user1")
 
@@ -40,7 +40,7 @@ func TestAdminDeleteUser(t *testing.T) {
 }
 
 func TestUserDeleteAccount(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user8")
 	csrf := GetCSRF(t, session, "/user/settings/account")
@@ -55,7 +55,7 @@ func TestUserDeleteAccount(t *testing.T) {
 }
 
 func TestUserDeleteAccountStillOwnRepos(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	csrf := GetCSRF(t, session, "/user/settings/account")
diff --git a/integrations/download_test.go b/integrations/download_test.go
index 3fd858887e6..6bc5e5a9afd 100644
--- a/integrations/download_test.go
+++ b/integrations/download_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestDownloadByID(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
@@ -24,7 +24,7 @@ func TestDownloadByID(t *testing.T) {
 }
 
 func TestDownloadByIDMedia(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
diff --git a/integrations/empty_repo_test.go b/integrations/empty_repo_test.go
index 2d72546e7d9..77b8adf686f 100644
--- a/integrations/empty_repo_test.go
+++ b/integrations/empty_repo_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestEmptyRepo(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	subpaths := []string{
 		"commits/master",
 		"raw/foo",
diff --git a/integrations/explore_repos_test.go b/integrations/explore_repos_test.go
index 7408f063028..c6f695612a8 100644
--- a/integrations/explore_repos_test.go
+++ b/integrations/explore_repos_test.go
@@ -10,7 +10,7 @@ import (
 )
 
 func TestExploreRepos(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/explore/repos")
 	MakeRequest(t, req, http.StatusOK)
diff --git a/integrations/git_test.go b/integrations/git_test.go
index c0e1d7d2841..f6137a947a6 100644
--- a/integrations/git_test.go
+++ b/integrations/git_test.go
@@ -43,7 +43,7 @@ func testGit(t *testing.T, u *url.URL) {
 	forkedUserCtx := NewAPITestContext(t, "user4", "repo1")
 
 	t.Run("HTTP", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		ensureAnonymousClone(t, u)
 		httpContext := baseAPITestContext
 		httpContext.Reponame = "repo-tmp-17"
@@ -77,7 +77,7 @@ func testGit(t *testing.T, u *url.URL) {
 		})
 	})
 	t.Run("SSH", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		sshContext := baseAPITestContext
 		sshContext.Reponame = "repo-tmp-18"
 		keyname := "my-testing-key"
@@ -127,7 +127,7 @@ func ensureAnonymousClone(t *testing.T, u *url.URL) {
 
 func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
 	t.Run("Standard", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		little, big = commitAndPushTest(t, dstPath, "data-file-")
 	})
 	return
@@ -135,7 +135,7 @@ func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string
 
 func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
 	t.Run("LFS", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		setting.CheckLFSVersion()
 		if !setting.LFS.StartServer {
 			t.Skip()
@@ -168,7 +168,7 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin
 		littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
 
 		t.Run("Locks", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			lockTest(t, dstPath)
 		})
 	})
@@ -177,9 +177,9 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin
 
 func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
 	t.Run("PushCommit", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		t.Run("Little", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			little = doCommitAndPush(t, littleSize, dstPath, prefix)
 		})
 		t.Run("Big", func(t *testing.T) {
@@ -187,7 +187,7 @@ func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string
 				t.Skip("Skipping test in short mode.")
 				return
 			}
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			big = doCommitAndPush(t, bigSize, dstPath, prefix)
 		})
 	})
@@ -196,7 +196,7 @@ func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string
 
 func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
 	t.Run("Raw", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		username := ctx.Username
 		reponame := ctx.Reponame
 
@@ -232,7 +232,7 @@ func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS s
 
 func mediaTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
 	t.Run("Media", func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 
 		username := ctx.Username
 		reponame := ctx.Reponame
@@ -331,7 +331,7 @@ func generateCommitWithNewData(size int, repoPath, email, fullName, prefix strin
 
 func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
 	return func(t *testing.T) {
-		PrintCurrentTest(t)
+		defer PrintCurrentTest(t)()
 		t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected"))
 		t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
 
diff --git a/integrations/gpg_git_test.go b/integrations/gpg_git_test.go
index cc06a5fdd22..a5a3406b868 100644
--- a/integrations/gpg_git_test.go
+++ b/integrations/gpg_git_test.go
@@ -66,7 +66,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("Unsigned-Initial", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			t.Run("CreateRepository", doAPICreateRepository(testCtx, false))
 			t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) {
@@ -90,7 +90,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			t.Run("CreateCRUDFile-ParentSigned", crudActionCreateFile(
 				t, testCtx, user, "master", "parentsigned", "signed-parent.txt", func(t *testing.T, response api.FileResponse) {
@@ -107,7 +107,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("Unsigned-Initial-CRUD-Never", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			t.Run("CreateCRUDFile-Never", crudActionCreateFile(
 				t, testCtx, user, "parentsigned", "parentsigned-never", "unsigned-never2.txt", func(t *testing.T, response api.FileResponse) {
@@ -120,7 +120,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("Unsigned-Initial-CRUD-Always", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			t.Run("CreateCRUDFile-Always", crudActionCreateFile(
 				t, testCtx, user, "master", "always", "signed-always.txt", func(t *testing.T, response api.FileResponse) {
@@ -139,7 +139,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			t.Run("CreateCRUDFile-Always-ParentSigned", crudActionCreateFile(
 				t, testCtx, user, "always", "always-parentsigned", "signed-always-parentsigned.txt", func(t *testing.T, response api.FileResponse) {
@@ -153,7 +153,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("AlwaysSign-Initial", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-always")
 			t.Run("CreateRepository", doAPICreateRepository(testCtx, false))
 			t.Run("CheckMasterBranchSigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) {
@@ -169,7 +169,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("AlwaysSign-Initial-CRUD-Never", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-always")
 			t.Run("CreateCRUDFile-Never", crudActionCreateFile(
 				t, testCtx, user, "master", "never", "unsigned-never.txt", func(t *testing.T, response api.FileResponse) {
@@ -182,7 +182,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("AlwaysSign-Initial-CRUD-ParentSigned-On-Always", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-always")
 			t.Run("CreateCRUDFile-ParentSigned", crudActionCreateFile(
 				t, testCtx, user, "master", "parentsigned", "signed-parent.txt", func(t *testing.T, response api.FileResponse) {
@@ -196,7 +196,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("AlwaysSign-Initial-CRUD-Always", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-always")
 			t.Run("CreateCRUDFile-Always", crudActionCreateFile(
 				t, testCtx, user, "master", "always", "signed-always.txt", func(t *testing.T, response api.FileResponse) {
@@ -212,7 +212,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("UnsignedMerging", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			var err error
 			t.Run("CreatePullRequest", func(t *testing.T) {
@@ -233,7 +233,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("BaseSignedMerging", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			var err error
 			t.Run("CreatePullRequest", func(t *testing.T) {
@@ -254,7 +254,7 @@ func TestGPGGit(t *testing.T) {
 		u.Path = baseAPITestContext.GitPath()
 
 		t.Run("CommitsSignedMerging", func(t *testing.T) {
-			PrintCurrentTest(t)
+			defer PrintCurrentTest(t)()
 			testCtx := NewAPITestContext(t, username, "initial-unsigned")
 			var err error
 			t.Run("CreatePullRequest", func(t *testing.T) {
diff --git a/integrations/integration_test.go b/integrations/integration_test.go
index 8d7f47dcfbd..4177493930b 100644
--- a/integrations/integration_test.go
+++ b/integrations/integration_test.go
@@ -173,19 +173,20 @@ func initIntegrationTest() {
 	routers.GlobalInit()
 }
 
-func prepareTestEnv(t testing.TB, skip ...int) {
+func prepareTestEnv(t testing.TB, skip ...int) func() {
 	t.Helper()
 	ourSkip := 2
 	if len(skip) > 0 {
 		ourSkip += skip[0]
 	}
-	PrintCurrentTest(t, ourSkip)
+	deferFn := PrintCurrentTest(t, ourSkip)
 	assert.NoError(t, models.LoadFixtures())
 	assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
 	assert.NoError(t, os.RemoveAll(models.LocalCopyPath()))
 
 	assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
 		setting.RepoRootPath))
+	return deferFn
 }
 
 type TestSession struct {
diff --git a/integrations/issue_test.go b/integrations/issue_test.go
index aa17c44254f..5a4b75b7510 100644
--- a/integrations/issue_test.go
+++ b/integrations/issue_test.go
@@ -49,14 +49,14 @@ func assertMatch(t testing.TB, issue *models.Issue, keyword string) {
 }
 
 func TestNoLoginViewIssues(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2/repo1/issues")
 	MakeRequest(t, req, http.StatusOK)
 }
 
 func TestViewIssuesSortByType(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
@@ -84,7 +84,7 @@ func TestViewIssuesSortByType(t *testing.T) {
 }
 
 func TestViewIssuesKeyword(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 
@@ -104,7 +104,7 @@ func TestViewIssuesKeyword(t *testing.T) {
 }
 
 func TestNoLoginViewIssue(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2/repo1/issues/1")
 	MakeRequest(t, req, http.StatusOK)
@@ -173,13 +173,13 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content,
 }
 
 func TestNewIssue(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	testNewIssue(t, session, "user2", "repo1", "Title", "Description")
 }
 
 func TestIssueCommentClose(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	issueURL := testNewIssue(t, session, "user2", "repo1", "Title", "Description")
 	testIssueAddComment(t, session, issueURL, "Test comment 1", "")
@@ -195,7 +195,7 @@ func TestIssueCommentClose(t *testing.T) {
 }
 
 func TestIssueCrossReference(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	// Issue that will be referenced
 	_, issueBase := testIssueWithBean(t, "user2", 1, "Title", "Description")
diff --git a/integrations/lfs_getobject_test.go b/integrations/lfs_getobject_test.go
index e9c1d1178fc..15d9c52a756 100644
--- a/integrations/lfs_getobject_test.go
+++ b/integrations/lfs_getobject_test.go
@@ -57,7 +57,7 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string
 }
 
 func doLfs(t *testing.T, content *[]byte, expectGzip bool) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	setting.CheckLFSVersion()
 	if !setting.LFS.StartServer {
 		t.Skip()
diff --git a/integrations/links_test.go b/integrations/links_test.go
index 468c8a0f21d..97b390ed12d 100644
--- a/integrations/links_test.go
+++ b/integrations/links_test.go
@@ -18,7 +18,7 @@ import (
 )
 
 func TestLinksNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	var links = []string{
 		"/explore/repos",
@@ -44,7 +44,7 @@ func TestLinksNoLogin(t *testing.T) {
 }
 
 func TestRedirectsNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	var redirects = map[string]string{
 		"/user2/repo1/commits/master":                "/user2/repo1/commits/branch/master",
@@ -144,7 +144,7 @@ func testLinksAsUser(userName string, t *testing.T) {
 }
 
 func TestLinksLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	testLinksAsUser("user2", t)
 }
diff --git a/integrations/migration-test/migration_test.go b/integrations/migration-test/migration_test.go
index 8dc366dc3f3..4fe36dc0211 100644
--- a/integrations/migration-test/migration_test.go
+++ b/integrations/migration-test/migration_test.go
@@ -29,8 +29,8 @@ import (
 
 var currentEngine *xorm.Engine
 
-func initMigrationTest(t *testing.T) {
-	integrations.PrintCurrentTest(t, 2)
+func initMigrationTest(t *testing.T) func() {
+	deferFn := integrations.PrintCurrentTest(t, 2)
 	giteaRoot := base.SetupGiteaRoot()
 	if giteaRoot == "" {
 		integrations.Printf("Environment variable $GITEA_ROOT not set\n")
@@ -56,6 +56,7 @@ func initMigrationTest(t *testing.T) {
 	setting.CheckLFSVersion()
 	setting.InitDBConfig()
 	setting.NewLogServices(true)
+	return deferFn
 }
 
 func availableVersions() ([]string, error) {
@@ -209,7 +210,7 @@ func wrappedMigrate(x *xorm.Engine) error {
 }
 
 func doMigrationTest(t *testing.T, version string) {
-	integrations.PrintCurrentTest(t)
+	defer integrations.PrintCurrentTest(t)()
 	integrations.Printf("Performing migration test for %s version: %s\n", setting.Database.Type, version)
 	if !restoreOldDB(t, version) {
 		return
@@ -225,7 +226,7 @@ func doMigrationTest(t *testing.T, version string) {
 }
 
 func TestMigrations(t *testing.T) {
-	initMigrationTest(t)
+	defer initMigrationTest(t)()
 
 	dialect := setting.Database.Type
 	versions, err := availableVersions()
diff --git a/integrations/nonascii_branches_test.go b/integrations/nonascii_branches_test.go
index e59a5ef8bc9..22d71e6ee20 100644
--- a/integrations/nonascii_branches_test.go
+++ b/integrations/nonascii_branches_test.go
@@ -161,7 +161,7 @@ func TestNonasciiBranches(t *testing.T) {
 		},
 	}
 
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	user := "user2"
 	repo := "utf8"
diff --git a/integrations/oauth_test.go b/integrations/oauth_test.go
index ed5761a86bd..1307baba891 100644
--- a/integrations/oauth_test.go
+++ b/integrations/oauth_test.go
@@ -16,20 +16,20 @@ import (
 const defaultAuthorize = "/login/oauth/authorize?client_id=da7da3ba-9a13-4167-856f-3899de0b0138&redirect_uri=a&response_type=code&state=thestate"
 
 func TestNoClientID(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", "/login/oauth/authorize")
 	ctx := loginUser(t, "user2")
 	ctx.MakeRequest(t, req, 400)
 }
 
 func TestLoginRedirect(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", "/login/oauth/authorize")
 	assert.Contains(t, MakeRequest(t, req, 302).Body.String(), "/user/login")
 }
 
 func TestShowAuthorize(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", defaultAuthorize)
 	ctx := loginUser(t, "user4")
 	resp := ctx.MakeRequest(t, req, 200)
@@ -40,7 +40,7 @@ func TestShowAuthorize(t *testing.T) {
 }
 
 func TestRedirectWithExistingGrant(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequest(t, "GET", defaultAuthorize)
 	ctx := loginUser(t, "user1")
 	resp := ctx.MakeRequest(t, req, 302)
@@ -51,7 +51,7 @@ func TestRedirectWithExistingGrant(t *testing.T) {
 }
 
 func TestAccessTokenExchange(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
@@ -74,7 +74,7 @@ func TestAccessTokenExchange(t *testing.T) {
 }
 
 func TestAccessTokenExchangeWithoutPKCE(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
@@ -97,7 +97,7 @@ func TestAccessTokenExchangeWithoutPKCE(t *testing.T) {
 }
 
 func TestAccessTokenExchangeJSON(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
@@ -109,7 +109,7 @@ func TestAccessTokenExchangeJSON(t *testing.T) {
 }
 
 func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	// invalid client id
 	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
@@ -163,7 +163,7 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) {
 }
 
 func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"redirect_uri":  "a",
@@ -204,7 +204,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
 }
 
 func TestRefreshTokenInvalidation(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
diff --git a/integrations/org_test.go b/integrations/org_test.go
index d86c82989d4..b0212f4af7a 100644
--- a/integrations/org_test.go
+++ b/integrations/org_test.go
@@ -13,7 +13,7 @@ import (
 )
 
 func TestOrgRepos(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	var (
 		users = []string{"user1", "user2"}
@@ -43,7 +43,7 @@ func TestOrgRepos(t *testing.T) {
 }
 
 func TestLimitedOrg(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	// not logged in user
 	req := NewRequest(t, "GET", "/limited_org")
@@ -73,7 +73,7 @@ func TestLimitedOrg(t *testing.T) {
 }
 
 func TestPrivateOrg(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	// not logged in user
 	req := NewRequest(t, "GET", "/privated_org")
diff --git a/integrations/pull_compare_test.go b/integrations/pull_compare_test.go
index b473e03653f..1dec39a28f5 100644
--- a/integrations/pull_compare_test.go
+++ b/integrations/pull_compare_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestPullCompare(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	req := NewRequest(t, "GET", "/user2/repo1/pulls")
diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go
index a63e27e1494..218f0e4da66 100644
--- a/integrations/pull_merge_test.go
+++ b/integrations/pull_merge_test.go
@@ -105,7 +105,7 @@ func TestPullRebase(t *testing.T) {
 
 func TestPullRebaseMerge(t *testing.T) {
 	onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 
 		hookTasks, err := models.HookTasks(1, 1) //Retrieve previous hook number
 		assert.NoError(t, err)
@@ -129,7 +129,7 @@ func TestPullRebaseMerge(t *testing.T) {
 
 func TestPullSquash(t *testing.T) {
 	onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 
 		hookTasks, err := models.HookTasks(1, 1) //Retrieve previous hook number
 		assert.NoError(t, err)
@@ -154,7 +154,7 @@ func TestPullSquash(t *testing.T) {
 
 func TestPullCleanUpAfterMerge(t *testing.T) {
 	onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 		session := loginUser(t, "user1")
 		testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
 		testEditFileToNewBranch(t, session, "user1", "repo1", "master", "feature/test", "README.md", "Hello, World (Edited)\n")
@@ -190,7 +190,7 @@ func TestPullCleanUpAfterMerge(t *testing.T) {
 
 func TestCantMergeWorkInProgress(t *testing.T) {
 	onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 		session := loginUser(t, "user1")
 		testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
 		testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n")
@@ -212,7 +212,7 @@ func TestCantMergeWorkInProgress(t *testing.T) {
 
 func TestCantMergeConflict(t *testing.T) {
 	onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 		session := loginUser(t, "user1")
 		testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
 		testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n")
@@ -258,7 +258,7 @@ func TestCantMergeConflict(t *testing.T) {
 
 func TestCantMergeUnrelated(t *testing.T) {
 	onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 		session := loginUser(t, "user1")
 		testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
 		testEditFileToNewBranch(t, session, "user1", "repo1", "master", "base", "README.md", "Hello, World (Edited Twice)\n")
diff --git a/integrations/pull_review_test.go b/integrations/pull_review_test.go
index b4ddc0e7419..d8f7b52d549 100644
--- a/integrations/pull_review_test.go
+++ b/integrations/pull_review_test.go
@@ -9,7 +9,7 @@ import (
 )
 
 func TestPullView_ReviewerMissed(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user1")
 
 	req := NewRequest(t, "GET", "/pulls")
diff --git a/integrations/release_test.go b/integrations/release_test.go
index 135607153eb..85564249018 100644
--- a/integrations/release_test.go
+++ b/integrations/release_test.go
@@ -58,7 +58,7 @@ func checkLatestReleaseAndCount(t *testing.T, session *TestSession, repoURL, ver
 }
 
 func TestViewReleases(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	req := NewRequest(t, "GET", "/user2/repo1/releases")
@@ -66,14 +66,14 @@ func TestViewReleases(t *testing.T) {
 }
 
 func TestViewReleasesNoLogin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2/repo1/releases")
 	MakeRequest(t, req, http.StatusOK)
 }
 
 func TestCreateRelease(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	createNewRelease(t, session, "/user2/repo1", "v0.0.1", "v0.0.1", false, false)
@@ -82,7 +82,7 @@ func TestCreateRelease(t *testing.T) {
 }
 
 func TestCreateReleasePreRelease(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	createNewRelease(t, session, "/user2/repo1", "v0.0.1", "v0.0.1", true, false)
@@ -91,7 +91,7 @@ func TestCreateReleasePreRelease(t *testing.T) {
 }
 
 func TestCreateReleaseDraft(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	createNewRelease(t, session, "/user2/repo1", "v0.0.1", "v0.0.1", false, true)
@@ -100,7 +100,7 @@ func TestCreateReleaseDraft(t *testing.T) {
 }
 
 func TestCreateReleasePaging(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	// Create enaugh releases to have paging
diff --git a/integrations/repo_branch_test.go b/integrations/repo_branch_test.go
index dbde2769938..68806f347bd 100644
--- a/integrations/repo_branch_test.go
+++ b/integrations/repo_branch_test.go
@@ -110,7 +110,7 @@ func testCreateBranches(t *testing.T, giteaURL *url.URL) {
 		},
 	}
 	for _, test := range tests {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 		session := loginUser(t, "user2")
 		if test.CreateRelease != "" {
 			createNewRelease(t, session, "/user2/repo1", test.CreateRelease, test.CreateRelease, false, false)
@@ -129,7 +129,7 @@ func testCreateBranches(t *testing.T, giteaURL *url.URL) {
 }
 
 func TestCreateBranchInvalidCSRF(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	req := NewRequestWithValues(t, "POST", "user2/repo1/branches/_new/branch/master", map[string]string{
 		"_csrf":           "fake_csrf",
diff --git a/integrations/repo_commits_search_test.go b/integrations/repo_commits_search_test.go
index c8bc1b56e65..3cd548e8102 100644
--- a/integrations/repo_commits_search_test.go
+++ b/integrations/repo_commits_search_test.go
@@ -14,7 +14,7 @@ import (
 )
 
 func testRepoCommitsSearch(t *testing.T, query, commit string) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
diff --git a/integrations/repo_commits_test.go b/integrations/repo_commits_test.go
index 7a4761adc64..2aa0260a169 100644
--- a/integrations/repo_commits_test.go
+++ b/integrations/repo_commits_test.go
@@ -18,7 +18,7 @@ import (
 )
 
 func TestRepoCommits(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
@@ -33,7 +33,7 @@ func TestRepoCommits(t *testing.T) {
 }
 
 func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	token := getTokenForLoggedInUser(t, session)
diff --git a/integrations/repo_fork_test.go b/integrations/repo_fork_test.go
index 64bc46f7771..d0542c1a72c 100644
--- a/integrations/repo_fork_test.go
+++ b/integrations/repo_fork_test.go
@@ -54,13 +54,13 @@ func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkO
 }
 
 func TestRepoFork(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user1")
 	testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
 }
 
 func TestRepoForkToOrg(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	testRepoFork(t, session, "user2", "repo1", "user3", "repo1")
 
diff --git a/integrations/repo_generate_test.go b/integrations/repo_generate_test.go
index b8f2a45e1e3..1aa91236ea3 100644
--- a/integrations/repo_generate_test.go
+++ b/integrations/repo_generate_test.go
@@ -55,13 +55,13 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, tem
 }
 
 func TestRepoGenerate(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user1")
 	testRepoGenerate(t, session, "user27", "template1", "user1", "generated1")
 }
 
 func TestRepoGenerateToOrg(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	testRepoGenerate(t, session, "user27", "template1", "user2", "generated2")
 }
diff --git a/integrations/repo_migrate_test.go b/integrations/repo_migrate_test.go
index 41791c1d0b4..f95218a114c 100644
--- a/integrations/repo_migrate_test.go
+++ b/integrations/repo_migrate_test.go
@@ -36,7 +36,7 @@ func testRepoMigrate(t testing.TB, session *TestSession, cloneAddr, repoName str
 }
 
 func TestRepoMigrate(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	testRepoMigrate(t, session, "https://github.com/go-gitea/git.git", "git")
 }
diff --git a/integrations/repo_search_test.go b/integrations/repo_search_test.go
index 32a872e409f..eb843525fb8 100644
--- a/integrations/repo_search_test.go
+++ b/integrations/repo_search_test.go
@@ -29,7 +29,7 @@ func resultFilenames(t testing.TB, doc *HTMLDoc) []string {
 }
 
 func TestSearchRepo(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	repo, err := models.GetRepositoryByOwnerAndName("user2", "repo1")
 	assert.NoError(t, err)
diff --git a/integrations/repo_test.go b/integrations/repo_test.go
index b733c9679fc..b5ff072ea4c 100644
--- a/integrations/repo_test.go
+++ b/integrations/repo_test.go
@@ -17,7 +17,7 @@ import (
 )
 
 func TestViewRepo(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2/repo1")
 	MakeRequest(t, req, http.StatusOK)
@@ -30,7 +30,7 @@ func TestViewRepo(t *testing.T) {
 }
 
 func TestViewRepo2(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user3/repo3")
 	session := loginUser(t, "user2")
@@ -38,7 +38,7 @@ func TestViewRepo2(t *testing.T) {
 }
 
 func TestViewRepo3(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user3/repo3")
 	session := loginUser(t, "user4")
@@ -46,7 +46,7 @@ func TestViewRepo3(t *testing.T) {
 }
 
 func TestViewRepo1CloneLinkAnonymous(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2/repo1")
 	resp := MakeRequest(t, req, http.StatusOK)
@@ -60,7 +60,7 @@ func TestViewRepo1CloneLinkAnonymous(t *testing.T) {
 }
 
 func TestViewRepo1CloneLinkAuthorized(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
@@ -78,7 +78,7 @@ func TestViewRepo1CloneLinkAuthorized(t *testing.T) {
 }
 
 func TestViewRepoWithSymlinks(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
@@ -106,7 +106,7 @@ func TestViewAsRepoAdmin(t *testing.T) {
 		"user2": true,
 		"user4": false,
 	} {
-		prepareTestEnv(t)
+		defer prepareTestEnv(t)()
 
 		session := loginUser(t, user)
 
diff --git a/integrations/setting_test.go b/integrations/setting_test.go
index 54f4fded661..518a3b7c6f8 100644
--- a/integrations/setting_test.go
+++ b/integrations/setting_test.go
@@ -14,7 +14,7 @@ import (
 )
 
 func TestSettingShowUserEmailExplore(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	showUserEmail := setting.UI.ShowUserEmail
 	setting.UI.ShowUserEmail = true
@@ -42,7 +42,7 @@ func TestSettingShowUserEmailExplore(t *testing.T) {
 }
 
 func TestSettingShowUserEmailProfile(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	showUserEmail := setting.UI.ShowUserEmail
 	setting.UI.ShowUserEmail = true
@@ -81,7 +81,7 @@ func TestSettingShowUserEmailProfile(t *testing.T) {
 }
 
 func TestSettingLandingPage(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	landingPage := setting.LandingPageURL
 
diff --git a/integrations/signin_test.go b/integrations/signin_test.go
index 4a2bb8857ac..390bf6408bf 100644
--- a/integrations/signin_test.go
+++ b/integrations/signin_test.go
@@ -31,7 +31,7 @@ func testLoginFailed(t *testing.T, username, password, message string) {
 }
 
 func TestSignin(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 
diff --git a/integrations/signout_test.go b/integrations/signout_test.go
index 002cb42daad..65957b244e6 100644
--- a/integrations/signout_test.go
+++ b/integrations/signout_test.go
@@ -10,7 +10,7 @@ import (
 )
 
 func TestSignOut(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 
diff --git a/integrations/signup_test.go b/integrations/signup_test.go
index e122efa39c5..02262ec8537 100644
--- a/integrations/signup_test.go
+++ b/integrations/signup_test.go
@@ -12,7 +12,7 @@ import (
 )
 
 func TestSignup(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	setting.Service.EnableCaptcha = false
 
diff --git a/integrations/testlogger.go b/integrations/testlogger.go
index 91b94ac9f3c..624abf3f811 100644
--- a/integrations/testlogger.go
+++ b/integrations/testlogger.go
@@ -27,20 +27,23 @@ var writerCloser = &testLoggerWriterCloser{}
 
 type testLoggerWriterCloser struct {
 	sync.RWMutex
-	t testing.TB
+	t []*testing.TB
 }
 
 func (w *testLoggerWriterCloser) setT(t *testing.TB) {
 	w.Lock()
-	w.t = *t
+	w.t = append(w.t, t)
 	w.Unlock()
 }
 
 func (w *testLoggerWriterCloser) Write(p []byte) (int, error) {
 	w.RLock()
-	t := w.t
+	var t *testing.TB
+	if len(w.t) > 0 {
+		t = w.t[len(w.t)-1]
+	}
 	w.RUnlock()
-	if t != nil {
+	if t != nil && *t != nil {
 		if len(p) > 0 && p[len(p)-1] == '\n' {
 			p = p[:len(p)-1]
 		}
@@ -65,18 +68,23 @@ func (w *testLoggerWriterCloser) Write(p []byte) (int, error) {
 			}
 		}()
 
-		t.Log(string(p))
+		(*t).Log(string(p))
 		return len(p), nil
 	}
 	return len(p), nil
 }
 
 func (w *testLoggerWriterCloser) Close() error {
+	w.Lock()
+	if len(w.t) > 0 {
+		w.t = w.t[:len(w.t)-1]
+	}
+	w.Unlock()
 	return nil
 }
 
 // PrintCurrentTest prints the current test to os.Stdout
-func PrintCurrentTest(t testing.TB, skip ...int) {
+func PrintCurrentTest(t testing.TB, skip ...int) func() {
 	actualSkip := 1
 	if len(skip) > 0 {
 		actualSkip = skip[0]
@@ -89,6 +97,9 @@ func PrintCurrentTest(t testing.TB, skip ...int) {
 		fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", t.Name(), strings.TrimPrefix(filename, prefix), line)
 	}
 	writerCloser.setT(&t)
+	return func() {
+		_ = writerCloser.Close()
+	}
 }
 
 // Printf takes a format and args and prints the string to os.Stdout
diff --git a/integrations/timetracking_test.go b/integrations/timetracking_test.go
index 890f12b300d..cd3002e1acc 100644
--- a/integrations/timetracking_test.go
+++ b/integrations/timetracking_test.go
@@ -16,20 +16,20 @@ import (
 )
 
 func TestViewTimetrackingControls(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	testViewTimetrackingControls(t, session, "user2", "repo1", "1", true)
 	//user2/repo1
 }
 
 func TestNotViewTimetrackingControls(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user5")
 	testViewTimetrackingControls(t, session, "user2", "repo1", "1", false)
 	//user2/repo1
 }
 func TestViewTimetrackingControlsDisabled(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	session := loginUser(t, "user2")
 	testViewTimetrackingControls(t, session, "user3", "repo3", "1", false)
 }
diff --git a/integrations/user_test.go b/integrations/user_test.go
index 452ea2ddf0d..999a182bfd3 100644
--- a/integrations/user_test.go
+++ b/integrations/user_test.go
@@ -16,14 +16,14 @@ import (
 )
 
 func TestViewUser(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	req := NewRequest(t, "GET", "/user2")
 	MakeRequest(t, req, http.StatusOK)
 }
 
 func TestRenameUsername(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	session := loginUser(t, "user2")
 	req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
@@ -39,7 +39,7 @@ func TestRenameUsername(t *testing.T) {
 }
 
 func TestRenameInvalidUsername(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	invalidUsernames := []string{
 		"%2f*",
@@ -71,7 +71,7 @@ func TestRenameInvalidUsername(t *testing.T) {
 }
 
 func TestRenameReservedUsername(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	reservedUsernames := []string{
 		"admin",
@@ -117,7 +117,7 @@ func TestRenameReservedUsername(t *testing.T) {
 }
 
 func TestExportUserGPGKeys(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	//Export empty key list
 	testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
 
diff --git a/integrations/version_test.go b/integrations/version_test.go
index e63ae7aee25..a1d2f6c882c 100644
--- a/integrations/version_test.go
+++ b/integrations/version_test.go
@@ -15,7 +15,7 @@ import (
 )
 
 func TestVersion(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 
 	setting.AppVer = "test-version-1"
 	req := NewRequest(t, "GET", "/api/v1/version")
diff --git a/integrations/xss_test.go b/integrations/xss_test.go
index d93d0ec036a..425165dccc8 100644
--- a/integrations/xss_test.go
+++ b/integrations/xss_test.go
@@ -14,7 +14,7 @@ import (
 )
 
 func TestXSSUserFullName(t *testing.T) {
-	prepareTestEnv(t)
+	defer prepareTestEnv(t)()
 	user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	const fullName = `name & <script class="evil">alert('Oh no!');</script>`