github.com/prebid/prebid-server@v0.275.0/util/jsonutil/stringInt_test.go (about)

     1  package jsonutil
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	"github.com/buger/jsonparser"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestStringIntUnmarshalJSON(t *testing.T) {
    12  	type Item struct {
    13  		ItemId StringInt `json:"item_id"`
    14  	}
    15  
    16  	t.Run("string", func(t *testing.T) {
    17  		jsonData := []byte(`{"item_id":"30"}`)
    18  		var item Item
    19  		assert.NoError(t, json.Unmarshal(jsonData, &item))
    20  		assert.Equal(t, 30, int(item.ItemId))
    21  	})
    22  
    23  	t.Run("int", func(t *testing.T) {
    24  		jsonData := []byte(`{"item_id":30}`)
    25  		var item Item
    26  		assert.NoError(t, json.Unmarshal(jsonData, &item))
    27  		assert.Equal(t, 30, int(item.ItemId))
    28  	})
    29  
    30  	t.Run("empty_id", func(t *testing.T) {
    31  		jsonData := []byte(`{"item_id": ""}`)
    32  		var item Item
    33  		assert.NoError(t, json.Unmarshal(jsonData, &item))
    34  	})
    35  
    36  	t.Run("invalid_input", func(t *testing.T) {
    37  		jsonData := []byte(`{"item_id":true}`)
    38  		var item Item
    39  		err := json.Unmarshal(jsonData, &item)
    40  		assert.Equal(t, jsonparser.MalformedValueError, err)
    41  	})
    42  }