仰望星辰工作室

gitcat

gitcat/ internal/server/archive_test.go 2.3 KB · 75 行 原始文件
1package server
2
3import (
4 "archive/zip"
5 "bytes"
6 "io"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "testing"
11)
12
13// TestArchiveDownload 确认源码包端点按 ref 输出可解压的 zip,且默认使用
14// 仓库默认分支;非法 ref 不得进入 git 命令行。
15func TestArchiveDownload(t *testing.T) {
16 srv, st, _, _ := newTestServer(t)
17 dir := makeRepo(t, srv, st, "proj", nil)
18 commitFiles(t, dir, "init", map[string]string{"a.txt": "hello", "b.txt": "world"})
19
20 check := func(path string) {
21 t.Helper()
22 r := httptest.NewRequest(http.MethodGet, path, nil)
23 w := httptest.NewRecorder()
24 srv.Handler().ServeHTTP(w, r)
25 if w.Code != http.StatusOK {
26 t.Fatalf("%s 状态码 = %d,期望 200", path, w.Code)
27 }
28 if ct := w.Header().Get("Content-Type"); ct != "application/zip" {
29 t.Errorf("Content-Type = %q,期望 application/zip", ct)
30 }
31 if disp := w.Header().Get("Content-Disposition"); !strings.Contains(disp, "proj-main.zip") {
32 t.Errorf("Content-Disposition = %q,期望包含 proj-main.zip", disp)
33 }
34 zr, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
35 if err != nil {
36 t.Fatalf("响应不是合法 zip: %v", err)
37 }
38 files := map[string]string{}
39 for _, f := range zr.File {
40 rc, err := f.Open()
41 if err != nil {
42 t.Fatalf("打开 %s 失败: %v", f.Name, err)
43 }
44 b, _ := io.ReadAll(rc)
45 _ = rc.Close()
46 files[f.Name] = string(b)
47 }
48 for name, want := range map[string]string{"proj-main/a.txt": "hello", "proj-main/b.txt": "world"} {
49 if files[name] != want {
50 t.Errorf("zip 内 %s = %q,期望 %q", name, files[name], want)
51 }
52 }
53 }
54
55 check("/proj/archive?ref=main")
56 check("/proj/archive") // 缺省 ref 使用默认分支
57
58 // 仓库主页应出现下载入口,并指向当前 ref。
59 r := httptest.NewRequest(http.MethodGet, "/proj", nil)
60 w := httptest.NewRecorder()
61 srv.Handler().ServeHTTP(w, r)
62 if !strings.Contains(w.Body.String(), "Download ZIP") ||
63 !strings.Contains(w.Body.String(), `/proj/archive?ref=main`) {
64 t.Error("项目主页缺少 Download ZIP 入口")
65 }
66
67 for _, ref := range []string{"--upload-pack=evil", "-x", "a..b"} {
68 r := httptest.NewRequest(http.MethodGet, "/proj/archive?ref="+ref, nil)
69 w := httptest.NewRecorder()
70 srv.Handler().ServeHTTP(w, r)
71 if w.Code == http.StatusOK {
72 t.Errorf("非法 ref %q 被放行", ref)
73 }
74 }
75}