github.com/stripe/stripe-go/v76@v76.25.0/event_test.go (about)

     1  package stripe
     2  
     3  import (
     4  	"testing"
     5  
     6  	assert "github.com/stretchr/testify/require"
     7  )
     8  
     9  func TestGetObjectValue(t *testing.T) {
    10  	event := &Event{
    11  		Data: &EventData{
    12  			Object: map[string]interface{}{
    13  				"top_level_key": "top_level",
    14  				"integer_key":   123,
    15  				"map": map[string]interface{}{
    16  					"nested_key": "nested",
    17  				},
    18  				"slice": []interface{}{
    19  					"index-0",
    20  					"index-1",
    21  					"index-2",
    22  				},
    23  				"slice_of_maps": []interface{}{
    24  					map[string]interface{}{
    25  						"slice_nested_key": "slice_nested",
    26  					},
    27  				},
    28  			},
    29  		},
    30  	}
    31  
    32  	assert.Equal(t, "top_level", event.GetObjectValue("top_level_key"))
    33  
    34  	// Check that it coerces non-string values into strings (this behavior is
    35  	// somewhat questionable, but I'm going with how it already works)
    36  	assert.Equal(t, "123", event.GetObjectValue("integer_key"))
    37  
    38  	assert.Equal(t, "nested", event.GetObjectValue("map", "nested_key"))
    39  	assert.Equal(t, "index-1", event.GetObjectValue("slice", "1"))
    40  	assert.Equal(t, "slice_nested",
    41  		event.GetObjectValue("slice_of_maps", "0", "slice_nested_key"))
    42  
    43  	// By design a `nil` just returns an empty string
    44  	assert.Equal(t, "", event.GetObjectValue("bad_key"))
    45  
    46  	// Panic conditions. Usually the function tries to just return a value is
    47  	// fairly forgiving, but it does panic under certain obviously impossible
    48  	// cases.
    49  	assert.PanicsWithValue(t, "Cannot access nested slice element with non-integer key: string_key", func() {
    50  		event.GetObjectValue("slice", "string_key")
    51  	})
    52  	assert.PanicsWithValue(t, "Cannot descend into non-map non-slice object with key: bad_key", func() {
    53  		event.GetObjectValue("top_level_key", "bad_key")
    54  	})
    55  }