Skip to content

Commit 8d408c5

Browse files
lvan100lianghuan
authored andcommitted
refactor(gs): clean code
1 parent 8707e89 commit 8d408c5

File tree

5 files changed

+113
-82
lines changed

5 files changed

+113
-82
lines changed

gs/gs.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"context"
2121
"reflect"
2222
"runtime"
23+
"strings"
2324

2425
"github.com/go-spring/log"
2526
"github.com/go-spring/spring-core/conf"
@@ -189,7 +190,7 @@ func Property(key string, val string) {
189190
_, file, _, _ := runtime.Caller(1)
190191
fileID := gs_conf.SysConf.AddFile(file)
191192
if err := gs_conf.SysConf.Set(key, val, fileID); err != nil {
192-
log.Errorf(context.Background(), log.TagAppDef, "failed to set property key=%s, err=%v", key, err)
193+
log.Errorf(context.Background(), log.TagAppDef, "failed to set property key=%s err=%v", key, err)
193194
}
194195
}
195196

@@ -223,7 +224,8 @@ func Module(conditions []ConditionOnProperty, fn func(p conf.Properties) error)
223224
}
224225

225226
// Group registers beans in a group based on configuration properties.
226-
func Group[T any, R any](key string, fn func(c T) (R, error), d func(R) error) {
227+
func Group[T any, R any](tag string, fn func(c T) (R, error), d func(R) error) {
228+
key := strings.TrimSuffix(strings.TrimPrefix(tag, "${"), "}")
227229
app.C.Module([]ConditionOnProperty{
228230
OnProperty(key),
229231
}, func(p conf.Properties) error {

gs/gs_test.go

Lines changed: 0 additions & 46 deletions
This file was deleted.

gs/http.go

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -27,30 +27,28 @@ import (
2727
)
2828

2929
func init() {
30-
Module(
31-
[]ConditionOnProperty{
32-
OnEnableServers(),
33-
OnProperty(EnableSimpleHttpServerProp).HavingValue("true").MatchIfMissing(),
34-
},
35-
func(p conf.Properties) error {
36-
37-
// Register the default ServeMux as a bean if no other ServeMux instance exists
38-
Object(http.DefaultServeMux).Export(gs.As[http.Handler]()).Condition(
39-
OnMissingBean[http.Handler](),
40-
)
41-
42-
// Provide a new SimpleHttpServer instance with configuration bindings.
43-
Provide(
44-
NewSimpleHttpServer,
45-
IndexArg(1, BindArg(SetHttpServerAddr, TagArg("${http.server.addr:=0.0.0.0:9090}"))),
46-
IndexArg(1, BindArg(SetHttpServerReadTimeout, TagArg("${http.server.readTimeout:=5s}"))),
47-
IndexArg(1, BindArg(SetHttpServerHeaderTimeout, TagArg("${http.server.headerTimeout:=1s}"))),
48-
IndexArg(1, BindArg(SetHttpServerWriteTimeout, TagArg("${http.server.writeTimeout:=5s}"))),
49-
IndexArg(1, BindArg(SetHttpServerIdleTimeout, TagArg("${http.server.idleTimeout:=60s}"))),
50-
).AsServer()
51-
52-
return nil
53-
})
30+
Module([]ConditionOnProperty{
31+
OnEnableServers(),
32+
OnProperty(EnableSimpleHttpServerProp).HavingValue("true").MatchIfMissing(),
33+
}, func(p conf.Properties) error {
34+
35+
// Register the default ServeMux as a bean if no other ServeMux instance exists
36+
Object(http.DefaultServeMux).Export(gs.As[http.Handler]()).Condition(
37+
OnMissingBean[http.Handler](),
38+
)
39+
40+
// Provide a new SimpleHttpServer instance with configuration bindings.
41+
Provide(
42+
NewSimpleHttpServer,
43+
IndexArg(1, BindArg(SetHttpServerAddr, TagArg("${http.server.addr:=0.0.0.0:9090}"))),
44+
IndexArg(1, BindArg(SetHttpServerReadTimeout, TagArg("${http.server.readTimeout:=5s}"))),
45+
IndexArg(1, BindArg(SetHttpServerHeaderTimeout, TagArg("${http.server.headerTimeout:=1s}"))),
46+
IndexArg(1, BindArg(SetHttpServerWriteTimeout, TagArg("${http.server.writeTimeout:=5s}"))),
47+
IndexArg(1, BindArg(SetHttpServerIdleTimeout, TagArg("${http.server.idleTimeout:=60s}"))),
48+
).AsServer()
49+
50+
return nil
51+
})
5452
}
5553

5654
// HttpServerConfig holds configuration options for the HTTP server.

gs/test.go

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,20 @@ import (
2525
"github.com/go-spring/spring-core/util"
2626
)
2727

28-
// BeanMock is a mock for bean.
28+
// BeanMock represents a mock bean for testing.
2929
type BeanMock[T any] struct {
3030
selector gs.BeanSelector
3131
}
3232

33-
// MockFor creates a mock for bean.
33+
// MockFor creates a BeanMock for the given type and optional bean name.
3434
func MockFor[T any](name ...string) BeanMock[T] {
3535
return BeanMock[T]{
3636
selector: gs.BeanSelectorFor[T](name...),
3737
}
3838
}
3939

40-
// With registers a mock bean.
40+
// With registers a mock instance into the IoC container,
41+
// replacing the target bean defined by the selector.
4142
func (m BeanMock[T]) With(obj T) {
4243
app.C.AddMock(gs.BeanMock{
4344
Object: obj,
@@ -47,23 +48,29 @@ func (m BeanMock[T]) With(obj T) {
4748

4849
var testers []any
4950

50-
// AddTester adds a tester to the test suite.
51+
// AddTester registers a tester instance into the test suite.
52+
// The tester will be scanned for methods prefixed with 'Test'
53+
// and automatically added as Go test functions.
5154
func AddTester(t any) {
5255
testers = append(testers, t)
5356
app.C.RootBean(app.C.Object(t))
5457
}
5558

56-
// TestMain is the entry point for testing.
59+
// TestMain is the custom entry point for the Go test framework.
60+
// It patches the internal 'tests' slice of testing.M to include
61+
// methods defined in registered testers, then runs the app and tests.
5762
func TestMain(m *testing.M) {
5863

59-
// patch m.tests
64+
// Patch m.tests using reflection (non-standard hack).
6065
mValue := util.PatchValue(reflect.ValueOf(m))
6166
fValue := util.PatchValue(mValue.Elem().FieldByName("tests"))
6267
tests := fValue.Interface().([]testing.InternalTest)
68+
69+
// Scan all registered testers for methods starting with 'Test'.
6370
for _, tester := range testers {
6471
tt := reflect.TypeOf(tester)
6572
typeName := tt.Elem().String()
66-
for i := range tt.NumMethod() {
73+
for i := 0; i < tt.NumMethod(); i++ {
6774
methodType := tt.Method(i)
6875
if strings.HasPrefix(methodType.Name, "Test") {
6976
tests = append(tests, testing.InternalTest{
@@ -78,15 +85,15 @@ func TestMain(m *testing.M) {
7885
}
7986
fValue.Set(reflect.ValueOf(tests))
8087

81-
// run app
88+
// Run the application asynchronously.
8289
stop, err := RunAsync()
8390
if err != nil {
8491
panic(err)
8592
}
8693

87-
// run test
94+
// Run the tests.
8895
m.Run()
8996

90-
// stop app
97+
// Stop the application gracefully after tests complete.
9198
stop()
9299
}

gs/test_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* Copyright 2025 The Go-Spring Authors.
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+
* https://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 gs_test
18+
19+
import (
20+
"fmt"
21+
"testing"
22+
23+
"github.com/go-spring/gs-assert/assert"
24+
"github.com/go-spring/spring-core/gs"
25+
)
26+
27+
func init() {
28+
gs.Object(&GreetingService{})
29+
gs.AddTester(&GreetingTester{})
30+
}
31+
32+
func init() {
33+
gs.MockFor[*GreetingService]().With(
34+
&GreetingService{
35+
Message: "Hello, World!",
36+
},
37+
)
38+
}
39+
40+
func TestMain(m *testing.M) {
41+
gs.TestMain(m)
42+
}
43+
44+
func TestGreeting(t *testing.T) {
45+
fmt.Println(t.Name()) // TestGreeting
46+
}
47+
48+
func TestFarewell(t *testing.T) {
49+
fmt.Println(t.Name()) // TestFarewell
50+
}
51+
52+
type GreetingService struct {
53+
Message string `value:"${app.greeting:=Hello, Go-Spring!}"`
54+
}
55+
56+
type GreetingTester struct {
57+
Svc *GreetingService `autowire:""`
58+
}
59+
60+
func (u *GreetingTester) TestGreeting(t *testing.T) {
61+
fmt.Println(t.Name()) // gs_test.GreetingTester.TestFarewell
62+
assert.That(t, u.Svc).NotNil()
63+
assert.ThatString(t, u.Svc.Message).Equal("Hello, World!")
64+
}
65+
66+
func (u *GreetingTester) TestFarewell(t *testing.T) {
67+
fmt.Println(t.Name()) // gs_test.GreetingTester.TestGreeting
68+
assert.That(t, u.Svc).NotNil()
69+
assert.ThatString(t, u.Svc.Message).Equal("Hello, World!")
70+
}

0 commit comments

Comments
 (0)