Skip to content

Commit

Permalink
gjson
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Jan 12, 2024
1 parent ad831d0 commit 688f058
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 30 deletions.
22 changes: 17 additions & 5 deletions util/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ func (s *Builder) SetOptions(path string, value interface{}, opts *Options) erro
func (s *Builder) SetRaw(path, value string) error {
j, err := sjson.SetRaw(s.json, path, value)
if err == nil {
if !Valid(j) {
return errors.New("invalid json value: " + value)
}
s.json = j
}
return err
Expand All @@ -140,6 +143,9 @@ func (s *Builder) SetRaw(path, value string) error {
func (s *Builder) SetRawOptions(path, value string, opts *Options) error {
j, err := sjson.SetRawOptions(s.json, path, value, opts)
if err == nil {
if !Valid(j) {
return errors.New("invalid json value: " + value)
}
s.json = j
}
return err
Expand Down Expand Up @@ -188,23 +194,29 @@ func (s *Builder) Get(path string) Result {
}
}

// String get the json string of *Builder
// String convert the *Builder to JSON string,
func (s *Builder) String() string {
return s.json
}

// AsJSONObject convert the *Builder to *JSONObject,
// Interface convert the *Builder to Go DATA,
func (s *Builder) Interface() (v interface{}) {
json.Unmarshal([]byte(s.json), &v)
return
}

// JSONObject convert the *Builder to *JSONObject,
// if the *Builder is not a json object, nil returned.
func (s *Builder) AsJSONObject() *JSONObject {
func (s *Builder) JSONObject() *JSONObject {
if s.json != "" && !strings.HasPrefix(s.json, "{") {
return nil
}
return NewJSONObject(s.json)
}

// AsJSONArray convert the *Builder to *AsJSONArray,
// JSONArray convert the *Builder to *JSONArray,
// if the *Builder is not a json array, nil returned.
func (s *Builder) AsJSONArray() *JSONArray {
func (s *Builder) JSONArray() *JSONArray {
if s.json != "" && !strings.HasPrefix(s.json, "[") {
return nil
}
Expand Down
58 changes: 33 additions & 25 deletions util/json/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,64 +101,54 @@ func TestJSONResult_SetData(t *testing.T) {
}

func TestJSONResult_WriteToCtx(t *testing.T) {
// 创建一个模拟的 HTTP 请求
req, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}

// 创建一个 ResponseRecorder 来记录响应
recorder := httptest.NewRecorder()

// 处理请求
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := gctx.NewCtx().CloneWithHTTP(w, r)
result := NewResult(200, "OK", "data")
result.WriteToCtx(ctx)
})

// 将请求发送到处理器
handler.ServeHTTP(recorder, req)

expected := `{"code":200,"data":"data","message":"OK"}`
assert.Equal(t, expected, recorder.Body.String())
}

func TestJSONResult_Success(t *testing.T) {
// 创建一个模拟的 HTTP 请求
req, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}

// 创建一个 ResponseRecorder 来记录响应
recorder := httptest.NewRecorder()

// 处理请求
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := gctx.NewCtxWithHTTP(w, r)
result := NewResultCtx(ctx)
result.Success("success")
})

// 将请求发送到处理器
handler.ServeHTTP(recorder, req)

expected := `{"code":0,"data":"success","message":""}`
assert.Equal(t, expected, recorder.Body.String())
}

func TestJSONResult_Fail(t *testing.T) {
// 创建一个模拟的 HTTP 请求
req, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}

// 创建一个 ResponseRecorder 来记录响应
recorder := httptest.NewRecorder()

// 处理请求
Expand All @@ -168,43 +158,41 @@ func TestJSONResult_Fail(t *testing.T) {
result.Fail("fail")
})

// 将请求发送到处理器
handler.ServeHTTP(recorder, req)

expected := `{"code":1,"data":null,"message":"fail"}`
assert.Equal(t, expected, recorder.Body.String())
}

func TestBuilderOperations(t *testing.T) {
// 创建一个新的 Builder 实例
builder := NewBuilder(`{"name": "John", "age": 30, "city": "New York"}`)

// 测试 Set 方法
err := builder.Set("name", "Doe")
if err != nil {
t.Errorf("Set method failed: %v", err)
}

// 测试 Delete 方法
err = builder.Delete("age")
if err != nil {
t.Errorf("Delete method failed: %v", err)
}

// 测试 SetRaw 方法
err = builder.SetRaw("country", `"USA"`)
if err != nil {
t.Errorf("SetRaw method failed: %v", err)
}

// 测试 Get 方法
err = builder.SetRaw("country", `USA`)
if err == nil {
t.Errorf("SetRaw method failed: %v", err)
}

result := builder.Get("name")
if result.String() != "Doe" {
t.Errorf("Get method failed, expected 'Doe', got '%s'", result.String())
}
assert.Equal(t, result.Path(), "name")

// 测试 GetMany 方法
results := builder.GetMany("name", "country")
if len(results) != 2 {
t.Errorf("GetMany method failed, expected 2 results, got %d", len(results))
Expand All @@ -216,22 +204,24 @@ func TestBuilderOperations(t *testing.T) {
}

func TestBuilderAdditionalOperations(t *testing.T) {
// 创建一个新的 Builder 实例
builder := NewBuilder(`{"name": "John", "age": 30, "city": "New York"}`)

// 测试 SetOptions 方法
opts := &Options{Optimistic: false}
err := builder.SetOptions("address", "123 Main St", opts)
if err != nil {
t.Errorf("SetOptions method failed: %v", err)
}

// 测试 SetRawOptions 方法
rawOpts := &Options{Optimistic: false}
err = builder.SetRawOptions("info", `{"key": "value"}`, rawOpts)
if err != nil {
t.Errorf("SetRawOptions method failed: %v", err)
}

err = builder.SetRawOptions("info", `abc`, rawOpts)
if err == nil {
t.Errorf("SetRawOptions method failed: %v", err)
}
}

func TestJSONArray_Append(t *testing.T) {
Expand Down Expand Up @@ -290,13 +280,13 @@ func TestJSONArray_Merge(t *testing.T) {

func TestBuilder_AsJSONObject(t *testing.T) {
a := NewBuilder(`[]`)
assert.Nil(t, a.AsJSONObject())
assert.NotNil(t, a.AsJSONArray())
assert.Nil(t, a.JSONObject())
assert.NotNil(t, a.JSONArray())
assert.Equal(t, "[]", a.String())
assert.Error(t, a.AsJSONArray().Append(http.Client{}))
assert.Error(t, a.JSONArray().Append(http.Client{}))
a = NewBuilder(`{}`)
assert.Nil(t, a.AsJSONArray())
assert.NotNil(t, a.AsJSONObject())
assert.Nil(t, a.JSONArray())
assert.NotNil(t, a.JSONObject())
assert.Equal(t, "{}", a.String())
}

Expand All @@ -323,3 +313,21 @@ func TestNewJSONObjectE(t *testing.T) {
_, err = NewJSONArrayE(map[string]string{})
assert.Error(t, err)
}

func TestBuilder_Interface(t *testing.T) {
a := NewBuilder(nil)
assert.Nil(t, a.Interface())

a = NewBuilder("")
assert.Nil(t, a)

a = NewBuilder(`{"a":"b"}`)
assert.Equal(t, map[string]interface{}{"a": "b"}, a.Interface())
a = NewBuilder(map[string]interface{}{"a": "b"})
assert.Equal(t, map[string]interface{}{"a": "b"}, a.Interface())

a = NewBuilder(`[123]`)
assert.Equal(t, []interface{}{float64(123)}, a.Interface())
a = NewBuilder([]interface{}{123})
assert.Equal(t, []interface{}{float64(123)}, a.Interface())
}

0 comments on commit 688f058

Please sign in to comment.