Skip to content

Commit

Permalink
fix(JSON): mixing numeric and named placeholders didn't work correctly
Browse files Browse the repository at this point in the history
Signed-off-by: Maxime Soulé <btik-git@scoubidou.com>
  • Loading branch information
maxatome committed Oct 27, 2023
1 parent 24ab660 commit 121b1d8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
7 changes: 2 additions & 5 deletions td/td_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,7 @@ func (u tdJSONUnmarshaler) unmarshal(expectedJSON any, params []any) (any, *ctxe
var byTag map[string]any

for i, p := range params {
switch op := p.(type) {
case *tdTag:
if op, ok := p.(*tdTag); ok && op.err == nil {
if byTag[op.tag] != nil {
return nil, ctxerr.OpBad(u.Func, `2 params have the same tag "%s"`, op.tag)
}
Expand All @@ -141,10 +140,8 @@ func (u tdJSONUnmarshaler) unmarshal(expectedJSON any, params []any) (any, *ctxe
p = op.expectedValue.Interface()
}
byTag[op.tag] = newJSONNamedPlaceholder(op.tag, p)

default:
params[i] = newJSONNumPlaceholder(uint64(i+1), p)
}
params[i] = newJSONNumPlaceholder(uint64(i+1), p)
}

final, err := json.Parse(b, json.ParseOpts{
Expand Down
19 changes: 19 additions & 0 deletions td/td_json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,16 @@ func TestJSON(t *testing.T) {
td.Tag("age", td.Between(40, 45)),
td.Tag("gender", td.NotEmpty())))

// Tag placeholders + numeric placeholders
checkOK(t, []MyStruct{got, got},
td.JSON(`[
{"name":"$1","age":$age,"gender":"$3"},
{"name":"$1","age":$2,"gender":"$3"}
]`,
td.Re(`^Bo`), // $1
td.Tag("age", td.Between(40, 45)), // $2
"male")) // $3

// Tag placeholders + operators are not JSON marshallable
checkOK(t, got,
td.JSON(`$all`, td.Tag("all", map[string]any{
Expand All @@ -113,6 +123,15 @@ func TestJSON(t *testing.T) {
"gender": td.NotEmpty(),
})))

checkError(t, got,
td.JSON(`{"name":$1, "age":$1, "gender":$1}`,
td.Tag("!!", td.Ignore())),
expectedError{
Message: mustBe("bad usage of Tag operator"),
Summary: mustBe("Invalid tag, should match (Letter|_)(Letter|_|Number)*"),
Under: mustContain("under operator Tag"),
})

// Tag placeholders + nil
checkOK(t, nil, td.JSON(`$all`, td.Tag("all", nil)))

Expand Down

0 comments on commit 121b1d8

Please sign in to comment.