2023-06-08 14:49:51 +00:00
|
|
|
package cwhub
|
2022-03-29 12:20:26 +00:00
|
|
|
|
|
|
|
import (
|
2024-03-25 09:40:41 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
2022-05-19 08:48:08 +00:00
|
|
|
"os"
|
2024-03-25 09:40:41 +00:00
|
|
|
"path/filepath"
|
2022-03-29 12:20:26 +00:00
|
|
|
"testing"
|
|
|
|
|
2023-10-03 09:20:56 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
2023-11-24 14:57:32 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
2024-03-25 09:40:41 +00:00
|
|
|
|
|
|
|
"github.com/crowdsecurity/go-cs-lib/cstest"
|
2022-03-29 12:20:26 +00:00
|
|
|
)
|
|
|
|
|
2023-06-29 14:35:19 +00:00
|
|
|
func TestDownloadFile(t *testing.T) {
|
2024-03-25 09:40:41 +00:00
|
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
switch r.URL.Path {
|
|
|
|
case "/xx":
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
_, _ = io.WriteString(w, "example content oneoneone")
|
|
|
|
default:
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
_, _ = io.WriteString(w, "not found")
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
defer ts.Close()
|
|
|
|
|
|
|
|
dest := filepath.Join(t.TempDir(), "example.txt")
|
|
|
|
defer os.Remove(dest)
|
|
|
|
|
|
|
|
err := downloadFile(ts.URL+"/xx", dest)
|
2023-11-24 14:57:32 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
2024-03-25 09:40:41 +00:00
|
|
|
content, err := os.ReadFile(dest)
|
2022-03-29 12:20:26 +00:00
|
|
|
assert.Equal(t, "example content oneoneone", string(content))
|
2023-11-24 14:57:32 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
2024-03-08 09:55:30 +00:00
|
|
|
// bad uri
|
2024-03-25 09:40:41 +00:00
|
|
|
err = downloadFile("https://zz.com", dest)
|
|
|
|
cstest.RequireErrorContains(t, err, "lookup zz.com")
|
|
|
|
cstest.RequireErrorContains(t, err, "no such host")
|
2023-11-24 14:57:32 +00:00
|
|
|
|
2024-03-08 09:55:30 +00:00
|
|
|
// 404
|
2024-03-25 09:40:41 +00:00
|
|
|
err = downloadFile(ts.URL+"/x", dest)
|
|
|
|
cstest.RequireErrorContains(t, err, "bad http code 404")
|
2023-11-24 14:57:32 +00:00
|
|
|
|
2024-03-08 09:55:30 +00:00
|
|
|
// bad target
|
2024-03-25 09:40:41 +00:00
|
|
|
err = downloadFile(ts.URL+"/xx", "")
|
|
|
|
cstest.RequireErrorContains(t, err, cstest.PathNotFoundMessage)
|
|
|
|
|
|
|
|
// destination directory does not exist
|
|
|
|
err = downloadFile(ts.URL+"/xx", filepath.Join(t.TempDir(), "missing/example.txt"))
|
|
|
|
cstest.RequireErrorContains(t, err, cstest.PathNotFoundMessage)
|
2022-03-29 12:20:26 +00:00
|
|
|
}
|