github.com/stripe/stripe-go/v76@v76.25.0/paymentsource_test.go (about) 1 package stripe 2 3 import ( 4 "encoding/json" 5 "testing" 6 7 assert "github.com/stretchr/testify/require" 8 "github.com/stripe/stripe-go/v76/form" 9 ) 10 11 func TestSourceParams_AppendTo(t *testing.T) { 12 { 13 params := &PaymentSourceSourceParams{Token: String("tok_123")} 14 body := &form.Values{} 15 form.AppendTo(body, params) 16 t.Logf("body = %+v", body) 17 assert.Equal(t, []string{"tok_123"}, body.Get("source")) 18 } 19 20 { 21 params := &PaymentSourceSourceParams{Card: &CardParams{Number: String("4242424242424242")}} 22 body := &form.Values{} 23 form.AppendTo(body, params) 24 t.Logf("body = %+v", body) 25 assert.Equal(t, []string{"4242424242424242"}, body.Get("source[number]")) 26 assert.Equal(t, []string{"card"}, body.Get("source[object]")) 27 } 28 } 29 30 func TestPaymentSource_MarshalJSON(t *testing.T) { 31 { 32 id := "card_123" 33 name := "alice cooper" 34 paymentSource := &PaymentSource{ 35 Type: PaymentSourceTypeCard, 36 ID: id, 37 Card: &Card{ 38 ID: id, 39 Name: name, 40 }, 41 } 42 43 d, err := json.Marshal(paymentSource) 44 assert.NoError(t, err) 45 assert.NotNil(t, d) 46 47 unmarshalled := &PaymentSource{} 48 err = json.Unmarshal(d, unmarshalled) 49 assert.NoError(t, err) 50 51 assert.Equal(t, unmarshalled.ID, id) 52 assert.NotNil(t, unmarshalled.Card) 53 assert.Equal(t, unmarshalled.Card.ID, id) 54 assert.Equal(t, unmarshalled.Card.Name, name) 55 } 56 57 { 58 id := "ba_123" 59 name := "big bank" 60 paymentSource := &PaymentSource{ 61 Type: PaymentSourceTypeBankAccount, 62 ID: id, 63 BankAccount: &BankAccount{ 64 ID: id, 65 AccountHolderName: name, 66 }, 67 } 68 69 d, err := json.Marshal(paymentSource) 70 assert.NoError(t, err) 71 assert.NotNil(t, d) 72 73 unmarshalled := &PaymentSource{} 74 err = json.Unmarshal(d, unmarshalled) 75 assert.NoError(t, err) 76 77 assert.Equal(t, unmarshalled.ID, id) 78 assert.NotNil(t, unmarshalled.BankAccount) 79 assert.Equal(t, unmarshalled.BankAccount.ID, id) 80 assert.Equal(t, unmarshalled.BankAccount.AccountHolderName, name) 81 } 82 } 83 84 func TestPaymentSource_UnmarshalJSON(t *testing.T) { 85 // Unmarshals from a JSON string 86 { 87 var v PaymentSource 88 err := json.Unmarshal([]byte(`"ba_123"`), &v) 89 assert.NoError(t, err) 90 assert.Equal(t, "ba_123", v.ID) 91 } 92 93 // Unmarshals from a JSON object 94 { 95 // We build the JSON object manually here because it's key that the 96 // `object` field is included so that the source knows what type to 97 // decode 98 data := []byte(`{"id":"ba_123", "object":"bank_account"}`) 99 100 var v PaymentSource 101 err := json.Unmarshal(data, &v) 102 assert.NoError(t, err) 103 assert.Equal(t, PaymentSourceTypeBankAccount, v.Type) 104 105 // The payment source has a field for each possible type, so the bank 106 // account is located one level down 107 assert.Equal(t, "ba_123", v.BankAccount.ID) 108 } 109 }