github.com/weaviate/weaviate@v1.24.6/test/helper/eventually_equal.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package helper
    13  
    14  import (
    15  	"fmt"
    16  	"testing"
    17  	"time"
    18  
    19  	"github.com/stretchr/testify/assert"
    20  )
    21  
    22  type fakeT struct {
    23  	lastError error
    24  }
    25  
    26  func (f *fakeT) Reset() {
    27  	f.lastError = nil
    28  }
    29  
    30  func (f *fakeT) Errorf(msg string, args ...interface{}) {
    31  	f.lastError = fmt.Errorf(msg, args...)
    32  }
    33  
    34  // AssertEventuallyEqual retries the 'actual' thunk every 10ms for a total of
    35  // 300ms. If a single one succeeds, it returns, if all fails it eventually
    36  // fails
    37  func AssertEventuallyEqual(t *testing.T, expected interface{}, actualThunk func() interface{}, msg ...interface{}) {
    38  	t.Helper()
    39  	interval := 10 * time.Millisecond
    40  	timeout := 4000 * time.Millisecond
    41  	elapsed := 0 * time.Millisecond
    42  	fakeT := &fakeT{}
    43  
    44  	for elapsed < timeout {
    45  		fakeT.Reset()
    46  		actual := actualThunk()
    47  		assert.Equal(fakeT, expected, actual, msg...)
    48  
    49  		if fakeT.lastError == nil {
    50  			return
    51  		}
    52  
    53  		time.Sleep(interval)
    54  		elapsed += interval
    55  	}
    56  
    57  	t.Errorf("waiting for %s, but never succeeded:\n\n%s", elapsed, fakeT.lastError)
    58  }
    59  
    60  func AssertEventuallyEqualWithFrequencyAndTimeout(t *testing.T, expected interface{}, actualThunk func() interface{},
    61  	interval time.Duration, timeout time.Duration, msg ...interface{},
    62  ) {
    63  	elapsed := 0 * time.Millisecond
    64  	fakeT := &fakeT{}
    65  
    66  	for elapsed < timeout {
    67  		fakeT.Reset()
    68  		actual := actualThunk()
    69  		assert.Equal(fakeT, expected, actual, msg...)
    70  
    71  		if fakeT.lastError == nil {
    72  			return
    73  		}
    74  
    75  		time.Sleep(interval)
    76  		elapsed += interval
    77  	}
    78  
    79  	t.Errorf("waiting for %s, but never succeeded:\n\n%s", elapsed, fakeT.lastError)
    80  }