github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/manager/state/testutils/mock_proposer.go (about)

     1  package testutils
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	"github.com/docker/swarmkit/api"
     8  	"github.com/docker/swarmkit/manager/state"
     9  )
    10  
    11  // MockProposer is a simple proposer implementation for use in tests.
    12  type MockProposer struct {
    13  	index   uint64
    14  	changes []state.Change
    15  }
    16  
    17  // ProposeValue propagates a value. In this mock implementation, it just stores
    18  // the value locally.
    19  func (mp *MockProposer) ProposeValue(ctx context.Context, storeAction []api.StoreAction, cb func()) error {
    20  	mp.index += 3
    21  	mp.changes = append(mp.changes,
    22  		state.Change{
    23  			Version:      api.Version{Index: mp.index},
    24  			StoreActions: storeAction,
    25  		},
    26  	)
    27  	if cb != nil {
    28  		cb()
    29  	}
    30  	return nil
    31  }
    32  
    33  // GetVersion returns the current version.
    34  func (mp *MockProposer) GetVersion() *api.Version {
    35  	return &api.Version{Index: mp.index}
    36  }
    37  
    38  // ChangesBetween returns changes after "from" up to and including "to".
    39  func (mp *MockProposer) ChangesBetween(from, to api.Version) ([]state.Change, error) {
    40  	var changes []state.Change
    41  
    42  	if len(mp.changes) == 0 {
    43  		return nil, errors.New("no history")
    44  	}
    45  
    46  	lastIndex := mp.changes[len(mp.changes)-1].Version.Index
    47  
    48  	if to.Index > lastIndex || from.Index > lastIndex {
    49  		return nil, errors.New("out of bounds")
    50  	}
    51  
    52  	for _, change := range mp.changes {
    53  		if change.Version.Index > from.Index && change.Version.Index <= to.Index {
    54  			changes = append(changes, change)
    55  		}
    56  	}
    57  
    58  	return changes, nil
    59  }