diff --git a/internal/backend/fs.go b/internal/backend/fs.go index 688927dae4..64f1106820 100644 --- a/internal/backend/fs.go +++ b/internal/backend/fs.go @@ -159,6 +159,9 @@ func (s *storageFS) GetBucket(name string) (Bucket, error) { func getBucketAttributes(path string) (BucketAttrs, error) { content, err := os.ReadFile(path + bucketMetadataSuffix) if err != nil { + if os.IsNotExist(err) { + return BucketAttrs{}, nil + } return BucketAttrs{}, err } var attrs BucketAttrs diff --git a/internal/backend/fs_test.go b/internal/backend/fs_test.go new file mode 100644 index 0000000000..d946de62ec --- /dev/null +++ b/internal/backend/fs_test.go @@ -0,0 +1,76 @@ +// Copyright 2023 Francisco Souza. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package backend + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestGetAttributes(t *testing.T) { + t.Parallel() + + tempDir := t.TempDir() + testBucket := filepath.Join(tempDir, "some-bucket") + bucketAttrs := BucketAttrs{ + DefaultEventBasedHold: false, + VersioningEnabled: true, + } + data, _ := json.Marshal(bucketAttrs) + err := os.WriteFile(testBucket+bucketMetadataSuffix, data, 0o644) + if err != nil { + t.Fatal(err) + } + notABucket := filepath.Join(tempDir, "not-a-bucket") + err = os.WriteFile(notABucket+bucketMetadataSuffix, []byte("this is not valid json"), 0o644) + if err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + inputPath string + expectedAttrs BucketAttrs + expectErr bool + }{ + { + name: "file not found", + inputPath: filepath.Join(tempDir, "unknown-bucket"), + }, + { + name: "existing bucket", + inputPath: testBucket, + expectedAttrs: bucketAttrs, + }, + { + name: "invalid file", + inputPath: notABucket, + expectErr: true, + }, + } + + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + t.Parallel() + attrs, err := getBucketAttributes(test.inputPath) + if test.expectErr && err == nil { + t.Fatal("expected error, but got ") + } + + if !test.expectErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if diff := cmp.Diff(attrs, test.expectedAttrs); diff != "" { + t.Errorf("incorrect attributes returned\nwant: %#v\ngot: %#v\ndiff: %s", test.expectedAttrs, attrs, diff) + } + }) + } +}