Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions acceptance/acceptance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"github.com/databricks/cli/internal/build"
"github.com/databricks/cli/internal/testutil"
"github.com/databricks/cli/libs/auth"
"github.com/databricks/cli/libs/retry"
"github.com/databricks/cli/libs/testdiff"
"github.com/databricks/cli/libs/testserver"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -86,6 +87,8 @@ func init() {
flag.BoolVar(&WorkspaceTmpDir, "workspace-tmp-dir", false, "Run tests on the workspace file system (For DBR testing).")
flag.BoolVar(&OnlyOutTestToml, "only-out-test-toml", false, "Only regenerate out.test.toml files without running tests")
flag.BoolVar(&Subset, "subset", false, "Select a subset of EnvMatrix variants that cover all output files. Auto-enabled on -update (unless -run specifies a variant with '=').")
flag.StringVar(&internal.FaultPlanPath, "faultplan", "", "Fail one request per test as planned in this JSON file and skip the tests it does not list (see acceptance/internal/request_fault.go, tools/fault_sweep.py)")
flag.StringVar(&internal.FaultLogPath, "faultlog", "", "Append each test's request count and injected fault to this file as JSON lines")
flag.BoolVar(&DebugSandbox, "debugsandbox", false, "Use a per-test blocking proxy instead of a shared one; shows exactly which test caused unexpected internet access (slower)")
}

Expand Down Expand Up @@ -245,6 +248,14 @@ func testAccept(t *testing.T, inprocessMode bool, selectedTests []string, skipTo
Subset = true
}

if internal.FaultMode() {
// Outputs under injected faults must not become goldens, and a real workspace cannot be
// made to fail a chosen request.
require.False(t, testdiff.OverwriteMode, "-faultplan and -faultlog cannot be combined with -update")
require.Empty(t, os.Getenv("CLOUD_ENV"), "-faultplan and -faultlog only work against the local testserver")
require.NoError(t, internal.LoadFaultPlan())
}

repls := testdiff.ReplacementsContext{}
cwd, err := os.Getwd()
require.NoError(t, err)
Expand Down Expand Up @@ -890,6 +901,10 @@ func runTest(t *testing.T,
testEnv := buildTestEnv(config.Env, customEnv)
checkEnvFilters(t, testEnv, envFilters)

if reason := internal.FaultPlanSkipReason(t); reason != "" {
t.Skip(reason)
}

if LogConfig {
configBytes, err := json.MarshalIndent(config, "", " ")
require.NoError(t, err)
Expand Down Expand Up @@ -1067,6 +1082,11 @@ func runTest(t *testing.T,
cmd.Env = append(cmd.Env, "GIT_CONFIG_GLOBAL="+os.DevNull)
cmd.Env = append(cmd.Env, "GIT_CONFIG_SYSTEM="+os.DevNull)

if _, ok := internal.FaultPlanned(t); ok {
// The CLI's own retries (libs/retry) pause 15s; a test's Env can still override this.
cmd.Env = append(cmd.Env, retry.IntervalMsVariable+"=100")
}

for _, kv := range testEnv {
key, value, _ := strings.Cut(kv, "=")
// Only add replacement by default if value is part of EnvMatrix with more than 1 option and length is 4 or more chars
Expand Down
43 changes: 37 additions & 6 deletions acceptance/internal/prepare_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func PrepareServerAndClient(t *testing.T, config TestConfig, logRequests bool, o

// If we are not recording requests, and no custom server stubs are configured,
// use the default shared server.
if len(config.Server) == 0 && !recordRequests {
if len(config.Server) == 0 && !recordRequests && !FaultMode() {
cfg := &sdkconfig.Config{
Host: env.Get(t.Context(), "DATABRICKS_DEFAULT_HOST"),
Token: token,
Expand All @@ -225,6 +225,10 @@ type requestRecorder struct {
t *testing.T
includeHeaders []string
outputDir string
// onlyInjected treats only requests failed by a planned request fault as failed attempts,
// not every transient status: a testserver stub that answers with an error does so on
// purpose, and its goldens show every attempt.
onlyInjected bool

mu sync.Mutex
// entries holds what was written for requests still waiting for a response; nil unless
Expand Down Expand Up @@ -354,8 +358,9 @@ func isTransientStatus(status int) bool {
// not repeated stays recorded. Before it repeats a failed create, the CLI reads the resource to
// see whether the request created it anyway; a read answered with 404 is dropped with the failed
// attempt. A read that finds the resource stays recorded, since no repeat follows, and ends the
// recovery. Only the proxy uses this: the testserver answers with an error only when a test
// injects one, and its goldens show that.
// recovery. The proxy uses this, and so does the testserver when a planned request fault (see
// request_fault.go) fails a request: otherwise the testserver answers with an error only when a
// test injects one, and its goldens show that.
func (r *requestRecorder) noteResponse(request *testserver.Request, response *testserver.EncodedResponse) {
r.mu.Lock()
defer r.mu.Unlock()
Expand All @@ -365,7 +370,11 @@ func (r *requestRecorder) noteResponse(request *testserver.Request, response *te
if !ok {
return
}
if isTransientStatus(response.StatusCode) {
failed := isTransientStatus(response.StatusCode)
if r.onlyInjected {
failed = request.InjectedFault != ""
}
if failed {
r.failed[entry]++
if request.Method == http.MethodPost {
// The id of the resource a create names travels in a query parameter such as project_id.
Expand Down Expand Up @@ -424,15 +433,37 @@ func startLocalServer(t *testing.T,
) string {
s := testserver.New(t)

var planned *PlannedFault
if FaultMode() {
planned = setupRequestFault(t, s)
}

var responseCallbacks []func(request *testserver.Request, response *testserver.EncodedResponse)

// Record API requests in out.requests.txt if RecordRequests is true
// in test.toml
if recordRequests {
s.RequestCallback = newRequestRecorder(t, includeHeaders, outputDir, false).record
// With a fault planned, the CLI repeats the failed request, and the failed attempt is
// dropped from out.requests.txt as on cloud, so the test's goldens still apply.
recorder := newRequestRecorder(t, includeHeaders, outputDir, planned != nil)
s.RequestCallback = recorder.record
if planned != nil {
recorder.onlyInjected = true
responseCallbacks = append(responseCallbacks, recorder.noteResponse)
}
}

// Log API responses if the -logrequests flag is set.
if logRequests {
s.ResponseCallback = logResponseCallback(t)
responseCallbacks = append(responseCallbacks, logResponseCallback(t))
}

if len(responseCallbacks) > 0 {
s.ResponseCallback = func(request *testserver.Request, response *testserver.EncodedResponse) {
for _, callback := range responseCallbacks {
callback(request, response)
}
}
}

for ind := range stubs {
Expand Down
133 changes: 133 additions & 0 deletions acceptance/internal/request_fault.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package internal

import (
"encoding/json"
"fmt"
"os"
"sync"
"testing"

"github.com/databricks/cli/libs/testserver"
"github.com/stretchr/testify/require"
)

// Request fault mode checks that the CLI and the tests survive a single backend error: each
// planned test gets one request failed (see testserver.SetRequestFault), and the test must
// still pass. tools/fault_sweep.py drives it: it learns each test's request count from runs
// with only -faultlog, then picks a request and a fault kind per test.

// FaultPlanPath is the -faultplan flag: a JSON object mapping a test name (as go test prints it)
// to the fault to inject, e.g. {"TestAccept/bundle/deploy/basic": {"at": 3, "kind": "503"}}.
// Tests not in the plan are skipped.
var FaultPlanPath string

// FaultLogPath is the -faultlog flag: a file each test run against the testserver appends a
// FaultLogEntry line to. Setting it alone runs the tests unchanged and records request counts.
var FaultLogPath string

// PlannedFault is one -faultplan entry.
type PlannedFault struct {
At int `json:"at"`
Kind string `json:"kind"`
}

// FaultLogEntry is one line of the -faultlog file.
type FaultLogEntry struct {
Test string `json:"test"`
Requests int `json:"requests"`
Planned *PlannedFault `json:"planned,omitempty"`
Fired *testserver.FiredRequestFault `json:"fired,omitempty"`
Failed bool `json:"failed"`
Skipped bool `json:"skipped"`
}

var (
faultPlan map[string]PlannedFault
faultLogLock sync.Mutex
)

// LoadFaultPlan reads -faultplan, if set. It must run before any test starts.
func LoadFaultPlan() error {
if FaultPlanPath == "" {
return nil
}
data, err := os.ReadFile(FaultPlanPath)
if err != nil {
return err
}
if err := json.Unmarshal(data, &faultPlan); err != nil {
return fmt.Errorf("%s: %w", FaultPlanPath, err)
}
if faultPlan == nil {
faultPlan = map[string]PlannedFault{}
}
return nil
}

// FaultMode reports whether -faultplan or -faultlog is set. In this mode every test gets its
// own testserver, so its requests can be counted and failed.
func FaultMode() bool {
return FaultPlanPath != "" || FaultLogPath != ""
}

// FaultPlanned returns the fault planned for the test and whether -faultplan lists it.
func FaultPlanned(t *testing.T) (PlannedFault, bool) {
fault, ok := faultPlan[t.Name()]
return fault, ok
}

// FaultPlanSkipReason returns why the test is skipped under -faultplan, or "".
func FaultPlanSkipReason(t *testing.T) string {
if FaultPlanPath == "" {
return ""
}
if _, ok := FaultPlanned(t); ok {
return ""
}
return "not in -faultplan"
}

// setupRequestFault arms the test's planned fault on s and logs the outcome when the test ends.
// It returns the planned fault, or nil.
func setupRequestFault(t *testing.T, s *testserver.Server) *PlannedFault {
var planned *PlannedFault
if fault, ok := FaultPlanned(t); ok {
require.NoError(t, s.SetRequestFault(fault.At, fault.Kind))
planned = &fault
}
if FaultLogPath != "" {
t.Cleanup(func() {
appendFaultLog(t, FaultLogEntry{
Test: t.Name(),
Requests: s.RequestCount(),
Planned: planned,
Fired: s.FiredRequestFault(),
Failed: t.Failed(),
Skipped: t.Skipped(),
})
})
}
if planned != nil {
t.Cleanup(func() {
if fired := s.FiredRequestFault(); fired != nil {
t.Logf("Injected fault %s into request %d: %s %s", fired.Kind, fired.At, fired.Method, fired.Path)
} else {
t.Logf("Planned fault %s at request %d did not fire: the test made %d requests", planned.Kind, planned.At, s.RequestCount())
}
})
}
return planned
}

func appendFaultLog(t *testing.T, entry FaultLogEntry) {
line, err := json.Marshal(entry)
require.NoError(t, err)

faultLogLock.Lock()
defer faultLogLock.Unlock()
f, err := os.OpenFile(FaultLogPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
require.NoError(t, err)
defer f.Close()
_, err = f.Write(append(line, '\n'))
require.NoError(t, err)
}
60 changes: 60 additions & 0 deletions acceptance/internal/request_fault_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package internal

import (
"net/http"
"os"
"path/filepath"
"strings"
"testing"

"github.com/databricks/cli/libs/testserver"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// planFault plans a fault for the running test, as -faultplan would.
func planFault(t *testing.T, fault PlannedFault) {
oldPath, oldPlan := FaultPlanPath, faultPlan
t.Cleanup(func() { FaultPlanPath, faultPlan = oldPath, oldPlan })
FaultPlanPath = "plan.json"
faultPlan = map[string]PlannedFault{t.Name(): fault}
}

func get(t *testing.T, url string) int {
resp, err := http.Get(url)
require.NoError(t, err)
resp.Body.Close()
return resp.StatusCode
}

func TestRequestFaultDropsRetriedAttempt(t *testing.T) {
planFault(t, PlannedFault{At: 2, Kind: testserver.FaultUnavailable})
outputDir := t.TempDir()
stubs := []ServerStub{
{Pattern: "GET /api/2.0/ok", Response: testserver.Response{Body: "{}"}},
// A stub answering with an error keeps every attempt recorded, fault or not.
{Pattern: "GET /api/2.0/stub-error", Response: testserver.Response{StatusCode: 503, Body: "{}"}},
}
url := startLocalServer(t, stubs, true, false, nil, outputDir)

assert.Equal(t, 200, get(t, url+"/api/2.0/ok"))
assert.Equal(t, 503, get(t, url+"/api/2.0/ok"))
assert.Equal(t, 200, get(t, url+"/api/2.0/ok"))
assert.Equal(t, 503, get(t, url+"/api/2.0/stub-error"))
assert.Equal(t, 503, get(t, url+"/api/2.0/stub-error"))

data, err := os.ReadFile(filepath.Join(outputDir, "out.requests.txt"))
require.NoError(t, err)
assert.Equal(t, 2, strings.Count(string(data), `"path": "/api/2.0/ok"`))
assert.Equal(t, 2, strings.Count(string(data), `"path": "/api/2.0/stub-error"`))
}

func TestFaultPlanSkipReason(t *testing.T) {
assert.Empty(t, FaultPlanSkipReason(t))

planFault(t, PlannedFault{At: 1, Kind: testserver.FaultUnavailable})
assert.Empty(t, FaultPlanSkipReason(t))

faultPlan = map[string]PlannedFault{"TestAccept/other": {At: 1, Kind: testserver.FaultUnavailable}}
assert.Equal(t, "not in -faultplan", FaultPlanSkipReason(t))
}
Loading
Loading