github.com/creachadair/ffs@v0.17.3/file/root/root_test.go (about) 1 // Copyright 2021 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 root_test 16 17 import ( 18 "io/fs" 19 "testing" 20 21 "github.com/creachadair/ffs/blob" 22 "github.com/creachadair/ffs/blob/memstore" 23 "github.com/creachadair/ffs/file" 24 "github.com/creachadair/ffs/file/root" 25 "github.com/google/go-cmp/cmp" 26 "github.com/google/go-cmp/cmp/cmpopts" 27 ) 28 29 func TestRoot(t *testing.T) { 30 kv := memstore.NewKV() 31 cas := blob.CASFromKV(kv) 32 ctx := t.Context() 33 34 r := root.New(kv, &root.Options{ 35 Description: "Test root", 36 IndexKey: "hey you get off of my cloud", 37 ChainKey: "->>", 38 }) 39 40 // Create a new empty file to use as the root file. 41 rfKey, err := file.New(cas, &file.NewOptions{ 42 Stat: &file.Stat{Mode: fs.ModeDir | 0755}, 43 PersistStat: true, 44 }).Flush(ctx) 45 if err != nil { 46 t.Fatalf("Flushing root file: %v", err) 47 } 48 49 // Saving the root blob to storage should fail if there is no file key set. 50 if err := r.Save(ctx, "test-root"); err == nil { 51 t.Error("Save should not have succeeded with an empty FileKey") 52 } 53 54 // Saving the root should succeed once the file key is present. 55 r.FileKey = rfKey 56 if err := r.Save(ctx, "test-root"); err != nil { 57 t.Fatalf("Save failed: %v", err) 58 } 59 60 // Load a copy of the root back in and make sure it looks sensible. 61 rc, err := root.Open(ctx, kv, "test-root") 62 if err != nil { 63 t.Fatalf("Open failed: %v", err) 64 } 65 66 // Check the reloaded contents match. 67 if diff := cmp.Diff(rc, r, cmpopts.IgnoreUnexported(root.Root{})); diff != "" { 68 t.Errorf("Loaded root (-got, +want):\n%s", diff) 69 } 70 71 // Verify that we can save and reload a chained root. 72 ckey, err := r.SaveChain(ctx, cas) 73 if err != nil { 74 t.Fatalf("SaveChain failed: %v", err) 75 } 76 rc.ChainKey = ckey 77 78 // Verify that we got the expected root back from this. 79 rcc, err := rc.Chain(ctx, cas) 80 if err != nil { 81 t.Fatalf("Load chain failed: %v", err) 82 } 83 if diff := cmp.Diff(rcc, r, cmpopts.IgnoreUnexported(root.Root{})); diff != "" { 84 t.Errorf("Loaded chained root (-got, +want):\n%s", diff) 85 } 86 }