github.com/bytedance/mockey@v1.2.10/mock_sequence.go (about)

     1  /*
     2   * Copyright 2022 ByteDance Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package mockey
    18  
    19  import "github.com/bytedance/mockey/internal/tool"
    20  
    21  type SequenceOpt interface {
    22  	// Private make sure it is mockey private interface
    23  	Private
    24  	// GetNext is used by mockey, don't use it if you don't know what it does
    25  	GetNext() []interface{}
    26  }
    27  
    28  type sequenceOpt interface {
    29  	SequenceOpt
    30  	Times(int) sequenceOpt
    31  	Then(...interface{}) sequenceOpt
    32  }
    33  
    34  type sequence struct {
    35  	MockeyPrivate // make sure it does implements mockey SequenceOpt
    36  	values        []*sequenceValue
    37  	curV          int // current value
    38  	curT          int // current value times
    39  }
    40  
    41  type sequenceValue struct {
    42  	v []interface{}
    43  	t int
    44  }
    45  
    46  func (s *sequence) GetNext() []interface{} {
    47  	seqV := s.values[s.curV]
    48  	s.curT++
    49  	if s.curT >= seqV.t {
    50  		s.curT = 0
    51  		s.curV++
    52  		if s.curV >= len(s.values) {
    53  			s.curV = 0
    54  		}
    55  	}
    56  	return seqV.v
    57  }
    58  
    59  func (s *sequence) Then(value ...interface{}) sequenceOpt {
    60  	s.values = append(s.values, &sequenceValue{
    61  		v: value,
    62  		t: 1,
    63  	})
    64  	return s
    65  }
    66  
    67  func (s *sequence) Times(t int) sequenceOpt {
    68  	tool.Assert(t > 0, "return times should more than 0")
    69  	s.values[len(s.values)-1].t = t
    70  	return s
    71  }
    72  
    73  func Sequence(value ...interface{}) sequenceOpt {
    74  	seq := &sequence{}
    75  	seq.Then(value...)
    76  	return seq
    77  }