Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions dto/values.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,20 @@ func (s StringValue) MarshalJSON() ([]byte, error) {
type IntValue int

func (i *IntValue) UnmarshalJSON(b []byte) error {
var n int
if err := json.Unmarshal(b, &n); err == nil {
*i = IntValue(n)
var f float64
if err := json.Unmarshal(b, &f); err == nil {
*i = IntValue(int(f))
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
v, err := strconv.Atoi(s)
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
*i = IntValue(v)
*i = IntValue(int(v))
return nil
}

Expand Down
36 changes: 36 additions & 0 deletions dto/values_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package dto

import (
"testing"

"github.com/QuantumNous/new-api/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// Ali task usage durations arrive as int, float, or numeric string; any form must decode without failing the whole response (#6166).
func TestIntValueUnmarshalNumericForms(t *testing.T) {
tests := []struct {
name string
in string
want int
}{
{"int", `5`, 5},
{"float", `13.93`, 13},
{"whole float", `5.0`, 5},
{"int string", `"5"`, 5},
{"float string", `"13.93"`, 13},
{"negative float", `-2.5`, -2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var v IntValue
require.NoError(t, common.Unmarshal([]byte(tt.in), &v))
assert.Equal(t, tt.want, int(v))
})
}

var v IntValue
require.Error(t, common.Unmarshal([]byte(`"abc"`), &v))
require.Error(t, common.Unmarshal([]byte(`true`), &v))
}