text
stringlengths
14
100k
source
stringclasses
1 value
repo
stringclasses
810 values
language
stringclasses
13 values
<|fim_suffix|> assert.True(t, count >= 75, fmt.Sprintf("should be greater than 75, actual %d", count)) } <|fim_prefix|>package breaker import ( "context" "errors" "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/stat" ) func init() { stat.SetReporter(nil) } func TestBr...
fim
zeromicro/go-zero
go
<|fim_prefix|>package breaker const ( success = iota fail drop ) // bucket defines the bucket that holds sum and num of additions. type bucket struct { Sum int64 Success int64 Failure int64<|fim_suffix|> func (b *bucket) Reset() { b.Sum = 0 b.Success = 0 b.Failure = 0 b.Drop = 0 } func (b *bucket) drop...
fim
zeromicro/go-zero
go
<|fim_suffix|>b.Drop, "Drop should be reset to 0") } <|fim_prefix|>package breaker import ( "testing" "github.com/stretchr/testify/assert" ) func TestBucketAdd(t *testing.T) { b := &bucket{} // Test succeed b.Add(0) // Using 0 for success assert.Equal(t, int64(1), b.Sum, "Sum shou<|fim_middle|>ld be increment...
fim
zeromicro/go-zero
go
<|fim_prefix|>package breaker import ( "time" "github.com/zeromicro/go-zero/core/collection" "github.com/zeromicro/go-zero/core/mathx" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/core/timex" ) const ( // 250ms for bucket duration window = time.Second * 10 buckets ...
fim
zeromicro/go-zero
go
<|fim_suffix|> return nil }, defaultAcceptable) == nil }) } func TestGoogleBreakerReject(t *testing.T) { b := getGoogleBreaker() markSuccess(b, 100) assert.Nil(t, b.accept()) markFailed(b, 10000) time.Sleep(testInterval) assert.Equal(t, ErrServiceUnavailable, b.doReq(func() error { return ErrServiceUnavaila...
fim
zeromicro/go-zero
go
<|fim_prefix|>package breaker import "context" const nopBreakerName = "nopBreaker" type nopBreaker struct{} // NopBreaker returns a breaker that never trigger breaker circuit. func NopBreaker() Breaker { return nopBreaker{} } func (b nopBreaker) Name() string { return nopBreakerName } func (b nopBreaker) Allow(...
fim
zeromicro/go-zero
go
<|fim_suffix|>nc() error { return errDummy }, func(err error) error { return nil }, defaultAcceptable)) } <|fim_prefix|>package breaker import ( "context" "errors" "testing" "github.c<|fim_middle|>om/stretchr/testify/assert" ) func TestNopBreaker(t *testing.T) { b := NopBreaker() assert.Equal(t, nopBreak...
fim
zeromicro/go-zero
go
<|fim_suffix|> fmt.Print(prompt) input, _ := bufio.NewReader(os.Stdin).ReadString('\n') return strings.TrimSpace(input) } <|fim_prefix|>package cmdline import ( "bufio" "fmt" "os" "strings" ) // EnterT<|fim_middle|>oContinue let stdin waiting for an enter key to continue. func EnterToContinue() { fmt.Print("P...
fim
zeromicro/go-zero
go
<|fim_prefix|>package cmdline import ( "fmt" "os" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/iox" "github.com/zeromicro/g<|fim_suffix|>Wait() close(wait) }() select { case <-time.After(time.Second): t.Error("timeout") case <-wait: } } <|fim_middle...
fim
zeromicro/go-zero
go
<|fim_suffix|>end(ciphertext, padtext...) } func pkcs5Unpadding(src []byte, blockSize int) ([]byte, error) { length := len(src) if length == 0 { return nil, ErrPaddingSize } unpadding := int(src[length-1]) if unpadding < 1 || unpadding > blockSize || unpadding > length { return nil, ErrPaddingSize } for _...
fim
zeromicro/go-zero
go
<|fim_suffix|>rypter(block) assert.Equal(t, 16, decrypter.BlockSize()) dst = make([]byte, 8) assert.Panics(t, func() { encrypter.CryptBlocks(dst, val) }) dst = make([]byte, 8) assert.Panics(t, func() { encrypter.CryptBlocks(dst, valLong) }) dst = make([]byte, 8) assert.Panics(t, func() { decrypter.Cry...
fim
zeromicro/go-zero
go
<|fim_suffix|>eKey() (*DhKey, error) { var err error var x *big.Int for { x, err = rand.Int(rand.Reader, p) if err != nil { return nil, err } if zero.Cmp(x) < 0 { break } } key := new(DhKey) key.PriKey = x key.PubKey = new(big.Int).Exp(g, x, p) return key, nil } // NewPublicKey returns a pu...
fim
zeromicro/go-zero
go
<|fim_prefix|>package codec import ( "math/big" "testing" "github.com/stretchr/testify/assert" ) func TestDiffieHellman(t *testing.T) { key1, err := GenerateKey() assert.Nil(t, err) key2, err := GenerateKey() assert.Nil(t, err) pubKey1, err := ComputeKey(key1.PubKey, key2.PriKey) assert.Nil(t, err) pubKey...
fim
zeromicro/go-zero
go
<|fim_suffix|>ytes.Buffer if _, err = io.Copy(&c, io.LimitReader(r, unzipLimit)); err != nil { return nil, err } return c.Bytes(), nil } <|fim_prefix|>package codec import ( "bytes" "compress/gzip" "io" ) const unzipLimit = 100 * 1024 * 1024 // 100MB // Gzip compresses bs. func Gzip(bs []byte) []byte { var...
fim
zeromicro/go-zero
go
<|fim_prefix|>package codec import ( "bytes" "compress/gzip" "errors" "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestGzip(t *testing.T) { var buf bytes.Buffer for i := 0; i < 10000; i++ { fmt.Fprint(&buf, i) } bs := Gzip(buf.Bytes()) actual, err := Gunzip(bs) assert.Nil(t, err) asse...
fim
zeromicro/go-zero
go
<|fim_suffix|>} // HmacBase64 returns the base64 encoded string of HMAC for body with the given key. func HmacBase64(key []byte, body string) string { return base64.StdEncoding.EncodeToString(Hmac(key, body)) } <|fim_prefix|>package codec import ( "crypto/hmac" "crypto/sha256" "encod<|fim_middle|>ing/base64" "io...
fim
zeromicro/go-zero
go
<|fim_prefix|>package codec import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestHmac(t *testing.T) { ret := Hmac([]byte("foo"), "bar") a<|fim_suffix|>be7vr5tEGUxc=", ret) } <|fim_middle|>ssert.Equal(t, "f9320baf0249169e73850cd6156ded0106e2bb6ad8cab01b7bbbebe6d1065317", fmt.Sprintf("%x", r...
fim
zeromicro/go-zero
go
<|fim_prefix|>package codec import ( "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/pem" "errors" "os" ) var ( // ErrPrivateKey indicates the invalid private key. ErrPrivateKey = errors.New("private key error") // ErrPublicKey indicates the invalid public key. ErrPubl...
fim
zeromicro/go-zero
go
<|fim_suffix|> badPem, err := fs.TempFilenameWithText("-----BEGIN RSA PRIVATE KEY-----\nYmFk\n-----END RSA PRIVATE KEY-----") assert.Nil(t, err) defer os.Remove(badPem) _, err = NewRsaOAEPDecrypter(badPem) assert.Error(t, err) // not PEM content at all notPem, err := fs.TempFilenameWithText("not a pem file") a...
fim
zeromicro/go-zero
go
<|fim_prefix|>package collection import ( "container/list" "sync" "sync/atomic" "time" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/mathx" "github.com/zeromicro/go-zero/core/syncx" ) const ( defaultCacheName = "proc" slots = 300 statInterval = time.Minute // m...
fim
zeromicro/go-zero
go
<|fim_suffix|>eTake(t *testing.T) { cache, err := NewCache(time.Second * 2) assert.Nil(t, err) var count int32 var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func() { cache.Take("first", func() (any, error) { atomic.AddInt32(&count, 1) time.Sleep(time.Millisecond * 100) return "f...
fim
zeromicro/go-zero
go
<|fim_prefix|>package collection import "sync" // A Queue is a FIFO queue. type Queue struct { lock sync.Mutex elements []any size int head int tail int count int } // NewQueue returns a Queue objec<|fim_suffix|> } // Empty checks if q is empty. func (q *Queue) Empty() bool { q.lock.Lock()...
fim
zeromicro/go-zero
go
<|fim_suffix|> := range elements { queue.Put(elements[i]) } for _, element := range elements { body, ok := queue.Take() assert.True(t, ok) assert.Equal(t, string(element), string(body.([]byte))) } } func TestPutMoreWithHeaderNotZero(t *testing.T) { elements := [][]byte{ []byte("hello"), []byte("world"...
fim
zeromicro/go-zero
go
<|fim_suffix|>{ size = rlen start = r.index % rlen } else { size = r.index } elements := make([]any, size) for i := 0; i < size; i++ { elements[i] = r.elements[(start+i)%rlen] } return elements } <|fim_prefix|>package collection import "sync" // A Ring can be used as fixed size ring. type Ring struct ...
fim
zeromicro/go-zero
go
<|fim_suffix|>t *testing.T) { ring := NewRing(5051) wg := sync.WaitGroup{} for i := 1; i <= 100; i++ { wg.Add(1) go func(i int) { defer wg.Done() for j := 1; j <= i; j++ { ring.Add(i) } }(i) } wg.Wait() assert.Equal(t, 5050, len(ring.Take())) } func BenchmarkRingAdd(b *testing.B) { ring := Ne...
fim
zeromicro/go-zero
go
<|fim_suffix|>val time boundary rw.lastTime = now - (now-rw.lastTime)%rw.interval } // Bucket defines the bucket that holds sum and num of additions. type Bucket[T Numerical] struct { Sum T Count int64 } func (b *Bucket[T]) Add(v T) { b.Sum += v b.Count++ } func (b *Bucket[T]) Reset() { b.Sum = 0 b.Count = ...
fim
zeromicro/go-zero
go
<|fim_suffix|>pse() assert.Equal(t, []float64{0, 1}, listBuckets()) elapse() assert.Equal(t, []float64{1}, listBuckets()) elapse() assert.Nil(t, listBuckets()) // cross window r.Add(1) time.Sleep(duration * 10) assert.Nil(t, listBuckets()) } func TestRollingWindowReduce(t *testing.T) { const size = 4 tests...
fim
zeromicro/go-zero
go
<|fim_suffix|>dirtyNew = make(map[any]any) m.deletionNew = 0 } if m.deletionNew >= maxDeletion && len(m.dirtyNew) < copyThreshold { for k, v := range m.dirtyNew { m.dirtyOld[k] = v } m.dirtyNew = make(map[any]any) m.deletionNew = 0 } } // Get gets the value with the given key from m. func (m *SafeMap) ...
fim
zeromicro/go-zero
go
<|fim_prefix|>package collection import ( "sync/atomic" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/stringx" ) func TestSafeMap(t *testing.T) { tests := []struct { size int exception int }{ { 100000, 2000, }, { 100000, 50, }, } for _, test :=...
fim
zeromicro/go-zero
go
<|fim_prefix|>package collection import "github.com/zeromicro/go-zero/core/lang" // Set is a type-safe generic set collection. // It's not thread-safe, use with synchronization for concurrent access. type Set[T comparable] struct { data map[T]lang.PlaceholderType } // NewSet returns a new type-safe set. func NewSet...
fim
zeromicro/go-zero
go
package collection import ( "sort" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx" ) func init() { logx.Disable() } // Set functionality tests func TestTypedSetInt(t *testing.T) { set := NewSet[int]() values := []int{1, 2, 3, 2, 1} // Contains duplicates // Test addi...
fim
zeromicro/go-zero
go
<|fim_prefix|>package collection import ( "container/list" "errors" "fmt" "time" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/threading" "github.com/zeromicro/go-zero/core/timex" ) const drainWorkers = 8 var ( ErrClosed = errors.New("TimingWheel is closed already") ErrArgum...
fim
zeromicro/go-zero
go
<|fim_prefix|>package collection import ( "sort" "sync" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/core/timex" ) const ( tes...
fim
zeromicro/go-zero
go
<|fim_suffix|> {color.BgRed, color.FgHiWhite, color.Bold}, BgGreen: {color.BgGreen, color.FgHiWhite, color.Bold}, BgYellow: {color.BgHiYellow, color.FgHiBlack, color.Bold}, BgBlue: {color.BgBlue, color.FgHiWhite, color.Bold}, BgMagenta: {color.BgMagenta, color.FgHiWhite, color.Bold}, BgCyan: {color.BgCyan...
fim
zeromicro/go-zero
go
<|fim_suffix|>gRed) assert.Equal(t, " Hello ", output) } <|fim_prefix|>package<|fim_middle|> color import ( "testing" "github.com/stretchr/testify/assert" ) func TestWithColor(t *testing.T) { output := WithColor("Hello", BgRed) assert.Equal(t, "Hello", output) } func TestWithColorPadding(t *testing.T) { outpu...
fim
zeromicro/go-zero
go
package conf import ( "fmt" "log" "os" "path" "reflect" "strings" "github.com/zeromicro/go-zero/core/jsonx" "github.com/zeromicro/go-zero/core/mapping" "github.com/zeromicro/go-zero/internal/encoding" ) const ( jsonTagKey = "json" jsonTagSep = ',' ) var ( fillDefaultUnmarshaler = mapping.NewUnmarshaler(...
fim
zeromicro/go-zero
go
package conf import ( "errors" "os" "reflect" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/fs" "github.com/zeromicro/go-zero/core/hash" ) var dupErr conflictKeyError func TestLoadConfig_notExists(t *testing.T) { assert.NotNil(t, Load("not_a_file", nil)) } func TestLoadC...
fim
zeromicro/go-zero
go
<|fim_prefix|>package conf type ( // Option defines the method to customize the config options. Option func(opt *options) options <|fim_suffix|>{ env bool } ) // UseEnv customizes the config to use environment variables. func UseEnv() Option { return func(opt *options) { opt.env = true } } <|fim_middle|>st...
fim
zeromicro/go-zero
go
<|fim_prefix|>package conf import ( "fmt" "os" "strconv" "strings" "sync" "github.com/zeromicro/go-zero/core/iox" ) // PropertyError represents a configuration error message. type<|fim_suffix|>key] = os.ExpandEnv(value) } else { raw[key] = value } } return &mapBasedProperties{ properties: raw, }, ...
fim
zeromicro/go-zero
go
<|fim_suffix|>ame) } else { assert.Nil(t, err, "unexpected error for case: %s", tt.name) } }) } } <|fim_prefix|>package conf import ( "os" "testing" "gi<|fim_middle|>thub.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/fs" ) func TestProperties(t *testing.T) { text := `app.name = te...
fim
zeromicro/go-zero
go
<|fim_prefix|>package conf import "github.c<|fim_suffix|>lidator); ok { return val.Validate() } return nil } <|fim_middle|>om/zeromicro/go-zero/core/validation" // validate validates the value if it implements the Validator interface. func validate(v any) error { if val, ok := v.(validation.Va<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_suffix|>.name, func(t *testing.T) { assert.Error(t, validate(tt.v)) }) } } <|fim_prefix|>package conf import ( "errors" "testing" "github.com/stretchr/testify/assert" ) type mockType int func (m mockType) Validate() error { if m < 10 { return errors.New("invalid value") } return nil } type ano...
fim
zeromicro/go-zero
go
<|fim_suffix|>, err: %+v, content [%s]", err.Error(), data) } } case reflect.String: if str, ok := any(data).(T); ok { v.marshalData = str } else { v.err = errMissingUnmarshalerType } default: if c.conf.Log { logx.Errorf("ConfigCenter unmarshal configuration missing unmarshaler for type: %s...
fim
zeromicro/go-zero
go
<|fim_prefix|>package configurator import ( "errors" "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func TestNewConfigCenter(t *testing.T) { _, err := NewConfigCenter[any](Config{ Log: true, }, &mockSubscriber{}) assert.Error(t, err) _, err = NewConfigCenter[any](Config{ Type: "json", ...
fim
zeromicro/go-zero
go
<|fim_prefix|>package subscriber import ( "sync" "sync/atomic" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/logx" ) type ( // etcdSubscriber is a subscriber that subscribes to etcd. etcdSubscriber struct { *discov.Subscriber } // EtcdConf is the configuration for etcd. Et...
fim
zeromicro/go-zero
go
<|fim_suffix|>, c.GetValues()) }) } } <|fim_prefix|>package subscriber import ( "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/discov" ) const ( actionAdd = iota actionDel ) func TestConfigCenterContainer(t *testing.T) { type action struct { act int key string val s...
fim
zeromicro/go-zero
go
<|fim_suffix|>func()) error // Value returns the value of the subscriber. Value() (string, error) } <|fim_prefix|>p<|fim_middle|>ackage subscriber // Subscriber is the interface for configcenter subscribers. type Subscriber interface { // AddListener adds a listener to the subscriber. AddListener(listener <|endoft...
fim
zeromicro/go-zero
go
<|fim_prefix|>package configurator import ( "sync" "github.com/zeromicro/go-zero/core/conf" ) var registry = &unmarshalerRegistry{ unmarshalers: map[string]LoaderFn{ "json": conf.LoadFromJsonBytes, "toml": conf.LoadFromTomlBytes, "yaml": conf.LoadFromYamlBytes, }, } type ( // L<|fim_suffix|>() registry....
fim
zeromicro/go-zero
go
<|fim_prefix|>package configurator import ( "testing" "github.com/stretchr/testify/assert" ) func TestRegisterUnmarsha<|fim_suffix|>t") assert.True(t, ok) _, ok = Unmarshaler("test2") assert.False(t, ok) _, ok = Unmarshaler("json") assert.True(t, ok) _, ok = Unmarshaler("toml") assert.True(t, ok) _, ok...
fim
zeromicro/go-zero
go
<|fim_suffix|>ct { context.Context } func (cv contextValuer) Value(key string) (any, bool) { v := cv.Context.Value(key) return v, v != nil } // For unmarshals ctx into v. func For(ctx context.Context, v any) error { return unmarshaler.UnmarshalValuer(contextValuer{ Context: ctx, }, v) } <|fim_prefix|>package c...
fim
zeromicro/go-zero
go
<|fim_suffix|>erson struct { Name string `ctx:"name"` Age int `ctx:"age"` } type name string const PersonNameKey name = "name" ctx := context.Background() ctx = context.WithValue(ctx, PersonNameKey, "kevin") var person Person err := For(ctx, &person) assert.NotNil(t, err) } <|fim_prefix|>package cont...
fim
zeromicro/go-zero
go
<|fim_prefix|>package <|fim_suffix|>adline() (deadline time.Time, ok bool) { return } func (valueOnlyContext) Done() <-chan struct{} { return nil } func (valueOnlyContext) Err() error { return nil } // ValueOnlyFrom takes all values from the given ctx, without deadline and error control. func ValueOnlyFrom(ctx co...
fim
zeromicro/go-zero
go
<|fim_suffix|>)) assert.Nil(t, c.Err()) select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } } cancel() <-c1.Done() assert.Nil(t, o.Err()) assert.Equal(t, context.Canceled, c1.Err()) assert.NotEqual(t, context.Canceled, c2.Err()) } func TestCont...
fim
zeromicro/go-zero
go
package discov import "github.com/zeromicro/go-zero/core/discov/internal" // RegisterAccount registers the username/password to the given etcd cluster. func RegisterAccount(endpoints []string, user, pass string) { internal.AddAccount(endpoints, user, pass) } // RegisterTLS registers the CertFile/CertKeyFile/CACertF...
fim
zeromicro/go-zero
go
<|fim_prefix|>package discov import ( "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/discov/internal" "github.com/zeromicro/go-zero/core/stringx" ) func TestRegisterAccount(t *testing.T) { endpoints := []string{ "localhost:2379", } user := "foo" + stringx.Rand() RegisterA...
fim
zeromicro/go-zero
go
<|fim_suffix|>ing) (string, bool) { return extract(etcdKey, indexOfId) } func makeEtcdKey(key string, id int64) string { return fmt.Sprintf("%s%c%d", key, internal.Delimiter, id) } <|fim_prefix|>package discov import ( "fmt" "strings" "github.com/zeromicro/go-zero/core/discov/internal" ) const ( _ = iota ind...
fim
zeromicro/go-zero
go
<|fim_prefix|>package discov import ( "sync" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/discov/internal" ) var mockLock sync.Mutex func setMockClient(cli internal.EtcdClient) func() { mockLock.Lock() internal.NewClient = func([]string) (internal.EtcdClient, error) { re...
fim
zeromicro/go-zero
go
<|fim_suffix|>.New("empty etcd key") ) // EtcdConf is the config item with the given key on etcd. type EtcdConf struct { Hosts []string Key string ID int64 `json:",optional"` User string `json:",optional"` Pass string `json:",optional"` Cer...
fim
zeromicro/go-zero
go
<|fim_prefix|>package discov import ( "test<|fim_suffix|>ting.T) { tests := []struct { EtcdConf hasServerID bool }{ { EtcdConf: EtcdConf{ Hosts: []string{"any"}, ID: -1, }, hasServerID: false, }, { EtcdConf: EtcdConf{ Hosts: []string{"any"}, ID: 0, }, hasServerID: f...
fim
zeromicro/go-zero
go
<|fim_suffix|>As: pool, InsecureSkipVerify: insecureSkipVerify, } return nil } // GetAccount gets the username/password for the given etcd cluster. func GetAccount(endpoints []string) (Account, bool) { lock.RLock() defer lock.RUnlock() account, ok := accounts[getClusterKey(endpoints)] return accou...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/stringx" ) const ( certContent = `-----BEGIN CERTIFICATE----- MIIDazCCAlOgAwIBAgIUEg9GVO2oaPn+YSmiqmFIuAo10WIwDQYJKoZIhvcNAQEM BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBg...
fim
zeromicro/go-zero
go
<|fim_prefix|>//go:generate mockgen -package internal -destination etcdclient_mock.go -source etcdclient.go Etc<|fim_suffix|>) Grant(ctx context.Context, ttl int64) (*clientv3.LeaseGrantResponse, error) KeepAlive(ctx context.Context, id clientv3.LeaseID) (<-chan *clientv3.LeaseKeepAliveResponse, error) Put(ctx conte...
fim
zeromicro/go-zero
go
<|fim_suffix|>r() ret := m.ctrl.Call(m, "Ctx") ret0, _ := ret[0].(context.Context) return ret0 } // Ctx indicates an expected call of Ctx. func (mr *MockEtcdClientMockRecorder) Ctx() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ctx", reflect.TypeOf((*MockEtcdClient...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal // Listene<|fim_suffix|>e OnUpdate method. type Listener interface { OnUpdate(keys, values []string, newKey string) } <|fim_middle|>r interface wraps th<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "context" "errors" "fmt" "io" "sort" "strings" "sync" "time" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/mathx" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/core/thr...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "context" "os" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/contextx" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicr...
fim
zeromicro/go-zero
go
<|fim_suffix|>c (sw *stateWatcher) watch(conn etcdConn) { sw.currentState = conn.GetState() for { if conn.WaitForStateChange(context.Background(), sw.currentState) { sw.updateState(conn) } } } <|fim_prefix|>//go:generate mockgen -package internal -destination statewatcher_mock.go -source statewatcher.go etcdC...
fim
zeromicro/go-zero
go
<|fim_prefix|>// Code generated by MockGen. DO NOT EDIT. // Source: statewatcher.go // // Generated by this command: // // mockgen -package internal -destination statewatcher_mock.go -source statewatcher.go etcdConn // // Package internal is a generated GoMock package. package internal import ( context "context" re...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "sync" "testing" "go.uber.org/mock/gomock" "google.golang.org/grpc/connectivity" ) func TestStateWatcher_watch(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() watcher := newStateWatcher() var wg sync.WaitGroup wg.Add(1) watcher.addListener(func() ...
fim
zeromicro/go-zero
go
<|fim_prefix|>//go:generate mockgen -package internal -destination updatelistener_mock.go -source upd<|fim_suffix|>d(kv KV) OnDelete(kv KV) } ) <|fim_middle|>atelistener.go UpdateListener package internal type ( // A KV is used to store an etcd entry with key and value. KV struct { Key string Val string } ...
fim
zeromicro/go-zero
go
<|fim_prefix|>// Code generated by MockGen. DO NOT EDIT. // Source: updatelistener.go // // Generated by this command: // // mockgen -package internal -destination updatelistener_mock.go -source updatelistener.go UpdateListener // // Package internal is a generated GoMock package. package internal import ( reflect "...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import "time" const ( // Delimiter is a separator that separates the etcd path. Delim<|fim_suffix|> endpointsSeparator = "," ) var ( // DialTimeout is the dial timeout. DialTimeout = dialTimeout // RequestTimeout is the request timeout. RequestTimeout = requestTimeout // NewCli...
fim
zeromicro/go-zero
go
<|fim_prefix|>package discov import ( "time" "github.com/zeromicro/go-zero/core/discov/internal" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/core/syncx" "github...
fim
zeromicro/go-zero
go
<|fim_prefix|>package discov import ( "context" "errors" "net" "os" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/discov/internal" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stringx"...
fim
zeromicro/go-zero
go
<|fim_suffix|>Container(container Container) SubOption { return func(sub *Subscriber) { sub.items = container } } type ( Container interface { OnAdd(kv internal.KV) OnDelete(kv internal.KV) AddListener(listener func()) GetValues() []string } container struct { exclusive bool values map[string][]...
fim
zeromicro/go-zero
go
<|fim_suffix|>ct: actionAdd, key: "third", val: "a", }, { act: actionDel, key: "first", }, { act: actionDel, key: "second", }, }, expect: []string{"a"}, }, { name: "add three, dup values, delete two, delete not added", do: []action{ { act: actio...
fim
zeromicro/go-zero
go
<|fim_suffix|> v.(error) } return nil } <|fim_prefix|>package errorx import "sync/atomic" // AtomicError defines an atomic error. type AtomicError struct { err atomic.Value // error } // Set sets the error. func (ae *AtomicError) Set(err error) { if err != nil { ae.err.Store(err) } } // Load returns the erro...
fim
zeromicro/go-zero
go
package errorx import ( "errors" "sync" "sync/atomic" "testing" "github.com/stretchr/testify/assert" ) var errDummy = errors.New("hello") func TestAtomicError(t *testing.T) { var err AtomicError err.Set(errDummy) assert.Equal(t, errDummy, err.Load()) } func TestAtomicErrorSetNil(t *testing.T) { var ( er...
fim
zeromicro/go-zero
go
package errorx import ( "errors" "sync" ) // BatchError is an error that can hold multiple errors. type BatchError struct { errs []error lock sync.RWMutex } // Add adds one or more non-nil errors to the BatchError instance. func (be *BatchError) Add(errs ...error) { be.lock.Lock() defer be.lock.Unlock() for ...
fim
zeromicro/go-zero
go
<|fim_prefix|>package errorx import ( "errors" "fmt" <|fim_suffix|> after adding a mix of nil and non-nil errors") } func TestBatchError_Err(t *testing.T) { var be BatchError // Test Err() on empty BatchError assert.Nil(t, be.Err(), "Expected nil error for empty BatchError") // Test Err() with multiple error...
fim
zeromicro/go-zero
go
<|fim_suffix|>range fns { if err := fn(); err != nil { return err } } return nil } <|fim_prefix|>package errorx // Chain runs funs one by one until an error occurred. fu<|fim_middle|>nc Chain(fns ...func() error) error { for _, fn := <|endoftext|>
fim
zeromicro/go-zero
go
package errorx import ( "errors" "testing" "github.com/stretchr/testify/assert" ) func TestChain(t *testing.T) { errDummy := errors.New("dummy") assert.Nil(t, Chain(func() error { return nil }, func() error { return nil })) assert.Equal(t, errDummy, Chain(func() error { return errDummy }, func() error...
fim
zeromicro/go-zero
go
<|fim_suffix|>or, errs ...error) bool { for _, each := range errs { if errors.Is(err, each) { return true } } return false } <|fim_prefix|>package errorx import "errors" //<|fim_middle|> In checks if the given err is one of errs. func In(err err<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_suffix|> t.Errorf("In() = %v, want %v", got, tt.want) } }) } } <|fim_prefix|>package errorx import ( "errors" "testing" ) func TestIn(t *testing.T) { err1 := errors.New("error 1") err2 := errors.New("error 2") err3 := errors.New("error 3") tests := []struct { name string err error errs []...
fim
zeromicro/go-zero
go
<|fim_suffix|>err) } // Wrapf returns an error that wraps err with given format and args. func Wrapf(err error, format string, args ...any) error { if err == nil { return nil } return fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), err) } <|fim_prefix|>package errorx import "fmt" // Wrap returns an error th...
fim
zeromicro/go-zero
go
<|fim_prefix|>package errorx import ( "errors" "testing" "github.com/stretchr/test<|fim_suffix|> { assert.Nil(t, Wrapf(nil, "%s", "test")) assert.Equal(t, "foo bar: quz", Wrapf(errors.New("quz"), "foo %s", "bar").Error()) err := errors.New("foo") assert.True(t, errors.Is(Wrapf(err, "foo %s", "bar"), err)) } <...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import "time" const defaultBulkTasks = 1000 type ( // BulkOption defines the method to customize a BulkExecutor. BulkOption func(options *bulkOptions) // A BulkExecutor is an executor that can execute tasks on either requirement meets: // 1. up to given size of tasks // 2. flush...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import ( "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func TestBulkExecutor(t *testing.T) { var values []int var lock sync.Mutex executor := NewBulkExecutor(func(items []any) { lock.Lock() values = append(values, len(items)) lock.Unlock() }, WithBulkTa...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import "time" const defaultChunkSize = 1024 * 1024 // 1M type ( // ChunkOption defines the method to customize a ChunkExecutor. ChunkOption func(options *chunkOptions) // A ChunkExecutor is an executor to execute tasks when either requirement meets: // 1. up to given chunk size ...
fim
zeromicro/go-zero
go
<|fim_suffix|>stChunkExecutorFlush(t *testing.T) { const ( caches = 10 tasks = 5 ) var wait sync.WaitGroup wait.Add(1) be := NewChunkExecutor(func(items []any) { assert.Equal(t, tasks, len(items)) wait.Done() }, WithChunkBytes(caches), WithFlushInterval(time.Minute)) for i := 0; i < tasks; i++ { be.A...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import ( "sync" "time" "github.com/zeromicro/go-zero/core/threading" ) // A DelayExecutor delays a tasks on given delay interval. type DelayExecutor struct { fn func() delay time.Duration triggered bool lock sync.Mutex } // NewDelayExecutor returns a DelayExecu...
fim
zeromicro/go-zero
go
package executors import ( "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" ) func TestDelayExecutor(t *testing.T) { var count int32 ex := NewDelayExecutor(func() { atomic.AddInt32(&count, 1) }, time.Millisecond*10) for i := 0; i < 100; i++ { ex.Trigger() } time.Sleep(time.Millisecon...
fim
zeromicro/go-zero
go
<|fim_suffix|>reshold time.Duration) *LessExecutor { return &LessExecutor{ threshold: threshold, lastTime: syncx.NewAtomicDuration(), } } // DoOrDiscard executes or discards the task depends on if // another task was executed within the time interval. func (le *LessExecutor) DoOrDiscard(execute func()) bool { ...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/timex" ) func TestLessExecutor_DoOrDiscard(t *testing.T) { executor := NewLessExecutor(time.Minute) assert.True(t, executor.DoOrDiscard(func() {})) assert.False(t, executor.DoOrDis...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import ( "reflect" "sync" "sync/atomic" "time" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/core/threading" "github.com/zeromicro/go-zero/core/timex" ) const idleRound...
fim
zeromicro/go-zero
go
<|fim_prefix|>package executors import ( "runtime" "sync" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/core/timex" ) const threshold = 10 type container struct { interval time.Duration tasks []int execute fu...
fim
zeromicro/go-zero
go
<|fim_suffix|>method to execute tasks. type Execute func(tasks []any) <|fim_prefix|>package executors import<|fim_middle|> "time" const defaultFlushInterval = time.Second // Execute defines the <|endoftext|>
fim
zeromicro/go-zero
go
<|fim_suffix|>:n-1] n-- } else { buf = buf[:n] } for i := n - 1; i >= 0; i-- { if buf[i] == '\n' { return string(append(buf[i+1:], last...)), nil } } last = append(buf, last...) } return string(last), nil } <|fim_prefix|>package filex import ( "io" "os" ) const bufSize = 1024 // Firs...
fim
zeromicro/go-zero
go
<|fim_suffix|> filename, err := fs.TempFilenameWithText(string(content)) assert.Nil(t, err) defer os.Remove(filename) val, err := FirstLine(filename) assert.Nil(t, err) assert.Equal(t, string(content[:bufSize-1]), val) } func TestLastLineExactlyBufSize(t *testing.T) { content := make([]byte, bufSize) for i :...
fim
zeromicro/go-zero
go
<|fim_suffix|>= 0; i < n; i++ { if skipBuf[i] != '\r' && skipBuf[i] != '\n' { offset++ } else { for ; i < n; i++ { if skipBuf[i] == '\r' || skipBuf[i] == '\n' { offset++ } else { return offset, nil } } return offset, nil } } } } <|fim_prefix|>package filex import ...
fim
zeromicro/go-zero
go