~bigbes/sr-ht-ecore

ref: 00d758288173ba73e6c117516c4d3828769667ba sr-ht-ecore/apimeta/apimeta_test.go -rw-r--r-- 2.3 KiB
00d75828 — Eugene Blikh mcphttp: test Unwrap for what it actually carries 2 days ago
                                                                                
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
package apimeta

import (
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"sourcecraft.dev/bigbes/sr-ht-core/crypto"

	"sourcecraft.dev/bigbes/sr-ht-ecore/ecoretest"
)

func TestMain(m *testing.M) {
	ecoretest.InitCrypto()
	m.Run()
}

func serve(t *testing.T, scopes ...string) (*httptest.ResponseRecorder, Meta) {
	t.Helper()
	rec := httptest.NewRecorder()
	Handler(scopes...).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, Path, nil))

	var got Meta
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
	return rec, got
}

func TestHandlerPublishesTheScopesAndTheWebhookKey(t *testing.T) {
	rec, got := serve(t, "repos")

	require.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
	assert.Equal(t, []string{"repos"}, got.Scopes)

	want := base64.StdEncoding.EncodeToString(crypto.WebhookPubkey)
	assert.Equal(t, want, got.WebhookPubkey)
	assert.NotEmpty(t, got.WebhookPubkey, "the instance's webhook key is what a consumer verifies payloads with")
}

// The failure this guards is not this service's: meta.sr.ht iterates every
// discovered service's scopes on one page, so a null here 500s the
// personal-token page for the whole instance. It is checked on the wire and not
// on the struct, because it is the JSON that travels.
func TestNoScopesIsAnEmptyListAndNeverNull(t *testing.T) {
	for _, tc := range []struct {
		name   string
		scopes []string
	}{
		{"no arguments at all", nil},
		{"an explicitly empty slice", []string{}},
	} {
		t.Run(tc.name, func(t *testing.T) {
			rec, got := serve(t, tc.scopes...)

			assert.NotContains(t, rec.Body.String(), "null")
			assert.Contains(t, rec.Body.String(), `"scopes":[]`)
			assert.NotNil(t, got.Scopes)
			assert.Empty(t, got.Scopes)
		})
	}
}

func TestHandlerAnswersEveryRequestIdentically(t *testing.T) {
	h := Handler("repos", "objects")

	var bodies []string
	for range 3 {
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, Path, nil))
		require.Equal(t, http.StatusOK, rec.Code)
		bodies = append(bodies, rec.Body.String())
	}
	assert.Equal(t, bodies[0], bodies[1])
	assert.Equal(t, bodies[1], bodies[2])
	assert.Contains(t, bodies[0], `"scopes":["repos","objects"]`, "the scopes keep the order they were declared in")
}