oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "html"
8 "net/http"
9 "net/url"
10 "os"
11 "path/filepath"
12 "strings"
13 "sync"
14 "testing"
15 "testing/fstest"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/equipo"
19 "amadan.net/rastrillo/rastrillo"
20 "amadan.net/rastrillo/rastrillo/migrate"
21)
22
23func TestRefusalReasons(t *testing.T) {
24 f, c := pageOwner(t)
25 check := func(path string, form url.Values, status int, message string) {
26 t.Helper()
27 res := clientPost(t, c, f.server.URL+path, testOrigin, form)
28 body := html.UnescapeString(readBody(t, res))
29 if res.StatusCode != status || !strings.Contains(body, message) {
30 t.Errorf("%s: status %d want %d; missing message %q", path, res.StatusCode, status, message)
31 }
32 }
33 for _, change := range []struct{ role, active string }{{"member", "true"}, {"owner", "false"}} {
34 check("/team/members", url.Values{"address": {ownerAddress}, "role": {change.role}, "active": {change.active}, "revision": {"1"}}, 403, "Add another owner before changing or removing the last owner.")
35 }
36 setMember(t, f.store, memberAddress, equipo.RoleMember, true)
37 a, err := f.store.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: "Oficina"})
38 if err != nil {
39 t.Fatal(err)
40 }
41 p := projectInput(a)
42 _, err = f.store.SaveProject(context.Background(), ownerActor, p, []equipo.DecisionOwner{{Decision: "work", Address: ownerAddress}, {Decision: "merge", Address: memberAddress}}, "first")
43 if err != nil {
44 t.Fatal(err)
45 }
46 check("/team/members", url.Values{"address": {memberAddress}, "role": {"member"}, "active": {"false"}, "revision": {"1"}}, 409, "Reassign this person's project decisions before removing them.")
47 check("/projects", url.Values{"account_id": {fmt.Sprint(a.ID)}, "name": {"Duplicate"}, "kind": {"app"}, "repository": {p.Repository}, "app_name": {p.AppName}, "default_branch": {"main"}, "owner_work": {ownerAddress}, "owner_merge": {memberAddress}, "request_id": {"second"}, "revision": {"0"}}, 409, "Another project uses this repository and app. Choose a different pair.")
48 check("/accounts", url.Values{"label": {" oficina "}, "id": {"0"}, "revision": {"0"}}, 409, "This account label already exists. Use it or choose another label.")
49}
50
51func TestAccountLabelDuplicates(t *testing.T) {
52 t.Parallel()
53 s, d, a := projectStore(t)
54 before := scalar(t, d, "SELECT count(*) FROM audit_events")
55 for _, label := range []string{"Oficina", " oficina ", "OFICINA"} {
56 if _, err := s.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: label}); !errors.Is(err, equipo.ErrConflict) {
57 t.Errorf("duplicate %q: %v", label, err)
58 }
59 }
60 if scalar(t, d, "SELECT count(*) FROM accounts") != 1 || scalar(t, d, "SELECT count(*) FROM audit_events") != before {
61 t.Fatal("duplicate changed records or audit")
62 }
63 b, err := s.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: "Other"})
64 if err != nil {
65 t.Fatal(err)
66 }
67 b.Label = " oficina "
68 if _, err := s.SaveAccount(context.Background(), ownerActor, b); !errors.Is(err, equipo.ErrConflict) {
69 t.Fatal("duplicate rename", err)
70 }
71 // A retry of a rename to its own label is still allowed at the current revision.
72 a.Label = " OFICINA "
73 if _, err := s.SaveAccount(context.Background(), ownerActor, a); err != nil {
74 t.Fatal(err)
75 }
76 for _, query := range []string{"INSERT INTO accounts(label, revision) VALUES (' oficina ', 1)", "UPDATE accounts SET label='oficina' WHERE label='Other'"} {
77 if _, err := d.Writer().Exec(query); err == nil {
78 t.Error("database accepted duplicate", query)
79 }
80 }
81}
82
83func TestBootstrapNamesOwnersSetting(t *testing.T) {
84 t.Parallel()
85 for _, owners := range [][]string{nil, {""}, {"not-an-address"}} {
86 s, d := rosterStore(t)
87 err := s.Bootstrap(context.Background(), owners)
88 if !errors.Is(err, equipo.ErrInvalid) || !strings.Contains(err.Error(), "EQUIPO_OWNERS") {
89 t.Errorf("boot refusal: %v", err)
90 }
91 if scalar(t, d, "SELECT count(*) FROM teams") != 0 {
92 t.Fatal("invalid bootstrap persisted team")
93 }
94 }
95}
96
97func TestConfigureRejectsWrongRoot(t *testing.T) {
98 defer func() {
99 if recover() == nil {
100 t.Error("Configure accepted a non-Equipo root")
101 }
102 }()
103 mux := http.NewServeMux()
104 mux.HandleFunc("/", func(http.ResponseWriter, *http.Request) {})
105 equipo.Configure(&rastrillo.Options{}, mux, time.Now())
106}
107
108func TestUnavailableUsageAndErrorParents(t *testing.T) {
109 f, c := pageOwner(t)
110 for _, path := range []string{"/projects/accounts", "/settings"} {
111 body := pageBody(t, c, f.server.URL, path)
112 if !strings.Contains(body, `data-usage="unavailable"`) || strings.Contains(body, `data-usage="0"`) {
113 t.Errorf("%s: unknown usage presented as zero", path)
114 }
115 }
116 setMember(t, f.store, "second@example.com", equipo.RoleOwner, true)
117 setMember(t, f.store, ownerAddress, equipo.RoleMember, true)
118 res := clientGet(t, c, f.server.URL+"/projects/new")
119 body := html.UnescapeString(readBody(t, res))
120 if res.StatusCode != 403 || !strings.Contains(body, `<a href="/projects">Back to the form</a>`) {
121 t.Errorf("403 has no project parent: %d", res.StatusCode)
122 }
123}
124
125func TestAccountLabelMigration(t *testing.T) {
126 t.Parallel()
127 for _, duplicate := range []bool{false, true} {
128 t.Run(fmt.Sprint(duplicate), func(t *testing.T) {
129 d, _ := foundationDB(t)
130 fs := fstest.MapFS{}
131 paths, err := filepath.Glob("../equipo/migrations/000[1-5]_*.sql")
132 if err != nil || len(paths) != 5 {
133 t.Fatal("old migrations", paths, err)
134 }
135 for _, path := range paths {
136 data, err := os.ReadFile(path)
137 if err != nil {
138 t.Fatal(err)
139 }
140 fs["migrations/"+filepath.Base(path)] = &fstest.MapFile{Data: data}
141 }
142 old := migrate.MustFromFS(fs, "equipo")
143 if _, err := migrate.Apply(context.Background(), d, old); err != nil {
144 t.Fatal(err)
145 }
146 if _, err := d.Writer().Exec("INSERT INTO accounts(id,label,revision) VALUES (1,'Oficina',3)"); err != nil {
147 t.Fatal(err)
148 }
149 if duplicate {
150 if _, err := d.Writer().Exec("INSERT INTO accounts(id,label,revision) VALUES (2,' oficina ',1)"); err != nil {
151 t.Fatal(err)
152 }
153 }
154 _, err = migrate.Apply(context.Background(), d, equipo.Schema)
155 if duplicate {
156 if err == nil {
157 t.Fatal("migration silently accepted legacy duplicates")
158 }
159 if scalar(t, d, "SELECT count(*) FROM accounts") != 2 {
160 t.Fatal("migration deleted legacy accounts")
161 }
162 // An owner can rename the duplicate on the old app before retrying.
163 if _, err := d.Writer().Exec("UPDATE accounts SET label='Other' WHERE id=2"); err != nil {
164 t.Fatal(err)
165 }
166 if _, err := migrate.Apply(context.Background(), d, equipo.Schema); err != nil {
167 t.Fatal(err)
168 }
169 } else if err != nil {
170 t.Fatal(err)
171 }
172 if scalar(t, d, "SELECT revision FROM accounts WHERE id=1 AND label='Oficina'") != 3 {
173 t.Fatal("migration changed account")
174 }
175 if _, err := d.Writer().Exec("INSERT INTO accounts(label,revision) VALUES (' OFICINA ',1)"); err == nil {
176 t.Fatal("migration did not enforce uniqueness")
177 }
178 if result, err := migrate.Apply(context.Background(), d, equipo.Schema); err != nil || len(result.Applied) != 0 {
179 t.Fatal("migration repeated", result, err)
180 }
181 })
182 }
183}
184
185func TestAccountConcurrentDuplicate(t *testing.T) {
186 t.Parallel()
187 s, d, _ := projectStore(t)
188 var wg sync.WaitGroup
189 results := make(chan error, 8)
190 for i := 0; i < 8; i++ {
191 wg.Add(1)
192 go func() {
193 defer wg.Done()
194 _, err := s.SaveAccount(context.Background(), ownerActor, equipo.Account{Label: "Concurrent"})
195 results <- err
196 }()
197 }
198 wg.Wait()
199 close(results)
200 saved := 0
201 for err := range results {
202 if err == nil {
203 saved++
204 } else if !errors.Is(err, equipo.ErrAccountLabelExists) {
205 t.Fatal(err)
206 }
207 }
208 if saved != 1 || scalar(t, d, "SELECT count(*) FROM accounts WHERE label='Concurrent'") != 1 {
209 t.Fatal("concurrent duplicate saved", saved)
210 }
211}
212
213func TestRefusalCategories(t *testing.T) {
214 for _, tc := range []struct{ specific, category error }{
215 {equipo.ErrDecisionOwnerAssigned, equipo.ErrConflict},
216 {equipo.ErrBindingInUse, equipo.ErrConflict},
217 {equipo.ErrLastOwner, equipo.ErrForbidden},
218 {equipo.ErrAccountLabelExists, equipo.ErrConflict},
219 {equipo.ErrBootstrapOwners, equipo.ErrInvalid},
220 } {
221 if tc.specific == tc.category || !errors.Is(tc.specific, tc.category) {
222 t.Errorf("lost category: %v", tc.specific)
223 }
224 }
225}
226