Skip to content

Commit

Permalink
Add unit test for storeFailedAdvisory
Browse files Browse the repository at this point in the history
  • Loading branch information
s-l-teichmann committed Sep 28, 2023
1 parent f5bd94e commit ecdb2cd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 9 deletions.
12 changes: 3 additions & 9 deletions cmd/csaf_downloader/forwarder.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,16 +187,10 @@ func (f *forwarder) buildRequest(
// storeFailedAdvisory stores an advisory in a special folder
// in case the forwarding failed.
func (f *forwarder) storeFailedAdvisory(filename, doc, sha256, sha512 string) error {
dir := filepath.Join(f.cfg.Directory, failedForwardDir)
// Create special folder if it does not exist.
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
} else {
return err
}
dir := filepath.Join(f.cfg.Directory, failedForwardDir)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
// Store parts which are not empty.
for _, x := range []struct {
Expand Down
44 changes: 44 additions & 0 deletions cmd/csaf_downloader/forwarder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"testing"

Expand Down Expand Up @@ -237,3 +238,46 @@ func TestLimitedString(t *testing.T) {
t.Fatal("expected to fail with an error")
}
}

func TestStoreFailedAdvisory(t *testing.T) {
dir, err := os.MkdirTemp("", "storeFailed")
if err != nil {
t.Fatal(err)
}
defer func() {
os.Chmod(dir, 0700)
os.RemoveAll(dir)
}()

cfg := &config{Directory: dir}
fw := newForwarder(cfg)

badDir := filepath.Join(dir, failedForwardDir)
if err := os.WriteFile(badDir, []byte("test"), 0664); err != nil {
t.Fatal(err)
}

if err := fw.storeFailedAdvisory("advisory.json", "{}", "256", "512"); err == nil {
t.Fatal("if the destination exists as a file an error should occur")
}

if err := os.Remove(badDir); err != nil {
t.Fatal(err)
}

if err := fw.storeFailedAdvisory("advisory.json", "{}", "256", "512"); err != nil {
t.Fatal(err)
}

sha256Path := filepath.Join(dir, failedForwardDir, "advisory.json.sha256")

// Write protect advisory.
if err := os.Chmod(sha256Path, 0); err != nil {
t.Fatal(err)
}

if err := fw.storeFailedAdvisory("advisory.json", "{}", "256", "512"); err == nil {
t.Fatal("expected to fail with an error")
}

}

0 comments on commit ecdb2cd

Please sign in to comment.