internal/bench/export_bench_test.go

package bench

import (
	"bytes"
	"io"
	"testing"
	"time"

	"mercemay.top/httptap/internal/export/curl"
	"mercemay.top/httptap/internal/export/har"
	"mercemay.top/httptap/internal/export/markdown"
	"mercemay.top/httptap/internal/parser"
)

func benchMsgPair() (parser.Message, parser.Message) {
	req := parser.Message{
		StartLine: "POST /api HTTP/1.1",
		Protocol:  "HTTP/1.1",
		Headers:   [][2]string{{"Host", "api.example.com"}, {"Content-Type", "application/json"}},
		Body:      bytes.Repeat([]byte(`{"k":"v"},`), 16),
	}
	resp := parser.Message{
		StartLine: "HTTP/1.1 201 Created",
		Protocol:  "HTTP/1.1",
		Headers:   [][2]string{{"Content-Type", "application/json"}, {"Content-Length", "2"}},
		Body:      []byte("{}"),
	}
	return req, resp
}

func BenchmarkHARWrite(b *testing.B) {
	req, resp := benchMsgPair()
	at := time.Now()
	entries := []har.Entry{har.FromPair(req, resp, at, 7*time.Millisecond)}
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if err := har.Write(io.Discard, entries); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkCurlRender(b *testing.B) {
	req, _ := benchMsgPair()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		_ = curl.Render(req, curl.Default())
	}
}

func BenchmarkMarkdownWrite(b *testing.B) {
	req, resp := benchMsgPair()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		_ = markdown.Write(io.Discard, req, resp,
			time.Unix(0, 0), 5*time.Millisecond, markdown.Default())
	}
}