You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.2 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package matcher
import (
"encoding/json"
"testing"
"github.com/noahlann/nnet/internal/codec"
"github.com/noahlann/nnet/internal/request"
"github.com/noahlann/nnet/internal/response"
ctxpkg "github.com/noahlann/nnet/pkg/context"
routerpkg "github.com/noahlann/nnet/pkg/router"
"github.com/stretchr/testify/assert"
)
func TestFrameDataMatcher(t *testing.T) {
// 创建测试Context
conn := &mockConnection{id: "test-conn"}
// 创建包含JSON数据的请求使用float64以匹配JSON解析后的类型
data := map[string]interface{}{
"user": map[string]interface{}{
"id": float64(1), // JSON解析后数字是float64类型
"name": "test",
},
}
jsonData, _ := json.Marshal(data)
req := request.New(jsonData, nil)
// 使用AsRequestSetter设置Data模拟已解析的JSON数据
if setter := request.AsRequestSetter(req); setter != nil {
setter.SetData(data)
}
codecRegistry := codec.NewRegistry()
resp := response.New(conn, nil, codecRegistry, "json")
ctx := ctxpkg.New(nil, conn, req, resp)
// 创建帧数据匹配器
matcher := NewFrameDataMatcher("user.id", "==", float64(1))
// 测试匹配
input := routerpkg.MatchInput{
Raw: jsonData,
DataBytes: jsonData,
Data: data,
}
assert.True(t, matcher.Match(input, ctx), "Expected match for user.id == 1")
}
func TestFrameDataMatcherNotMatch(t *testing.T) {
conn := &mockConnection{id: "test-conn"}
data := map[string]interface{}{
"user": map[string]interface{}{
"id": float64(2), // JSON解析后数字是float64类型
"name": "test",
},
}
jsonData, _ := json.Marshal(data)
req := request.New(jsonData, nil)
if setter := request.AsRequestSetter(req); setter != nil {
setter.SetData(data)
}
codecRegistry := codec.NewRegistry()
resp := response.New(conn, nil, codecRegistry, "json")
ctx := ctxpkg.New(nil, conn, req, resp)
matcher := NewFrameDataMatcher("user.id", "==", float64(1))
input := routerpkg.MatchInput{
Raw: jsonData,
DataBytes: jsonData,
Data: data,
}
assert.False(t, matcher.Match(input, ctx), "Expected no match")
}
func TestFrameDataMatcherPriority(t *testing.T) {
matcher := NewFrameDataMatcher("path", "==", "value")
assert.Equal(t, 150, matcher.Priority(), "Expected priority to be 150")
}