MCPcopy Index your code
hub / github.com/coder/coder / TestInstrument

Function TestInstrument

coderd/promoauth/oauth2_test.go:24–103  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

22)
23
24func TestInstrument(t *testing.T) {
25 t.Parallel()
26
27 ctx := testutil.Context(t, testutil.WaitShort)
28 idp := oidctest.NewFakeIDP(t, oidctest.WithServing())
29 reg := prometheus.NewRegistry()
30 t.Cleanup(func() {
31 if t.Failed() {
32 t.Log(promhelp.RegistryDump(reg))
33 }
34 })
35
36 const id = "test"
37 labels := prometheus.Labels{
38 "name": id,
39 "status_code": "200",
40 }
41 const metricname = "coderd_oauth2_external_requests_total"
42 count := func(source string) int {
43 labels["source"] = source
44 return promhelp.CounterValue(t, reg, "coderd_oauth2_external_requests_total", labels)
45 }
46
47 factory := promoauth.NewFactory(reg)
48
49 cfg := externalauth.Config{
50 InstrumentedOAuth2Config: factory.New(id, idp.OIDCConfig(t, []string{})),
51 ID: "test",
52 ValidateURL: must[*url.URL](t)(idp.IssuerURL().Parse("/oauth2/userinfo")).String(),
53 }
54
55 // 0 Requests before we start
56 require.Nil(t, promhelp.MetricValue(t, reg, metricname, labels), "no metrics at start")
57
58 noClientCtx := ctx
59 // This should never be done, but promoauth should not break the default client
60 // even if this happens. So intentionally do this to verify nothing breaks.
61 ctx = context.WithValue(ctx, oauth2.HTTPClient, http.DefaultClient)
62 // Exchange should trigger a request
63 code := idp.CreateAuthCode(t, "foo")
64 _, err := cfg.Exchange(ctx, code)
65 require.NoError(t, err)
66 require.Equal(t, count("Exchange"), 1)
67
68 // Do an exchange without a default http client as well to verify original
69 // transport is not broken.
70 code = idp.CreateAuthCode(t, "bar")
71 token, err := cfg.Exchange(noClientCtx, code)
72 require.NoError(t, err)
73 require.Equal(t, count("Exchange"), 2)
74
75 // Force a refresh
76 token.Expiry = time.Now().Add(time.Hour * -1)
77 src := cfg.TokenSource(ctx, token)
78 refreshed, err := src.Token()
79 require.NoError(t, err)
80 require.NotEqual(t, token.AccessToken, refreshed.AccessToken, "token refreshed")
81 require.Equal(t, count("TokenSource"), 1)

Callers

nothing calls this directly

Calls 15

NewMethod · 0.95
OIDCConfigMethod · 0.95
IssuerURLMethod · 0.95
CreateAuthCodeMethod · 0.95
ExchangeMethod · 0.95
TokenSourceMethod · 0.95
ValidateTokenMethod · 0.95
ContextFunction · 0.92
NewFakeIDPFunction · 0.92
WithServingFunction · 0.92
RegistryDumpFunction · 0.92
CounterValueFunction · 0.92

Tested by

no test coverage detected