nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: zeromicro/go-zero
Pull request #1962 (2022-06-03 12:18:04)

Chore/goctl version


Patch:
diff --git a/readme-cn.md b/readme-cn.md
index 92ac45ae..df80be41 100644
--- a/readme-cn.md
+++ b/readme-cn.md
@@ -23,7 +23,7 @@
 > 
 > `GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/go-zero/tools/goctl@latest`
 > 
-> `goctl migrate —verbose —version v1.3.3`
+> `goctl migrate —verbose —version v1.3.4`
 
 ## 0. go-zero 介绍
 
diff --git a/readme.md b/readme.md
index c79c53d0..ca1bcf1e 100644
--- a/readme.md
+++ b/readme.md
@@ -21,7 +21,7 @@ English | [简体中文](readme-cn.md)
 > 
 > `go install github.com/zeromicro/go-zero/tools/goctl@latest`
 > 
-> `goctl migrate —verbose —version v1.3.3`
+> `goctl migrate —verbose —version v1.3.4`
 
 ## 0. what is go-zero
 
diff --git a/tools/goctl/internal/version/version.go b/tools/goctl/internal/version/version.go
index 234832de..6a15e97b 100644
--- a/tools/goctl/internal/version/version.go
+++ b/tools/goctl/internal/version/version.go
@@ -6,7 +6,7 @@ import (
 )
 
 // BuildVersion is the version of goctl.
-const BuildVersion = "1.3.6"
+const BuildVersion = "1.3.7"
 
 var tag = map[string]int{"pre-alpha": 0, "alpha": 1, "pre-bata": 2, "beta": 3, "released": 4, "": 5}
 


Test patch:
diff --git a/core/logx/logs_test.go b/core/logx/logs_test.go
index 71038ca3..e3aadf93 100644
--- a/core/logx/logs_test.go
+++ b/core/logx/logs_test.go
@@ -709,7 +709,6 @@ func put(b []byte) {
 func doTestStructedLog(t *testing.T, level string, w *mockWriter, write func(...interface{})) {
 	const message = "hello there"
 	write(message)
-	fmt.Println(w.String())
 	var entry logEntry
 	if err := json.Unmarshal([]byte(w.String()), &entry); err != nil {
 		t.Error(err)
diff --git a/core/logx/tracelogger_test.go b/core/logx/tracelogger_test.go
index 8f8fe1b4..0866b663 100644
--- a/core/logx/tracelogger_test.go
+++ b/core/logx/tracelogger_test.go
@@ -3,7 +3,6 @@ package logx
 import (
 	"context"
 	"encoding/json"
-	"fmt"
 	"strings"
 	"sync/atomic"
 	"testing"
@@ -65,11 +64,9 @@ func TestTraceError(t *testing.T) {
 	validate(t, w.String(), true, true)
 	w.Reset()
 	l.WithDuration(time.Second).Errorv(testlog)
-	fmt.Println(w.String())
 	validate(t, w.String(), true, true)
 	w.Reset()
 	l.WithDuration(time.Second).Errorw(testlog, Field("foo", "bar"))
-	fmt.Println(w.String())
 	validate(t, w.String(), true, true)
 	assert.True(t, strings.Contains(w.String(), "foo"), w.String())
 	assert.True(t, strings.Contains(w.String(), "bar"), w.String())
@@ -165,7 +162,6 @@ func TestTraceSlow(t *testing.T) {
 	assert.True(t, strings.Contains(w.String(), spanKey))
 	w.Reset()
 	l.WithDuration(time.Second).Slowf(testlog)
-	fmt.Println("buf:", w.String())
 	validate(t, w.String(), true, true)
 	w.Reset()
 	l.WithDuration(time.Second).Slowv(testlog)
Repository: zeromicro/go-zero
Pull request #1967 (2022-06-04 11:32:37)

chore: make print pretty


Patch:
diff --git a/rest/engine.go b/rest/engine.go
index fad45771..224c5906 100644
--- a/rest/engine.go
+++ b/rest/engine.go
@@ -196,8 +196,9 @@ func (ng *engine) print() {
 
 	sort.Strings(routes)
 
+	fmt.Println("routes:")
 	for _, route := range routes {
-		fmt.Println(route)
+		fmt.Printf("  %s\n", route)
 	}
 }
 


Test patch:
diff --git a/rest/server_test.go b/rest/server_test.go
index 06dd6d13..98f37736 100644
--- a/rest/server_test.go
+++ b/rest/server_test.go
@@ -350,10 +350,11 @@ func TestServer_PrintRoutes(t *testing.T) {
 Name: foo
 Port: 54321
 `
-		expect = `GET /bar
-GET /foo
-GET /foo/:bar
-GET /foo/:bar/baz
+		expect = `routes:
+  GET /bar
+  GET /foo
+  GET /foo/:bar
+  GET /foo/:bar/baz
 `
 	)
Repository: zeromicro/go-zero
Pull request #1971 (2022-06-05 03:57:31)

chore: make methods consistent in signatures


Patch:
diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go
index 7b6df276..57e05979 100644
--- a/core/mapping/unmarshaler.go
+++ b/core/mapping/unmarshaler.go
@@ -231,7 +231,7 @@ func (u *Unmarshaler) processFieldPrimitive(field reflect.StructField, value ref
 			return u.processFieldPrimitiveWithJSONNumber(field, value, v, opts, fullName)
 		default:
 			if typeKind == valueKind {
-				if err := validateValueInOptions(opts.options(), mapValue); err != nil {
+				if err := validateValueInOptions(mapValue, opts.options()); err != nil {
 					return err
 				}
 
@@ -253,7 +253,7 @@ func (u *Unmarshaler) processFieldPrimitiveWithJSONNumber(field reflect.StructFi
 		return err
 	}
 
-	if err := validateValueInOptions(opts.options(), v); err != nil {
+	if err := validateValueInOptions(v, opts.options()); err != nil {
 		return err
 	}
 
diff --git a/core/mapping/utils.go b/core/mapping/utils.go
index ad336cbc..fee4e99c 100644
--- a/core/mapping/utils.go
+++ b/core/mapping/utils.go
@@ -592,16 +592,16 @@ func validateNumberRange(fv float64, nr *numberRange) error {
 	return nil
 }
 
-func validateValueInOptions(options []string, value interface{}) error {
+func validateValueInOptions(val interface{}, options []string) error {
 	if len(options) > 0 {
-		switch v := value.(type) {
+		switch v := val.(type) {
 		case string:
 			if !stringx.Contains(options, v) {
 				return fmt.Errorf(`error: value "%s" is not defined in options "%v"`, v, options)
 			}
 		default:
 			if !stringx.Contains(options, Repr(v)) {
-				return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, value, options)
+				return fmt.Errorf(`error: value "%v" is not defined in options "%v"`, val, options)
 			}
 		}
 	}


Test patch:
diff --git a/core/logx/tracelogger_test.go b/core/logx/tracelogger_test.go
index 7dac6d01..fc5964ea 100644
--- a/core/logx/tracelogger_test.go
+++ b/core/logx/tracelogger_test.go
@@ -210,7 +210,6 @@ func validate(t *testing.T, body string, expectedTrace, expectedSpan bool) {
 		val = doc
 	}
 
-	assert.Nil(t, json.Unmarshal([]byte(body), &val), body)
 	assert.Equal(t, expectedTrace, len(val.Trace) > 0, body)
 	assert.Equal(t, expectedSpan, len(val.Span) > 0, body)
 }
diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go
index 521e574f..3c113ed1 100644
--- a/core/mapping/unmarshaler_test.go
+++ b/core/mapping/unmarshaler_test.go
@@ -1184,6 +1184,14 @@ func TestUnmarshalWithJsonNumberOptionsIncorrect(t *testing.T) {
 	assert.NotNil(t, UnmarshalKey(m, &in))
 }
 
+func TestUnmarshaler_UnmarshalIntOptions(t *testing.T) {
+	var val struct {
+		Sex int `json:"sex,options=0|1"`
+	}
+	input := []byte(`{"sex": 2}`)
+	assert.NotNil(t, UnmarshalJsonBytes(input, &val))
+}
+
 func TestUnmarshalWithUintOptionsCorrect(t *testing.T) {
 	type inner struct {
 		Value  string `key:"value,options=first|second"`
Repository: zeromicro/go-zero
Pull request #2085 (2022-07-01 15:32:27)

chore: refactor


Patch:
diff --git a/core/mapping/utils.go b/core/mapping/utils.go
index a793ecbe..a6fff1a1 100644
--- a/core/mapping/utils.go
+++ b/core/mapping/utils.go
@@ -60,20 +60,6 @@ func Deref(t reflect.Type) reflect.Type {
 	return t
 }
 
-// DerefVal dereferences a value, if pointer value nil set new a value, returns is not a ptr element value.
-func DerefVal(v reflect.Value) reflect.Value {
-	for {
-		if v.Kind() != reflect.Ptr {
-			break
-		}
-		if v.IsNil() {
-			v.Set(reflect.New(v.Type().Elem()))
-		}
-		v = v.Elem()
-	}
-	return v
-}
-
 // Repr returns the string representation of v.
 func Repr(v interface{}) string {
 	if v == nil {
@@ -157,6 +143,23 @@ func doParseKeyAndOptions(field reflect.StructField, value string) (string, *fie
 	return key, &fieldOpts, nil
 }
 
+// ensureValue ensures nested members not to be nil.
+// If pointer value is nil, set to a new value.
+func ensureValue(v reflect.Value) reflect.Value {
+	for {
+		if v.Kind() != reflect.Ptr {
+			break
+		}
+
+		if v.IsNil() {
+			v.Set(reflect.New(v.Type().Elem()))
+		}
+		v = v.Elem()
+	}
+
+	return v
+}
+
 func implicitValueRequiredStruct(tag string, tp reflect.Type) (bool, error) {
 	numFields := tp.NumField()
 	for i := 0; i < numFields; i++ {
@@ -491,8 +494,8 @@ func setValue(kind reflect.Kind, value reflect.Value, str string) error {
 	if !value.CanSet() {
 		return errValueNotSettable
 	}
-	value = DerefVal(value)
 
+	value = ensureValue(value)
 	v, err := convertType(kind, str)
 	if err != nil {
 		return err


Test patch:
diff --git a/core/mapping/utils_test.go b/core/mapping/utils_test.go
index eac00beb..dec08584 100644
--- a/core/mapping/utils_test.go
+++ b/core/mapping/utils_test.go
@@ -100,7 +100,7 @@ func TestDerefValInt(t *testing.T) {
 
 	for _, each := range cases {
 		t.Run(each.t.String(), func(t *testing.T) {
-			assert.Equal(t, each.expect, DerefVal(each.t).Kind())
+			assert.Equal(t, each.expect, ensureValue(each.t).Kind())
 		})
 	}
 }
Repository: zeromicro/go-zero
Pull request #2182 (2022-07-22 14:59:35)

chore: refactoring


Patch:
diff --git a/core/logx/rotatelogger.go b/core/logx/rotatelogger.go
index 39798f51..5944d593 100644
--- a/core/logx/rotatelogger.go
+++ b/core/logx/rotatelogger.go
@@ -19,14 +19,14 @@ import (
 )
 
 const (
-	rfc3339DateFormat = time.RFC3339
-	dateFormat        = "2006-01-02"
-	hoursPerDay       = 24
-	bufferSize        = 100
-	defaultDirMode    = 0o755
-	defaultFileMode   = 0o600
-	gzipExt           = ".gz"
-	megaBytes         = 1 << 20
+	dateFormat      = "2006-01-02"
+	fileTimeFormat  = time.RFC3339
+	hoursPerDay     = 24
+	bufferSize      = 100
+	defaultDirMode  = 0o755
+	defaultFileMode = 0o600
+	gzipExt         = ".gz"
+	megaBytes       = 1 << 20
 )
 
 // ErrLogFileClosed is an error that indicates the log file is already closed.
@@ -195,7 +195,7 @@ func (r *SizeLimitRotateRule) OutdatedFiles() []string {
 
 	// test if any too old backups
 	if r.days > 0 {
-		boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay*r.days)).Format(rfc3339DateFormat)
+		boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay*r.days)).Format(fileTimeFormat)
 		boundaryFile := filepath.Join(dir, fmt.Sprintf("%s%s%s%s", prefix, r.delimiter, boundary, ext))
 		if r.gzip {
 			boundaryFile += gzipExt
@@ -413,7 +413,7 @@ func getNowDate() string {
 }
 
 func getNowDateInRFC3339Format() string {
-	return time.Now().Format(rfc3339DateFormat)
+	return time.Now().Format(fileTimeFormat)
 }
 
 func gzipFile(file string) error {
diff --git a/zrpc/internal/rpcpubserver.go b/zrpc/internal/rpcpubserver.go
index de720c95..5a2a5136 100644
--- a/zrpc/internal/rpcpubserver.go
+++ b/zrpc/internal/rpcpubserver.go
@@ -41,12 +41,12 @@ type keepAliveServer struct {
 	Server
 }
 
-func (ags keepAliveServer) Start(fn RegisterFn) error {
-	if err := ags.registerEtcd(); err != nil {
+func (s keepAliveServer) Start(fn RegisterFn) error {
+	if err := s.registerEtcd(); err != nil {
 		return err
 	}
 
-	return ags.Server.Start(fn)
+	return s.Server.Start(fn)
 }
 
 func figureOutListenOn(listenOn string) string {


Test patch:
diff --git a/core/logx/rotatelogger_test.go b/core/logx/rotatelogger_test.go
index 75865c09..51cc888d 100644
--- a/core/logx/rotatelogger_test.go
+++ b/core/logx/rotatelogger_test.go
@@ -51,7 +51,7 @@ func TestSizeLimitRotateRuleOutdatedFiles(t *testing.T) {
 
 func TestSizeLimitRotateRuleShallRotate(t *testing.T) {
 	var rule SizeLimitRotateRule
-	rule.rotatedTime = time.Now().Add(time.Hour * 24).Format(rfc3339DateFormat)
+	rule.rotatedTime = time.Now().Add(time.Hour * 24).Format(fileTimeFormat)
 	rule.maxSize = 0
 	assert.False(t, rule.ShallRotate(0))
 	rule.maxSize = 100
Repository: zeromicro/go-zero
Pull request #2186 (2022-07-24 05:18:46)

chore: let logx.SetWriter can be called anytime


Patch:
diff --git a/core/logx/logs.go b/core/logx/logs.go
index a9116806..aa72fe73 100644
--- a/core/logx/logs.go
+++ b/core/logx/logs.go
@@ -199,11 +199,8 @@ func SetLevel(level uint32) {
 }
 
 // SetWriter sets the logging writer. It can be used to customize the logging.
-// Call Reset before calling SetWriter again.
 func SetWriter(w Writer) {
-	if writer.Load() == nil {
-		writer.Store(w)
-	}
+	writer.Store(w)
 }
 
 // SetUp sets up the logx. If already set up, just return nil.
diff --git a/zrpc/internal/serverinterceptors/statinterceptor.go b/zrpc/internal/serverinterceptors/statinterceptor.go
index 05cd04b4..37ff6025 100644
--- a/zrpc/internal/serverinterceptors/statinterceptor.go
+++ b/zrpc/internal/serverinterceptors/statinterceptor.go
@@ -69,8 +69,7 @@ func logDuration(ctx context.Context, method string, req interface{}, duration t
 		if err != nil {
 			logx.WithContext(ctx).Errorf("%s - %s", addr, err.Error())
 		} else if duration > slowThreshold.Load() {
-			logger.Slowf("[RPC] slowcall - %s - %s - %s",
-				addr, method, string(content))
+			logger.Slowf("[RPC] slowcall - %s - %s - %s", addr, method, string(content))
 		} else {
 			logger.Infof("%s - %s - %s", addr, method, string(content))
 		}


Test patch:
diff --git a/core/logx/logs_test.go b/core/logx/logs_test.go
index e3aadf93..89faeb16 100644
--- a/core/logx/logs_test.go
+++ b/core/logx/logs_test.go
@@ -603,8 +603,9 @@ func TestSetWriter(t *testing.T) {
 	SetWriter(nopWriter{})
 	assert.NotNil(t, writer.Load())
 	assert.True(t, writer.Load() == nopWriter{})
-	SetWriter(new(mockWriter))
-	assert.True(t, writer.Load() == nopWriter{})
+	mocked := new(mockWriter)
+	SetWriter(mocked)
+	assert.Equal(t, mocked, writer.Load())
 }
 
 func TestWithGzip(t *testing.T) {
Repository: zeromicro/go-zero
Pull request #2255 (2022-08-11 14:28:19)

fix: time repr wrapper


Patch:
diff --git a/core/stores/sqlx/utils.go b/core/stores/sqlx/utils.go
index d10ae88b..58428ecc 100644
--- a/core/stores/sqlx/utils.go
+++ b/core/stores/sqlx/utils.go
@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"strconv"
 	"strings"
+	"time"
 
 	"github.com/zeromicro/go-zero/core/logx"
 	"github.com/zeromicro/go-zero/core/mapping"
@@ -152,6 +153,14 @@ func writeValue(buf *strings.Builder, arg interface{}) {
 		buf.WriteByte('\'')
 		buf.WriteString(escape(v))
 		buf.WriteByte('\'')
+	case time.Time:
+		buf.WriteByte('\'')
+		buf.WriteString(v.String())
+		buf.WriteByte('\'')
+	case *time.Time:
+		buf.WriteByte('\'')
+		buf.WriteString(v.String())
+		buf.WriteByte('\'')
 	default:
 		buf.WriteString(mapping.Repr(v))
 	}


Test patch:
diff --git a/core/stores/sqlx/utils_test.go b/core/stores/sqlx/utils_test.go
index c3761c5e..f09e5ae4 100644
--- a/core/stores/sqlx/utils_test.go
+++ b/core/stores/sqlx/utils_test.go
@@ -3,6 +3,7 @@ package sqlx
 import (
 	"strings"
 	"testing"
+	"time"
 
 	"github.com/stretchr/testify/assert"
 )
@@ -138,3 +139,14 @@ func TestFormat(t *testing.T) {
 		})
 	}
 }
+
+func TestWriteValue(t *testing.T) {
+	var buf strings.Builder
+	tm := time.Now()
+	writeValue(&buf, &tm)
+	assert.Equal(t, "'"+tm.String()+"'", buf.String())
+
+	buf.Reset()
+	writeValue(&buf, tm)
+	assert.Equal(t, "'"+tm.String()+"'", buf.String())
+}
Repository: zeromicro/go-zero
Pull request #2312 (2022-08-28 01:29:09)

chore: remove unused packages


Patch:
diff --git a/go.mod b/go.mod
index 4bf784af..0e1eee19 100644
--- a/go.mod
+++ b/go.mod
@@ -16,7 +16,6 @@ require (
 	github.com/golang/protobuf v1.5.2
 	github.com/google/uuid v1.3.0
 	github.com/jhump/protoreflect v1.12.0
-	github.com/justinas/alice v1.2.0
 	github.com/lib/pq v1.10.6
 	github.com/olekukonko/tablewriter v0.0.5
 	github.com/pelletier/go-toml/v2 v2.0.5
diff --git a/go.sum b/go.sum
index 3494820f..6dd18ba3 100644
--- a/go.sum
+++ b/go.sum
@@ -280,8 +280,6 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1
 github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
 github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
 github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
-github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
-github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
 github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
 github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
 github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=


Test patch:
diff --git a/rest/handler/tracinghandler_test.go b/rest/handler/tracinghandler_test.go
index 94af55e0..7f1948dd 100644
--- a/rest/handler/tracinghandler_test.go
+++ b/rest/handler/tracinghandler_test.go
@@ -6,9 +6,9 @@ import (
 	"net/http/httptest"
 	"testing"
 
-	"github.com/justinas/alice"
 	"github.com/stretchr/testify/assert"
 	ztrace "github.com/zeromicro/go-zero/core/trace"
+	"github.com/zeromicro/go-zero/rest/chain"
 	"go.opentelemetry.io/otel"
 	"go.opentelemetry.io/otel/propagation"
 	"go.opentelemetry.io/otel/trace"
@@ -24,7 +24,7 @@ func TestOtelHandler(t *testing.T) {
 
 	for _, test := range []string{"", "bar"} {
 		t.Run(test, func(t *testing.T) {
-			h := alice.New(TracingHandler("foo", test)).Then(
+			h := chain.New(TracingHandler("foo", test)).Then(
 				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 					ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
 					spanCtx := trace.SpanContextFromContext(ctx)
Repository: zeromicro/go-zero
Pull request #2316 (2022-08-28 09:03:38)

refactor: sequential range over safemap


Patch:
diff --git a/core/collection/safemap.go b/core/collection/safemap.go
index 7be1e4af..4856f147 100644
--- a/core/collection/safemap.go
+++ b/core/collection/safemap.go
@@ -68,6 +68,24 @@ func (m *SafeMap) Get(key interface{}) (interface{}, bool) {
 	return val, ok
 }
 
+// Range calls f sequentially for each key and value present in the map.
+// If f returns false, range stops the iteration.
+func (m *SafeMap) Range(f func(key, val interface{}) bool) {
+	m.lock.RLock()
+	defer m.lock.RUnlock()
+
+	for k, v := range m.dirtyOld {
+		if !f(k, v) {
+			return
+		}
+	}
+	for k, v := range m.dirtyNew {
+		if !f(k, v) {
+			return
+		}
+	}
+}
+
 // Set sets the value into m with the given key.
 func (m *SafeMap) Set(key, value interface{}) {
 	m.lock.Lock()
@@ -94,31 +112,3 @@ func (m *SafeMap) Size() int {
 	m.lock.RUnlock()
 	return size
 }
-
-// Range calls f sequentially for each key and value present in the map.
-// If f returns false, range stops the iteration.
-// Range m .
-func (m *SafeMap) Range(f func(key, value interface{}) bool) {
-	m.lock.RLock()
-	defer m.lock.RUnlock()
-	var wg sync.WaitGroup
-
-	wg.Add(2)
-	go func() {
-		for k, v := range m.dirtyOld {
-			if !f(k, v) {
-				break
-			}
-		}
-		wg.Done()
-	}()
-	go func() {
-		for k, v := range m.dirtyNew {
-			if !f(k, v) {
-				break
-			}
-		}
-		wg.Done()
-	}()
-	wg.Wait()
-}


Test patch:
diff --git a/core/collection/safemap_test.go b/core/collection/safemap_test.go
index 4e9ca1d7..24f42152 100644
--- a/core/collection/safemap_test.go
+++ b/core/collection/safemap_test.go
@@ -1,7 +1,7 @@
 package collection
 
 import (
-	"go.uber.org/atomic"
+	"sync/atomic"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -115,8 +115,9 @@ func TestSafeMap_Range(t *testing.T) {
 		exception1 = 5
 		exception2 = 500
 	)
+
 	m := NewSafeMap()
-	m_new := NewSafeMap()
+	newMap := NewSafeMap()
 
 	for i := 0; i < size; i++ {
 		m.Set(i, i)
@@ -136,14 +137,13 @@ func TestSafeMap_Range(t *testing.T) {
 		}
 	}
 
-	count := atomic.Int32{}
+	var count int32
 	m.Range(func(k, v interface{}) bool {
-		count.Add(1)
-		m_new.Set(k, v)
+		atomic.AddInt32(&count, 1)
+		newMap.Set(k, v)
 		return true
 	})
-	assert.Equal(t, int(count.Load()), m.Size())
-	assert.Equal(t, m.dirtyNew, m_new.dirtyNew)
-	assert.Equal(t, m.dirtyOld, m_new.dirtyOld)
-
+	assert.Equal(t, int(atomic.LoadInt32(&count)), m.Size())
+	assert.Equal(t, m.dirtyNew, newMap.dirtyNew)
+	assert.Equal(t, m.dirtyOld, newMap.dirtyOld)
 }
Repository: zeromicro/go-zero
Pull request #2317 (2022-08-28 09:38:18)

fix: range validation on mapping


Patch:
diff --git a/core/mapping/utils.go b/core/mapping/utils.go
index 7f052bdf..7d8af4df 100644
--- a/core/mapping/utils.go
+++ b/core/mapping/utils.go
@@ -311,10 +311,20 @@ func parseNumberRange(str string) (*numberRange, error) {
 		right = math.MaxFloat64
 	}
 
-	if left >= right {
+	if left > right {
 		return nil, errNumberRange
 	}
 
+	// [2:2] valid
+	// [2:2) invalid
+	// (2:2] invalid
+	// (2:2) invalid
+	if left == right {
+		if !leftInclude || !rightInclude {
+			return nil, errNumberRange
+		}
+	}
+
 	return &numberRange{
 		left:         left,
 		leftInclude:  leftInclude,


Test patch:
diff --git a/core/mapping/marshaler_test.go b/core/mapping/marshaler_test.go
index fe98b8f6..5e34dd85 100644
--- a/core/mapping/marshaler_test.go
+++ b/core/mapping/marshaler_test.go
@@ -281,6 +281,58 @@ func TestMarshal_RangeIllegal(t *testing.T) {
 	}
 }
 
+func TestMarshal_RangeLeftEqualsToRight(t *testing.T) {
+	tests := []struct {
+		name  string
+		value interface{}
+		err   error
+	}{
+		{
+			name: "left inclusive, right inclusive",
+			value: struct {
+				Int int `json:"int,range=[2:2]"`
+			}{
+				Int: 2,
+			},
+		},
+		{
+			name: "left inclusive, right exclusive",
+			value: struct {
+				Int int `json:"int,range=[2:2)"`
+			}{
+				Int: 2,
+			},
+			err: errNumberRange,
+		},
+		{
+			name: "left exclusive, right inclusive",
+			value: struct {
+				Int int `json:"int,range=(2:2]"`
+			}{
+				Int: 2,
+			},
+			err: errNumberRange,
+		},
+		{
+			name: "left exclusive, right exclusive",
+			value: struct {
+				Int int `json:"int,range=(2:2)"`
+			}{
+				Int: 2,
+			},
+			err: errNumberRange,
+		},
+	}
+
+	for _, test := range tests {
+		test := test
+		t.Run(test.name, func(t *testing.T) {
+			_, err := Marshal(test.value)
+			assert.Equal(t, test.err, err)
+		})
+	}
+}
+
 func TestMarshal_FromString(t *testing.T) {
 	v := struct {
 		Age int `json:"age,string"`
Repository: zeromicro/go-zero
Pull request #2409 (2022-09-18 06:47:38)

chore: add more tests


Patch:
diff --git a/gateway/internal/eventhandler.go b/gateway/internal/eventhandler.go
index a840930f..e3a0f0c2 100644
--- a/gateway/internal/eventhandler.go
+++ b/gateway/internal/eventhandler.go
@@ -27,15 +27,6 @@ func NewEventHandler(writer io.Writer, resolver jsonpb.AnyResolver) *EventHandle
 	}
 }
 
-func (h *EventHandler) OnResolveMethod(_ *desc.MethodDescriptor) {
-}
-
-func (h *EventHandler) OnSendHeaders(_ metadata.MD) {
-}
-
-func (h *EventHandler) OnReceiveHeaders(_ metadata.MD) {
-}
-
 func (h *EventHandler) OnReceiveResponse(message proto.Message) {
 	if err := h.marshaler.Marshal(h.writer, message); err != nil {
 		logx.Error(err)
@@ -45,3 +36,12 @@ func (h *EventHandler) OnReceiveResponse(message proto.Message) {
 func (h *EventHandler) OnReceiveTrailers(status *status.Status, _ metadata.MD) {
 	h.Status = status
 }
+
+func (h *EventHandler) OnResolveMethod(_ *desc.MethodDescriptor) {
+}
+
+func (h *EventHandler) OnSendHeaders(_ metadata.MD) {
+}
+
+func (h *EventHandler) OnReceiveHeaders(_ metadata.MD) {
+}


Test patch:
diff --git a/gateway/internal/eventhandler_test.go b/gateway/internal/eventhandler_test.go
new file mode 100644
index 00000000..cf81ace1
--- /dev/null
+++ b/gateway/internal/eventhandler_test.go
@@ -0,0 +1,20 @@
+package internal
+
+import (
+	"io"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+)
+
+func TestEventHandler(t *testing.T) {
+	h := NewEventHandler(io.Discard, nil)
+	h.OnResolveMethod(nil)
+	h.OnSendHeaders(nil)
+	h.OnReceiveHeaders(nil)
+	h.OnReceiveTrailers(status.New(codes.OK, ""), nil)
+	assert.Equal(t, codes.OK, h.Status.Code())
+	h.OnReceiveResponse(nil)
+}