github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/internal/metadata/metadata_test.go (about) 1 package metadata 2 3 import ( 4 "context" 5 "reflect" 6 "testing" 7 ) 8 9 func TestMetadataSet(t *testing.T) { 10 ctx := Set(context.TODO(), "Key", "val") 11 12 val, ok := Get(ctx, "Key") 13 if !ok { 14 t.Fatal("key Key not found") 15 } 16 if val != "val" { 17 t.Errorf("key Key with value val != %v", val) 18 } 19 } 20 21 func TestMetadataDelete(t *testing.T) { 22 md := Metadata{ 23 "Foo": "bar", 24 "Baz": "empty", 25 } 26 27 ctx := NewContext(context.TODO(), md) 28 ctx = Delete(ctx, "Baz") 29 30 emd, ok := FromContext(ctx) 31 if !ok { 32 t.Fatal("key Key not found") 33 } 34 35 _, ok = emd["Baz"] 36 if ok { 37 t.Fatal("key Baz not deleted") 38 } 39 40 } 41 42 func TestMetadataCopy(t *testing.T) { 43 md := Metadata{ 44 "Foo": "bar", 45 "bar": "baz", 46 } 47 48 cp := Copy(md) 49 50 for k, v := range md { 51 if cv := cp[k]; cv != v { 52 t.Fatalf("Got %s:%s for %s:%s", k, cv, k, v) 53 } 54 } 55 } 56 57 func TestMetadataContext(t *testing.T) { 58 md := Metadata{ 59 "Foo": "bar", 60 } 61 62 ctx := NewContext(context.TODO(), md) 63 64 emd, ok := FromContext(ctx) 65 if !ok { 66 t.Errorf("Unexpected error retrieving metadata, got %t", ok) 67 } 68 69 if emd["Foo"] != md["Foo"] { 70 t.Errorf("Expected key: %s val: %s, got key: %s val: %s", "Foo", md["Foo"], "Foo", emd["Foo"]) 71 } 72 73 if i := len(emd); i != 1 { 74 t.Errorf("Expected metadata length 1 got %d", i) 75 } 76 } 77 78 func TestMergeContext(t *testing.T) { 79 type args struct { 80 existing Metadata 81 append Metadata 82 overwrite bool 83 } 84 tests := []struct { 85 name string 86 args args 87 want Metadata 88 }{ 89 { 90 name: "matching key, overwrite false", 91 args: args{ 92 existing: Metadata{"Foo": "bar", "Sumo": "demo"}, 93 append: Metadata{"Sumo": "demo2"}, 94 overwrite: false, 95 }, 96 want: Metadata{"Foo": "bar", "Sumo": "demo"}, 97 }, 98 { 99 name: "matching key, overwrite true", 100 args: args{ 101 existing: Metadata{"Foo": "bar", "Sumo": "demo"}, 102 append: Metadata{"Sumo": "demo2"}, 103 overwrite: true, 104 }, 105 want: Metadata{"Foo": "bar", "Sumo": "demo2"}, 106 }, 107 } 108 for _, tt := range tests { 109 t.Run(tt.name, func(t *testing.T) { 110 if got, _ := FromContext(MergeContext(NewContext(context.TODO(), tt.args.existing), tt.args.append, tt.args.overwrite)); !reflect.DeepEqual(got, tt.want) { 111 t.Errorf("MergeContext() = %v, want %v", got, tt.want) 112 } 113 }) 114 } 115 }