text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
package filex
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
)
func TestSplitLineChunks(t *testing.T) {
const text = `first line
second line
third line
fourth line
fifth line
sixth line
seventh line
`
fp, err := fs.TempFileWithText(text)
assert.Nil(t, err)
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package filex
import "gopkg.in/cheggaaa/pb.v1"
type (
// A Scanner is used to read lines.
Scanner interface {
// Scan checks if it has remaining to read.
Scan() bool
// Text returns next line.
Text() string
}
progressScanner <|fim_suffix|>64(len(s)) + 1) // take newlines into account
retur... | fim | zeromicro/go-zero | go |
<|fim_suffix|>c (s *mockedScanner) Scan() bool {
return s.builder.Len() > 0
}
func (s *mockedScanner) Text() string {
return s.builder.String()
}
<|fim_prefix|>package filex
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/cheggaaa/pb.v1"
)
func TestProgressScanner(t *testing.T) {
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package filex
import (
"error<|fim_suffix|> p = p[:rr.stop-rr.start]
}
n, err = rr.file.ReadAt(p, rr.start)
if err != nil {
return n, err
}
rr.start += int64(n)
return
}
<|fim_middle|>s"
"os"
)
// errExceedFileSize indicates that the file size is exceeded.
var errExceedFileSize = errors.New... | fim | zeromicro/go-zero | go |
<|fim_suffix|>(file.Name())
}()
reader := NewRangeReader(file, 5, 8)
buf := make([]byte, 10)
n, err := reader.Read(buf)
assert.Nil(t, err)
assert.Equal(t, 3, n)
assert.Equal(t, `
wo`, string(buf[:n]))
}
func TestRangeReader_OutOfRange(t *testing.T) {
const text = `hello
world`
file, err := fs.TempFileWithTex... | fim | zeromicro/go-zero | go |
<|fim_suffix|>{
}
<|fim_prefix|>//go:build windows
package fs
import "os"
func CloseOnExec(*os.F<|fim_middle|>ile) <|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>//go:build linux || darwin || freebsd
package fs
import <|fim_suffix|> "syscall"
)
// CloseOnExec makes sure closing the file on process forking.
func CloseOnExec(file *os.File) {
if file != nil {
syscall.CloseOnExec(int(file.Fd()))
}
}
<|fim_middle|>(
"os"
<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fs
import (
"os"
"testing"
"<|fim_suffix|>tchr/testify/assert"
)
func TestCloseOnExec(t *testing.T) {
file := os.NewFile(0, os.DevNull)
assert.NotPanics(t, func() {
CloseOnExec(file)
})
}
<|fim_middle|>github.com/stre<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>c TempFileWithText(text string) (*os.File, error) {
tmpFile, err := os.CreateTemp(os.TempDir(), hash.Md5Hex([]byte(text)))
if err != nil {
return nil, err
}
if err := os.WriteFile(tmpFile.Name(), []byte(text), os.ModeTemporary); err != nil {
return nil, err
}
return tmpFile, nil
}
// TempFile... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package f<|fim_suffix|>r)
if len(bs) != 4 {
t.Error("TempFileWithText returned wrong file size")
}
if f.Close() != nil {
t.Error("TempFileWithText returned error on close")
}
}
func TestTempFilenameWithText(t *testing.T) {
f, err := TempFilenameWithText("test")
if err != nil {
t.Error(err)
}... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fx
import (
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/core/threading"
)
// Parallel runs fns parallelly and waits for done.
func Parallel(fns ...func()) {
group := threading.NewRoutineGroup()
for _, fn := range fns {
group.RunSafe(fn)
}
group.Wait()
}
func... | fim | zeromicro/go-zero | go |
<|fim_suffix|>{
time.Sleep(time.Millisecond * 100)
atomic.AddInt32(&count, 2)
return nil
},
func() error {
time.Sleep(time.Millisecond * 100)
atomic.AddInt32(&count, 3)
return nil
},
)
assert.Equal(t, int32(6), count)
assert.NoError(t, err)
}
<|fim_prefix|>package fx
import (
"errors"
"s... | fim | zeromicro/go-zero | go |
<|fim_suffix|>n retryCount indicates the current number of retries, starting from 0
// Note that if the fn function accesses global variables outside the function
// and performs modification operations, it is best to lock them,
// otherwise there may be data race issues
func DoWithRetryCtx(ctx context.Context, fn func... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fx
import (
"context"
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRetry(t *testing.T) {
assert.NotNil(t, DoWithRetry(func() error {
return errors.New("any")
}))
times1 := 0
assert.Nil(t, DoWithRetry(func() error {
times1++
if times1 == defaultRetryT... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fx
import (
"sort"
"sync"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/threading"
)
const (
defaultWorkers = 16
minWorkers = 1
)
type (
rxOptions struct {
unlimitedWorkers bool
workers int
}... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fx
import (
"math/rand"
"reflect"
"runtime"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
"github.com/zeromicro/go-zero/core/stringx"
"go.uber.org/goleak"
)
func TestBuffer(t *testing.T) {
runCheck... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fx
import (
"context"
"fmt"
"runtime/debug"
"strings"
"time"
)
var (
// ErrCanceled is the error returned when the context is canceled.
ErrCanceled = context.Canceled
// ErrTimeout is the error returned when the context's deadline passes.
ErrTimeout = context.DeadlineExceeded
)
// DoOp... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package fx
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestWithPanic(t *testing.T) {
assert.Panics(t, func() {
<|fim_suffix|>illisecond))
}
func TestWithoutTimeout(t *testing.T) {
assert.Nil(t, DoWithTimeout(func() error {
return nil
}, time.Millisecond*50... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package hash
import (
"fmt"
"sort"
"strconv"
"sync"
"github.com/zeromicro/go-zero/core/lang"
)
const (
// TopWeight is the top weight that one entry might set.
TopWeight = 100
minReplicas = 100
prime = 16777619
)
type (
// Func defines the hash method.
Func func(data []byte) uint64
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package hash
import (
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/mathx"
)
const (
keySize = 20
requestSize = 1000
)
func<|fim_suffix|>Hash(t *testing.T) {
ch := NewCustomConsistentHash(0, nil)
val, ok := ch.Get("any")
assert.False(t,... | fim | zeromicro/go-zero | go |
<|fim_suffix|>.EncodeToString(Md5(data))
}
<|fim_prefix|>package hash
import (
"crypto/md5"
"encoding/hex"
"github.com/spaolacci/murmur3"
)
// Hash returns the hash value of data.
func Hash(data []byte) uint64 {
return murmur3.Sum64(data)
}
// Md5 returns the md5 bytes of data.<|fim_middle|>
func Md5(data []byt... | fim | zeromicro/go-zero | go |
<|fim_suffix|> := 0; i < b.N; i++ {
Hash([]byte(text))
}
}
<|fim_prefix|>package hash
import (
"crypto/md5"
"fmt"
"hash/fnv"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
)
const (
text = "hello, world!\n"
md5Digest = "910c8bc73110b0cd1bc5d2bcae782511"
)
func TestMd5(t *testing.T) {
act... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ewBufferPool(capability int) *BufferPool {
return &BufferPool{
capability: capability,
pool: &sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
},
}
}
// Get returns a bytes.Buffer object from bp.
func (bp *BufferPool) Get() *bytes.Buffer {
buf := bp.pool.Get().(*bytes.Buffer)
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ol(1024)
pool.Put(bytes.NewBuffer(make([]byte, 0, 512)))
val := pool.Get()
assert.IsType(t, new(bytes.Buffer), val)
})
t.Run("with more-cap buf", func(t *testing.T) {
pool := NewBufferPool(1024)
pool.Put(bytes.NewBuffer(make([]byte, 0, 1024<<1)))
val := pool.Get()
assert.IsType(t, new(byt... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package iox
import "io"
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error {
return nil
}
// NopClose<|fim_suffix|>o.WriteCloser {
return nopCloser{w}
}
<|fim_middle|>r returns an io.WriteCloser that does nothing on calling Close.
func NopCloser(w io.Writer) i<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package iox
import (
"testin<|fim_suffix|>tify/assert"
)
func TestNopCloser(t *testing.T) {
closer := NopCloser(nil)
assert.NoError(t, closer.Close())
}
<|fim_middle|>g"
"github.com/stretchr/tes<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|> or
os.Stdout = ow
}
return
}
<|fim_prefix|>package iox
import "os"
<|fim_middle|>// RedirectInOut redirects stdin to r, stdout to w, and callers need to call restore afterward.
func RedirectInOut() (restore func(), err error) {
var r, w *os.File
r, w, err = os.Pipe()
if err != nil {
return
}... | fim | zeromicro/go-zero | go |
package iox
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRedirectInOut(t *testing.T) {
restore, err := RedirectInOut()
assert.Nil(t, err)
defer restore()
}
<|endoftext|> | fim | zeromicro/go-zero | go |
package iox
import (
"bufio"
"bytes"
"io"
"os"
"strings"
)
type (
textReadOptions struct {
keepSpace bool
withoutBlanks bool
omitPrefix string
}
// TextReadOption defines the method to customize the text reading functions.
TextReadOption func(*textReadOptions)
)
// DupReadCloser returns two io... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package iox
import (
"bytes"
"io"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
"github.com/zeromicro/go-zero/core/stringx"
)
func TestReadText(t *testing.T) {
tests := []struct {
input string
expect string
}{
{
input: `a`,
exp... | fim | zeromicro/go-zero | go |
<|fim_suffix|>r) Read(p []byte) (n int, err error) {
n, err = t.r.Read(p)
if n > 0 && t.n > 0 {
limit := int64(n)
if limit > t.n {
limit = t.n
}
if n, err := t.w.Write(p[:limit]); err != nil {
return n, err
}
t.n -= limit
}
return
}
<|fim_prefix|>package iox
import "io"
// LimitTeeReader retur... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
}
n, err := r.Read(dst)
assert.Equal(t, 0, n)
assert.Equal(t, io.EOF, err)
rb = bytes.NewBuffer(src)
pr, pw := io.Pipe()
if assert.NoError(t, pr.Close()) {
r = LimitTeeReader(rb, pw, limit)
n, err := io.ReadFull(r, dst)
assert.Equal(t,... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package iox
import (
"bytes"
"errors"
"io"
"os"
)
const bufSize = 32 * 1024
// CountLines returns the number of lines in the file.
func CountLines(file string) (int, error) {
f, err := os.Open(file)
if err != nil {
return 0, err
}
defer f.Close()
var noEol bool
buf := make([]byte, bufSize)... | fim | zeromicro/go-zero | go |
<|fim_suffix|>nes(file.Name())
assert.Nil(t, err)
assert.Equal(t, 4, lines)
}
func TestCountLinesError(t *testing.T) {
_, err := CountLines("not-exist")
assert.NotNil(t, err)
}
<|fim_prefix|>package iox
import (
"os"
"testing"
"github.com/stretchr/testify/asser<|fim_middle|>t"
)
func TestCountLines(t *testin... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package iox
import (
"bufio"
"errors"
"io"
"strings"
)
// A TextLineScanner is a scanner that can scan lines from the given reader.
type TextLineScanner struct {
reader *bufio.Reader
hasNext bool
lin<|fim_suffix|>nner.err = err
return false
}
return true
}
// Line returns the next available... | fim | zeromicro/go-zero | go |
<|fim_suffix|>sert.False(t, scanner.Scan())
_, err := scanner.Line()
assert.ErrorIs(t, err, iotest.ErrTimeout)
}
<|fim_prefix|>package iox
import (
"strings"
"testing"
"testing/iotest"
"github.com/stretc<|fim_middle|>hr/testify/assert"
)
func TestScanner(t *testing.T) {
const val = `1
2
3
4`
reader := string... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package jsonx
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
)
// Marshal marshals v into json bytes, without escaping HTML and removes the trailing newline.
func Marshal(v any) ([]byte, error) {
// why not use json.Marshal? https://github.com/golang/go/issues/28453
// it changes the beha... | fim | zeromicro/go-zero | go |
<|fim_suffix|>name=test&age=25"},
want: []byte(`"https://example.com/api?name=test&age=25"`),
wantErr: assert.NoError,
},
{
name: "url with encoded query params",
args: args{"https://example.com/api?data=hello%20world&special=%26%3D"},
want: []byte(`"https://example.com/api?data=hello%20w... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package lang
import (
"fmt"
"reflect"
"strconv"
)
// Placeholder is a placeholder object that can be used globally.
var Placeholder PlaceholderType
type (
// AnyType can be used to hold any type.
AnyType = any
// PlaceholderType represents a placeholder type.
PlaceholderType = struct{}
)
// Rep... | fim | zeromicro/go-zero | go |
<|fim_suffix|>d"
}
type mockPtr struct{}
func newMockPtr() *mockPtr {
return new(mockPtr)
}
func (m *mockPtr) String() string {
return "mockptr"
}
type mockOpacity struct {
val int
}
<|fim_prefix|>package lang
import (
"encoding/json"
"errors"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
fu... | fim | zeromicro/go-zero | go |
<|fim_suffix|>wPeriodLimit(period, quota int, limitStore *redis.Redis, keyPrefix string,
opts ...PeriodOption) *PeriodLimit {
limiter := &PeriodLimit{
period: period,
quota: quota,
limitStore: limitStore,
keyPrefix: keyPrefix,
}
for _, opt := range opts {
opt(limiter)
}
return limiter
}
// ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package limit
import (
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
)
func TestPeriodLimit_Take(t *testing.T) {
testPeriodLimit(t)
}
func TestPeriodLim... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package limit
import (
"context"
_ "embed"
"errors"
"fmt"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
xrate "golang.org/x/t<|fim_suffix|>scue", resp)
lim.startMoni... | fim | zeromicro/go-zero | go |
package limit
import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
)
func init() {
logx.Disable()
}
fun... | fim | zeromicro/go-zero | go |
<|fim_suffix|>int64]) {
if b.Sum > result {
result = b.Sum
}
})
return result
}
func (as *adaptiveShedder) minRt() float64 {
// if no requests in previous windows, return defaultMinRt,
// its a reasonable large value to avoid dropping requests.
result := defaultMinRt
as.rtCounter.Reduce(func(b *collecti... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package load
import (
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/stat"
"github.com/z... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package load
type nopShedder struct{}
func newNopShedder()<|fim_suffix|>urn nopShedder{}
}
func (s nopShedder) Allow() (Promise, error) {
return nopPromise{}, nil
}
type nopPromise struct{}
func (p nopPromise) Pass() {
}
func (p nopPromise) Fail() {
}
<|fim_middle|> Shedder {
ret<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package load
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNopShedder(t *testing.T) {
Disable()
shedder<|fim_suffix|>)
for i := 0; i < 1000; i++ {
p, err := shedder.Allow()
assert.Nil(t, err)
p.Fail()
}
p, err := shedder.Allow()
assert.Nil(t, err)
p.Pass()
}
<|fim_m... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package load
import (
"io"
"github.com/zeromicro/go-zero/core/syncx"
)
// A ShedderGroup is<|fim_suffix|>oser) Close() error {
return nil
}
<|fim_middle|> a manager to manage key-based shedders.
type ShedderGroup struct {
options []ShedderOption
manager *syncx.ResourceManager
}
// NewShedderGroup... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package load
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGroup(t *testing.T) {
group <|fim_suffix|>
limiter := group.GetShedder("test")
assert.NotNil(t, limiter)
})
}
func TestShedderClose(t *testing.T) {
var nop nopCloser
assert.Nil(t, nop.Close())
}
<|fim_middle|>:= ... | fim | zeromicro/go-zero | go |
package load
import (
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stat"
)
type (
// A SheddingStat is used to store the statistics for load shedding.
SheddingStat struct {
name string
total int64
pass int64
drop int64
}
snapshot struct {
Tota... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package load
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestSheddingStat(t *testing.T) {
st := NewSheddingStat("any")
for i := 0; i < 3; i++ {
st.IncrementTotal()
}
for i := 0; i < 5; i++ {
st.IncrementPass()
}
for i := 0; i < 7; i++ {
st.IncrementDrop()
}
re... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t, msg string, fields ...LogField) {
getLogger(ctx).Errorw(msg, fields...)
}
// Field returns a LogField for the given key and value.
func Field(key string, value any) LogField {
return logx.Field(key, value)
}
// Info writes v into access log.
func Info(ctx context.Context, v ...any) {
getLogger(ctx... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t *testing.T) {
buf := logtest.NewCollector(t)
file, line := getFileLine()
Debugw(context.Background(), "foo", Field("a", "b"))
assert.True(t, strings.Contains(buf.String(), fmt.Sprintf("%s:%d", file, line+1)))
}
func TestMust(t *testing.T) {
assert.NotPanics(t, func() {
Must(nil)
})
assert.NotP... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"sync/atomic"
"github.com/zeromicro/go-zero/core/color"
)
// WithColor is a helper function to add color to a string, only in plain encoding.
func WithColor(text string, colour color.Color) string {
if <|fim_suffix|>lour color.Color) string {
if atomic.LoadUint32(&encoding) ==... | fim | zeromicro/go-zero | go |
package logx
import (
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/color"
)
func TestWithColor(t *testing.T) {
old := atomic.SwapUint32(&encoding, plainEncodingType)
defer atomic.StoreUint32(&encoding, old)
output := WithColor("hello", color.BgBlue)
assert.... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
type (
// A LogConf is a logging config.
LogConf struct {
// ServiceName represents the service name.
ServiceName string `json:",optional"`
// Mode represents the logging mode, default is `console`.
// console: log to console.
// file: log to file.
// volume: used in k8s, prepe... | fim | zeromicro/go-zero | go |
<|fim_suffix|>.Context {
return ContextWithFields(ctx, fields...)
}
<|fim_prefix|>package logx
import (
"context"
"sync"
"sync/atomic"
)
var (
globalFields atomic.Value
globalFieldsLock sync.Mutex
)
type fieldsKey struct{}
// AddGlobalFields adds global fields.
func AddGlobalFields(fields ...LogField) {
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"bytes"
"context"
"encoding/json"
"strconv"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAddGlobalFields(t *testing.T) {
var buf bytes.Buffer
writer := NewWriter(&buf)
old := Reset()
SetWriter(writer)
defer SetWriter(old)
Info("hell... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"io"
"os"
)
var fileSys realFileSystem
type (
fileSystem i<|fim_suffix|>.Reader) (int64, error) {
return io.Copy(writer, reader)
}
func (fs realFileSystem) Create(name string) (*os.File, error) {
return os.Create(name)
}
func (fs realFileSystem) Open(name string) (*os.File,... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
//<|fim_suffix|>n the given duration.
func (logger *LessLogger) Error(v ...any) {
logger.logOrDiscard(func() {
Error(v...)
})
}
// Errorf logs v with format into error log or discard it if more than once in the given duration.
func (logger *LessLogger) Errorf(format string, v ...any) {
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>s.Count(w.String(), "\n"))
}
<|fim_prefix|>packa<|fim_middle|>ge logx
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLessLogger_Error(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
l := NewLessLogger(500)
for i := 0; i < 100; i+... | fim | zeromicro/go-zero | go |
<|fim_suffix|> writer,
}
}
func (w *lessWriter) Write(p []byte) (n int, err error) {
w.logOrDiscard(func() {
w.writer.Write(p)
})
return len(p), nil
}
<|fim_prefix|>package logx
import "io"
type lessWriter struct {
<|fim_middle|> *limitedExecutor
writer io.Writer
}
func newLessWriter(writer io.Writer, mill... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package <|fim_suffix|> assert.Nil(t, err)
}
assert.Equal(t, "hello", builder.String())
}
<|fim_middle|>logx
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLessWriter(t *testing.T) {
var builder strings.Builder
w := newLessWriter(&builder, 500)
for i := 0; i < 100... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
)
type limitedExecutor struct {
threshold time.Duration
lastTime *syncx.AtomicDuration
discarded uint32
}
func newLimitedExecutor(milliseconds int) *limitedExecutor {
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github<|fim_suffix|>mic.AddInt32(&run, 1)
})
if test.executed {
assert.Equal(t, int32(1), atomic.LoadInt32(&run))
} else {
assert.Equal(t, int32(0), atomic.LoadInt32(&run))
assert.Equal(t... | fim | zeromicro/go-zero | go |
<|fim_suffix|>info level.
Infof(string, ...any)
// Infofn logs a message at info level.
Infofn(func() any)
// Infov logs a message at info level.
Infov(any)
// Infow logs a message at info level.
Infow(string, ...LogField)
// Slow logs a message at slow level.
Slow(...any)
// Slowf logs a message at slow leve... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"fmt"
"io"
"log"
"os"
"path"
"reflect"
"runtime/debug"
"sync"
"sync/atomic"
"github.com/zeromicro/go-zero/core/sysx"
)
const callerDepth = 4
var (
timeFormat = "2006-01-02T15:04:05.000Z07:00"
encoding uint32 = jsonEncodingType
// maxContentLength is used to ... | fim | zeromicro/go-zero | go |
<|fim_suffix|>func(v ...any) {
Slowf("%s", fmt.Sprint(v...))
})
}
func TestStructedLogSlowfn(t *testing.T) {
t.Run("slowfn with output", func(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
doTestStructedLog(t, levelSlow, w, func(v ...any) {
Slowfn(func() any {
re... | fim | zeromicro/go-zero | go |
<|fim_suffix|> struct {
buf *bytes.Buffer
t *testing.T
}
func Discard(t *testing.T) {
prev := logx.Reset()
logx.SetWriter(logx.NewWriter(io.Discard))
t.Cleanup(func() {
logx.SetWriter(prev)
})
}
func NewCollector(t *testing.T) *Buffer {
var buf bytes.Buffer
writer := logx.NewWriter(&buf)
prev := logx.Re... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logtest
import (
"errors"
"testing"
"github.com/stretchr/tes<|fim_suffix|> c.Reset()
c.buf.WriteString(`{"content":1}`)
assert.Equal(t, "1", c.Content())
}
<|fim_middle|>tify/assert"
"github.com/zeromicro/go-zero/core/logx"
)
func TestCollector(t *testing.T) {
const input = "hello"
c :=... | fim | zeromicro/go-zero | go |
<|fim_suffix|>iter struct {
logger *log.Logger
}
func newLogWriter(logger *log.Logger) logWriter {
return logWriter{
logger: logger,
}
}
func (lw logWriter) Close() error {
return nil
}
func (lw logWriter) Write(data []byte) (int, error) {
lw.logger.Print(string(data))
return len(data), nil
}
<|fim_prefix|>p... | fim | zeromicro/go-zero | go |
package logx
import (
"context"
"fmt"
"time"
"github.com/zeromicro/go-zero/core/timex"
"github.com/zeromicro/go-zero/internal/trace"
)
// WithCallerSkip returns a Logger with given caller skip.
func WithCallerSkip(skip int) Logger {
if skip <= 0 {
return new(richLogger)
}
return &richLogger{
callerSkip:... | fim | zeromicro/go-zero | go |
package logx
import (
"context"
"encoding/json"
"fmt"
"io"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
func TestTraceLog(t *testing.T) {
SetLevel(InfoLevel)
w := new(mockWriter)
old := writer.Sw... | fim | zeromicro/go-zero | go |
<|fim_suffix|>time.Duration(hoursPerDay*r.days)).Format(time.DateOnly)
buf.WriteString(r.filename)
buf.WriteString(r.delimiter)
buf.WriteString(boundary)
if r.gzip {
buf.WriteString(gzipExt)
}
boundaryFile := buf.String()
var outdates []string
for _, file := range files {
if file < boundaryFile {
outdat... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"errors"
"io"
"os"
"path"
"path/filepath"
"sync/atomic"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
"github.com/zeromicro/go-zero/core/stringx"
)
func TestDailyRotateRuleMarkRotated(t *testing.T) {
t.Run("dail... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ny
}
// maskSensitive returns the value returned by MaskSensitive method,
// if the value implements Sensitive interface.
func maskSensitive(v any) any {
if s, ok := v.(Sensitive); ok {
return s.MaskSensitive()
}
return v
}
<|fim_prefix|>package logx
// Sensitive is an interface that defines a met... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"testing"
"github.com/stretchr/testify/assert"
)
const maskedContent = "******"
type User struct {
Name string
Pass string
}
func (u User) MaskSensitive() any {
return User{
Name: u.Name,
Pass: maskedContent,
}
}
type NonSensitiveUser struct {
Name string
Pass strin... | fim | zeromicro/go-zero | go |
<|fim_suffix|>p), nil
}
<|fim_prefix|>pa<|fim_middle|>ckage logx
import "log"
type redirector struct{}
// CollectSysLog redirects system log into logx info
func CollectSysLog() {
log.SetOutput(new(redirector))
}
func (r *redirector) Write(p []byte) (n int, err error) {
Info(string(p))
return len(<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"encoding/json"
"log"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
const testlog = "Stay hungry, stay foolish."
var testobj = map[string]any{"foo": "bar"}
func TestCollectSysLog(t *testing.T) {
CollectSysLog()
content := getContent(captureOutp... | fim | zeromicro/go-zero | go |
package logx
import (
"fmt"
"runtime"
"strings"
"time"
)
func getCaller(callDepth int) string {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
return ""
}
return prettyCaller(file, line)
}
func getTimestamp() string {
return time.Now().Format(timeFormat)
}
func prettyCaller(file string, line in... | fim | zeromicro/go-zero | go |
<|fim_suffix|>_test.go",
line: 1234,
want: "logx/util_test.go:1234",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, prettyCaller(test.file, test.line))
})
}
}
func BenchmarkGetCaller(b *testing.B) {
b.ReportAllocs()
for i := 0; i ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"errors"
"github.com/zeromicro/go-zero/core/syncx"
)
const (
// DebugLevel logs everything
DebugLevel uint32 = iota
// InfoLevel does not include debugs
InfoLevel
// ErrorLevel includes errors, slows, stacks
ErrorLevel
// SevereLevel only log severe messages
SevereLevel
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"path"
"runtime/debug"
"sync"
"sync/atomic"
"time"
fatihcolor "github.com/fatih/color"
"github.com/zeromicro/go-zero/core/color"
"github.com/zeromicro/go-zero/core/errorx"
)
type (
// Writer is the interface for writing logs.
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package logx
import (
"bytes"
"encoding/json"
"errors"
"log"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestNewWriter(t *testing.T) {
const literal = "foo bar"
var buf bytes.Buffer
w := NewWriter(&buf)
w.Info(literal)
assert.Conta... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import "fmt"
const notSymbol = '!'
type (
// use context and OptionalDep option to determine the value of Optional
// nothing to do with context.Context
fieldOptionsWithContext struct {
Inherit bool
FromString bool
Optional bool
Options []string
Default string
... | fim | zeromicro/go-zero | go |
package mapping
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
type Bar struct {
Val string `json:"val"`
}
func TestFieldOptionOptionalDep(t *testing.T) {
var bar Bar
rt := reflect.TypeOf(bar)
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
val, opt, err := parseKeyAndOptio... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"io"
"github.com/zeromicro/go-zero/core/jsonx"
)
const jsonTagKey = "json"
var jsonUnmarshaler = NewUnmarshaler(jsonTagKey)
// UnmarshalJsonBytes unmarshals content into v.
func UnmarshalJsonBytes(content []byte, v any, opts ...UnmarshalOption) error {
return unmarshalJson... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"bytes"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUnmarshalBytes(t *testing.T) {
var c struct {
Name string
}
content := []byte(`{"Name": "liao"}`)
assert.Nil(t, UnmarshalJsonBytes(content, &c))
assert.Equal(t, "liao", c.Name)
}
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>4(v)
case uint:
val = float64(v)
case uint8:
val = float64(v)
case uint16:
val = float64(v)
case uint32:
val = float64(v)
case uint64:
val = float64(v)
case float32:
val = float64(v)
case float64:
val = v
default:
return fmt.Errorf("unknown support type for range %q", value.Type().... | fim | zeromicro/go-zero | go |
package mapping
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMarshal(t *testing.T) {
v := struct {
Name string `path:"name"`
Address string `json:"address,options=[beijing,shanghai]"`
Age int `json:"age"`
Anonymous bool
}{
Name: "kevin",
Address: "shanghai... | fim | zeromicro/go-zero | go |
<|fim_suffix|>
return err
}
return UnmarshalTomlBytes(b, v, opts...)
}
<|fim_prefix|>package mapping
import (
"<|fim_middle|>io"
"github.com/zeromicro/go-zero/internal/encoding"
)
// UnmarshalTomlBytes unmarshals TOML bytes into the given v.
func UnmarshalTomlBytes(content []byte, v any, opts ...UnmarshalOpti... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestUnmarshalToml(t *testing.T) {
const input = `a = "foo"
b = 1
c = "${FOO}"
d = "abcd!@#$112"
`
var val struct {
A string `json:"a"`
B int `json:"b"`
C string `json:"c"`
D string `json:"d"`
}
as... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"encoding"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/jsonx"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/proc"
)
const (
defaultKeyName ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"cmp"
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"github.com/zeromicro/go-zero/core/lang"
)
const (
defaultOption = "default"
envOption = "env"
inheritOption = "inherit"
stringOption = "string"
op... | fim | zeromicro/go-zero | go |
package mapping
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
const testTagName = "key"
type Foo struct {
Str string
StrWithTag string `key:"stringwithtag"`
StrWithTagAndOption string `key:"stringwithtag,string"`
}
func TestDerefInt(t *testing.T) {
i := 1
s :=... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
type (
// A Valuer interface defines the way to get values from the underlying object with keys.
Valuer interface {
// Value gets the value associated with the given key.
Value(key string) (any, bool)
}
// A valuerWithParent defines a node that has a parent node.
valuerWithParen... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMapValuerWithInherit_Value(t *testing.T) {
input := map[string]any{
"discovery": map[string]any{
"host": "localhost",
"port": 8080,
},
"component": map[string]any{
"name": "test",
},
}
valuer := rec... | fim | zeromicro/go-zero | go |
<|fim_suffix|>n err
}
return UnmarshalYamlBytes(b, v, opts...)
}
<|fim_prefix|>package mapping
import (
"io"
"github.com/zeromicro/go-zero/internal/encoding"
)
// UnmarshalYa<|fim_middle|>mlBytes unmarshals content into v.
func UnmarshalYamlBytes(content []byte, v any, opts ...UnmarshalOption) error {
b, err :... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mapping
import (
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/utils/io"
)
func TestUnmarshalYamlBytes(t *testing.T) {
var c struct {
Name string
}
content := []byte(`Name: liao`)
assert.Nil(t, UnmarshalYamlBytes(content, &c))
assert.Equal(t, "liao", c.... | fim | zeromicro/go-zero | go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.