File: errors_history_test.go

package info (click to toggle)
golang-github-avast-retry-go 4.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 156 kB
  • sloc: makefile: 47
file content (45 lines) | stat: -rw-r--r-- 998 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package retry_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/avast/retry-go/v4"
	"github.com/stretchr/testify/assert"
)

// TestErrorHistory shows an example of how to get all the previous errors when
// retry.Do ends in success
func TestErrorHistory(t *testing.T) {
	attempts := 3 // server succeeds after 3 attempts
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if attempts > 0 {
			attempts--
			w.WriteHeader(http.StatusBadGateway)
			return
		}
		w.WriteHeader(http.StatusOK)
	}))
	defer ts.Close()
	var allErrors []error
	err := retry.Do(
		func() error {
			resp, err := http.Get(ts.URL)
			if err != nil {
				return err
			}
			defer resp.Body.Close()
			if resp.StatusCode != 200 {
				return fmt.Errorf("failed HTTP - %d", resp.StatusCode)
			}
			return nil
		},
		retry.OnRetry(func(n uint, err error) {
			allErrors = append(allErrors, err)
		}),
	)
	assert.NoError(t, err)
	assert.Len(t, allErrors, 3)
}