Skip to content

Commit e5abc35

Browse files
authored
acc: add -logrequests option (#2627)
## Changes - New option to acceptance test runner: -logrequests. When specified request + responses from testserver are logged. ## Why - Debugging the test server & CLI interaction. ## Tests Manually: `go test .. -run ^TestAccept$/^selftest$ -v -logrequests` ``` acceptance_test.go:409: 200 GET /api/2.0/preview/scim/v2/Me > User-Agent: curl/8.7.1 > Accept: */* # X-Databricks-Org-Id: 900800700600 # { # "id": "1000012345", # "userName": "tester@databricks.com" # } ```
1 parent ea51d02 commit e5abc35

File tree

2 files changed

+59
-18
lines changed

2 files changed

+59
-18
lines changed

acceptance/acceptance_test.go

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ var (
4141
VerboseTest bool = os.Getenv("VERBOSE_TEST") != ""
4242
Tail bool
4343
Forcerun bool
44+
LogRequests bool
4445
)
4546

4647
// In order to debug CLI running under acceptance test, search for TestInprocessMode and update
@@ -58,6 +59,7 @@ func init() {
5859
flag.BoolVar(&NoRepl, "norepl", false, "Do not apply any replacements (for debugging)")
5960
flag.BoolVar(&Tail, "tail", false, "Log output of script in real time. Use with -v to see the logs: -tail -v")
6061
flag.BoolVar(&Forcerun, "forcerun", false, "Force running the specified tests, ignore all reasons to skip")
62+
flag.BoolVar(&LogRequests, "logrequests", false, "Log request and responses from testserver")
6163
}
6264

6365
const (
@@ -389,10 +391,10 @@ func runTest(t *testing.T, dir, coverDir string, repls testdiff.ReplacementsCont
389391
server = testserver.New(t)
390392
if isTruePtr(config.RecordRequests) {
391393
requestsPath := filepath.Join(tmpDir, "out.requests.txt")
392-
server.RecordRequestsCallback = func(request *testserver.Request) {
394+
server.RequestCallback = func(request *testserver.Request) {
393395
req := getLoggedRequest(request, config.IncludeRequestHeaders)
394396
reqJson, err := json.MarshalIndent(req, "", " ")
395-
assert.NoErrorf(t, err, "Failed to indent: %#v", req)
397+
assert.NoErrorf(t, err, "Failed to json-encode: %#v", req)
396398

397399
f, err := os.OpenFile(requestsPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
398400
assert.NoError(t, err)
@@ -403,6 +405,16 @@ func runTest(t *testing.T, dir, coverDir string, repls testdiff.ReplacementsCont
403405
}
404406
}
405407

408+
if LogRequests {
409+
server.ResponseCallback = func(request *testserver.Request, response *testserver.EncodedResponse) {
410+
t.Logf("%d %s %s\n%s\n%s",
411+
response.StatusCode, request.Method, request.URL,
412+
formatHeadersAndBody("> ", request.Headers, request.Body),
413+
formatHeadersAndBody("# ", response.Headers, response.Body),
414+
)
415+
}
416+
}
417+
406418
// We want later stubs takes precedence, because then leaf configs take precedence over parent directory configs
407419
// In gorilla/mux earlier handlers take precedence, so we need to reverse the order
408420
slices.Reverse(config.Server)
@@ -943,3 +955,25 @@ func buildDatabricksBundlesWheel(t *testing.T, buildDir string) (string, error)
943955
return "", fmt.Errorf("databricks-bundles wheel not found in %s", buildDir)
944956
}
945957
}
958+
959+
func formatHeadersAndBody(prefix string, headers http.Header, body []byte) string {
960+
var result []string
961+
for key, values := range headers {
962+
if len(values) == 1 {
963+
result = append(result, fmt.Sprintf("%s%s: %s", prefix, key, values[0]))
964+
} else {
965+
result = append(result, fmt.Sprintf("%s%s: %s", prefix, key, values))
966+
}
967+
}
968+
if len(body) > 0 {
969+
var s string
970+
if utf8.Valid(body) {
971+
s = string(body)
972+
} else {
973+
s = fmt.Sprintf("[Binary %d bytes]", len(body))
974+
}
975+
s = strings.ReplaceAll(s, "\n", "\n"+prefix)
976+
result = append(result, prefix+s)
977+
}
978+
return strings.Join(result, "\n")
979+
}

libs/testserver/server.go

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ type Server struct {
2626
fakeWorkspaces map[string]*FakeWorkspace
2727
mu *sync.Mutex
2828

29-
RecordRequestsCallback func(request *Request)
29+
RequestCallback func(request *Request)
30+
ResponseCallback func(request *Request, response *EncodedResponse)
3031
}
3132

3233
type Request struct {
@@ -44,7 +45,7 @@ type Response struct {
4445
Body any
4546
}
4647

47-
type encodedResponse struct {
48+
type EncodedResponse struct {
4849
StatusCode int
4950
Headers http.Header
5051
Body []byte
@@ -66,31 +67,31 @@ func NewRequest(t testutil.TestingT, r *http.Request, fakeWorkspace *FakeWorkspa
6667
}
6768
}
6869

69-
func normalizeResponse(t testutil.TestingT, resp any) encodedResponse {
70+
func normalizeResponse(t testutil.TestingT, resp any) EncodedResponse {
7071
result := normalizeResponseBody(t, resp)
7172
if result.StatusCode == 0 {
7273
result.StatusCode = 200
7374
}
7475
return result
7576
}
7677

77-
func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
78+
func normalizeResponseBody(t testutil.TestingT, resp any) EncodedResponse {
7879
if isNil(resp) {
7980
t.Errorf("Handler must not return nil")
80-
return encodedResponse{StatusCode: 500}
81+
return EncodedResponse{StatusCode: 500}
8182
}
8283

8384
respBytes, ok := resp.([]byte)
8485
if ok {
85-
return encodedResponse{
86+
return EncodedResponse{
8687
Body: respBytes,
8788
Headers: getHeaders(respBytes),
8889
}
8990
}
9091

9192
respString, ok := resp.(string)
9293
if ok {
93-
return encodedResponse{
94+
return EncodedResponse{
9495
Body: []byte(respString),
9596
Headers: getHeaders([]byte(respString)),
9697
}
@@ -99,7 +100,7 @@ func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
99100
respStruct, ok := resp.(Response)
100101
if ok {
101102
if isNil(respStruct.Body) {
102-
return encodedResponse{
103+
return EncodedResponse{
103104
StatusCode: respStruct.StatusCode,
104105
Headers: respStruct.Headers,
105106
Body: []byte{},
@@ -108,7 +109,7 @@ func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
108109

109110
bytesVal, isBytes := respStruct.Body.([]byte)
110111
if isBytes {
111-
return encodedResponse{
112+
return EncodedResponse{
112113
StatusCode: respStruct.StatusCode,
113114
Headers: respStruct.Headers,
114115
Body: bytesVal,
@@ -117,7 +118,7 @@ func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
117118

118119
stringVal, isString := respStruct.Body.(string)
119120
if isString {
120-
return encodedResponse{
121+
return EncodedResponse{
121122
StatusCode: respStruct.StatusCode,
122123
Headers: respStruct.Headers,
123124
Body: []byte(stringVal),
@@ -127,7 +128,7 @@ func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
127128
respBytes, err := json.MarshalIndent(respStruct.Body, "", " ")
128129
if err != nil {
129130
t.Errorf("JSON encoding error: %s", err)
130-
return encodedResponse{
131+
return EncodedResponse{
131132
StatusCode: 500,
132133
Body: []byte("internal error"),
133134
}
@@ -138,7 +139,7 @@ func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
138139
headers = getJsonHeaders()
139140
}
140141

141-
return encodedResponse{
142+
return EncodedResponse{
142143
StatusCode: respStruct.StatusCode,
143144
Headers: headers,
144145
Body: respBytes,
@@ -148,13 +149,13 @@ func normalizeResponseBody(t testutil.TestingT, resp any) encodedResponse {
148149
respBytes, err := json.MarshalIndent(resp, "", " ")
149150
if err != nil {
150151
t.Errorf("JSON encoding error: %s", err)
151-
return encodedResponse{
152+
return EncodedResponse{
152153
StatusCode: 500,
153154
Body: []byte("internal error"),
154155
}
155156
}
156157

157-
return encodedResponse{
158+
return EncodedResponse{
158159
Body: respBytes,
159160
Headers: getJsonHeaders(),
160161
}
@@ -253,9 +254,11 @@ func (s *Server) Handle(method, path string, handler HandlerFunc) {
253254
}
254255

255256
request := NewRequest(s.t, r, fakeWorkspace)
256-
if s.RecordRequestsCallback != nil {
257-
s.RecordRequestsCallback(&request)
257+
258+
if s.RequestCallback != nil {
259+
s.RequestCallback(&request)
258260
}
261+
259262
respAny := handler(request)
260263
resp := normalizeResponse(s.t, respAny)
261264

@@ -265,6 +268,10 @@ func (s *Server) Handle(method, path string, handler HandlerFunc) {
265268

266269
w.WriteHeader(resp.StatusCode)
267270

271+
if s.ResponseCallback != nil {
272+
s.ResponseCallback(&request, &resp)
273+
}
274+
268275
if _, err := w.Write(resp.Body); err != nil {
269276
s.t.Errorf("Failed to write response: %s", err)
270277
return

0 commit comments

Comments
 (0)