github.com/grahambrereton-form3/tilt@v0.10.18/internal/store/testing_store.go (about)

     1  package store
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"sync"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  var _ RStore = &TestingStore{}
    12  
    13  type TestingStore struct {
    14  	state   *EngineState
    15  	stateMu sync.RWMutex
    16  
    17  	Actions []Action
    18  }
    19  
    20  func NewTestingStore() *TestingStore {
    21  	return &TestingStore{}
    22  }
    23  
    24  func (s *TestingStore) SetState(state EngineState) {
    25  	s.stateMu.Lock()
    26  	defer s.stateMu.Unlock()
    27  	s.state = &state
    28  }
    29  
    30  func (s *TestingStore) RLockState() EngineState {
    31  	s.stateMu.RLock()
    32  	return *(s.state)
    33  }
    34  
    35  func (s *TestingStore) RUnlockState() {
    36  	s.stateMu.RUnlock()
    37  }
    38  
    39  func (s *TestingStore) Dispatch(action Action) {
    40  	s.Actions = append(s.Actions, action)
    41  }
    42  
    43  // for use by tests (with a real channel-based store, NOT a TestingStore), to wait until
    44  // an action of the specified type comes out of the given chan at some point we might want
    45  // it to return the index it was found at, and then take an index, so that we can start
    46  // searching from the next index
    47  func WaitForAction(t testing.TB, typ reflect.Type, getActions func() []Action) Action {
    48  	start := time.Now()
    49  	timeout := 300 * time.Millisecond
    50  
    51  	for time.Since(start) < timeout {
    52  		actions := getActions()
    53  		for _, a := range actions {
    54  			if reflect.TypeOf(a) == typ {
    55  				return a
    56  			} else if la, ok := a.(LogAction); ok {
    57  				fmt.Println(string(la.Message()))
    58  			}
    59  		}
    60  	}
    61  	t.Fatalf("timed out waiting for action of type %s. Saw the following actions while waiting: %+v",
    62  		typ.Name(),
    63  		getActions())
    64  	return nil
    65  }
    66  
    67  // for use by tests (with a real channel-based store, NOT a TestingStore). Assert that
    68  // we don't see an action of the given type
    69  func AssertNoActionOfType(t testing.TB, typ reflect.Type, getActions func() []Action) Action {
    70  	start := time.Now()
    71  	timeout := 150 * time.Millisecond
    72  
    73  	for time.Since(start) < timeout {
    74  		actions := getActions()
    75  		for _, a := range actions {
    76  			if reflect.TypeOf(a) == typ {
    77  				t.Fatalf("Found action of type %s where none was expected: %+v", typ.Name(), a)
    78  			} else if la, ok := a.(LogAction); ok {
    79  				fmt.Println(string(la.Message()))
    80  			}
    81  		}
    82  	}
    83  	return nil
    84  }