github.com/yaling888/clash@v1.53.0/component/script/expr_matcher_test.go (about)

     1  package script
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  
    10  	C "github.com/yaling888/clash/constant"
    11  )
    12  
    13  func TestStringInString(t *testing.T) {
    14  	code := `("example" in host) and ("com" in host)`
    15  	m, err := NewExprMatcher("test", code)
    16  	assert.NoError(t, err)
    17  
    18  	mtd := &C.Metadata{
    19  		Host: "example.com",
    20  	}
    21  
    22  	v, err := m.Match(mtd)
    23  	assert.NoError(t, err)
    24  	assert.True(t, v)
    25  
    26  	mtd.Host = "test1.com"
    27  	v, err = m.Match(mtd)
    28  	assert.NoError(t, err)
    29  	assert.False(t, v)
    30  
    31  	code2 := `"test-" in "a-test-b"`
    32  	m2, err := NewExprMatcher("test2", code2)
    33  	assert.NoError(t, err)
    34  
    35  	v, err = m2.Match(mtd)
    36  	assert.NoError(t, err)
    37  	assert.True(t, v)
    38  
    39  	code3 := `22 in [33, 44]`
    40  	m3, err := NewExprMatcher("test3", code3)
    41  	assert.NoError(t, err)
    42  
    43  	v, err = m3.Match(mtd)
    44  	assert.NoError(t, err)
    45  	assert.False(t, v)
    46  }
    47  
    48  func TestNow(t *testing.T) {
    49  	hour := time.Now().Hour()
    50  	weekday := time.Now().Weekday()
    51  	code := fmt.Sprintf(`now.hour == %d && now.weekday == %d`, hour, weekday)
    52  	m, err := NewExprMatcher("test", code)
    53  	assert.NoError(t, err)
    54  
    55  	v, err := m.Match(&C.Metadata{})
    56  	assert.NoError(t, err)
    57  	assert.True(t, v)
    58  }
    59  
    60  func TestPipes(t *testing.T) {
    61  	code := `(host | lower()) == "test pipes"`
    62  	m, err := NewExprMatcher("test", code)
    63  	assert.NoError(t, err)
    64  
    65  	v, err := m.Match(&C.Metadata{Host: "TEST Pipes"})
    66  	assert.NoError(t, err)
    67  	assert.True(t, v)
    68  
    69  	code2 := `(1..9 | map(# + 1) | filter(# % 2 == 0)) == [2, 4, 6, 8, 10]`
    70  	m2, err := NewExprMatcher("test2", code2)
    71  	assert.NoError(t, err)
    72  
    73  	v, err = m2.Match(&C.Metadata{})
    74  	assert.NoError(t, err)
    75  	assert.True(t, v)
    76  }