1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6 "crypto/sha1" // #nosec G505 -- ids for tests
7 "encoding/hex"
8 "testing"
9
10 "github.com/stretchr/testify/assert"
11
12 "bnema.dev/ermite/internal/domain"
13)
14
15// commitOf is a commit id derived from a name, so that two refs of one name
16// share their commit.
17func commitOf(name string) domain.ObjectID {
18 sum := sha1.Sum([]byte(name)) // #nosec G401 -- an id for a test, not a hash for security
19 id, err := domain.ParseObjectID(hex.EncodeToString(sum[:]))
20 if err != nil {
21 panic(err)
22 }
23 return id
24}
25
26func ref(kind domain.RefKind, short string) domain.Ref {
27 id := commitOf(short)
28 return domain.Ref{Name: "refs/x/" + short, ShortName: short, Kind: kind, ID: id, CommitID: id}
29}
30
31// AC3: a ref with slashes is found by the longest matching prefix.
32func TestResolveRef(t *testing.T) {
33 t.Parallel()
34 b, tag := domain.RefKindBranch, domain.RefKindTag
35 refs := []domain.Ref{
36 ref(b, "main"), ref(b, "feature"), ref(b, "feature/x"), ref(b, "feature/x/y"), ref(tag, "v1/rc"),
37 ref(domain.RefKindHead, "main"), ref(tag, "main"),
38 }
39 tests := []struct {
40 path, ref, rest string
41 kind domain.RefKind
42 ok bool
43 }{
44 {"main", "main", "", b, true},
45 {"main/src/a.go", "main", "src/a.go", b, true},
46 {"feature/x/y/z.txt", "feature/x/y", "z.txt", b, true},
47 {"feature/x/z.txt", "feature/x", "z.txt", b, true},
48 {"feature/other", "feature", "other", b, true},
49 {"/feature/x/", "feature/x", "", b, true},
50 {"v1/rc/README", "v1/rc", "README", tag, true},
51 {"v1/README", "", "", "", false},
52 {"nope/main", "", "", "", false},
53 {"", "", "", "", false},
54 }
55 for _, tt := range tests {
56 t.Run(tt.path, func(t *testing.T) {
57 t.Parallel()
58 r, rest, ok := resolveRef(refs, tt.path)
59 assert.Equal(t, tt.ok, ok)
60 if !ok {
61 return
62 }
63 assert.Equal(t, tt.ref, r.ShortName)
64 assert.Equal(t, tt.kind, r.Kind, "a branch wins over a tag of the same name")
65 assert.Equal(t, tt.rest, rest)
66 })
67 }
68}
69
70func TestRepoHref(t *testing.T) {
71 t.Parallel()
72 assert.Equal(t, "/demo", repoHref("demo"))
73 assert.Equal(t, "/demo/tree/feature/x/a%20b/c%23.go", repoHref("demo", "tree", "feature/x", "a b/c#.go"))
74 assert.Equal(t, "/demo/blob/main/%3Fq", repoHref("demo", "blob", "main", "", "?q"))
75}