Skip to content

Commit

Permalink
internal/driver: return an error on failed source fetching
Browse files Browse the repository at this point in the history
This change inverts checks to ensure that we return
a wrapped fs.ErrNotExist error if we completely fail
to find a source fetcher, instead of panicking.

Fixes google#863
  • Loading branch information
odeke-em committed May 24, 2024
1 parent 9665fa2 commit 114a2f2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
16 changes: 13 additions & 3 deletions internal/driver/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"bytes"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -510,10 +511,19 @@ func fetch(source string, duration, timeout time.Duration, ui plugin.UI, tr http
src = sourceURL
}
}
if err == nil {
defer f.Close()
p, err = profile.Parse(f)

if err != nil {
return
}

if f == nil {
err = fmt.Errorf("could not fetch source: %q: %w", source, fs.ErrNotExist)
return
}

defer f.Close()
p, err = profile.Parse(f)

return
}

Expand Down
15 changes: 15 additions & 0 deletions internal/driver/fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/fs"
"math/big"
"net"
"net/http"
Expand Down Expand Up @@ -824,3 +826,16 @@ func selfSignedCert(t *testing.T, host string) (tls.Certificate, []byte, []byte)
}
return cert, bc, bk
}

func TestFetchDoesNotPanicOnMissingSource(t *testing.T) {
_, _, err := fetch("non-existent-source", 10*time.Millisecond, 10*time.Millisecond, nil, http.DefaultTransport)
if err == nil {
t.Fatal("expected a non-nil error")
}
if g, w := err, fs.ErrNotExist; !errors.Is(g, w) {
t.Fatalf("mismatched type: got %T, want %T", g, w)
}
if g, w := err.Error(), "could not fetch"; !strings.Contains(g, w) {
t.Fatalf("error substring mismatch\n\tGot %q\n\tWant %q", g, w)
}
}

0 comments on commit 114a2f2

Please sign in to comment.