github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/mdis/mdis_test.go (about) 1 package mdis_test 2 3 import ( 4 "testing" 5 "github.com/v2pro/plz/test" 6 "github.com/v2pro/plz/countlog" 7 "github.com/v2pro/plz/test/must" 8 "github.com/v2pro/plz/mdis" 9 ) 10 11 type myOrder struct { 12 productId int 13 scenario int 14 brand int 15 } 16 17 var myFunc = func(order *myOrder, arg1 string) string { 18 return "orig " + arg1 19 } 20 21 func Test_mdis(t *testing.T) { 22 t.Run("orig", test.Case(func(ctx *countlog.Context) { 23 must.Equal("orig arg1", myFunc(&myOrder{}, "arg1")) 24 })) 25 t.Run("by exact much", test.Case(func(ctx *countlog.Context) { 26 mdis.Register(&myFunc, &myOrder{ 27 productId: 1, 28 scenario: 2, 29 brand: 3, 30 }, func(order *myOrder, arg1 string) string { 31 return "dispatched " + arg1 32 }) 33 must.Equal("orig arg1", myFunc(&myOrder{}, "arg1")) 34 must.Equal("dispatched arg1", myFunc(&myOrder{ 35 productId: 1, 36 scenario: 2, 37 brand: 3, 38 }, "arg1")) 39 })) 40 t.Run("by table", test.Case(func(ctx *countlog.Context) { 41 selector := func(order *myOrder) string { 42 if order.productId == 1 && order.brand > 2 { 43 return "vip product" 44 } 45 return "normal product" 46 } 47 mdis.RegisterTable(&myFunc, selector, 48 "vip product", func(order *myOrder, arg1 string) string { 49 return "vip " + arg1 50 }, 51 "normal product", func(order *myOrder, arg1 string) string { 52 return "normal " + arg1 53 }) 54 must.Equal("vip arg1", myFunc(&myOrder{ 55 productId: 1, 56 scenario: 2, 57 brand: 3, 58 }, "arg1")) 59 must.Equal("normal arg1", myFunc(&myOrder{ 60 productId: 1, 61 scenario: 2, 62 brand: 2, 63 }, "arg1")) 64 })) 65 }