| 1 |
package mautrix |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"net/http" |
| 6 |
"testing" |
| 7 |
"time" |
| 8 |
) |
| 9 |
|
| 10 |
type testLogger struct { |
| 11 |
StubLogger |
| 12 |
|
| 13 |
lastLogged string |
| 14 |
} |
| 15 |
|
| 16 |
func (tl *testLogger) Warnfln(message string, args ...interface{}) { |
| 17 |
tl.lastLogged = fmt.Sprintf(message, args...) |
| 18 |
} |
| 19 |
|
| 20 |
func TestBackoffFromResponse(t *testing.T) { |
| 21 |
now := time.Now().Truncate(time.Second) |
| 22 |
|
| 23 |
defaultBackoff := time.Duration(123) |
| 24 |
|
| 25 |
for name, tt := range map[string]struct { |
| 26 |
headerValue string |
| 27 |
expected time.Duration |
| 28 |
expectedLog string |
| 29 |
}{ |
| 30 |
"AsDate": { |
| 31 |
headerValue: now.In(time.UTC).Add(5 * time.Hour).Format(http.TimeFormat), |
| 32 |
expected: time.Duration(5) * time.Hour, |
| 33 |
expectedLog: "", |
| 34 |
}, |
| 35 |
"AsSeconds": { |
| 36 |
headerValue: "12345", |
| 37 |
expected: time.Duration(12345) * time.Second, |
| 38 |
expectedLog: "", |
| 39 |
}, |
| 40 |
"Missing": { |
| 41 |
headerValue: "", |
| 42 |
expected: defaultBackoff, |
| 43 |
expectedLog: "", |
| 44 |
}, |
| 45 |
"Bad": { |
| 46 |
headerValue: "invalid", |
| 47 |
expected: defaultBackoff, |
| 48 |
expectedLog: `Failed to parse Retry-After header value "invalid"`, |
| 49 |
}, |
| 50 |
} { |
| 51 |
t.Run(name, func(t *testing.T) { |
| 52 |
logger := &testLogger{} |
| 53 |
|
| 54 |
c := &Client{Logger: logger} |
| 55 |
|
| 56 |
actual := c.parseBackoffFromResponse( |
| 57 |
&http.Response{ |
| 58 |
Header: http.Header{ |
| 59 |
"Retry-After": []string{tt.headerValue}, |
| 60 |
}, |
| 61 |
}, |
| 62 |
now, |
| 63 |
time.Duration(123), |
| 64 |
) |
| 65 |
|
| 66 |
if actual != tt.expected { |
| 67 |
t.Fatalf("Backoff duration output mismatch, expected %s, got %s", tt.expected, actual) |
| 68 |
} |
| 69 |
|
| 70 |
if logger.lastLogged != tt.expectedLog { |
| 71 |
t.Fatalf(`Log line mismatch, expected "%s", got "%s"`, tt.expectedLog, logger.lastLogged) |
| 72 |
} |
| 73 |
}) |
| 74 |
} |
| 75 |
} |