#23: unit_test.go, integration_test.go

This commit is contained in:
Aliaksandr Pliutau 2017-03-02 10:43:23 +07:00
parent 77132c2781
commit dd920d5151
16 changed files with 492 additions and 549 deletions

View File

@ -3,7 +3,8 @@ go:
- 1.5 - 1.5
- 1.6 - 1.6
- 1.7 - 1.7
- 1.8
install: install:
- export PATH=$PATH:$HOME/gopath/bin - export PATH=$PATH:$HOME/gopath/bin
script: script:
- go test -v - go test -tags-unit

View File

@ -39,28 +39,21 @@
### Missing endpoints ### Missing endpoints
It is possible that some endpoints are missing in this SDK Client, but you can use built-in **paypalsdk** functions to perform a request: **NewClient -> NewRequest -> SendWithAuth** It is possible that some endpoints are missing in this SDK Client, but you can use built-in **paypalsdk** functions to perform a request: **NewClient -> NewRequest -> SendWithAuth**
### Create Client ### New Client
```go ```go
import "github.com/logpacker/PayPal-Go-SDK" import "github.com/logpacker/PayPal-Go-SDK"
```
```go
// Create a client instance // Create a client instance
c, err := paypalsdk.NewClient("clientID", "secretID", paypalsdk.APIBaseSandBox) c, err := paypalsdk.NewClient("clientID", "secretID", paypalsdk.APIBaseSandBox)
c.SetLog(os.Stdout) // Set log to terminal stdout c.SetLog(os.Stdout) // Set log to terminal stdout
```
### Get access token
```go
// When you will have authorization_code you can get an access_token
accessToken, err := c.GetAccessToken() accessToken, err := c.GetAccessToken()
``` ```
### Create direct paypal payment ### Create direct paypal payment
```go ```go
// Now we can create a paypal payment
amount := paypalsdk.Amount{ amount := paypalsdk.Amount{
Total: "7.00", Total: "7.00",
Currency: "USD", Currency: "USD",
@ -69,13 +62,9 @@ redirectURI := "http://example.com/redirect-uri"
cancelURI := "http://example.com/cancel-uri" cancelURI := "http://example.com/cancel-uri"
description := "Description for this payment" description := "Description for this payment"
paymentResult, err := c.CreateDirectPaypalPayment(amount, redirectURI, cancelURI, description) paymentResult, err := c.CreateDirectPaypalPayment(amount, redirectURI, cancelURI, description)
// If paymentResult.ID is not empty and paymentResult.Links is also
// we can redirect user to approval page (paymentResult.Links[1]).
// After approval user will be redirected to return_url from Request with PaymentID
``` ```
### Create any payment ### Create custom payment
```go ```go
p := paypalsdk.Payment{ p := paypalsdk.Payment{
Intent: "sale", Intent: "sale",
@ -111,10 +100,7 @@ paymentResponse, err := client.CreatePayment(p)
### Execute approved payment ### Execute approved payment
```go ```go
// And the last step is to execute approved payment
// paymentID is returned via return_url
paymentID := "PAY-17S8410768582940NKEE66EQ" paymentID := "PAY-17S8410768582940NKEE66EQ"
// payerID is returned via return_url
payerID := "7E7MGXCWTTKK2" payerID := "7E7MGXCWTTKK2"
executeResult, err := c.ExecuteApprovedPayment(paymentID, payerID) executeResult, err := c.ExecuteApprovedPayment(paymentID, payerID)
``` ```
@ -122,22 +108,19 @@ executeResult, err := c.ExecuteApprovedPayment(paymentID, payerID)
### Get payment by ID ### Get payment by ID
```go ```go
// Get created payment info payment, err := c.GetPayment("PAY-17S8410768582940NKEE66EQ")
payment, err := c.GetPayment(paymentID)
``` ```
### Get list of payments ### Get list of payments
```go ```go
// Get all payments slice
payments, err := c.GetPayments() payments, err := c.GetPayments()
``` ```
### Get authorization by ID ### Get authorization by ID
```go ```go
authID := "2DC87612EK520411B" auth, err := c.GetAuthorization("2DC87612EK520411B")
auth, err := c.GetAuthorization(authID)
``` ```
### Capture authorization ### Capture authorization
@ -161,8 +144,7 @@ auth, err := c.ReauthorizeAuthorization(authID, &paypalsdk.Amount{Total: "7.00",
### Get Sale by ID ### Get Sale by ID
```go ```go
saleID := "36C38912MN9658832" sale, err := c.GetSale("36C38912MN9658832")
sale, err := c.GetSale(saleID)
``` ```
### Refund Sale by ID ### Refund Sale by ID
@ -177,14 +159,13 @@ refund, err := c.RefundSale(saleID, &paypalsdk.Amount{Total: "7.00", Currency: "
### Get Refund by ID ### Get Refund by ID
```go ```go
orderID := "O-4J082351X3132253H" refund, err := c.GetRefund("O-4J082351X3132253H")
refund, err := c.GetRefund(orderID)
``` ```
### Get Order by ID ### Get Order by ID
```go ```go
order, err := c.GetOrder(orderID) order, err := c.GetOrder("O-4J082351X3132253H")
``` ```
### Authorize Order ### Authorize Order
@ -208,7 +189,6 @@ order, err := c.VoidOrder(orderID)
### Identity ### Identity
```go ```go
// Retreive tolen by authorization code
token, err := c.GrantNewAccessTokenFromAuthCode("<Authorization-Code>", "http://example.com/myapp/return.php") token, err := c.GrantNewAccessTokenFromAuthCode("<Authorization-Code>", "http://example.com/myapp/return.php")
// ... or by refresh token // ... or by refresh token
token, err := c.GrantNewAccessTokenFromRefreshToken("<Refresh-Token>") token, err := c.GrantNewAccessTokenFromRefreshToken("<Refresh-Token>")
@ -302,8 +282,6 @@ err := c.DeleteWebProfile("XP-CP6S-W9DY-96H8-MVN2")
### Vault ### Vault
```go ```go
// https://developer.paypal.com/docs/api/vault/
// Store CC // Store CC
c.StoreCreditCard(paypalsdk.CreditCard{ c.StoreCreditCard(paypalsdk.CreditCard{
Number: "4417119669820331", Number: "4417119669820331",
@ -330,7 +308,7 @@ c.PatchCreditCard("CARD-ID-123", []paypalsdk.CreditCardField{
// Get it // Get it
c.GetCreditCard("CARD-ID-123") c.GetCreditCard("CARD-ID-123")
// get all stored credit cards // Get all stored credit cards
c.GetCreditCards(nil) c.GetCreditCards(nil)
``` ```
@ -338,6 +316,10 @@ c.GetCreditCards(nil)
* Fork a repository * Fork a repository
* Add/Fix something * Add/Fix something
* Run ./before-commit.sh to check that tests passed and code is formatted well * Check that tests are passing
* Push to your repository * Create PR
* Create pull request
### Tests
* Unit tests: `go test -tags=unit`
* Integration tests: `go test -tags=inegration`

View File

@ -1,68 +0,0 @@
package paypalsdk
import (
"fmt"
"testing"
)
func TestGetAccessToken(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
token, err := c.GetAccessToken()
if err != nil || token.Token == "" {
t.Errorf("Token is not returned by GetAccessToken")
}
}
func TestGetAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
a, err := c.GetAuthorization(testAuthID)
if err != nil || a.ID != testAuthID {
t.Errorf("GetAuthorization failed for ID=%s", testAuthID)
}
a, err = c.GetAuthorization(testFakeAuthID)
if err == nil {
t.Errorf("GetAuthorization must return error for ID=%s", testFakeAuthID)
}
}
func TestCaptureAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.CaptureAuthorization(testAuthID, &Amount{Total: "200", Currency: "USD"}, true)
if err == nil {
t.Errorf("Auth is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestVoidAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.VoidAuthorization(testAuthID)
if err == nil {
t.Errorf("Auth is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestReauthorizeAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.ReauthorizeAuthorization(testAuthID, &Amount{Total: "200", Currency: "USD"})
if err == nil {
t.Errorf("Reauthorization not allowed for this product, 500 error must be returned")
} else {
fmt.Println(err.Error())
}
}

View File

@ -6,30 +6,6 @@ import (
"net/http" "net/http"
) )
// GetAccessToken returns struct of TokenResponse
// No need to call SetAccessToken to apply new access token for current Client
// Endpoint: POST /v1/oauth2/token
func (c *Client) GetAccessToken() (*TokenResponse, error) {
buf := bytes.NewBuffer([]byte("grant_type=client_credentials"))
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v1/oauth2/token"), buf)
if err != nil {
return &TokenResponse{}, err
}
req.SetBasicAuth(c.ClientID, c.Secret)
req.Header.Set("Content-type", "application/x-www-form-urlencoded")
t := TokenResponse{}
err = c.Send(req, &t)
// Set Token fur current Client
if t.Token != "" {
c.Token = &t
}
return &t, err
}
// GetAuthorization returns an authorization by ID // GetAuthorization returns an authorization by ID
// Endpoint: GET /v1/payments/authorization/ID // Endpoint: GET /v1/payments/authorization/ID
func (c *Client) GetAuthorization(authID string) (*Authorization, error) { func (c *Client) GetAuthorization(authID string) (*Authorization, error) {

View File

@ -1,6 +0,0 @@
#!/bin/bash
gofmt -s -w .
golint ./...
go vet ./...
go test -v -race ./...

View File

@ -15,24 +15,39 @@ import (
// APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox // APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox
func NewClient(clientID string, secret string, APIBase string) (*Client, error) { func NewClient(clientID string, secret string, APIBase string) (*Client, error) {
if clientID == "" || secret == "" || APIBase == "" { if clientID == "" || secret == "" || APIBase == "" {
return &Client{}, errors.New("ClientID, Secret and APIBase are required to create a Client") return nil, errors.New("ClientID, Secret and APIBase are required to create a Client")
} }
return &Client{ return &Client{
&http.Client{}, client: &http.Client{},
clientID, ClientID: clientID,
secret, Secret: secret,
APIBase, APIBase: APIBase,
nil,
nil,
}, nil }, nil
} }
// SetLog will set/change the output destination. // GetAccessToken returns struct of TokenResponse
// If log file is set paypalsdk will log all requests and responses to this Writer // No need to call SetAccessToken to apply new access token for current Client
func (c *Client) SetLog(log io.Writer) error { // Endpoint: POST /v1/oauth2/token
c.Log = log func (c *Client) GetAccessToken() (*TokenResponse, error) {
return nil buf := bytes.NewBuffer([]byte("grant_type=client_credentials"))
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v1/oauth2/token"), buf)
if err != nil {
return &TokenResponse{}, err
}
req.SetBasicAuth(c.ClientID, c.Secret)
req.Header.Set("Content-type", "application/x-www-form-urlencoded")
t := TokenResponse{}
err = c.Send(req, &t)
// Set Token fur current Client
if t.Token != "" {
c.Token = &t
}
return &t, err
} }
// SetAccessToken sets saved token to current client // SetAccessToken sets saved token to current client
@ -44,6 +59,13 @@ func (c *Client) SetAccessToken(token string) error {
return nil return nil
} }
// SetLog will set/change the output destination.
// If log file is set paypalsdk will log all requests and responses to this Writer
func (c *Client) SetLog(log io.Writer) error {
c.Log = log
return nil
}
// Send makes a request to the API, the response body will be // Send makes a request to the API, the response body will be
// unmarshaled into v, or if v is an io.Writer, the response will // unmarshaled into v, or if v is an io.Writer, the response will
// be written to it without decoding // be written to it without decoding

View File

@ -1,33 +0,0 @@
package paypalsdk
import (
"fmt"
"testing"
)
// All test values are defined here
var testClientID = "AZgwu4yt5Ba0gyTu1dGBH3txHCJbMuFNvrmQxBaQbfDncDiCs6W_rwJD8Ir-0pZrN-_eq7n9zVd8Y-5f"
var testSecret = "EBzA1wRl5t73OMugOieDj_tI3vihfJmGl47ukQT-cpctooIzDu0K7IPESNC0cKodlLSOXzwI8qXSM0rd"
var testAuthID = "2DC87612EK520411B"
var testFakeAuthID = "FAKE-2DC87612EK520411B"
var testOrderID = "O-4J082351X3132253H"
var testFakeOrderID = "FAKE-O-4J082351X3132253H"
var testSaleID = "4CF18861HF410323U"
var testPaymentID = "PAY-5YK922393D847794YKER7MUI"
var testPayerID = "CR87QHB7JTRSC"
var testUserID = "https://www.paypal.com/webapps/auth/identity/user/WEssgRpQij92sE99_F9MImvQ8FPYgUEjrvCja2qH2H8"
var testCardID = "CARD-54E6956910402550WKGRL6EA"
func TestNewClient(t *testing.T) {
_, err := NewClient("", "", "")
if err == nil {
t.Errorf("All arguments are required in NewClient()")
} else {
fmt.Println(err.Error())
}
_, err = NewClient(testClientID, testSecret, APIBaseSandBox)
if err != nil {
t.Errorf("NewClient() must not return error for valid creds: %s", err.Error())
}
}

View File

@ -1,31 +0,0 @@
package paypalsdk
import "testing"
func TestGrantNewAccessTokenFromAuthCode(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
_, err := c.GrantNewAccessTokenFromAuthCode("123", "http://example.com/myapp/return.php")
if err == nil {
t.Errorf("GrantNewAccessTokenFromAuthCode must return error for invalid code")
}
}
func TestGrantNewAccessTokenFromRefreshToken(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
_, err := c.GrantNewAccessTokenFromRefreshToken("123")
if err == nil {
t.Errorf("GrantNewAccessTokenFromRefreshToken must return error for invalid refresh token")
}
}
func TestGetUserInfo(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
u, err := c.GetUserInfo("openid")
if u.ID != testUserID || err != nil {
t.Errorf("GetUserInfo must return valid test ID=%s", testUserID)
}
}

375
integration_test.go Normal file
View File

@ -0,0 +1,375 @@
// +build integration
package paypalsdk
import (
"fmt"
"os"
"testing"
)
// All test values are defined here
var testClientID = "AZgwu4yt5Ba0gyTu1dGBH3txHCJbMuFNvrmQxBaQbfDncDiCs6W_rwJD8Ir-0pZrN-_eq7n9zVd8Y-5f"
var testSecret = "EBzA1wRl5t73OMugOieDj_tI3vihfJmGl47ukQT-cpctooIzDu0K7IPESNC0cKodlLSOXzwI8qXSM0rd"
var testAuthID = "2DC87612EK520411B"
var testFakeAuthID = "FAKE-2DC87612EK520411B"
var testOrderID = "O-4J082351X3132253H"
var testFakeOrderID = "FAKE-O-4J082351X3132253H"
var testSaleID = "4CF18861HF410323U"
var testPaymentID = "PAY-5YK922393D847794YKER7MUI"
var testPayerID = "CR87QHB7JTRSC"
var testUserID = "https://www.paypal.com/webapps/auth/identity/user/WEssgRpQij92sE99_F9MImvQ8FPYgUEjrvCja2qH2H8"
var testCardID = "CARD-54E6956910402550WKGRL6EA"
func TestGetAccessToken(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
token, err := c.GetAccessToken()
if err != nil {
t.Errorf("Not expected error for GetAccessToken()")
}
if token.Token == "" {
t.Errorf("Expected non-empty token for GetAccessToken()")
}
}
func TestGetAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
a, err := c.GetAuthorization(testAuthID)
if err != nil || a.ID != testAuthID {
t.Errorf("GetAuthorization failed for ID=%s", testAuthID)
}
a, err = c.GetAuthorization(testFakeAuthID)
if err == nil {
t.Errorf("GetAuthorization must return error for ID=%s", testFakeAuthID)
}
}
func TestCaptureAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.CaptureAuthorization(testAuthID, &Amount{Total: "200", Currency: "USD"}, true)
if err == nil {
t.Errorf("Auth is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestVoidAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.VoidAuthorization(testAuthID)
if err == nil {
t.Errorf("Auth is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestReauthorizeAuthorization(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.ReauthorizeAuthorization(testAuthID, &Amount{Total: "200", Currency: "USD"})
if err == nil {
t.Errorf("Reauthorization not allowed for this product, 500 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestGrantNewAccessTokenFromAuthCode(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
_, err := c.GrantNewAccessTokenFromAuthCode("123", "http://example.com/myapp/return.php")
if err == nil {
t.Errorf("GrantNewAccessTokenFromAuthCode must return error for invalid code")
}
}
func TestGrantNewAccessTokenFromRefreshToken(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
_, err := c.GrantNewAccessTokenFromRefreshToken("123")
if err == nil {
t.Errorf("GrantNewAccessTokenFromRefreshToken must return error for invalid refresh token")
}
}
func TestGetUserInfo(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
u, err := c.GetUserInfo("openid")
if u.ID != testUserID || err != nil {
t.Errorf("GetUserInfo must return valid test ID=%s", testUserID)
}
}
func TestGetOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
o, err := c.GetOrder(testOrderID)
if err != nil || o.ID != testOrderID {
t.Errorf("GetOrder failed for ID=%s", testOrderID)
}
o, err = c.GetOrder(testFakeOrderID)
if err == nil {
t.Errorf("GetOrder must return error for ID=%s", testFakeOrderID)
}
}
func TestAuthorizeOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.AuthorizeOrder(testOrderID, &Amount{Total: "7.00", Currency: "USD"})
if err == nil {
t.Errorf("Order is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestCaptureOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.CaptureOrder(testOrderID, &Amount{Total: "100", Currency: "USD"}, true, nil)
if err == nil {
t.Errorf("Order is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestVoidOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.VoidOrder(testOrderID)
if err == nil {
t.Errorf("Order is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestCreateDirectPaypalPayment(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.SetLog(os.Stdout)
c.GetAccessToken()
amount := Amount{
Total: "15.11",
Currency: "USD",
}
p, err := c.CreateDirectPaypalPayment(amount, "http://example.com", "http://example.com", "test payment")
if err != nil || p.ID == "" {
t.Errorf("Test paypal payment is not created")
}
}
func TestGetPayment(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetPayment(testPaymentID)
if err == nil {
t.Errorf("404 for this payment ID")
} else {
fmt.Println(err.Error())
}
}
func TestGetPayments(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetPayments()
if err != nil {
t.Errorf("Nil error expected")
}
}
func TestExecuteApprovedPayment(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.ExecuteApprovedPayment(testPaymentID, testPayerID)
if err == nil {
t.Errorf("404 for this payment ID")
} else {
fmt.Println(err.Error())
}
}
func TestCreateSinglePayout(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
payout := Payout{
SenderBatchHeader: &SenderBatchHeader{
EmailSubject: "Subject will be displayed on PayPal",
},
Items: []PayoutItem{
{
RecipientType: "EMAIL",
Receiver: "single-email-payout@mail.com",
Amount: &AmountPayout{
Value: "15.11",
Currency: "USD",
},
Note: "Optional note",
SenderItemID: "Optional Item ID",
},
},
}
p, err := c.CreateSinglePayout(payout)
if err != nil || len(p.Items) != 1 {
t.Errorf("Test single payout is not created")
}
}
func TestGetSale(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetSale(testSaleID)
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
}
func TestRefundSale(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.RefundSale(testSaleID, nil)
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
_, err = c.RefundSale(testSaleID, &Amount{Total: "7.00", Currency: "USD"})
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
}
func TestGetRefund(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetRefund("1")
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
}
func TestStoreCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.StoreCreditCard(CreditCard{})
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for invalid CC")
}
r2, e2 := c.StoreCreditCard(CreditCard{
Number: "4417119669820331",
Type: "visa",
ExpireMonth: "11",
ExpireYear: "2020",
CVV2: "874",
FirstName: "Foo",
LastName: "Bar",
})
if e2 != nil || r2 == nil {
t.Errorf("200 code expected for valid CC card. Error: %v", e2)
}
}
func TestDeleteCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.DeleteCreditCard("")
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for invalid CC ID")
}
}
func TestGetCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.GetCreditCard("BBGGG")
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for invalid CC, got CC %v", r1)
}
}
func TestGetCreditCards(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.GetCreditCards(nil)
if e1 != nil || r1 == nil {
t.Errorf("200 code expected. Error: %v", e1)
}
if r1.TotalItems < 1 {
t.Errorf("Expected >0 CCs, got %d", r1.TotalItems)
}
if r1.TotalPages < 1 {
t.Errorf("Expected >0 CCs page")
}
r2, e2 := c.GetCreditCards(&CreditCardsFilter{
Page: 2,
PageSize: 7,
})
if e2 != nil || r2 == nil {
t.Errorf("200 code expected. Error: %v", e2)
}
if r2.TotalItems < 1 {
t.Errorf("Expected >0 CCs, got %d", r2.TotalItems)
}
if r2.TotalPages < 1 {
t.Errorf("Expected >0 CCs page")
}
}
func TestPatchCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.PatchCreditCard(testCardID, nil)
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for empty update info")
}
}

View File

@ -1,57 +0,0 @@
package paypalsdk
import (
"fmt"
"testing"
)
func TestGetOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
o, err := c.GetOrder(testOrderID)
if err != nil || o.ID != testOrderID {
t.Errorf("GetOrder failed for ID=%s", testOrderID)
}
o, err = c.GetOrder(testFakeOrderID)
if err == nil {
t.Errorf("GetOrder must return error for ID=%s", testFakeOrderID)
}
}
func TestAuthorizeOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.AuthorizeOrder(testOrderID, &Amount{Total: "7.00", Currency: "USD"})
if err == nil {
t.Errorf("Order is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestCaptureOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.CaptureOrder(testOrderID, &Amount{Total: "100", Currency: "USD"}, true, nil)
if err == nil {
t.Errorf("Order is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}
func TestVoidOrder(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.VoidOrder(testOrderID)
if err == nil {
t.Errorf("Order is expired, 400 error must be returned")
} else {
fmt.Println(err.Error())
}
}

View File

@ -1,61 +0,0 @@
package paypalsdk
import (
"fmt"
"os"
"testing"
)
func TestCreateDirectPaypalPayment(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.SetLog(os.Stdout)
c.GetAccessToken()
amount := Amount{
Total: "15.11",
Currency: "USD",
}
p, err := c.CreateDirectPaypalPayment(amount, "http://example.com", "http://example.com", "test payment")
if err != nil || p.ID == "" {
t.Errorf("Test paypal payment is not created")
}
}
func TestGetPayment(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetPayment(testPaymentID)
if err == nil {
t.Errorf("404 for this payment ID")
} else {
fmt.Println(err.Error())
}
}
func TestGetPayments(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetPayments()
if err != nil {
t.Errorf("Nil error expected")
}
}
func TestExecuteApprovedPayment(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.ExecuteApprovedPayment(testPaymentID, testPayerID)
if err == nil {
t.Errorf("404 for this payment ID")
} else {
fmt.Println(err.Error())
}
}

View File

@ -1,32 +0,0 @@
package paypalsdk
import "testing"
func TestCreateSinglePayout(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
payout := Payout{
SenderBatchHeader: &SenderBatchHeader{
EmailSubject: "Subject will be displayed on PayPal",
},
Items: []PayoutItem{
{
RecipientType: "EMAIL",
Receiver: "single-email-payout@mail.com",
Amount: &AmountPayout{
Value: "15.11",
Currency: "USD",
},
Note: "Optional note",
SenderItemID: "Optional Item ID",
},
},
}
p, err := c.CreateSinglePayout(payout)
if err != nil || len(p.Items) != 1 {
t.Errorf("Test single payout is not created")
}
}

View File

@ -1,49 +0,0 @@
package paypalsdk
import (
"fmt"
"testing"
)
func TestGetSale(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetSale(testSaleID)
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
}
func TestRefundSale(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.RefundSale(testSaleID, nil)
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
_, err = c.RefundSale(testSaleID, &Amount{Total: "7.00", Currency: "USD"})
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
}
func TestGetRefund(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
_, err := c.GetRefund("1")
if err == nil {
t.Errorf("404 must be returned for ID=%s", testSaleID)
} else {
fmt.Println(err.Error())
}
}

View File

@ -1,54 +0,0 @@
package paypalsdk
// These tests test responses conversion from JSON to golang structs
import (
"encoding/json"
"testing"
)
func TestTypeUserInfo(t *testing.T) {
response := `{
"user_id": "https://www.paypal.com/webapps/auth/server/64ghr894040044",
"name": "Peter Pepper",
"given_name": "Peter",
"family_name": "Pepper",
"email": "ppuser@example.com"
}`
u := &UserInfo{}
err := json.Unmarshal([]byte(response), u)
if err != nil {
t.Errorf("UserInfo Unmarshal failed")
}
if u.ID != "https://www.paypal.com/webapps/auth/server/64ghr894040044" ||
u.Name != "Peter Pepper" ||
u.GivenName != "Peter" ||
u.FamilyName != "Pepper" ||
u.Email != "ppuser@example.com" {
t.Errorf("UserInfo decoded result is incorrect, Given: %v", u)
}
}
func TestTypeItem(t *testing.T) {
response := `{
"name":"Item",
"price":"22.99",
"currency":"GBP",
"quantity":1
}`
i := &Item{}
err := json.Unmarshal([]byte(response), i)
if err != nil {
t.Errorf("Item Unmarshal failed")
}
if i.Name != "Item" ||
i.Price != "22.99" ||
i.Currency != "GBP" ||
i.Quantity != 1 {
t.Errorf("Item decoded result is incorrect, Given: %v", i)
}
}

View File

@ -1,3 +1,5 @@
// +build unit
package paypalsdk package paypalsdk
import ( import (
@ -12,6 +14,70 @@ type webprofileTestServer struct {
t *testing.T t *testing.T
} }
func TestNewClient(t *testing.T) {
c, err := NewClient("", "", "")
if err == nil {
t.Errorf("Expected error for NewClient('','','')")
}
if c != nil {
t.Errorf("Expected nil Client for NewClient('','',''), got %v", c)
}
c, err = NewClient("1", "2", "3")
if err != nil {
t.Errorf("Not expected error for NewClient(1, 2, 3), got %v", err)
}
if c == nil {
t.Errorf("Expected non-nil Client for NewClient(1, 2, 3)")
}
}
func TestTypeUserInfo(t *testing.T) {
response := `{
"user_id": "https://www.paypal.com/webapps/auth/server/64ghr894040044",
"name": "Peter Pepper",
"given_name": "Peter",
"family_name": "Pepper",
"email": "ppuser@example.com"
}`
u := &UserInfo{}
err := json.Unmarshal([]byte(response), u)
if err != nil {
t.Errorf("UserInfo Unmarshal failed")
}
if u.ID != "https://www.paypal.com/webapps/auth/server/64ghr894040044" ||
u.Name != "Peter Pepper" ||
u.GivenName != "Peter" ||
u.FamilyName != "Pepper" ||
u.Email != "ppuser@example.com" {
t.Errorf("UserInfo decoded result is incorrect, Given: %v", u)
}
}
func TestTypeItem(t *testing.T) {
response := `{
"name":"Item",
"price":"22.99",
"currency":"GBP",
"quantity":1
}`
i := &Item{}
err := json.Unmarshal([]byte(response), i)
if err != nil {
t.Errorf("Item Unmarshal failed")
}
if i.Name != "Item" ||
i.Price != "22.99" ||
i.Currency != "GBP" ||
i.Quantity != 1 {
t.Errorf("Item decoded result is incorrect, Given: %v", i)
}
}
// ServeHTTP implements http.Handler // ServeHTTP implements http.Handler
func (ts *webprofileTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (ts *webprofileTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ts.t.Log(r.RequestURI) ts.t.Log(r.RequestURI)

View File

@ -1,88 +0,0 @@
package paypalsdk
import (
"testing"
)
func TestStoreCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.StoreCreditCard(CreditCard{})
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for invalid CC")
}
r2, e2 := c.StoreCreditCard(CreditCard{
Number: "4417119669820331",
Type: "visa",
ExpireMonth: "11",
ExpireYear: "2020",
CVV2: "874",
FirstName: "Foo",
LastName: "Bar",
})
if e2 != nil || r2 == nil {
t.Errorf("200 code expected for valid CC card. Error: %v", e2)
}
}
func TestDeleteCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.DeleteCreditCard("")
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for invalid CC ID")
}
}
func TestGetCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.GetCreditCard("BBGGG")
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for invalid CC, got CC %v", r1)
}
}
func TestGetCreditCards(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.GetCreditCards(nil)
if e1 != nil || r1 == nil {
t.Errorf("200 code expected. Error: %v", e1)
}
if r1.TotalItems < 1 {
t.Errorf("Expected >0 CCs, got %d", r1.TotalItems)
}
if r1.TotalPages < 1 {
t.Errorf("Expected >0 CCs page")
}
r2, e2 := c.GetCreditCards(&CreditCardsFilter{
Page: 2,
PageSize: 7,
})
if e2 != nil || r2 == nil {
t.Errorf("200 code expected. Error: %v", e2)
}
if r2.TotalItems < 1 {
t.Errorf("Expected >0 CCs, got %d", r2.TotalItems)
}
if r2.TotalPages < 1 {
t.Errorf("Expected >0 CCs page")
}
}
func TestPatchCreditCard(t *testing.T) {
c, _ := NewClient(testClientID, testSecret, APIBaseSandBox)
c.GetAccessToken()
r1, e1 := c.PatchCreditCard(testCardID, nil)
if e1 == nil || r1 != nil {
t.Errorf("Error is expected for empty update info")
}
}