Skip to content

Commit

Permalink
chore(share/getters): add unit test for ctxwithsplittimeout (#2374)
Browse files Browse the repository at this point in the history
## Overview

Adds extra safety.

Co-authored-by: Hlib Kanunnikov <hlibwondertan@gmail.com>
  • Loading branch information
walldiss and Wondertan committed Jun 21, 2023
1 parent ce8ccb3 commit 367fc66
Showing 1 changed file with 115 additions and 0 deletions.
115 changes: 115 additions & 0 deletions share/getters/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package getters

import (
"context"
"errors"
"fmt"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func Test_ErrorContains(t *testing.T) {
Expand Down Expand Up @@ -101,3 +104,115 @@ func Test_ErrorContains(t *testing.T) {
})
}
}

func Test_ctxWithSplitTimeout(t *testing.T) {
type args struct {
ctxTimeout time.Duration
splitFactor []int
minTimeout time.Duration
}
tests := []struct {
name string
args args
want time.Duration
}{
{
name: "ctxTimeout > minTimeout, splitFactor <= 0",
args: args{
ctxTimeout: 3 * time.Minute,
splitFactor: []int{-1, 0},
minTimeout: time.Minute,
},
want: time.Minute,
},
{
name: "ctxTimeout > minTimeout, splitFactor = 1",
args: args{
ctxTimeout: 3 * time.Minute,
splitFactor: []int{1},
minTimeout: time.Minute,
},
want: 3 * time.Minute,
},
{
name: "ctxTimeout > minTimeout, splitFactor = 2",
args: args{
ctxTimeout: 3 * time.Minute,
splitFactor: []int{2},
minTimeout: time.Minute,
},
want: 3 * time.Minute / 2,
},
{
name: "ctxTimeout > minTimeout, resulted timeout limited by minTimeout",
args: args{
ctxTimeout: 3 * time.Minute,
splitFactor: []int{3, 4, 5},
minTimeout: time.Minute,
},
want: time.Minute,
},
{
name: "ctxTimeout < minTimeout",
args: args{
ctxTimeout: time.Minute,
splitFactor: []int{-1, 0, 1, 2, 3},
minTimeout: 2 * time.Minute,
},
want: time.Minute,
},
{
name: "minTimeout = 0, splitFactor <= 1",
args: args{
ctxTimeout: time.Minute,
splitFactor: []int{-1, 0, 1},
minTimeout: 0,
},
want: time.Minute,
},
{
name: "minTimeout = 0, splitFactor > 1",
args: args{
ctxTimeout: time.Minute,
splitFactor: []int{2},
minTimeout: 0,
},
want: time.Minute / 2,
},
{
name: "no context timeout",
args: args{
ctxTimeout: 0,
splitFactor: []int{-1, 0, 1, 2},
minTimeout: time.Minute,
},
want: 0,
},
{
name: "no context timeout, minTimeout = 0",
args: args{
ctxTimeout: 0,
splitFactor: []int{-1, 0, 1, 2},
minTimeout: 0,
},
want: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for _, sf := range tt.args.splitFactor {
ctx, cancel := context.WithTimeout(context.Background(), tt.args.ctxTimeout)
t.Cleanup(cancel)
got, _ := ctxWithSplitTimeout(ctx, sf, tt.args.minTimeout)
dl, ok := got.Deadline()
if !ok {
require.Equal(t, tt.want, 0)
continue
}
d := time.Until(dl)
require.True(t, d <= tt.want+time.Second)
require.True(t, d >= tt.want-time.Second)
}
})
}
}

0 comments on commit 367fc66

Please sign in to comment.