github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/layer/filestore_test.go (about) 1 package layer 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "math/rand" 7 "os" 8 "path/filepath" 9 "strings" 10 "syscall" 11 "testing" 12 13 "github.com/docker/distribution/digest" 14 ) 15 16 func randomLayerID(seed int64) ChainID { 17 r := rand.New(rand.NewSource(seed)) 18 19 return ChainID(digest.FromBytes([]byte(fmt.Sprintf("%d", r.Int63())))) 20 } 21 22 func newFileMetadataStore(t *testing.T) (*fileMetadataStore, string, func()) { 23 td, err := ioutil.TempDir("", "layers-") 24 if err != nil { 25 t.Fatal(err) 26 } 27 fms, err := NewFSMetadataStore(td) 28 if err != nil { 29 t.Fatal(err) 30 } 31 32 return fms.(*fileMetadataStore), td, func() { 33 if err := os.RemoveAll(td); err != nil { 34 t.Logf("Failed to cleanup %q: %s", td, err) 35 } 36 } 37 } 38 39 func assertNotDirectoryError(t *testing.T, err error) { 40 perr, ok := err.(*os.PathError) 41 if !ok { 42 t.Fatalf("Unexpected error %#v, expected path error", err) 43 } 44 45 if perr.Err != syscall.ENOTDIR { 46 t.Fatalf("Unexpected error %s, expected %s", perr.Err, syscall.ENOTDIR) 47 } 48 } 49 50 func TestCommitFailure(t *testing.T) { 51 fms, td, cleanup := newFileMetadataStore(t) 52 defer cleanup() 53 54 if err := ioutil.WriteFile(filepath.Join(td, "sha256"), []byte("was here first!"), 0644); err != nil { 55 t.Fatal(err) 56 } 57 58 tx, err := fms.StartTransaction() 59 if err != nil { 60 t.Fatal(err) 61 } 62 63 if err := tx.SetSize(0); err != nil { 64 t.Fatal(err) 65 } 66 67 err = tx.Commit(randomLayerID(5)) 68 if err == nil { 69 t.Fatalf("Expected error committing with invalid layer parent directory") 70 } 71 assertNotDirectoryError(t, err) 72 } 73 74 func TestStartTransactionFailure(t *testing.T) { 75 fms, td, cleanup := newFileMetadataStore(t) 76 defer cleanup() 77 78 if err := ioutil.WriteFile(filepath.Join(td, "tmp"), []byte("was here first!"), 0644); err != nil { 79 t.Fatal(err) 80 } 81 82 _, err := fms.StartTransaction() 83 if err == nil { 84 t.Fatalf("Expected error starting transaction with invalid layer parent directory") 85 } 86 assertNotDirectoryError(t, err) 87 88 if err := os.Remove(filepath.Join(td, "tmp")); err != nil { 89 t.Fatal(err) 90 } 91 92 tx, err := fms.StartTransaction() 93 if err != nil { 94 t.Fatal(err) 95 } 96 97 if expected := filepath.Join(td, "tmp"); strings.HasPrefix(expected, tx.String()) { 98 t.Fatalf("Unexpected transaction string %q, expected prefix %q", tx.String(), expected) 99 } 100 101 if err := tx.Cancel(); err != nil { 102 t.Fatal(err) 103 } 104 }