Skip to content

Commit

Permalink
Refine request/response formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
gavv committed Mar 22, 2023
1 parent 31fa192 commit 70906db
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 68 deletions.
66 changes: 35 additions & 31 deletions e2e_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func TestE2EReport_LineWidth(t *testing.T) {
below int
}

tests := []struct {
cases := []struct {
name string
formatter *DefaultFormatter
longestLine widthRange
Expand Down Expand Up @@ -146,15 +146,19 @@ func TestE2EReport_LineWidth(t *testing.T) {
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rep := &recordingReporter{}

fmt := tc.formatter
fmt.DisableRequests = true
fmt.DisableResponses = true

e := WithConfig(Config{
TestName: "TestExample",
BaseURL: server.URL,
AssertionHandler: &DefaultAssertionHandler{
Formatter: tt.formatter,
Formatter: fmt,
Reporter: rep,
},
})
Expand All @@ -181,11 +185,11 @@ func TestE2EReport_LineWidth(t *testing.T) {
}
}

if tt.longestLine.above != 0 {
assert.GreaterOrEqual(t, len(actualLongestLine), tt.longestLine.above)
if tc.longestLine.above != 0 {
assert.GreaterOrEqual(t, len(actualLongestLine), tc.longestLine.above)
}
if tt.longestLine.below != 0 {
assert.LessOrEqual(t, len(actualLongestLine), tt.longestLine.below)
if tc.longestLine.below != 0 {
assert.LessOrEqual(t, len(actualLongestLine), tc.longestLine.below)
}
})
}
Expand Down Expand Up @@ -312,7 +316,7 @@ func TestE2EReport_CustomTemplate(t *testing.T) {
})
}

func TestE2EReport_RequestAndResponse(t *testing.T) {
func TestE2EReport_RequestResponse(t *testing.T) {
mux := http.NewServeMux()

mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -324,49 +328,49 @@ func TestE2EReport_RequestAndResponse(t *testing.T) {
server := httptest.NewServer(mux)
defer server.Close()

tests := []struct {
cases := []struct {
name string
formatter *DefaultFormatter
}{
{
name: "request and response enabled",
formatter: &DefaultFormatter{
EnableRequests: true,
EnableResponses: true,
DisableRequests: false,
DisableResponses: false,
},
},
{
name: "request enabled, response disabled",
formatter: &DefaultFormatter{
EnableRequests: true,
EnableResponses: false,
DisableRequests: false,
DisableResponses: true,
},
},
{
name: "request disabled, response enabled",
formatter: &DefaultFormatter{
EnableRequests: false,
EnableResponses: true,
DisableRequests: true,
DisableResponses: false,
},
},
{
name: "request and response disabled",
formatter: &DefaultFormatter{
EnableRequests: false,
EnableResponses: false,
DisableRequests: true,
DisableResponses: true,
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rep := &recordingReporter{}

e := WithConfig(Config{
TestName: "TestExample",
BaseURL: server.URL,
AssertionHandler: &DefaultAssertionHandler{
Formatter: tt.formatter,
Formatter: tc.formatter,
Reporter: rep,
},
})
Expand All @@ -385,27 +389,27 @@ func TestE2EReport_RequestAndResponse(t *testing.T) {

logs := rep.recorded

if tt.formatter.EnableRequests {
assert.Contains(t,
if tc.formatter.DisableRequests {
assert.NotContains(t,
logs,
"GET /test HTTP/1.1",
"expected log output to contain request information")
"expected log output not to contain request information")
} else {
assert.NotContains(t,
assert.Contains(t,
logs,
"GET /test HTTP/1.1",
"expected log output not to contain request information")
"expected log output to contain request information")
}

if tt.formatter.EnableResponses {
assert.Contains(t,
logs,
"HTTP/1.1 200 OK", "expected log output to contain response information")
} else {
if tc.formatter.DisableResponses {
assert.NotContains(t,
logs,
"HTTP/1.1 200 OK",
"expected log output not to contain response information")
} else {
assert.Contains(t,
logs,
"HTTP/1.1 200 OK", "expected log output to contain response information")
}
})
}
Expand Down
82 changes: 45 additions & 37 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ type DefaultFormatter struct {
// Exclude diff from failure report.
DisableDiffs bool

// Enable printing of request on failure.
EnableRequests bool
// Exclude HTTP request from failure report.
DisableRequests bool

// Enable printing of response on failure.
EnableResponses bool
// Exclude HTTP response from failure report.
DisableResponses bool

// Thousand separator.
// Default is DigitSeparatorUnderscore.
Expand Down Expand Up @@ -196,9 +196,6 @@ type FormatData struct {
ExpectedKind string
Expected []string

Request string
Response string

HaveReference bool
Reference string

Expand All @@ -208,9 +205,14 @@ type FormatData struct {
HaveDiff bool
Diff string

EnableColors bool
HaveRequest bool
Request string

LineWidth int
HaveResponse bool
Response string

EnableColors bool
LineWidth int
}

const (
Expand Down Expand Up @@ -262,9 +264,6 @@ func (f *DefaultFormatter) buildFormatData(
data.AssertType = failure.Type.String()
data.AssertSeverity = failure.Severity.String()

f.fillRequest(&data, ctx, failure)
f.fillResponse(&data, ctx, failure)

f.fillErrors(&data, ctx, failure)

if failure.Actual != nil {
Expand All @@ -284,6 +283,9 @@ func (f *DefaultFormatter) buildFormatData(
if failure.Delta != nil {
f.fillDelta(&data, ctx, failure)
}

f.fillRequest(&data, ctx, failure)
f.fillResponse(&data, ctx, failure)
}

return &data
Expand Down Expand Up @@ -518,27 +520,30 @@ func (f *DefaultFormatter) fillDelta(
func (f *DefaultFormatter) fillRequest(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
if f.EnableRequests && !refIsNil(ctx.Request) {
if !f.DisableRequests && ctx.Request != nil && ctx.Request.httpReq != nil {
dump, err := httputil.DumpRequest(ctx.Request.httpReq, false)
if err != nil {
panic(err)
return
}

data.HaveRequest = true
data.Request = string(dump)
}
}

func (f *DefaultFormatter) fillResponse(
data *FormatData, ctx *AssertionContext, failure *AssertionFailure,
) {
if f.EnableResponses && !refIsNil(ctx.Request) {
if !f.DisableResponses && ctx.Response != nil && ctx.Response.httpResp != nil {
dump, err := httputil.DumpResponse(ctx.Response.httpResp, false)
if err != nil {
panic(err)
return
}

text := strings.Replace(string(dump), "\r\n", "\n", -1)
lines := strings.SplitN(text, "\n", 2)

data.HaveResponse = true
data.Response = fmt.Sprintf("%s %s\n%s", lines[0], ctx.Response.rtt, lines[1])
}
}
Expand Down Expand Up @@ -842,10 +847,13 @@ var defaultColors = map[string]color.Attribute{
}

var defaultTemplateFuncs = template.FuncMap{
"indent": func(s string) string {
"trim": func(input string) string {
return strings.TrimSpace(input)
},
"indent": func(input string) string {
var sb strings.Builder

for _, s := range strings.Split(s, "\n") {
for _, s := range strings.Split(input, "\n") {
if sb.Len() != 0 {
sb.WriteString("\n")
}
Expand All @@ -855,17 +863,17 @@ var defaultTemplateFuncs = template.FuncMap{

return sb.String()
},
"wrap": func(s string, width int) string {
s = strings.TrimSpace(s)
"wrap": func(width int, input string) string {
input = strings.TrimSpace(input)

width -= len(defaultIndent)
if width <= 0 {
return s
return input
}

return wordwrap.WrapString(s, uint(width))
return wordwrap.WrapString(input, uint(width))
},
"join": func(tokenList []string, width int) string {
"join": func(width int, tokenList []string) string {
width -= len(defaultIndent)
if width <= 0 {
return strings.Join(tokenList, ".")
Expand Down Expand Up @@ -902,19 +910,19 @@ var defaultTemplateFuncs = template.FuncMap{

return sb.String()
},
"color": func(enable bool, colorName, s string) string {
"color": func(enable bool, colorName, input string) string {
if !enable {
return s
return input
}
colorAttr := color.Reset
if ca, ok := defaultColors[colorName]; ok {
colorAttr = ca
}
return color.New(colorAttr).Sprint(s)
return color.New(colorAttr).Sprint(input)
},
"colordiff": func(enable bool, s string) string {
"colordiff": func(enable bool, input string) string {
if !enable {
return s
return input
}

prefixColor := []struct {
Expand All @@ -938,7 +946,7 @@ var defaultTemplateFuncs = template.FuncMap{
}

var sb strings.Builder
for _, line := range strings.Split(s, "\n") {
for _, line := range strings.Split(input, "\n") {
if sb.Len() != 0 {
sb.WriteString("\n")
}
Expand All @@ -950,14 +958,14 @@ var defaultTemplateFuncs = template.FuncMap{
},
}

var defaultSuccessTemplate = `[OK] {{ join .AssertPath .LineWidth }}`
var defaultSuccessTemplate = `[OK] {{ join .LineWidth .AssertPath }}`

var defaultFailureTemplate = `
{{- range $n, $err := .Errors }}
{{ if eq $n 0 -}}
{{ wrap $err $.LineWidth | color $.EnableColors "Red" }}
{{ $err | wrap $.LineWidth | color $.EnableColors "Red" }}
{{- else -}}
{{ wrap $err $.LineWidth | indent | color $.EnableColors "Red" }}
{{ $err | wrap $.LineWidth | indent | color $.EnableColors "Red" }}
{{- end -}}
{{- end -}}
{{- if .TestName }}
Expand All @@ -968,18 +976,18 @@ test name: {{ .TestName | color $.EnableColors "Cyan" }}
request name: {{ .RequestName | color $.EnableColors "Cyan" }}
{{- end -}}
{{- if .Request }}
{{- if .HaveRequest }}
request: {{ .Request | indent | color $.EnableColors "HiMagenta" }}
request: {{ .Request | indent | trim | color $.EnableColors "HiMagenta" }}
{{- end -}}
{{- if .Response }}
{{- if .HaveResponse }}
response: {{ .Response | indent | color $.EnableColors "HiMagenta" }}
response: {{ .Response | indent | trim | color $.EnableColors "HiMagenta" }}
{{- end -}}
{{- if .AssertPath }}
assertion:
{{ join .AssertPath .LineWidth | indent | color .EnableColors "Yellow" }}
{{ join .LineWidth .AssertPath | indent | color .EnableColors "Yellow" }}
{{- end -}}
{{- if .HaveExpected }}
Expand Down

0 comments on commit 70906db

Please sign in to comment.