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
17 changes: 15 additions & 2 deletions acceptance/bin/fault.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#!/usr/bin/env python3
"""Set up a fault rule on the testserver for the current test token.

Usage: fault.py [--after-handler] [--body-contains SUBSTR] PATTERN STATUS_CODE OFFSET TIMES [ERROR_CODE]
Usage: fault.py [--after-handler] [--body-contains SUBSTR] [--header NAME:VALUE] PATTERN STATUS_CODE OFFSET TIMES [ERROR_CODE]

--after-handler run the handler first; keep its effect and replace only the response
--body-contains only fire when the request body contains SUBSTR, e.g. to target one
file's /workspace/import upload (all uploads share that path)
--header add a header to the fault response, e.g. Retry-After:1; repeat for
more headers (a repeated name keeps the last value)
PATTERN HTTP method and path; * matches within one path segment, ** spans /,
e.g. "POST /api/2.0/bundle/deployments/*/versions/*/complete"
or "PATCH /api/2.0/bundle/**"
Expand Down Expand Up @@ -42,9 +44,19 @@
body_contains = args[i + 1]
del args[i : i + 2]

headers = {}
while "--header" in args:
i = args.index("--header")
name, sep, value = args[i + 1].partition(":") if i + 1 < len(args) else ("", "", "")
if not sep or not name.strip():
print("--header needs NAME:VALUE", file=sys.stderr)
sys.exit(1)
headers[name.strip()] = value.strip()
del args[i : i + 2]

if len(args) not in (4, 5):
print(
f"usage: {sys.argv[0]} [--after-handler] [--body-contains SUBSTR] PATTERN STATUS_CODE OFFSET TIMES [ERROR_CODE]",
f"usage: {sys.argv[0]} [--after-handler] [--body-contains SUBSTR] [--header NAME:VALUE] PATTERN STATUS_CODE OFFSET TIMES [ERROR_CODE]",
file=sys.stderr,
)
sys.exit(1)
Expand All @@ -62,6 +74,7 @@
"times": times,
"after_handler": after_handler,
"body_contains": body_contains,
"headers": headers,
}
).encode()

Expand Down
34 changes: 15 additions & 19 deletions libs/testserver/fault.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ type FaultRule struct {
// every upload through the same method+path, so the only way to target a
// single file's upload is by matching its multipart "path" form field.
bodyContains string

// headers are added to the fault response, e.g. Retry-After.
headers map[string]string
}

// FaultRules holds the active fault injection rules for a test server.
Expand All @@ -43,15 +46,10 @@ func NewFaultRules() *FaultRules {

// Set registers or replaces a fault rule for the given token and pattern.
func (fr *FaultRules) Set(token, pattern string, statusCode int, body string, offset, times int, bodyContains string) {
fr.set(token, pattern, statusCode, body, offset, times, false, bodyContains)
}

// SetAfterHandler is like Set, but the handler runs first so its effect is kept.
func (fr *FaultRules) SetAfterHandler(token, pattern string, statusCode int, body string, offset, times int, bodyContains string) {
fr.set(token, pattern, statusCode, body, offset, times, true, bodyContains)
fr.set(token, pattern, statusCode, body, offset, times, false, bodyContains, nil)
}

func (fr *FaultRules) set(token, pattern string, statusCode int, body string, offset, times int, afterHandler bool, bodyContains string) {
func (fr *FaultRules) set(token, pattern string, statusCode int, body string, offset, times int, afterHandler bool, bodyContains string, headers map[string]string) {
// Escape regex characters so the pattern starts as literal text.
escapedPattern := regexp.QuoteMeta(pattern)

Expand All @@ -74,6 +72,7 @@ func (fr *FaultRules) set(token, pattern string, statusCode int, body string, of
times: times,
pattern: matcher,
bodyContains: bodyContains,
headers: headers,
}
}

Expand Down Expand Up @@ -122,22 +121,19 @@ func (fr *FaultRules) Check(method, path, token string, body []byte) *FaultRule
func faultEndpointHandler(fr *FaultRules) HandlerFunc {
return func(req Request) any {
var body struct {
Pattern string `json:"pattern"`
StatusCode int `json:"status_code"`
Body string `json:"body"`
Offset int `json:"offset"`
Times int `json:"times"`
AfterHandler bool `json:"after_handler"`
BodyContains string `json:"body_contains"`
Pattern string `json:"pattern"`
StatusCode int `json:"status_code"`
Body string `json:"body"`
Offset int `json:"offset"`
Times int `json:"times"`
AfterHandler bool `json:"after_handler"`
BodyContains string `json:"body_contains"`
Headers map[string]string `json:"headers"`
}
if err := json.Unmarshal(req.Body, &body); err != nil {
return Response{StatusCode: 400, Body: map[string]string{"error": err.Error()}}
}
if body.AfterHandler {
fr.SetAfterHandler(req.Token, body.Pattern, body.StatusCode, body.Body, body.Offset, body.Times, body.BodyContains)
} else {
fr.Set(req.Token, body.Pattern, body.StatusCode, body.Body, body.Offset, body.Times, body.BodyContains)
}
fr.set(req.Token, body.Pattern, body.StatusCode, body.Body, body.Offset, body.Times, body.AfterHandler, body.BodyContains, body.Headers)
return Response{StatusCode: 200}
}
}
44 changes: 44 additions & 0 deletions libs/testserver/fault_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,47 @@ func TestServerFaultAfterHandlerKeepsTheHandlersEffect(t *testing.T) {

assert.Equal(t, int32(1), calls.Load())
}

func TestServerFaultHeaders(t *testing.T) {
server := testserver.New(t)
server.Handle("PUT", "/upload", func(req testserver.Request) any {
return map[string]string{}
})

body, err := json.Marshal(map[string]any{
"pattern": "PUT /upload",
"status_code": 503,
"body": `{"error_code": "INJECTED", "message": "Fault injected by test."}`,
"offset": 0,
"times": 1,
"headers": map[string]string{"Retry-After": "3"},
})
require.NoError(t, err)
setReq, err := http.NewRequest(http.MethodPost, server.URL+"/__testserver/fault", bytes.NewReader(body))
require.NoError(t, err)
setReq.Header.Set("Authorization", "Bearer dbapi-fault-test")
setResp, err := http.DefaultClient.Do(setReq)
require.NoError(t, err)
require.Equal(t, 200, setResp.StatusCode)
setResp.Body.Close()

put := func() (int, http.Header) {
req, err := http.NewRequest(http.MethodPut, server.URL+"/upload", bytes.NewReader([]byte("{}")))
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer dbapi-fault-test")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
return resp.StatusCode, resp.Header
}

status, header := put()
assert.Equal(t, 503, status)
assert.Equal(t, "3", header.Get("Retry-After"))
assert.Equal(t, "application/json", header.Get("Content-Type"))

// The header belongs to the fault response only.
status, header = put()
assert.Equal(t, 200, status)
assert.Empty(t, header.Get("Retry-After"))
}
3 changes: 3 additions & 0 deletions libs/testserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, handler HandlerFu
Body: []byte(fault.Body),
Headers: getJsonHeaders(),
}
for k, v := range fault.headers {
resp.Headers.Set(k, v)
}
}

maps.Copy(w.Header(), resp.Headers)
Expand Down
Loading