sq/libsq/source/fetcher/fetcher_test.go

68 lines
1.8 KiB
Go
Raw Normal View History

2020-08-06 20:58:47 +03:00
package fetcher_test
import (
"bytes"
"context"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/neilotoole/sq/libsq/source/fetcher"
"github.com/neilotoole/sq/testh/proj"
"github.com/neilotoole/sq/testh/sakila"
)
2021-01-02 07:10:02 +03:00
func TestFetcherHTTP(t *testing.T) {
2020-08-06 20:58:47 +03:00
wantData := proj.ReadFile(sakila.PathCSVActor)
buf := &bytes.Buffer{}
f := &fetcher.Fetcher{}
2021-01-02 07:10:02 +03:00
err := f.Fetch(context.Background(), sakila.URLActorCSV, buf)
2020-08-06 20:58:47 +03:00
require.NoError(t, err)
require.Equal(t, wantData, buf.Bytes())
}
func TestFetcherConfig(t *testing.T) {
ctx := context.Background()
serverSleepy := new(time.Duration)
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(*serverSleepy)
}))
server.Config.ErrorLog = log.New(ioutil.Discard, "", 0) // hush the server logging
server.StartTLS()
defer server.Close()
fetchr := &fetcher.Fetcher{}
// No config, expect error because of bad cert
2021-01-02 07:10:02 +03:00
err := fetchr.Fetch(ctx, server.URL, ioutil.Discard)
2020-08-06 20:58:47 +03:00
require.Error(t, err, "expect untrusted cert error")
cfg := &fetcher.Config{InsecureSkipVerify: true}
// Config as field of Fetcher
fetchr = &fetcher.Fetcher{Config: cfg}
2021-01-02 07:10:02 +03:00
err = fetchr.Fetch(ctx, server.URL, ioutil.Discard)
2020-08-06 20:58:47 +03:00
require.NoError(t, err)
// Test timeout
cfg.Timeout = time.Millisecond * 100
// Have the server sleep for longer than that
*serverSleepy = time.Millisecond * 200
2021-01-02 07:10:02 +03:00
fetchr = &fetcher.Fetcher{Config: cfg}
err = fetchr.Fetch(ctx, server.URL, ioutil.Discard)
2020-08-06 20:58:47 +03:00
require.Error(t, err, "should have seen a client timeout")
// Make the client timeout larger than server sleep time
cfg.Timeout = time.Millisecond * 500
2021-01-02 07:10:02 +03:00
err = fetchr.Fetch(ctx, server.URL, ioutil.Discard)
2020-08-06 20:58:47 +03:00
require.NoError(t, err)
}