github.com/creachadair/ffs@v0.17.3/storage/encoded/encoded_test.go (about) 1 // Copyright 2019 Michael J. Fromberger. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package encoded_test 16 17 import ( 18 "io" 19 "testing" 20 21 "github.com/creachadair/ffs/blob" 22 "github.com/creachadair/ffs/blob/memstore" 23 "github.com/creachadair/ffs/blob/storetest" 24 "github.com/creachadair/ffs/storage/encoded" 25 ) 26 27 func TestStore(t *testing.T) { 28 base := memstore.New(nil) 29 enc := encoded.New(base, identity{}) 30 storetest.Run(t, storetest.NopCloser(enc)) 31 } 32 33 // identity implements an identity Codec, that encodes blobs as themselves. 34 type identity struct{} 35 36 // Encode encodes src to w with no transformation. 37 func (identity) Encode(w io.Writer, src []byte) error { _, err := w.Write(src); return err } 38 39 // Decode decodes src to w with no transformation. 40 func (identity) Decode(w io.Writer, src []byte) error { _, err := w.Write(src); return err } 41 42 func TestRegression(t *testing.T) { 43 ctx := t.Context() 44 45 t.Run("DoubleEncode", func(t *testing.T) { 46 // Verify that a given Put or Get only encodes/decodes once. 47 base := memstore.New(nil) 48 enc := encoded.New(base, tagger("@")) 49 kv := storetest.SubKV(t, ctx, enc, "test") 50 51 const testValue = "bar" 52 if err := kv.Put(ctx, blob.PutOptions{ 53 Key: "foo", 54 Data: []byte(testValue), 55 }); err != nil { 56 t.Fatalf("Put foo: %v", err) 57 } 58 59 real := storetest.SubKV(t, ctx, base, "test") 60 if val, err := real.Get(ctx, "foo"); err != nil { 61 t.Fatalf("Get foo: %v", err) 62 } else if got, want := string(val), testValue+"@"; got != want { 63 t.Errorf("Base foo: got %q, want %q", got, want) 64 } 65 66 if val, err := kv.Get(ctx, "foo"); err != nil { 67 t.Fatalf("Get foo: %v", err) 68 } else if got, want := string(val), testValue; got != want { 69 t.Errorf("Get foo: got %q, want %q", got, want) 70 } 71 }) 72 } 73 74 type tagger string 75 76 func (t tagger) Encode(w io.Writer, src []byte) error { 77 _, err := w.Write(append(src, t...)) 78 return err 79 } 80 81 func (t tagger) Decode(w io.Writer, src []byte) error { 82 _, err := w.Write(src[:len(src)-1]) 83 return err 84 }