github.com/cloudwego/localsession@v0.0.2/backup/metainfo_test.go (about) 1 /* 2 * Copyright 2023 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package backup 18 19 import ( 20 "context" 21 "os" 22 "testing" 23 24 "github.com/bytedance/gopkg/cloud/metainfo" 25 ) 26 27 func TestMain(m *testing.M) { 28 opts := DefaultOptions() 29 opts.EnableImplicitlyTransmitAsync = true 30 opts.Enable = true 31 Init(opts) 32 os.Exit(m.Run()) 33 } 34 35 type CtxKeyTestType struct{} 36 37 var CtxKeyTest1 CtxKeyTestType 38 39 func TestRecoverCtxOndemands(t *testing.T) { 40 ctx := context.WithValue(context.Background(), CtxKeyTest1, "c") 41 BackupCtx(metainfo.WithPersistentValues(ctx, "a", "a", "b", "b")) 42 43 handler := BackupHandler(func(prev, cur context.Context) (ctx context.Context, backup bool) { 44 if v := cur.Value(CtxKeyTest1); v == nil { 45 v = prev.Value(CtxKeyTest1) 46 if v != nil { 47 ctx = context.WithValue(cur, CtxKeyTest1, v) 48 } else { 49 ctx = cur 50 } 51 return ctx, true 52 } 53 return cur, false 54 }) 55 type args struct { 56 ctx context.Context 57 handler BackupHandler 58 } 59 tests := []struct { 60 name string 61 args args 62 want context.Context 63 }{ 64 { 65 name: "triggered", 66 args: args{ 67 ctx: metainfo.WithValue(metainfo.WithPersistentValue(context.Background(), "a", "aa"), "b", "bb"), 68 handler: handler, 69 }, 70 want: metainfo.WithPersistentValues(ctx, "a", "aa", "b", "b"), 71 }, 72 { 73 name: "not triggered", 74 args: args{ 75 ctx: metainfo.WithValue(metainfo.WithPersistentValue(ctx, "a", "aa"), "b", "bb"), 76 handler: handler, 77 }, 78 want: metainfo.WithValue(metainfo.WithPersistentValue(ctx, "a", "aa"), "b", "bb"), 79 }, 80 } 81 for _, tt := range tests { 82 t.Run(tt.name, func(t *testing.T) { 83 if got := RecoverCtxOnDemands(tt.args.ctx, tt.args.handler); got != nil { 84 if v := got.Value(CtxKeyTest1); v == nil { 85 t.Errorf("not got CtxKeyTest1") 86 } 87 a, _ := metainfo.GetPersistentValue(got, "a") 88 ae, _ := metainfo.GetPersistentValue(tt.want, "a") 89 if a != ae { 90 t.Errorf("CurSession() = %v, want %v", a, ae) 91 } 92 b, _ := metainfo.GetPersistentValue(got, "b") 93 be, _ := metainfo.GetPersistentValue(tt.want, "b") 94 if b != be { 95 t.Errorf("CurSession() = %v, want %v", b, be) 96 } 97 } else { 98 t.Fatal("no got") 99 } 100 }) 101 } 102 }