internal/parser/http2/hpack_test.go

package http2

import (
	"bytes"
	"testing"

	"golang.org/x/net/http2/hpack"

	"github.com/google/go-cmp/cmp"
)

func encode(fields [][2]string) []byte {
	var buf bytes.Buffer
	enc := hpack.NewEncoder(&buf)
	for _, f := range fields {
		_ = enc.WriteField(hpack.HeaderField{Name: f[0], Value: f[1]})
	}
	return buf.Bytes()
}

func TestDecodeBlock(t *testing.T) {
	in := [][2]string{
		{":method", "GET"},
		{":path", "/"},
		{":authority", "example.com"},
		{":scheme", "https"},
		{"user-agent", "httptap/test"},
	}
	d := NewHPACK()
	got, err := d.DecodeBlock(encode(in))
	if err != nil {
		t.Fatal(err)
	}
	if diff := cmp.Diff(in, got); diff != "" {
		t.Fatalf("mismatch:\n%s", diff)
	}
}

func TestSplitPseudo(t *testing.T) {
	in := [][2]string{
		{":method", "POST"},
		{":path", "/x"},
		{"content-type", "application/json"},
	}
	p, r := SplitPseudo(in)
	if len(p) != 2 || len(r) != 1 {
		t.Fatalf("split got %d pseudo / %d regular", len(p), len(r))
	}
}

func TestAssembleStartLine(t *testing.T) {
	req := [][2]string{
		{":method", "GET"},
		{":path", "/api"},
		{":authority", "h.example"},
	}
	if got := AssembleStartLine(req); got != "GET h.example/api HTTP/2" {
		t.Fatalf("request start line = %q", got)
	}
	resp := [][2]string{{":status", "200"}}
	if got := AssembleStartLine(resp); got != "HTTP/2 200" {
		t.Fatalf("response start line = %q", got)
	}
	if got := AssembleStartLine([][2]string{{":method", "GET"}}); got != "" {
		t.Fatalf("expected empty, got %q", got)
	}
}