internal/filter/filter_test.go

package filter

import (
	"testing"

	"mercemay.top/httptap/internal/parser"
)

func sample() parser.Message {
	return parser.Message{
		StartLine: "GET /api/v1/orders HTTP/1.1",
		Headers: [][2]string{
			{"Host", "shop.example.com"},
			{"Content-Type", "application/json"},
		},
		Body: make([]byte, 1024),
	}
}

func TestCompileBasic(t *testing.T) {
	cases := map[string]bool{
		"":                                 true,
		"method=GET":                       true,
		"method=POST":                      false,
		"host=shop.example.com":            true,
		`header:content-type = "application/json"`: true,
		"body_size>=1000":                  true,
		"body_size<100":                    false,
		"status=0":                         true, // no response in sample
	}
	for src, want := range cases {
		t.Run(src, func(t *testing.T) {
			p := MustCompile(src)
			if got := p(sample()); got != want {
				t.Errorf("Compile(%q)=%v want %v", src, got, want)
			}
		})
	}
}

func TestCompileBadSyntax(t *testing.T) {
	for _, bad := range []string{
		"method==",
		"& trailing",
		"host=",
	} {
		if _, err := Compile(bad); err == nil {
			t.Errorf("expected error for %q", bad)
		}
	}
}

func TestMsgEnvHeaderLookup(t *testing.T) {
	env := msgEnv{sample()}
	v, ok := env.Lookup("header:host")
	if !ok {
		t.Fatal("header:host missing")
	}
	if v.String() != "shop.example.com" {
		t.Errorf("value = %q", v.String())
	}
}

func TestKnownFieldsStable(t *testing.T) {
	if len(KnownFields) < 5 {
		t.Errorf("known fields too short: %+v", KnownFields)
	}
}