From 754f97b1e2b73f6b4cbdea8b2322f00ac56a9b82 Mon Sep 17 00:00:00 2001
From: Gergely Nagy <forgejo@gergo.csillger.hu>
Date: Sat, 13 Jan 2024 23:07:12 +0100
Subject: [PATCH] tests: Add a testcase for missing branches

This tests the scenario reported in Codeberg/Community#1408: a branch
that is recorded in the database, but missing on disk was causing
internal server errors. With recent changes, that is no longer the case,
the error is logged and then ignored.

This test case tests this behaviour, that the repo's branches page on
the web UI functions even if the git branch is missing.

Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu>
---
 tests/integration/repo_branch_test.go | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)

diff --git a/tests/integration/repo_branch_test.go b/tests/integration/repo_branch_test.go
index 9eb17eda00..851abf95ca 100644
--- a/tests/integration/repo_branch_test.go
+++ b/tests/integration/repo_branch_test.go
@@ -1,4 +1,5 @@
 // Copyright 2017 The Gitea Authors. All rights reserved.
+// Copyright 2024 The Forgejo Authors c/o Codeberg e.V.. All rights reserved.
 // SPDX-License-Identifier: MIT
 
 package integration
@@ -10,8 +11,11 @@ import (
 	"strings"
 	"testing"
 
+	"code.gitea.io/gitea/models/db"
 	git_model "code.gitea.io/gitea/models/git"
+	repo_model "code.gitea.io/gitea/models/repo"
 	"code.gitea.io/gitea/models/unittest"
+	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/test"
 	"code.gitea.io/gitea/modules/translation"
@@ -159,3 +163,23 @@ func TestCreateBranchInvalidCSRF(t *testing.T) {
 		strings.TrimSpace(htmlDoc.doc.Find(".ui.message").Text()),
 	)
 }
+
+func TestDatabaseMissingABranch(t *testing.T) {
+	onGiteaRun(t, func(t *testing.T, URL *url.URL) {
+		session := loginUser(t, "user2")
+
+		// Create two branches
+		testCreateBranch(t, session, "user2", "repo1", "branch/master", "will-be-present", http.StatusSeeOther)
+		testCreateBranch(t, session, "user2", "repo1", "branch/master", "will-be-missing", http.StatusSeeOther)
+
+		// Delete one branch from git only, leaving it in the database
+		repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
+		cmd := git.NewCommand(db.DefaultContext, "branch", "-D").AddDynamicArguments("will-be-missing")
+		_, _, err := cmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()})
+		assert.NoError(t, err)
+
+		// Verify that loading the repo's branches page works still
+		req := NewRequest(t, "GET", "/user2/repo1/branches")
+		session.MakeRequest(t, req, http.StatusOK)
+	})
+}