Beispiel #1
0
func TestNoTimeout(t *testing.T) {
	ctx := context.Background()
	resp, err := doRequest(ctx)

	if resp == nil || err != nil {
		t.Fatalf("error received from client: %v %v", err, resp)
	}
}
Beispiel #2
0
func TestInterruptedTransferChunks(t *testing.T) {
	f, err := os.Open("googleapi.go")
	if err != nil {
		t.Fatalf("unable to open googleapi.go: %v", err)
	}
	defer f.Close()
	slurp, err := ioutil.ReadAll(f)
	if err != nil {
		t.Fatalf("unable to slurp file: %v", err)
	}
	st, err := f.Stat()
	if err != nil {
		t.Fatalf("unable to stat googleapi.go: %v", err)
	}
	tr := &interruptedTransport{
		statusCode: 308,
		buf:        make([]byte, 0, st.Size()),
	}
	oldChunkSize := chunkSize
	defer func() { chunkSize = oldChunkSize }()
	chunkSize = 100 // override to process small chunks for test.

	sleep = func(time.Duration) {} // override time.Sleep
	rx := &ResumableUpload{
		Client:        &http.Client{Transport: tr},
		Media:         f,
		MediaType:     "text/plain",
		ContentLength: st.Size(),
		Callback:      tr.ProgressUpdate,
	}
	res, err := rx.Upload(context.Background())
	if err != nil || res == nil || res.StatusCode != http.StatusOK {
		if res == nil {
			t.Errorf("transferChunks not successful, res=nil: %v", err)
		} else {
			t.Errorf("transferChunks not successful, statusCode=%v: %v", res.StatusCode, err)
		}
	}
	if len(tr.buf) != len(slurp) || bytes.Compare(tr.buf, slurp) != 0 {
		t.Errorf("transferred file corrupted:\ngot %s\nwant %s", tr.buf, slurp)
	}
	w := ""
	for i := chunkSize; i <= st.Size(); i += chunkSize {
		w += fmt.Sprintf("%v, %v\n", i, st.Size())
	}
	if st.Size()%chunkSize != 0 {
		w += fmt.Sprintf("%v, %v\n", st.Size(), st.Size())
	}
	if tr.progressBuf != w {
		t.Errorf("progress update error, got %v, want %v", tr.progressBuf, w)
	}
}
Beispiel #3
0
func ExampleWithTimeout() {
	// Pass a context with a timeout to tell a blocking function that it
	// should abandon its work after the timeout elapses.
	ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)
	select {
	case <-time.After(200 * time.Millisecond):
		fmt.Println("overslept")
	case <-ctx.Done():
		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
	}
	// Output:
	// context deadline exceeded
}
Beispiel #4
0
func TestCancelAfterRequest(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())

	resp, err := doRequest(ctx)

	// Cancel before reading the body.
	// Request.Body should still be readable after the context is canceled.
	cancel()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil || string(b) != requestBody {
		t.Fatalf("could not read body: %q %v", b, err)
	}
}
Beispiel #5
0
func TestTransferStatus(t *testing.T) {
	ctx := context.Background()
	for _, tr := range statusTests {
		rx := &ResumableUpload{
			Client: &http.Client{Transport: tr},
		}
		g, _, err := rx.transferStatus(ctx)
		if err != nil {
			t.Error(err)
		}
		if g != tr.want {
			t.Errorf("transferStatus got %v, want %v", g, tr.want)
		}
	}
}
Beispiel #6
0
func TestCancel(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		time.Sleep(requestDuration / 2)
		cancel()
	}()

	resp, err := doRequest(ctx)

	if resp != nil || err == nil {
		t.Fatalf("expected error, didn't get one. resp: %v", resp)
	}
	if err != ctx.Err() {
		t.Fatalf("expected error from context but got: %v", err)
	}
}
Beispiel #7
0
func TestExchangeRequest_NonBasicAuth(t *testing.T) {
	tr := &mockTransport{
		rt: func(r *http.Request) (w *http.Response, err error) {
			headerAuth := r.Header.Get("Authorization")
			if headerAuth != "" {
				t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
			}
			return nil, errors.New("no response")
		},
	}
	c := &http.Client{Transport: tr}
	conf := &Config{
		ClientID: "CLIENT_ID",
		Endpoint: Endpoint{
			AuthURL:  "https://accounts.google.com/auth",
			TokenURL: "https://accounts.google.com/token",
		},
	}

	ctx := context.WithValue(context.Background(), HTTPClient, c)
	conf.Exchange(ctx, "code")
}
Beispiel #8
0
// analyticsClient() takes in a clientid, secret, and a base64'd gob representing the cached oauth token.
// Generating the token is left as an exercise to the reader. (TODO)
func analyticsClient(clientid string, secret string, tokenstr string) (*http.Client, error) {
	ctx := context.Background()

	config := &oauth2.Config{
		ClientID:     clientid,
		ClientSecret: secret,
		Endpoint:     google.Endpoint,
		Scopes:       []string{analytics.AnalyticsScope},
	}

	token := new(oauth2.Token)
	// Decode the base64'd gob
	by, err := base64.StdEncoding.DecodeString(tokenstr)
	if err != nil {
		return nil, err
	}
	b := bytes.Buffer{}
	b.Write(by)
	d := gob.NewDecoder(&b)
	err = d.Decode(&token)

	return config.Client(ctx, token), nil
}
Beispiel #9
0
func TestCancelUpload(t *testing.T) {
	f, err := os.Open("googleapi.go")
	if err != nil {
		t.Fatalf("unable to open googleapi.go: %v", err)
	}
	defer f.Close()
	st, err := f.Stat()
	if err != nil {
		t.Fatalf("unable to stat googleapi.go: %v", err)
	}
	tr := &interruptedTransport{
		statusCode: 308,
		buf:        make([]byte, 0, st.Size()),
	}
	oldChunkSize := chunkSize
	defer func() { chunkSize = oldChunkSize }()
	chunkSize = 100 // override to process small chunks for test.

	sleep = func(time.Duration) {} // override time.Sleep
	rx := &ResumableUpload{
		Client:        &http.Client{Transport: tr},
		Media:         f,
		MediaType:     "text/plain",
		ContentLength: st.Size(),
		Callback:      tr.ProgressUpdate,
	}
	ctx, cancelFunc := context.WithCancel(context.Background())
	cancelFunc() // stop the upload that hasn't started yet
	res, err := rx.Upload(ctx)
	if err == nil || res == nil || res.StatusCode != http.StatusRequestTimeout {
		if res == nil {
			t.Errorf("transferChunks not successful, got res=nil, err=%v, want StatusRequestTimeout", err)
		} else {
			t.Errorf("transferChunks not successful, got statusCode=%v, err=%v, want StatusRequestTimeout", res.StatusCode, err)
		}
	}
}