tlog.app/go/tlog@v0.23.1/convert/rewriter_test.go (about) 1 package convert 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/nikandfor/assert" 8 "github.com/nikandfor/hacked/low" 9 "tlog.app/go/loc" 10 11 "tlog.app/go/tlog" 12 "tlog.app/go/tlog/tlwire" 13 ) 14 15 func TestRewriter(t *testing.T) { 16 var obj, b low.Buf 17 rew := NewRewriter(&b) 18 rew.Rule = RewriterFunc(func(b, p []byte, path []tlog.RawMessage, kst, st int) ([]byte, int, error) { 19 if st == len(p) { 20 t.Logf("path %x nil message", path) 21 return nil, 0, ErrFallback 22 } 23 24 var k []byte 25 if kst != -1 { 26 k, _ = rew.Bytes(p, kst) 27 } 28 29 tag, sub, _ := rew.Tag(p, st) 30 31 t.Logf("path %q k %q st %v tag %x %x", path, k, st, tag, sub) 32 33 return b, st, ErrFallback 34 }) 35 36 t.Logf("empty") 37 38 n, err := rew.Write(obj) 39 assert.NoError(t, err) 40 assert.Equal(t, len(obj), n) 41 assert.Equal(t, obj, b) 42 43 b = b[:0] 44 obj = tlog.AppendKVs(obj[:0], []interface{}{ 45 tlog.RawTag(tlwire.Map, -1), 46 "a", "b", 47 "d", tlog.NextIs(tlwire.Duration), 1, 48 tlog.Break, 49 }) 50 51 t.Logf("case1") 52 53 n, err = rew.Write(obj) 54 assert.NoError(t, err) 55 assert.Equal(t, len(obj), n) 56 if !assert.Equal(t, obj, b) { 57 t.Logf("%s", tlwire.Dump(b)) 58 } 59 } 60 61 func TestKeyRenamer(t *testing.T) { 62 var obj, exp, b low.Buf 63 64 rew := NewRewriter(&b) 65 ren := NewKeyRenamer(nil, 66 RenameRule{ 67 Path: []tlog.RawMessage{ 68 rew.AppendString(nil, tlog.KeyTimestamp), 69 tlog.RawTag(tlwire.Semantic, tlwire.Time), 70 }, 71 Rename: []byte("time"), 72 }, 73 RenameRule{ 74 Path: []tlog.RawMessage{ 75 rew.AppendString(nil, tlog.KeyCaller), 76 tlog.RawTag(tlwire.Semantic, tlwire.Caller), 77 }, 78 Remove: true, 79 }, 80 ) 81 rew.Rule = RewriterFunc(func(b, p []byte, path []tlog.RawMessage, kst, st int) ([]byte, int, error) { 82 r, i, err := ren.Rewrite(b, p, path, kst, st) 83 84 t.Logf("rename %q %x %x -> %x %v\n%s", path, kst, st, i, err, tlwire.Dump(r[len(b):])) 85 86 return r, i, err 87 }) 88 89 t.Logf("empty") 90 91 n, err := rew.Write(obj) 92 assert.NoError(t, err) 93 assert.Equal(t, len(obj), n) 94 assert.Equal(t, exp, b) 95 96 b = b[:0] 97 t.Logf("case 1") 98 99 obj = tlog.AppendKVs(obj[:0], []interface{}{ 100 tlog.RawTag(tlwire.Map, -1), 101 tlog.KeyTimestamp, time.Unix(100000000, 0), 102 tlog.KeyCaller, loc.Caller(0), 103 tlog.Break, 104 }) 105 106 exp = tlog.AppendKVs(exp[:0], []interface{}{ 107 tlog.RawTag(tlwire.Map, -1), 108 "time", time.Unix(100000000, 0), 109 tlog.Break, 110 }) 111 112 n, err = rew.Write(obj) 113 assert.NoError(t, err) 114 assert.Equal(t, len(obj), n) 115 if !assert.Equal(t, exp, b) { 116 t.Logf("obj\n%s", tlwire.Dump(obj)) 117 t.Logf("exp\n%s", tlwire.Dump(exp)) 118 t.Logf("buf\n%s", tlwire.Dump(b)) 119 } 120 }