Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ venv/
backend/.venv/
backend/venv/

# Go test artifacts
go-backend/tests/TEST_DESCRIPTIONS.md
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a listing/description file that you intended to add?


# Misc
*.pid
*.seed
Expand Down
4 changes: 4 additions & 0 deletions go-backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/gin-gonic/gin v1.12.0
github.com/go-git/go-git/v5 v5.17.0
github.com/joho/godotenv v1.5.1
github.com/stretchr/testify v1.11.1
go.uber.org/zap v1.27.1
)

Expand All @@ -20,6 +21,7 @@ require (
github.com/cloudflare/circl v1.6.3 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/cyphar/filepath-securejoin v0.4.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
Expand All @@ -41,6 +43,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pjbgf/sha1cd v0.3.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
Expand All @@ -57,4 +60,5 @@ require (
golang.org/x/text v0.34.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
170 changes: 170 additions & 0 deletions go-backend/tests/handlers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package tests

import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/gittuf/visualizer/go-backend/internal/handlers"
"github.com/gittuf/visualizer/go-backend/internal/models"
"github.com/gittuf/visualizer/go-backend/tests/helpers"
"github.com/stretchr/testify/assert"
)

func setupRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.Default()
r.POST("/commits", handlers.ListCommits)
r.POST("/metadata", handlers.GetMetadata)
r.POST("/commits-local", handlers.ListCommitsLocal)
r.POST("/metadata-local", handlers.GetMetadataLocal)
return r
}

func TestListCommits_Success(t *testing.T) {
remotePath, _, cleanupRemote := helpers.SetupTestRepo(t)
defer cleanupRemote()

r := setupRouter()
jsonValue, _ := json.Marshal(models.CommitsRequest{URL: remotePath})
req, _ := http.NewRequest("POST", "/commits", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusOK, w.Code)
var commits []models.Commit
assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &commits))
assert.NotEmpty(t, commits)
}

func TestListCommits_MissingURL(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.CommitsRequest{})
req, _ := http.NewRequest("POST", "/commits", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusBadRequest, w.Code)
}

func TestListCommits_InvalidURL(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.CommitsRequest{URL: "invalid-url"})
req, _ := http.NewRequest("POST", "/commits", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusInternalServerError, w.Code)
}

func TestGetMetadata_Success(t *testing.T) {
remotePath, commitHash, cleanupRemote := helpers.SetupTestRepo(t)
defer cleanupRemote()

r := setupRouter()
jsonValue, _ := json.Marshal(models.MetadataRequest{URL: remotePath, Commit: commitHash, File: "root.json"})
req, _ := http.NewRequest("POST", "/metadata", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusOK, w.Code)
var metadata map[string]interface{}
assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &metadata))
assert.Equal(t, "root", metadata["type"])
}

func TestGetMetadata_MissingURL(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.MetadataRequest{})
req, _ := http.NewRequest("POST", "/metadata", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusBadRequest, w.Code)
}

func TestListCommitsLocal_Success(t *testing.T) {
repoPath, _, cleanup := helpers.SetupTestRepo(t)
defer cleanup()

r := setupRouter()
jsonValue, _ := json.Marshal(models.CommitsLocalRequest{Path: repoPath})
req, _ := http.NewRequest("POST", "/commits-local", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusOK, w.Code)
var commits []models.Commit
assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &commits))
assert.NotEmpty(t, commits)
}

func TestListCommitsLocal_MissingPath(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.CommitsLocalRequest{})
req, _ := http.NewRequest("POST", "/commits-local", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusBadRequest, w.Code)
}

func TestListCommitsLocal_InvalidPath(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.CommitsLocalRequest{Path: "/invalid/path"})
req, _ := http.NewRequest("POST", "/commits-local", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusBadRequest, w.Code)
}

func TestGetMetadataLocal_Success(t *testing.T) {
repoPath, commitHash, cleanup := helpers.SetupTestRepo(t)
defer cleanup()

r := setupRouter()
jsonValue, _ := json.Marshal(models.MetadataLocalRequest{Path: repoPath, Commit: commitHash, File: "root.json"})
req, _ := http.NewRequest("POST", "/metadata-local", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusOK, w.Code)
var metadata map[string]interface{}
assert.NoError(t, json.Unmarshal(w.Body.Bytes(), &metadata))
assert.Equal(t, "root", metadata["type"])
}

func TestGetMetadataLocal_MissingFields(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.MetadataLocalRequest{})
req, _ := http.NewRequest("POST", "/metadata-local", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusBadRequest, w.Code)
}

func TestGetMetadataLocal_InvalidPath(t *testing.T) {
r := setupRouter()
jsonValue, _ := json.Marshal(models.MetadataLocalRequest{Path: "/invalid/path", Commit: "HEAD", File: "root.json"})
req, _ := http.NewRequest("POST", "/metadata-local", bytes.NewBuffer(jsonValue))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)

t.Logf("Response: %d %s", w.Code, w.Body.String())
assert.Equal(t, http.StatusBadRequest, w.Code)
}
92 changes: 92 additions & 0 deletions go-backend/tests/helpers/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package helpers

import (
"encoding/base64"
"fmt"
"os"
"path/filepath"
"testing"
"time"

"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
)

// SetupTestRepo creates a temporary git repository with two commits: an initial commit
// and a second commit containing a gittuf metadata envelope at metadata/root.json,
// with refs/gittuf/policy pointing at that second commit.
func SetupTestRepo(t *testing.T) (string, string, func()) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest using gittuf's testing helpers to create a repository here, e.g. copy/use https://github.com/gittuf/gittuf/blob/main/internal/policy/helpers_test.go.

Verification of gittuf repos is likely on the roadmap for the visualizer so having the test methods ready to plug in to that would be good.

t.Helper()

tempDir, err := os.MkdirTemp("", "gittuf-viz-test-repo-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}

repo, err := git.PlainInit(tempDir, false)
if err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to init git repo: %v", err)
}

w, err := repo.Worktree()
if err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to get worktree: %v", err)
}

dummyFile := filepath.Join(tempDir, "README.md")
if err := os.WriteFile(dummyFile, []byte("# Test Repo"), 0600); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to write dummy file: %v", err)
}
if _, err := w.Add("README.md"); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to add file: %v", err)
}
if _, err := w.Commit("Initial commit", &git.CommitOptions{
Author: &object.Signature{Name: "Test User", Email: "test@example.com", When: time.Now()},
}); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to commit: %v", err)
}

rootJSON := `{"type":"root", "expires":"2030-01-01T00:00:00Z"}`
rootB64 := base64.StdEncoding.EncodeToString([]byte(rootJSON))
envelope := fmt.Sprintf(`{"payload": "%s", "signatures": []}`, rootB64)

metadataDir := filepath.Join(tempDir, "metadata")
if err := os.MkdirAll(metadataDir, 0750); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to create metadata dir: %v", err)
}

policyFile := filepath.Join(metadataDir, "root.json")
if err := os.WriteFile(policyFile, []byte(envelope), 0600); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to write policy file: %v", err)
}
if _, err := w.Add("metadata/root.json"); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to add policy file: %v", err)
}

commitHash, err := w.Commit("Add root.json", &git.CommitOptions{
Author: &object.Signature{Name: "Gittuf Admin", Email: "admin@gittuf.com", When: time.Now()},
})
if err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to commit policy: %v", err)
}

ref := plumbing.NewHashReference("refs/gittuf/policy", commitHash)
if err := repo.Storer.SetReference(ref); err != nil {
os.RemoveAll(tempDir)
t.Fatalf("Failed to set policy ref: %v", err)
}

t.Logf("Test repo: path=%s policy_commit=%s", tempDir, commitHash)

return tempDir, commitHash.String(), func() { os.RemoveAll(tempDir) }
}
16 changes: 16 additions & 0 deletions go-backend/tests/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package tests

import (
"os"
"testing"

"github.com/gittuf/visualizer/go-backend/internal/logger"
)

// TestMain sets up the test environment and initializes the logger.
func TestMain(m *testing.M) {
logger.Initialize()
code := m.Run()
logger.Sync()
os.Exit(code)
}
Loading
Loading