This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
/
helpers.go
90 lines (77 loc) · 2.48 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package testutils
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
car "github.com/ipld/go-car/v2"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/storage/bsadapter"
selectorparse "github.com/ipld/go-ipld-prime/traversal/selector/parse"
cid "github.com/ipfs/go-cid"
carv2bs "github.com/ipld/go-car/v2/blockstore"
"github.com/stretchr/testify/require"
)
func ParseCar(t *testing.T, ctx context.Context, path string) (cid.Cid, []byte) {
from, err := carv2bs.OpenReadOnly(path)
require.NoError(t, err)
rts, err := from.Roots()
require.NoError(t, err)
ls := cidlink.DefaultLinkSystem()
bsa := bsadapter.Adapter{Wrapped: from}
ls.SetReadStorage(&bsa)
w := bytes.NewBuffer(nil)
_, err = car.TraverseV1(ctx, &ls, rts[0], selectorparse.CommonSelector_ExploreAllRecursively, w)
require.NoError(t, err)
require.NoError(t, from.Close())
return rts[0], w.Bytes()
}
func GetTestServerFor(t *testing.T, ctx context.Context, path string) (cid.Cid, []byte, *httptest.Server) {
root, contents := ParseCar(t, ctx, path)
return root, contents, GetTestServer(t, root.String(), contents)
}
func GetTestHangingServer(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(24 * time.Hour)
}))
}
func GetTestServerForRoots(t *testing.T, out map[string][]byte) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
v := q.Get("arg")
if len(v) == 0 {
http.Error(w, "invalid arg", http.StatusBadRequest)
return
}
bz, ok := out[v]
if !ok {
http.Error(w, "invalid arg", http.StatusBadRequest)
return
}
_, err := w.Write(bz)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
}
func GetTestServer(t *testing.T, root string, out []byte) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
q := r.URL.Query()
v := q.Get("arg")
if len(v) == 0 || v != root {
http.Error(w, "invalid arg", http.StatusBadRequest)
return
}
if _, err := w.Write(out); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
}
func GetTestErrorServer(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "bad req", http.StatusInternalServerError)
}))
}