Files
gitea-mcp/internal/tools/dir_list_test.go
Mathias Bergqvist 0eb9ebcafd feat(tools): dir_list
2026-05-06 22:49:50 +02:00

76 lines
2.8 KiB
Go

package tools_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"gitea.d-ma.be/mathias/gitea-mcp/internal/allowlist"
"gitea.d-ma.be/mathias/gitea-mcp/internal/gitea"
"gitea.d-ma.be/mathias/gitea-mcp/internal/tools"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDirListReturnsEntries(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/owner/repo/contents/src", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[
{"name":"main.go","path":"src/main.go","type":"file","sha":"abc","size":512},
{"name":"util","path":"src/util","type":"dir","sha":"def","size":0}
]`))
}))
defer srv.Close()
tool := tools.NewDirList(gitea.NewClient(srv.URL, "tok"), allowlist.New([]string{"owner"}))
out, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"owner","name":"repo","path":"src"}`))
require.NoError(t, err)
var result []map[string]any
require.NoError(t, json.Unmarshal(out, &result))
require.Len(t, result, 2)
assert.Equal(t, "main.go", result[0]["name"])
assert.Equal(t, "file", result[0]["type"])
assert.Equal(t, "util", result[1]["name"])
assert.Equal(t, "dir", result[1]["type"])
}
func TestDirListRootPath(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/owner/repo/contents/", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[]`))
}))
defer srv.Close()
tool := tools.NewDirList(gitea.NewClient(srv.URL, "tok"), allowlist.New([]string{"owner"}))
out, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"owner","name":"repo","path":""}`))
require.NoError(t, err)
var result []map[string]any
require.NoError(t, json.Unmarshal(out, &result))
assert.Empty(t, result)
}
func TestDirListOnFileReturnsError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"path":"README.md","sha":"abc","size":10,"content":"","encoding":"base64"}`))
}))
defer srv.Close()
tool := tools.NewDirList(gitea.NewClient(srv.URL, "tok"), allowlist.New([]string{"owner"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"owner","name":"repo","path":"README.md"}`))
require.Error(t, err)
assert.ErrorIs(t, err, gitea.ErrValidation)
}
func TestDirListAllowlistRejects(t *testing.T) {
tool := tools.NewDirList(gitea.NewClient("http://unused", ""), allowlist.New([]string{"allowed"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"evil","name":"repo","path":""}`))
require.Error(t, err)
}