File: test_retry.go

package info (click to toggle)
golang-github-linode-linodego 1.55.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,112 kB
  • sloc: makefile: 96; sh: 52; python: 24
file content (130 lines) | stat: -rw-r--r-- 2,205 bytes parent folder | download | duplicates (2)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package integration

import (
	"fmt"
	"runtime"
	"testing"
)

func retryStatement(t *testing.T, maxAttempts int, f func(t *TRetry)) {
	for i := 0; i < maxAttempts; i++ {
		newT := NewTRetry(t)
		t.Cleanup(newT.Close)

		go func() {
			f(newT)

			newT.SuccessChannel <- true
		}()

		select {
		case err := <-newT.ErrorChannel:
			t.Logf("Retrying on test failure: %s\n", err)
		case <-newT.SuccessChannel:
			return
		}
	}

	t.Fatalf("Test failed after %d attempts", maxAttempts)
}

// TRetry implements testing.T with additional retry logic
type TRetry struct {
	t *testing.T

	ErrorChannel   chan error
	SuccessChannel chan bool
}

func NewTRetry(t *testing.T) *TRetry {
	t.Helper()
	return &TRetry{
		t:              t,
		ErrorChannel:   make(chan error),
		SuccessChannel: make(chan bool),
	}
}

func (t *TRetry) Close() {
	close(t.ErrorChannel)
	close(t.SuccessChannel)
}

func (t *TRetry) Cleanup(f func()) {
	t.t.Cleanup(f)
}

func (t *TRetry) Error(args ...any) {
	t.ErrorChannel <- fmt.Errorf(fmt.Sprint(args...))
}

func (t *TRetry) Errorf(format string, args ...any) {
	t.ErrorChannel <- fmt.Errorf(format, args...)
}

func (t *TRetry) Fail() {
	runtime.Goexit()
}

func (t *TRetry) Failed() bool {
	// We wrap this logic using channels
	return false
}

func (t *TRetry) Fatal(args ...any) {
	t.ErrorChannel <- fmt.Errorf(fmt.Sprint(fmt.Sprint(args...)))
	t.Fail()
}

func (t *TRetry) Fatalf(format string, args ...any) {
	t.ErrorChannel <- fmt.Errorf(format, args...)
	t.Fail()
}

func (t *TRetry) Helper() {
	t.t.Helper()
}

func (t *TRetry) Log(args ...any) {
	t.t.Log(args...)
}

func (t *TRetry) Logf(format string, args ...any) {
	t.t.Logf(format, args...)
}

func (t *TRetry) Name() string {
	return t.t.Name()
}

func (t *TRetry) Setenv(key, value string) {
	t.t.Setenv(key, value)
}

func (t *TRetry) Skip(args ...any) {
	t.t.Skip(args...)
}

func (t *TRetry) SkipNow() {
	t.t.SkipNow()
}

func (t *TRetry) Skipf(format string, args ...any) {
	t.t.Skipf(format, args...)
}

func (t *TRetry) Skipped() bool {
	return t.t.Skipped()
}

func (t *TRetry) TempDir() string {
	return t.t.TempDir()
}

func (t *TRetry) FailNow() {
	t.Fail()
}

func (t *TRetry) Parallel() {
	t.t.Parallel()
}