2023-09-26 12:05:19 +01:00
|
|
|
package agenttest
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/url"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
|
|
|
|
|
"github.com/coder/coder/v2/agent"
|
2026-04-28 17:58:28 +03:00
|
|
|
"github.com/coder/coder/v2/agent/agentcontextconfig"
|
2023-09-26 12:05:19 +01:00
|
|
|
"github.com/coder/coder/v2/codersdk/agentsdk"
|
2024-11-18 14:09:22 +04:00
|
|
|
"github.com/coder/coder/v2/testutil"
|
2023-09-26 12:05:19 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// New starts a new agent for use in tests.
|
|
|
|
|
// The agent will use the provided coder URL and session token.
|
|
|
|
|
// The options passed to agent.New() can be modified by passing an optional
|
|
|
|
|
// variadic func(*agent.Options).
|
|
|
|
|
// Returns the agent. Closing the agent is handled by the test cleanup.
|
|
|
|
|
// It is the responsibility of the caller to call coderdtest.AwaitWorkspaceAgents
|
|
|
|
|
// to ensure agent is connected.
|
|
|
|
|
func New(t testing.TB, coderURL *url.URL, agentToken string, opts ...func(*agent.Options)) agent.Agent {
|
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
|
|
var o agent.Options
|
2024-11-18 14:09:22 +04:00
|
|
|
log := testutil.Logger(t).Named("agent")
|
2023-09-26 12:05:19 +01:00
|
|
|
o.Logger = log
|
2026-03-03 21:23:59 +04:00
|
|
|
o.SocketPath = testutil.AgentSocketPath(t)
|
2023-09-26 12:05:19 +01:00
|
|
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
|
opt(&o)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if o.Client == nil {
|
2025-09-03 10:38:42 +04:00
|
|
|
agentClient := agentsdk.New(coderURL, agentsdk.WithFixedToken(agentToken))
|
2023-09-26 12:05:19 +01:00
|
|
|
agentClient.SDK.SetLogger(log)
|
|
|
|
|
o.Client = agentClient
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if o.LogDir == "" {
|
|
|
|
|
o.LogDir = t.TempDir()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
agt := agent.New(o)
|
|
|
|
|
t.Cleanup(func() {
|
|
|
|
|
assert.NoError(t, agt.Close(), "failed to close agent during cleanup")
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return agt
|
|
|
|
|
}
|
2026-04-28 17:58:28 +03:00
|
|
|
|
|
|
|
|
// WithContextConfigFromEnv returns an agent option that
|
|
|
|
|
// populates ContextConfig from the current environment.
|
|
|
|
|
func WithContextConfigFromEnv() func(*agent.Options) {
|
|
|
|
|
return func(o *agent.Options) {
|
|
|
|
|
o.ContextConfig = agentcontextconfig.ReadEnvConfig()
|
|
|
|
|
}
|
|
|
|
|
}
|