package har
import (
"bytes"
"encoding/json"
"testing"
"time"
"mercemay.top/httptap/internal/parser"
)
func TestWriteHAR(t *testing.T) {
req := parser.Message{
StartLine: "GET /api HTTP/1.1",
Protocol: "HTTP/1.1",
Headers: [][2]string{{"Host", "example.com"}},
}
resp := parser.Message{
StartLine: "HTTP/1.1 200 OK",
Protocol: "HTTP/1.1",
Headers: [][2]string{{"Content-Type", "text/plain"}},
Body: []byte("hi"),
}
now := time.Date(2024, 11, 8, 10, 30, 0, 0, time.UTC)
ent := FromPair(req, resp, now, 12*time.Millisecond)
var buf bytes.Buffer
if err := Write(&buf, []Entry{ent}); err != nil {
t.Fatalf("Write: %v", err)
}
var got struct {
Log Log `json:"log"`
}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if got.Log.Version != "1.2" {
t.Errorf("version = %q", got.Log.Version)
}
if len(got.Log.Entries) != 1 {
t.Fatalf("entries = %d", len(got.Log.Entries))
}
e := got.Log.Entries[0]
if e.Request.Method != "GET" || e.Response.Status != 200 {
t.Errorf("entry = %+v", e)
}
if e.Time != 12 {
t.Errorf("time = %d", e.Time)
}
}
func TestTimingsDefaults(t *testing.T) {
tm := Timings{Blocked: -1, DNS: -1, Connect: -1, SSL: -1, Wait: 5}
b, _ := json.Marshal(tm)
if !bytes.Contains(b, []byte(`"blocked":-1`)) {
t.Fatalf("missing blocked: %s", b)
}
}
func TestToNameValues(t *testing.T) {
got := toNameValues([][2]string{{"X-A", "1"}, {"X-B", "2"}})
if got[0].Name != "X-A" || got[1].Value != "2" {
t.Fatalf("got = %+v", got)
}
}