Path: blob/main/component/otelcol/auth/basic/basic_test.go
4096 views
package basic_test12import (3"context"4"net/http"5"net/http/httptest"6"testing"7"time"89"github.com/grafana/agent/component/otelcol/auth"10"github.com/grafana/agent/component/otelcol/auth/basic"11"github.com/grafana/agent/pkg/flow/componenttest"12"github.com/grafana/agent/pkg/river"13"github.com/grafana/agent/pkg/util"14"github.com/stretchr/testify/assert"15"github.com/stretchr/testify/require"16"go.opentelemetry.io/collector/config/configauth"17)1819// Test performs a basic integration test which runs the otelcol.auth.basic20// component and ensures that it can be used for authentication.21func Test(t *testing.T) {22// Create an HTTP server which will assert that basic auth has been injected23// into the request.24srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {25username, password, ok := r.BasicAuth()26assert.True(t, ok, "no basic auth found")27assert.Equal(t, "foo", username, "basic auth username didn't match")28assert.Equal(t, "bar", password, "basic auth password didn't match")2930w.WriteHeader(http.StatusOK)31}))32defer srv.Close()3334ctx := componenttest.TestContext(t)35ctx, cancel := context.WithTimeout(ctx, time.Minute)36defer cancel()3738l := util.TestLogger(t)3940// Create and run our component41ctrl, err := componenttest.NewControllerFromID(l, "otelcol.auth.basic")42require.NoError(t, err)4344cfg := `45username = "foo"46password = "bar"47`48var args basic.Arguments49require.NoError(t, river.Unmarshal([]byte(cfg), &args))5051go func() {52err := ctrl.Run(ctx, args)53require.NoError(t, err)54}()5556require.NoError(t, ctrl.WaitRunning(time.Second), "component never started")57require.NoError(t, ctrl.WaitExports(time.Second), "component never exported anything")5859// Get the authentication extension from our component and use it to make a60// request to our test server.61exports := ctrl.Exports().(auth.Exports)62require.NotNil(t, exports.Handler.Extension, "handler extension is nil")6364clientAuth, ok := exports.Handler.Extension.(configauth.ClientAuthenticator)65require.True(t, ok, "handler does not implement configauth.ClientAuthenticator")6667rt, err := clientAuth.RoundTripper(http.DefaultTransport)68require.NoError(t, err)69cli := &http.Client{Transport: rt}7071// Wait until the request finishes. We don't assert anything else here; our72// HTTP handler won't write the response until it ensures that the basic auth73// was found.74req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)75require.NoError(t, err)76resp, err := cli.Do(req)77require.NoError(t, err, "HTTP request failed")78require.Equal(t, http.StatusOK, resp.StatusCode)79}808182