Files
coder/cli/connect_test.go
Spike Curtis 3b54254177 feat: add coder connect exists hidden subcommand (#17418)
Adds a new hidden subcommand `coder connect exists <hostname>` that checks if the name exists via Coder Connect. This will be used in SSH config to match only if Coder Connect is unavailable for the hostname in question, so that the SSH client will directly dial the workspace over an existing Coder Connect tunnel.

Also refactors the way we inject a test DNS resolver into the lookup functions so that we can test from outside the `workspacesdk` package.
2025-04-17 11:23:24 +04:00

77 lines
1.9 KiB
Go

package cli_test
import (
"bytes"
"context"
"net"
"testing"
"github.com/stretchr/testify/require"
"tailscale.com/net/tsaddr"
"github.com/coder/serpent"
"github.com/coder/coder/v2/cli"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/testutil"
)
func TestConnectExists_Running(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
var root cli.RootCmd
cmd, err := root.Command(root.AGPL())
require.NoError(t, err)
inv := (&serpent.Invocation{
Command: cmd,
Args: []string{"connect", "exists", "test.example"},
}).WithContext(withCoderConnectRunning(ctx))
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
inv.Stdout = stdout
inv.Stderr = stderr
err = inv.Run()
require.NoError(t, err)
}
func TestConnectExists_NotRunning(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
var root cli.RootCmd
cmd, err := root.Command(root.AGPL())
require.NoError(t, err)
inv := (&serpent.Invocation{
Command: cmd,
Args: []string{"connect", "exists", "test.example"},
}).WithContext(withCoderConnectNotRunning(ctx))
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
inv.Stdout = stdout
inv.Stderr = stderr
err = inv.Run()
require.ErrorIs(t, err, cli.ErrSilent)
}
type fakeResolver struct {
shouldReturnSuccess bool
}
func (f *fakeResolver) LookupIP(_ context.Context, _, _ string) ([]net.IP, error) {
if f.shouldReturnSuccess {
return []net.IP{net.ParseIP(tsaddr.CoderServiceIPv6().String())}, nil
}
return nil, &net.DNSError{IsNotFound: true}
}
func withCoderConnectRunning(ctx context.Context) context.Context {
return workspacesdk.WithTestOnlyCoderContextResolver(ctx, &fakeResolver{shouldReturnSuccess: true})
}
func withCoderConnectNotRunning(ctx context.Context) context.Context {
return workspacesdk.WithTestOnlyCoderContextResolver(ctx, &fakeResolver{shouldReturnSuccess: false})
}