Merge pull request 'fix:增加相关test.go文件' (#4) from mc_branch into master

This commit is contained in:
mengcheng 2026-05-28 17:01:06 +08:00
commit f256000fdb
5 changed files with 1700 additions and 1 deletions

BIN
gitlink-cli.exe Normal file

Binary file not shown.

View File

@ -48,7 +48,7 @@ func NewRuntimeContext(args map[string]string) (*RuntimeContext, error) {
format := cmdutil.Format
if format == "" {
format = "table"
format = "json"
}
return &RuntimeContext{

View File

@ -0,0 +1,626 @@
package issue
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/gitlink-org/gitlink-cli/internal/client"
"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)
// ---- helpers ----
func findShortcut(t *testing.T, name string) *common.Shortcut {
t.Helper()
for _, s := range Shortcuts() {
if s.Name == name {
return s
}
}
t.Fatalf("shortcut %q not found", name)
return nil
}
func runBatchCreateShortcut(t *testing.T, server *httptest.Server, args map[string]string) error {
t.Helper()
s := findShortcut(t, "batch-create")
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner",
Repo: "repo",
Format: "json",
Args: args,
}
return s.Run(ctx)
}
func writeJSONResp(t *testing.T, w http.ResponseWriter, v interface{}) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
func decodeReqBody(t *testing.T, r *http.Request) map[string]interface{} {
t.Helper()
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Fatalf("decode body: %v", err)
}
return payload
}
// ---- runBatchCreate tests ----
func TestBatchCreate_DryRun(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("no API calls expected in dry-run mode, got %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"titles": "标题1,标题2",
"dry-run": "true",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestBatchCreate_FromTitles(t *testing.T) {
var createdBodies []map[string]interface{}
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "POST" && strings.HasPrefix(r.URL.Path, "/v1/owner/repo/issues"):
callCount++
body := decodeReqBody(t, r)
createdBodies = append(createdBodies, body)
writeJSONResp(t, w, map[string]interface{}{
"project_issues_index": float64(100 + callCount),
})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"titles": "Bug修复,功能开发",
"state": "new",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if callCount != 2 {
t.Fatalf("expected 2 API calls, got %d", callCount)
}
if createdBodies[0]["subject"] != "Bug修复" {
t.Fatalf("first title: got %q, want %q", createdBodies[0]["subject"], "Bug修复")
}
if createdBodies[1]["subject"] != "功能开发" {
t.Fatalf("second title: got %q, want %q", createdBodies[1]["subject"], "功能开发")
}
// Verify required fields — values come through JSON as float64
for i, body := range createdBodies {
if body["done_ratio"] != float64(0) {
t.Fatalf("body[%d]: done_ratio = %v (type %T), want 0", i, body["done_ratio"], body["done_ratio"])
}
}
}
func TestBatchCreate_NoTitles(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"dry-run": "false",
})
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestBatchCreate_FromCSV(t *testing.T) {
csvPath := writeTempCSV(t, "title,priority,label,status\nCSV标题1,high,缺陷,new\nCSV标题2,normal,功能,new\n")
var created []map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && strings.HasPrefix(r.URL.Path, "/v1/owner/repo/issues") {
created = append(created, decodeReqBody(t, r))
writeJSONResp(t, w, map[string]interface{}{"project_issues_index": float64(1)})
return
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"from": csvPath,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(created) != 2 {
t.Fatalf("expected 2 creates, got %d", len(created))
}
if created[0]["subject"] != "CSV标题1" {
t.Fatalf("first subject: got %q", created[0]["subject"])
}
if created[1]["subject"] != "CSV标题2" {
t.Fatalf("second subject: got %q", created[1]["subject"])
}
}
func TestBatchCreate_CSVMissingTitleColumn(t *testing.T) {
csvPath := writeTempCSV(t, "name,description\nval1,desc1\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{"from": csvPath})
if err == nil {
t.Fatal("expected error for missing title column, got nil")
}
}
func TestBatchCreate_CSVOnlyHeader(t *testing.T) {
csvPath := writeTempCSV(t, "title,description\n")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{"from": csvPath})
if err == nil {
t.Fatal("expected error for header-only CSV, got nil")
}
}
func TestBatchCreate_PartialFailure(t *testing.T) {
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if callCount == 2 {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
writeJSONResp(t, w, map[string]interface{}{"project_issues_index": float64(callCount)})
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"titles": "ok1,fail1,ok2",
})
if err == nil {
t.Fatal("expected error from partial failure, got nil")
}
if !strings.Contains(err.Error(), "failed to create") {
t.Fatalf("error should mention failed count, got: %v", err)
}
}
// ---- buildCreateBody tests (direct call, values retain Go types) ----
func intVal(v interface{}) int {
switch n := v.(type) {
case int:
return n
case float64:
return int(n)
}
return -999
}
func TestBuildCreateBody_Basic(t *testing.T) {
ctx := &common.RuntimeContext{Owner: "o", Repo: "r", Args: map[string]string{}}
input := createIssueInput{Title: "Test issue", Status: "new"}
body := buildCreateBody(ctx, input, "")
if body["subject"] != "Test issue" {
t.Fatalf("subject: got %v", body["subject"])
}
if intVal(body["done_ratio"]) != 0 {
t.Fatalf("done_ratio: got %v (%T), want 0", body["done_ratio"], body["done_ratio"])
}
if intVal(body["status_id"]) != 1 {
t.Fatalf("status_id: got %v (%T), want 1", body["status_id"], body["status_id"])
}
if intVal(body["priority_id"]) != 2 {
t.Fatalf("priority_id: got %v (%T), want 2", body["priority_id"], body["priority_id"])
}
}
func TestBuildCreateBody_BugTemplate(t *testing.T) {
ctx := &common.RuntimeContext{Owner: "o", Repo: "r", Args: map[string]string{}}
input := createIssueInput{
Title: "登录报错",
Version: "v2.0",
Severity: "严重",
Steps: "1. 打开页面\n2. 点击登录",
Expected: "正常登录",
Actual: "报错 500",
}
body := buildCreateBody(ctx, input, "bug")
if body["subject"] != "登录报错" {
t.Fatalf("subject: got %v", body["subject"])
}
desc, _ := body["description"].(string)
if !strings.Contains(desc, "## Bug 描述") {
t.Fatal("bug description missing header")
}
if !strings.Contains(desc, "v2.0") {
t.Fatal("bug description missing version")
}
if !strings.Contains(desc, "严重") {
t.Fatal("bug description missing severity")
}
if rawTags, ok := body["issue_tag_ids"]; !ok {
t.Fatal("bug template missing issue_tag_ids")
} else {
ids := rawTags.([]interface{})
if intVal(ids[0]) != tagIDs["缺陷"] {
t.Fatalf("tag: got %v (type %T), want %v", ids[0], ids[0], tagIDs["缺陷"])
}
}
}
func TestBuildCreateBody_FeatureTemplate(t *testing.T) {
ctx := &common.RuntimeContext{Owner: "o", Repo: "r", Args: map[string]string{}}
input := createIssueInput{
Title: "用户搜索",
UserStory: "作为用户,我想搜索内容",
Acceptance: "搜索结果正确显示",
}
body := buildCreateBody(ctx, input, "feature")
desc, _ := body["description"].(string)
if !strings.Contains(desc, "## 用户故事") {
t.Fatal("feature description missing user story header")
}
if !strings.Contains(desc, "作为用户") {
t.Fatal("feature description missing user story content")
}
if !strings.Contains(desc, "## 验收标准") {
t.Fatal("feature description missing acceptance criteria")
}
}
func TestBuildCreateBody_WithPriorityLabel(t *testing.T) {
ctx := &common.RuntimeContext{Owner: "o", Repo: "r", Args: map[string]string{}}
input := createIssueInput{
Title: "紧急修复",
Priority: "high",
Label: "缺陷",
}
body := buildCreateBody(ctx, input, "")
if intVal(body["priority_id"]) != 3 {
t.Fatalf("priority_id: got %v (type %T), want 3 (high)", body["priority_id"], body["priority_id"])
}
if rawTags, ok := body["issue_tag_ids"]; ok {
ids := rawTags.([]interface{})
if intVal(ids[0]) != tagIDs["缺陷"] {
t.Fatalf("tag: got %v (type %T), want %v", ids[0], ids[0], tagIDs["缺陷"])
}
} else {
t.Fatal("missing issue_tag_ids")
}
}
// ---- buildBugDescription tests ----
func TestBuildBugDescription_AllFields(t *testing.T) {
input := createIssueInput{
Title: "登录报错",
Version: "v2.0",
Severity: "严重",
Steps: "1. 打开",
Expected: "正常",
Actual: "500错误",
}
result := buildBugDescription(input)
if !strings.Contains(result, "## Bug 描述") {
t.Fatal("missing Bug 描述")
}
if !strings.Contains(result, "登录报错") {
t.Fatal("missing title")
}
if !strings.Contains(result, "## 版本") {
t.Fatal("missing 版本")
}
if !strings.Contains(result, "## 严重程度") {
t.Fatal("missing 严重程度")
}
if !strings.Contains(result, "## 复现步骤") {
t.Fatal("missing 复现步骤")
}
if !strings.Contains(result, "## 期望结果") {
t.Fatal("missing 期望结果")
}
if !strings.Contains(result, "## 实际结果") {
t.Fatal("missing 实际结果")
}
}
func TestBuildBugDescription_PartialFields(t *testing.T) {
input := createIssueInput{Title: "小问题"}
result := buildBugDescription(input)
if !strings.Contains(result, "## Bug 描述") {
t.Fatal("missing header")
}
if strings.Contains(result, "## 版本") {
t.Fatal("should not have version section")
}
if strings.Contains(result, "## 严重程度") {
t.Fatal("should not have severity section")
}
}
// ---- buildFeatureDescription tests ----
func TestBuildFeatureDescription_AllFields(t *testing.T) {
input := createIssueInput{
Title: "搜索功能",
UserStory: "作为用户想搜索",
Body: "详细描述",
Acceptance: "搜索结果正确",
Priority: "high",
}
result := buildFeatureDescription(input)
if !strings.Contains(result, "## 用户故事") {
t.Fatal("missing user story")
}
if !strings.Contains(result, "作为用户想搜索") {
t.Fatal("missing user story content")
}
if !strings.Contains(result, "## 描述") {
t.Fatal("missing description")
}
if !strings.Contains(result, "## 验收标准") {
t.Fatal("missing acceptance criteria")
}
if !strings.Contains(result, "## 优先级") {
t.Fatal("missing priority")
}
}
func TestBuildFeatureDescription_FallbackToTitleAsUserStory(t *testing.T) {
input := createIssueInput{Title: "搜索功能"}
result := buildFeatureDescription(input)
if !strings.Contains(result, "搜索功能") {
t.Fatal("should fall back to title as user story")
}
}
// ---- readCreateInputsFromCSV tests ----
func TestReadCreateInputsFromCSV_Normal(t *testing.T) {
path := writeTempCSV(t, "title,priority,label,status,version,severity,steps,expected,actual\n标题1,high,缺陷,new,v1,严重,,,\n标题2,normal,功能,new,,,,,\n")
inputs, err := readCreateInputsFromCSV(path, "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(inputs) != 2 {
t.Fatalf("got %d inputs, want 2", len(inputs))
}
if inputs[0].Title != "标题1" {
t.Fatalf("first title: got %q", inputs[0].Title)
}
if inputs[0].Severity != "严重" {
t.Fatalf("severity: got %q", inputs[0].Severity)
}
if inputs[1].Label != "功能" {
t.Fatalf("label: got %q", inputs[1].Label)
}
}
func TestReadCreateInputsFromCSV_MissingTitleColumn(t *testing.T) {
path := writeTempCSV(t, "name,description\nval1,desc1\n")
_, err := readCreateInputsFromCSV(path, "")
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadCreateInputsFromCSV_OnlyHeader(t *testing.T) {
path := writeTempCSV(t, "title,priority\n")
_, err := readCreateInputsFromCSV(path, "")
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadCreateInputsFromCSV_SkipsEmptyTitle(t *testing.T) {
path := writeTempCSV(t, "title,priority\n标题1,high\n,normal\n标题2,low\n")
inputs, err := readCreateInputsFromCSV(path, "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(inputs) != 2 {
t.Fatalf("got %d inputs, want 2 (empty row skipped)", len(inputs))
}
}
// ---- parseTitles tests ----
func TestParseTitles_CommaSeparated(t *testing.T) {
ctx := &common.RuntimeContext{
Owner: "o", Repo: "r",
Args: map[string]string{"priority": "normal"},
}
inputs := parseTitles("标题1, 标题2, , 标题3", ctx)
if len(inputs) != 3 {
t.Fatalf("got %d inputs, want 3", len(inputs))
}
if inputs[0].Title != "标题1" {
t.Fatalf("got %q", inputs[0].Title)
}
if inputs[2].Title != "标题3" {
t.Fatalf("got %q", inputs[2].Title)
}
if inputs[0].Priority != "normal" {
t.Fatalf("priority not propagated: got %q", inputs[0].Priority)
}
}
// ---- normalizeHeader tests ----
func TestNormalizeHeader(t *testing.T) {
cases := []struct{ in, want string }{
{"Title", "title"},
{" PRIORITY ", "priority"},
{"user_story", "user_story"},
{"User Story", "user story"},
}
for _, c := range cases {
got := normalizeHeader(c.in)
if got != c.want {
t.Fatalf("normalizeHeader(%q) = %q, want %q", c.in, got, c.want)
}
}
}
// ---- getCol tests ----
func TestGetCol(t *testing.T) {
col := map[string]int{"title": 0, "priority": 1}
record := []string{"测试标题", "high"}
if got := getCol(record, col, "title"); got != "测试标题" {
t.Fatalf("got %q", got)
}
if got := getCol(record, col, "missing"); got != "" {
t.Fatalf("got %q, want empty", got)
}
if got := getCol(record, col, "priority"); got != "high" {
t.Fatalf("got %q", got)
}
}
// ---- truncate tests ----
func TestTruncate(t *testing.T) {
if got := truncate("short", 40); got != "short" {
t.Fatalf("got %q", got)
}
long := "这是一个很长的标题用来测试截断功能一二三四五六七八九十"
got := truncate(long, 10)
if len([]rune(got)) > 13 {
t.Fatalf("truncated too long: %q (%d runes)", got, len([]rune(got)))
}
if !strings.HasSuffix(got, "...") {
t.Fatal("truncated string should end with ...")
}
}
// ---- priority/label/status parse helpers ----
func TestParsePriorityStrings(t *testing.T) {
cases := []struct {
in string
want int
}{
{"low", 1}, {"normal", 2}, {"high", 3}, {"urgent", 4},
{"LOW", 1}, {"High", 3},
}
for _, c := range cases {
got, err := parsePriority(c.in)
if err != nil {
t.Fatalf("parsePriority(%q): %v", c.in, err)
}
if got != c.want {
t.Fatalf("parsePriority(%q) = %d, want %d", c.in, got, c.want)
}
}
}
func TestParsePriorityNumeric(t *testing.T) {
got, err := parsePriority("5")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != 5 {
t.Fatalf("got %d, want 5", got)
}
}
func TestParsePriorityInvalid(t *testing.T) {
if _, err := parsePriority("invalid"); err == nil {
t.Fatal("expected error")
}
}
func TestParseLabelValid(t *testing.T) {
id, err := parseLabel("缺陷")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if id == 0 {
t.Fatal("expected non-zero tag ID")
}
}
func TestParseLabelInvalid(t *testing.T) {
if _, err := parseLabel("不存在的标签"); err == nil {
t.Fatal("expected error")
}
}
func TestParseLabelNumeric(t *testing.T) {
id, err := parseLabel("999")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if id != 999 {
t.Fatalf("got %d, want 999", id)
}
}
func TestLabelNamesReturnsAll(t *testing.T) {
names := labelNames()
if !strings.Contains(names, "缺陷") {
t.Fatal("missing 缺陷 in label names")
}
if !strings.Contains(names, "功能") {
t.Fatal("missing 功能 in label names")
}
}
// ---- buildCreateBody status tests ----
func TestBuildCreateBody_DefaultStatus(t *testing.T) {
ctx := &common.RuntimeContext{Owner: "o", Repo: "r", Args: map[string]string{}}
input := createIssueInput{Title: "t", Status: ""}
body := buildCreateBody(ctx, input, "")
if intVal(body["status_id"]) != 1 {
t.Fatalf("default status_id: got %v (type %T), want 1", body["status_id"], body["status_id"])
}
}
func TestBuildCreateBody_ClosedStatus(t *testing.T) {
ctx := &common.RuntimeContext{Owner: "o", Repo: "r", Args: map[string]string{}}
input := createIssueInput{Title: "t", Status: "closed"}
body := buildCreateBody(ctx, input, "")
if intVal(body["status_id"]) != 5 {
t.Fatalf("closed status_id: got %v (type %T), want 5", body["status_id"], body["status_id"])
}
}
// ---- regression ----
func TestCollectIssueNumbers_FromBatchCreatePerspective(t *testing.T) {
got, err := collectIssueNumbers("1,2,3", "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
want := []string{"1", "2", "3"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}

View File

@ -0,0 +1,837 @@
package repo
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gitlink-org/gitlink-cli/internal/client"
"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)
// ---- helpers ----
func findShortcut(t *testing.T, name string) *common.Shortcut {
t.Helper()
for _, s := range Shortcuts() {
if s.Name == name {
return s
}
}
t.Fatalf("shortcut %q not found", name)
return nil
}
func runBatchCreateShortcut(t *testing.T, server *httptest.Server, args map[string]string) error {
t.Helper()
s := findShortcut(t, "batch-create")
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner",
Repo: "repo",
Format: "json",
Args: args,
}
return s.Run(ctx)
}
func runBatchUpdateShortcut(t *testing.T, server *httptest.Server, args map[string]string) error {
t.Helper()
s := findShortcut(t, "batch-update")
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner",
Repo: "repo",
Format: "json",
Args: args,
}
return s.Run(ctx)
}
func writeJSONResp(t *testing.T, w http.ResponseWriter, v interface{}) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
t.Fatalf("writeJSON: %v", err)
}
}
func decodeReqBody(t *testing.T, r *http.Request) map[string]interface{} {
t.Helper()
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Fatalf("decode body: %v", err)
}
return payload
}
func writeTempCSV(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "repos.csv")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("write temp csv: %v", err)
}
return path
}
// ---- runBatchCreate tests ----
func TestBatchCreate_DryRun(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("no API calls expected in dry-run mode, got %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "repo1,repo2",
"dry-run": "true",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestBatchCreate_FromNames(t *testing.T) {
var createdBodies []map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET" && r.URL.Path == "/users/me.json":
writeJSONResp(t, w, map[string]interface{}{
"login": "testuser",
"user_id": float64(42),
})
case r.Method == "POST" && strings.HasPrefix(r.URL.Path, "/testuser/"):
createdBodies = append(createdBodies, decodeReqBody(t, r))
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "repo-a,repo-b",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(createdBodies) != 2 {
t.Fatalf("expected 2 API calls, got %d", len(createdBodies))
}
if createdBodies[0]["name"] != "repo-a" {
t.Fatalf("first name: got %q, want %q", createdBodies[0]["name"], "repo-a")
}
if createdBodies[1]["name"] != "repo-b" {
t.Fatalf("second name: got %q, want %q", createdBodies[1]["name"], "repo-b")
}
for _, body := range createdBodies {
if body["repository_name"] != body["name"] {
t.Fatalf("repository_name should match name: %v vs %v", body["repository_name"], body["name"])
}
if body["user_id"] != float64(42) {
t.Fatalf("user_id: got %v, want 42", body["user_id"])
}
}
}
func TestBatchCreate_NoNames(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{})
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestBatchCreate_NoNamesDryRun(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{"dry-run": "true"})
if err == nil {
t.Fatal("expected error for no names even in dry-run, got nil")
}
}
func TestBatchCreate_WithPrivate(t *testing.T) {
var createdBody map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET" && r.URL.Path == "/users/me.json":
writeJSONResp(t, w, map[string]interface{}{
"login": "testuser",
"user_id": float64(42),
})
case r.Method == "POST":
createdBody = decodeReqBody(t, r)
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "private-repo",
"private": "true",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if createdBody["private"] != true {
t.Fatalf("private: got %v, want true", createdBody["private"])
}
}
func TestBatchCreate_WithDescription(t *testing.T) {
var createdBody map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET" && r.URL.Path == "/users/me.json":
writeJSONResp(t, w, map[string]interface{}{
"login": "testuser",
"user_id": float64(42),
})
case r.Method == "POST":
createdBody = decodeReqBody(t, r)
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "desc-repo",
"description": "shared description",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if createdBody["description"] != "shared description" {
t.Fatalf("description: got %q, want %q", createdBody["description"], "shared description")
}
}
func TestBatchCreate_FromCSV(t *testing.T) {
csvPath := writeTempCSV(t, "name,description,private\ncsv-repo1,desc one,false\ncsv-repo2,desc two,true\n")
var createdBodies []map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET" && r.URL.Path == "/users/me.json":
writeJSONResp(t, w, map[string]interface{}{
"login": "testuser",
"user_id": float64(42),
})
case r.Method == "POST":
createdBodies = append(createdBodies, decodeReqBody(t, r))
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{"from": csvPath})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(createdBodies) != 2 {
t.Fatalf("expected 2 creates, got %d", len(createdBodies))
}
if createdBodies[0]["name"] != "csv-repo1" {
t.Fatalf("first name: got %q", createdBodies[0]["name"])
}
if createdBodies[0]["description"] != "desc one" {
t.Fatalf("first description: got %q", createdBodies[0]["description"])
}
if createdBodies[1]["name"] != "csv-repo2" {
t.Fatalf("second name: got %q", createdBodies[1]["name"])
}
if createdBodies[1]["private"] != true {
t.Fatalf("second private: got %v, want true", createdBodies[1]["private"])
}
}
func TestBatchCreate_PartialFailure(t *testing.T) {
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET" && r.URL.Path == "/users/me.json":
writeJSONResp(t, w, map[string]interface{}{
"login": "testuser",
"user_id": float64(42),
})
case r.Method == "POST":
callCount++
if callCount == 2 {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
writeJSONResp(t, w, map[string]interface{}{"id": float64(callCount)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "ok1,fail1,ok2",
})
if err == nil {
t.Fatal("expected error from partial failure, got nil")
}
if !strings.Contains(err.Error(), "failed to create") {
t.Fatalf("error should mention failed count, got: %v", err)
}
}
func TestBatchCreate_UserLookupFails(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "repo1",
})
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "failed to get current user") {
t.Fatalf("error should mention user lookup, got: %v", err)
}
}
func TestBatchCreate_UserMissingLogin(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeJSONResp(t, w, map[string]interface{}{
"user_id": float64(42),
})
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "repo1",
})
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "cannot determine current user login") {
t.Fatalf("error should mention missing login, got: %v", err)
}
}
func TestBatchCreate_CSVAndNamesCombined(t *testing.T) {
csvPath := writeTempCSV(t, "name\ndual-repo\n")
var createdNames []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET" && r.URL.Path == "/users/me.json":
writeJSONResp(t, w, map[string]interface{}{
"login": "testuser",
"user_id": float64(42),
})
case r.Method == "POST":
body := decodeReqBody(t, r)
createdNames = append(createdNames, body["name"].(string))
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchCreateShortcut(t, server, map[string]string{
"names": "inline-repo",
"from": csvPath,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(createdNames) != 2 {
t.Fatalf("expected 2 creates, got %d", len(createdNames))
}
if createdNames[0] != "inline-repo" {
t.Fatalf("first: got %q", createdNames[0])
}
if createdNames[1] != "dual-repo" {
t.Fatalf("second: got %q", createdNames[1])
}
}
// ---- readRepoInputsFromCSV tests ----
func TestReadRepoInputsFromCSV_Normal(t *testing.T) {
path := writeTempCSV(t, "name,description,private\nrepo1,desc1,true\nrepo2,desc2,false\nrepo3,,0\n")
inputs, err := readRepoInputsFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(inputs) != 3 {
t.Fatalf("got %d inputs, want 3", len(inputs))
}
if inputs[0].Name != "repo1" || inputs[0].Description != "desc1" || !inputs[0].Private {
t.Fatalf("input[0]: %+v", inputs[0])
}
if inputs[1].Name != "repo2" || inputs[1].Private {
t.Fatalf("input[1]: %+v", inputs[1])
}
if inputs[2].Name != "repo3" || inputs[2].Private {
t.Fatalf("input[2]: %+v", inputs[2])
}
}
func TestReadRepoInputsFromCSV_MissingNameColumn(t *testing.T) {
path := writeTempCSV(t, "title,description\nval1,desc1\n")
_, err := readRepoInputsFromCSV(path)
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadRepoInputsFromCSV_OnlyHeader(t *testing.T) {
path := writeTempCSV(t, "name,description\n")
_, err := readRepoInputsFromCSV(path)
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadRepoInputsFromCSV_SkipsEmptyName(t *testing.T) {
path := writeTempCSV(t, "name,description\nrepo1,desc1\n,desc2\nrepo2,desc3\n")
inputs, err := readRepoInputsFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(inputs) != 2 {
t.Fatalf("got %d inputs, want 2", len(inputs))
}
}
func TestReadRepoInputsFromCSV_PrivateParsing(t *testing.T) {
path := writeTempCSV(t, "name,private\nr1,true\nr2,false\nr3,1\nr4,0\nr5,\n")
inputs, err := readRepoInputsFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(inputs) != 5 {
t.Fatalf("got %d inputs, want 5", len(inputs))
}
if !inputs[0].Private {
t.Fatal("r1 (true) should be private")
}
if inputs[1].Private {
t.Fatal("r2 (false) should not be private")
}
if !inputs[2].Private {
t.Fatal("r3 (1) should be private")
}
if inputs[3].Private {
t.Fatal("r4 (0) should not be private")
}
if inputs[4].Private {
t.Fatal("r5 (empty) should not be private")
}
}
func TestReadRepoInputsFromCSV_FileNotFound(t *testing.T) {
_, err := readRepoInputsFromCSV("/nonexistent/path.csv")
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadRepoInputsFromCSV_CaseInsensitiveHeader(t *testing.T) {
path := writeTempCSV(t, "NAME,Description,Private\nrepo1,desc1,TRUE\n")
inputs, err := readRepoInputsFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(inputs) != 1 {
t.Fatalf("got %d inputs, want 1", len(inputs))
}
if inputs[0].Name != "repo1" {
t.Fatalf("name: got %q", inputs[0].Name)
}
if !inputs[0].Private {
t.Fatal("should be private")
}
}
// ---- getCol tests ----
func TestGetCol_Found(t *testing.T) {
col := map[string]int{"name": 0, "description": 1}
record := []string{"my-repo", "my desc"}
if got := getCol(record, col, "name"); got != "my-repo" {
t.Fatalf("got %q", got)
}
if got := getCol(record, col, "description"); got != "my desc" {
t.Fatalf("got %q", got)
}
}
func TestGetCol_Missing(t *testing.T) {
col := map[string]int{"name": 0}
record := []string{"my-repo"}
if got := getCol(record, col, "missing"); got != "" {
t.Fatalf("got %q, want empty", got)
}
}
func TestGetCol_IndexOutOfRange(t *testing.T) {
col := map[string]int{"name": 5}
record := []string{"my-repo"}
if got := getCol(record, col, "name"); got != "" {
t.Fatalf("got %q, want empty", got)
}
}
// ---- runBatchUpdate tests ----
func TestBatchUpdate_DryRun(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("no API calls expected in dry-run mode, got %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "repo1,repo2",
"dry-run": "true",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestBatchUpdate_FromNames(t *testing.T) {
var fetchedRepos []string
var patchedBodies []map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/owner/"), ".json")
fetchedRepos = append(fetchedRepos, name)
writeJSONResp(t, w, map[string]interface{}{
"name": name,
"identifier": "ident-" + name,
})
case r.Method == "PATCH":
patchedBodies = append(patchedBodies, decodeReqBody(t, r))
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "repo-a,repo-b",
"private": "true",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(fetchedRepos) != 2 {
t.Fatalf("expected 2 fetches, got %d", len(fetchedRepos))
}
if len(patchedBodies) != 2 {
t.Fatalf("expected 2 patches, got %d", len(patchedBodies))
}
for _, body := range patchedBodies {
if body["private"] != true {
t.Fatalf("private should be true: %+v", body)
}
}
}
func TestBatchUpdate_NoNames(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{})
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestBatchUpdate_PrivatePublicConflict(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "repo1",
"private": "true",
"public": "true",
})
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "cannot use both --private and --public") {
t.Fatalf("error should mention conflict, got: %v", err)
}
}
func TestBatchUpdate_SetPublic(t *testing.T) {
var patchedBody map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
writeJSONResp(t, w, map[string]interface{}{
"name": "repo1",
"identifier": "abc123",
})
case r.Method == "PATCH":
patchedBody = decodeReqBody(t, r)
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "repo1",
"public": "true",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if patchedBody["private"] != false {
t.Fatalf("public should set private=false, got %v", patchedBody["private"])
}
}
func TestBatchUpdate_WithDescription(t *testing.T) {
var patchedBody map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
writeJSONResp(t, w, map[string]interface{}{
"name": "repo1",
"identifier": "abc123",
})
case r.Method == "PATCH":
patchedBody = decodeReqBody(t, r)
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "repo1",
"description": "updated description",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if patchedBody["description"] != "updated description" {
t.Fatalf("description: got %q", patchedBody["description"])
}
}
func TestBatchUpdate_FromCSV(t *testing.T) {
csvPath := writeTempCSV(t, "name\ncsv-repo1\ncsv-repo2\n")
var fetchedRepos []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/owner/"), ".json")
fetchedRepos = append(fetchedRepos, name)
writeJSONResp(t, w, map[string]interface{}{
"name": name,
"identifier": "ident-" + name,
})
case r.Method == "PATCH":
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{"from": csvPath})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(fetchedRepos) != 2 {
t.Fatalf("expected 2 fetches, got %d", len(fetchedRepos))
}
}
func TestBatchUpdate_PartialFailure(t *testing.T) {
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
switch {
case r.Method == "GET" && strings.Contains(r.URL.Path, "fail-repo"):
w.WriteHeader(http.StatusNotFound)
case r.Method == "GET":
writeJSONResp(t, w, map[string]interface{}{
"name": "ok-repo",
"identifier": "abc123",
})
case r.Method == "PATCH":
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "ok-repo,fail-repo",
})
if err == nil {
t.Fatal("expected error from partial failure, got nil")
}
if !strings.Contains(err.Error(), "failed to update") {
t.Fatalf("error should mention failed count, got: %v", err)
}
}
func TestBatchUpdate_PreservesIdentifier(t *testing.T) {
var patchedBody map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
writeJSONResp(t, w, map[string]interface{}{
"name": "my-repo",
"identifier": "xyz-789",
"description": "old desc",
})
case r.Method == "PATCH":
patchedBody = decodeReqBody(t, r)
writeJSONResp(t, w, map[string]interface{}{"id": float64(1)})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
err := runBatchUpdateShortcut(t, server, map[string]string{
"names": "my-repo",
"description": "new desc",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if patchedBody["name"] != "my-repo" {
t.Fatalf("name: got %q", patchedBody["name"])
}
if patchedBody["identifier"] != "xyz-789" {
t.Fatalf("identifier: got %q", patchedBody["identifier"])
}
if patchedBody["description"] != "new desc" {
t.Fatalf("description: got %q", patchedBody["description"])
}
}
// ---- readNamesFromCSV tests ----
func TestReadNamesFromCSV_Normal(t *testing.T) {
path := writeTempCSV(t, "name\nrepo1\nrepo2\nrepo3\n")
names, err := readNamesFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(names) != 3 {
t.Fatalf("got %d names, want 3", len(names))
}
if names[0] != "repo1" || names[1] != "repo2" || names[2] != "repo3" {
t.Fatalf("got %v", names)
}
}
func TestReadNamesFromCSV_MissingNameColumn(t *testing.T) {
path := writeTempCSV(t, "title,description\nval1,desc1\nval2,desc2\n")
names, err := readNamesFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(names) != 2 {
t.Fatalf("got %d names, want 2 (falls back to col 0)", len(names))
}
if names[0] != "val1" || names[1] != "val2" {
t.Fatalf("got %v", names)
}
}
func TestReadNamesFromCSV_OnlyHeader(t *testing.T) {
path := writeTempCSV(t, "name\n")
_, err := readNamesFromCSV(path)
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadNamesFromCSV_SkipsEmptyName(t *testing.T) {
path := writeTempCSV(t, "name\nrepo1\n\nrepo2\n")
names, err := readNamesFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(names) != 2 {
t.Fatalf("got %d names, want 2", len(names))
}
}
func TestReadNamesFromCSV_FileNotFound(t *testing.T) {
_, err := readNamesFromCSV("/nonexistent/path.csv")
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestReadNamesFromCSV_CaseInsensitiveHeader(t *testing.T) {
path := writeTempCSV(t, "NAME\nrepo1\nrepo2\n")
names, err := readNamesFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(names) != 2 {
t.Fatalf("got %d names, want 2", len(names))
}
}
func TestReadNamesFromCSV_ExtraColumns(t *testing.T) {
path := writeTempCSV(t, "name,extra,another\nrepo1,x,y\nrepo2,a,b\n")
names, err := readNamesFromCSV(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(names) != 2 {
t.Fatalf("got %d names, want 2", len(names))
}
if names[0] != "repo1" || names[1] != "repo2" {
t.Fatalf("got %v", names)
}
}

236
shortcuts/wiki/wiki_test.go Normal file
View File

@ -0,0 +1,236 @@
package wiki
import (
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/gitlink-org/gitlink-cli/internal/client"
"github.com/gitlink-org/gitlink-cli/internal/output"
"github.com/gitlink-org/gitlink-cli/shortcuts/common"
)
func resetProjectIDCache() {
projectIDCache = sync.Map{}
}
func newMockServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {
t.Helper()
return httptest.NewServer(handler)
}
func writeJSON(t *testing.T, w http.ResponseWriter, v interface{}) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
t.Fatalf("writeJSON: %v", err)
}
}
// ---- unwrapGatewayResponse tests ----
func TestUnwrapGatewayResponse_Success(t *testing.T) {
env := output.SuccessEnvelope(map[string]interface{}{
"code": float64(200),
"data": map[string]interface{}{"id": float64(1)},
}, nil)
result, err := unwrapGatewayResponse(env)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
data, ok := result.Data.(map[string]interface{})
if !ok {
t.Fatal("expected map data")
}
if data["id"] != float64(1) {
t.Fatalf("got %v, want 1", data["id"])
}
}
func TestUnwrapGatewayResponse_Code201(t *testing.T) {
env := output.SuccessEnvelope(map[string]interface{}{
"code": float64(201),
"data": "ok",
}, nil)
result, err := unwrapGatewayResponse(env)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data != "ok" {
t.Fatalf("got %v, want ok", result.Data)
}
}
func TestUnwrapGatewayResponse_BusinessError(t *testing.T) {
env := output.SuccessEnvelope(map[string]interface{}{
"code": float64(500),
"msg": "内部错误",
}, nil)
_, err := unwrapGatewayResponse(env)
if err == nil {
t.Fatal("expected error, got nil")
}
if err.Error() != "[500] 内部错误" {
t.Fatalf("got %q, want %q", err.Error(), "[500] 内部错误")
}
}
func TestUnwrapGatewayResponse_NoDataField(t *testing.T) {
env := output.SuccessEnvelope(map[string]interface{}{
"code": float64(200),
}, nil)
result, err := unwrapGatewayResponse(env)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Should return original envelope since no "data" field to extract
if result != env {
t.Fatal("expected original envelope when no data field")
}
}
func TestUnwrapGatewayResponse_NonMapData(t *testing.T) {
env := output.SuccessEnvelope("plain text", nil)
result, err := unwrapGatewayResponse(env)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data != "plain text" {
t.Fatalf("got %v, want plain text", result.Data)
}
}
// ---- resolveProjectID tests ----
func TestResolveProjectID_Success(t *testing.T) {
resetProjectIDCache()
server := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/owner1/repo1/detail.json" {
writeJSON(t, w, map[string]interface{}{"project_id": float64(123)})
return
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
})
defer server.Close()
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner1",
Repo: "repo1",
}
pid, err := resolveProjectID(ctx)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if pid != "123" {
t.Fatalf("got %q, want %q", pid, "123")
}
}
func TestResolveProjectID_Float64(t *testing.T) {
resetProjectIDCache()
server := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/owner2/repo2/detail.json" {
writeJSON(t, w, map[string]interface{}{"project_id": float64(456)})
return
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
})
defer server.Close()
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner2",
Repo: "repo2",
}
pid, err := resolveProjectID(ctx)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if pid != "456" {
t.Fatalf("got %q, want %q", pid, "456")
}
}
func TestResolveProjectID_CacheHit(t *testing.T) {
resetProjectIDCache()
callCount := 0
server := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
callCount++
if r.URL.Path == "/owner3/repo3/detail.json" {
writeJSON(t, w, map[string]interface{}{"project_id": float64(789)})
return
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
})
defer server.Close()
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner3",
Repo: "repo3",
}
pid1, err := resolveProjectID(ctx)
if err != nil {
t.Fatalf("first call: %v", err)
}
if pid1 != "789" {
t.Fatalf("first call: got %q, want %q", pid1, "789")
}
pid2, err := resolveProjectID(ctx)
if err != nil {
t.Fatalf("second call: %v", err)
}
if pid2 != "789" {
t.Fatalf("second call: got %q, want %q", pid2, "789")
}
if callCount != 1 {
t.Fatalf("API called %d times, want 1 (cache miss)", callCount)
}
}
func TestResolveProjectID_MissingProjectID(t *testing.T) {
resetProjectIDCache()
server := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
writeJSON(t, w, map[string]interface{}{"name": "no-project-id"})
})
defer server.Close()
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner4",
Repo: "repo4",
}
_, err := resolveProjectID(ctx)
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestResolveProjectID_APIError(t *testing.T) {
resetProjectIDCache()
server := newMockServer(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
defer server.Close()
ctx := &common.RuntimeContext{
Client: &client.Client{HTTP: server.Client(), BaseURL: server.URL},
Owner: "owner5",
Repo: "repo5",
}
_, err := resolveProjectID(ctx)
if err == nil {
t.Fatal("expected error, got nil")
}
}