From dd920d51517c4dde68d044dd0cd50716458f6194 Mon Sep 17 00:00:00 2001 From: Aliaksandr Pliutau Date: Thu, 2 Mar 2017 10:43:23 +0700 Subject: [PATCH] #23: unit_test.go, integration_test.go --- .travis.yml | 3 +- README.md | 48 ++-- auth_test.go | 68 ------ auth.go => authorization.go | 24 -- before-commit.sh | 6 - client.go | 46 +++- client_test.go | 33 --- identity_test.go | 31 --- integration_test.go | 375 +++++++++++++++++++++++++++++ order_test.go | 57 ----- payment_test.go | 61 ----- payout_test.go | 32 --- sale_test.go | 49 ---- types_test.go | 54 ----- webprofile_test.go => unit_test.go | 66 +++++ vault_test.go | 88 ------- 16 files changed, 492 insertions(+), 549 deletions(-) delete mode 100644 auth_test.go rename auth.go => authorization.go (79%) delete mode 100755 before-commit.sh delete mode 100644 client_test.go delete mode 100644 identity_test.go create mode 100644 integration_test.go delete mode 100644 order_test.go delete mode 100644 payment_test.go delete mode 100644 payout_test.go delete mode 100644 sale_test.go delete mode 100644 types_test.go rename webprofile_test.go => unit_test.go (84%) delete mode 100644 vault_test.go diff --git a/.travis.yml b/.travis.yml index 5d87905..4a2e093 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,8 @@ go: - 1.5 - 1.6 - 1.7 + - 1.8 install: - export PATH=$PATH:$HOME/gopath/bin script: - - go test -v + - go test -tags-unit diff --git a/README.md b/README.md index e23a435..da8096e 100644 --- a/README.md +++ b/README.md @@ -39,28 +39,21 @@ ### 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** -### Create Client +### New Client ```go import "github.com/logpacker/PayPal-Go-SDK" -``` -```go // Create a client instance c, err := paypalsdk.NewClient("clientID", "secretID", paypalsdk.APIBaseSandBox) 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() ``` ### Create direct paypal payment ```go -// Now we can create a paypal payment amount := paypalsdk.Amount{ Total: "7.00", Currency: "USD", @@ -69,13 +62,9 @@ redirectURI := "http://example.com/redirect-uri" cancelURI := "http://example.com/cancel-uri" description := "Description for this payment" 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 p := paypalsdk.Payment{ Intent: "sale", @@ -111,10 +100,7 @@ paymentResponse, err := client.CreatePayment(p) ### Execute approved payment ```go -// And the last step is to execute approved payment -// paymentID is returned via return_url paymentID := "PAY-17S8410768582940NKEE66EQ" -// payerID is returned via return_url payerID := "7E7MGXCWTTKK2" executeResult, err := c.ExecuteApprovedPayment(paymentID, payerID) ``` @@ -122,22 +108,19 @@ executeResult, err := c.ExecuteApprovedPayment(paymentID, payerID) ### Get payment by ID ```go -// Get created payment info -payment, err := c.GetPayment(paymentID) +payment, err := c.GetPayment("PAY-17S8410768582940NKEE66EQ") ``` ### Get list of payments ```go -// Get all payments slice payments, err := c.GetPayments() ``` ### Get authorization by ID ```go -authID := "2DC87612EK520411B" -auth, err := c.GetAuthorization(authID) +auth, err := c.GetAuthorization("2DC87612EK520411B") ``` ### Capture authorization @@ -161,8 +144,7 @@ auth, err := c.ReauthorizeAuthorization(authID, &paypalsdk.Amount{Total: "7.00", ### Get Sale by ID ```go -saleID := "36C38912MN9658832" -sale, err := c.GetSale(saleID) +sale, err := c.GetSale("36C38912MN9658832") ``` ### Refund Sale by ID @@ -177,14 +159,13 @@ refund, err := c.RefundSale(saleID, &paypalsdk.Amount{Total: "7.00", Currency: " ### Get Refund by ID ```go -orderID := "O-4J082351X3132253H" -refund, err := c.GetRefund(orderID) +refund, err := c.GetRefund("O-4J082351X3132253H") ``` ### Get Order by ID ```go -order, err := c.GetOrder(orderID) +order, err := c.GetOrder("O-4J082351X3132253H") ``` ### Authorize Order @@ -208,7 +189,6 @@ order, err := c.VoidOrder(orderID) ### Identity ```go -// Retreive tolen by authorization code token, err := c.GrantNewAccessTokenFromAuthCode("", "http://example.com/myapp/return.php") // ... or by refresh token token, err := c.GrantNewAccessTokenFromRefreshToken("") @@ -302,8 +282,6 @@ err := c.DeleteWebProfile("XP-CP6S-W9DY-96H8-MVN2") ### Vault ```go -// https://developer.paypal.com/docs/api/vault/ - // Store CC c.StoreCreditCard(paypalsdk.CreditCard{ Number: "4417119669820331", @@ -330,7 +308,7 @@ c.PatchCreditCard("CARD-ID-123", []paypalsdk.CreditCardField{ // Get it c.GetCreditCard("CARD-ID-123") -// get all stored credit cards +// Get all stored credit cards c.GetCreditCards(nil) ``` @@ -338,6 +316,10 @@ c.GetCreditCards(nil) * Fork a repository * Add/Fix something -* Run ./before-commit.sh to check that tests passed and code is formatted well -* Push to your repository -* Create pull request +* Check that tests are passing +* Create PR + +### Tests + +* Unit tests: `go test -tags=unit` +* Integration tests: `go test -tags=inegration` \ No newline at end of file diff --git a/auth_test.go b/auth_test.go deleted file mode 100644 index 37e9067..0000000 --- a/auth_test.go +++ /dev/null @@ -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()) - } -} diff --git a/auth.go b/authorization.go similarity index 79% rename from auth.go rename to authorization.go index 1b4bdf0..61a879b 100644 --- a/auth.go +++ b/authorization.go @@ -6,30 +6,6 @@ import ( "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 // Endpoint: GET /v1/payments/authorization/ID func (c *Client) GetAuthorization(authID string) (*Authorization, error) { diff --git a/before-commit.sh b/before-commit.sh deleted file mode 100755 index 5058759..0000000 --- a/before-commit.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -gofmt -s -w . -golint ./... -go vet ./... -go test -v -race ./... diff --git a/client.go b/client.go index 10f9c1b..7f59c64 100644 --- a/client.go +++ b/client.go @@ -15,24 +15,39 @@ import ( // APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox func NewClient(clientID string, secret string, APIBase string) (*Client, error) { 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{ - &http.Client{}, - clientID, - secret, - APIBase, - nil, - nil, + client: &http.Client{}, + ClientID: clientID, + Secret: secret, + APIBase: APIBase, }, 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 +// 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 } // SetAccessToken sets saved token to current client @@ -44,6 +59,13 @@ func (c *Client) SetAccessToken(token string) error { 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 // unmarshaled into v, or if v is an io.Writer, the response will // be written to it without decoding diff --git a/client_test.go b/client_test.go deleted file mode 100644 index 706bad0..0000000 --- a/client_test.go +++ /dev/null @@ -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()) - } -} diff --git a/identity_test.go b/identity_test.go deleted file mode 100644 index 9593b6d..0000000 --- a/identity_test.go +++ /dev/null @@ -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) - } -} diff --git a/integration_test.go b/integration_test.go new file mode 100644 index 0000000..1dbe71c --- /dev/null +++ b/integration_test.go @@ -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") + } +} diff --git a/order_test.go b/order_test.go deleted file mode 100644 index 31829b4..0000000 --- a/order_test.go +++ /dev/null @@ -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()) - } -} diff --git a/payment_test.go b/payment_test.go deleted file mode 100644 index ed088b3..0000000 --- a/payment_test.go +++ /dev/null @@ -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()) - } -} diff --git a/payout_test.go b/payout_test.go deleted file mode 100644 index e77e0bc..0000000 --- a/payout_test.go +++ /dev/null @@ -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") - } -} diff --git a/sale_test.go b/sale_test.go deleted file mode 100644 index 544e3a6..0000000 --- a/sale_test.go +++ /dev/null @@ -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()) - } -} diff --git a/types_test.go b/types_test.go deleted file mode 100644 index 3f87c13..0000000 --- a/types_test.go +++ /dev/null @@ -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) - } -} diff --git a/webprofile_test.go b/unit_test.go similarity index 84% rename from webprofile_test.go rename to unit_test.go index 0b654a2..92feaa5 100644 --- a/webprofile_test.go +++ b/unit_test.go @@ -1,3 +1,5 @@ +// +build unit + package paypalsdk import ( @@ -12,6 +14,70 @@ type webprofileTestServer struct { 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 func (ts *webprofileTestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { ts.t.Log(r.RequestURI) diff --git a/vault_test.go b/vault_test.go deleted file mode 100644 index 4bfd8d4..0000000 --- a/vault_test.go +++ /dev/null @@ -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") - } -}