internal/filter/expr/eval_test.go

package expr

import "testing"

type kvEnv map[string]string

func (e kvEnv) Lookup(name string) (Value, bool) {
	v, ok := e[name]
	return S(v), ok
}

func TestEvalComparisons(t *testing.T) {
	env := kvEnv{
		"method": "GET",
		"host":   "example.com",
		"status": "404",
	}
	cases := map[string]bool{
		"method=GET":            true,
		"method=POST":           false,
		"method!=POST":          true,
		"host=example.com":      true,
		`host~"\.com$"`:         true,
		"status<500":            true,
		"status>=400 and status<500": true,
		"method=GET or method=POST":  true,
		"not method=POST":       true,
		`(method=GET and status>=400) or method=POST`: true,
	}
	for src, want := range cases {
		t.Run(src, func(t *testing.T) {
			n, err := Parse(src)
			if err != nil {
				t.Fatalf("parse: %v", err)
			}
			if got := Eval(n, env); got != want {
				t.Errorf("Eval(%q) = %v, want %v", src, got, want)
			}
		})
	}
}

func TestRegexCacheReuses(t *testing.T) {
	n, _ := Parse(`host~"\.com$"`)
	env := kvEnv{"host": "a.com"}
	for i := 0; i < 4; i++ {
		if !Eval(n, env) {
			t.Fatal("expected match")
		}
	}
}

func TestPrintableASCII(t *testing.T) {
	if !IsPrintableASCII("hello") {
		t.Fatal("hello should be printable ASCII")
	}
	if IsPrintableASCII("héllo") {
		t.Fatal("é should not be ASCII")
	}
}