<commit_before>package auctiontypes

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/cloudfoundry-incubator/runtime-schema/models"
)

//errors
var InsufficientResources = errors.New("insufficient resources for instance")
var NothingToStop = errors.New("found nothing to stop")

//AuctionRunner
type AuctionRunner interface {
	RunLRPStartAuction(auctionRequest StartAuctionRequest) (StartAuctionResult, error)
	RunLRPStopAuction(auctionRequest StopAuctionRequest) (StopAuctionResult, error)
}

type StartAuctionRequest struct {
	LRPStartAuction models.LRPStartAuction
	RepGuids        RepGuids
	Rules           StartAuctionRules
}

type StartAuctionResult struct {
	LRPStartAuction   models.LRPStartAuction
	Winner            string
	NumRounds         int
	NumCommunications int

	AuctionStartTime time.Time
	BiddingDuration  time.Duration
	Duration         time.Duration
	Events           AuctionEvents
}

type AuctionEvents []AuctionEvent

func (a AuctionEvents) String() string {
	s := ""
	round := 0
	for _, event := range a {
		if round != event.Round {
			s += fmt.Sprintf("%d:\n", event.Round)
			round = event.Round
		}
		components := []string{event.Event}
		if event.Duration > 0 {
			components = append(components, event.Duration.String())
		}
		if event.Communication > 0 {
			components = append(components, fmt.Sprintf("+%d", event.Communication))
		}
		if event.Info != "" {
			components = append(components, event.Info)
		}

		s += "  " + strings.Join(components, " ") + "\n"
	}

	return s
}

type AuctionEvent struct {
	Event         string
	Duration      time.Duration
	Round         int
	Communication int
	Info          string
}

type StopAuctionRequest struct {
	LRPStopAuction models.LRPStopAuction
	RepGuids       RepGuids
}

type StopAuctionResult struct {
	LRPStopAuction    models.LRPStopAuction
	Winner            string
	NumCommunications int
	BiddingDuration   time.Duration
	Duration          time.Duration
}

type StartAuctionRules struct {
	Algorithm              string
	MaxRounds              int
	MaxBiddingPoolFraction float64
	MinBiddingPool         int
	ComparisonPercentile   float64
}

type RepGuids []string

type RepPoolClient interface {
	BidForStartAuction(repGuids []string, startAuctionInfo StartAuctionInfo) StartAuctionBids
	BidForStopAuction(repGuids []string, stopAuctionInfo StopAuctionInfo) StopAuctionBids
	RebidThenTentativelyReserve(repGuids []string, startAuction models.LRPStartAuction) StartAuctionBids
	ReleaseReservation(repGuids []string, startAuction models.LRPStartAuction)
	Run(repGuid string, startAuction models.LRPStartAuction)
	Stop(repGuid string, stopInstance models.StopLRPInstance)
}

type AuctionRepDelegate interface {
	RemainingResources() (Resources, error)
	TotalResources() (Resources, error)
	NumInstancesForProcessGuid(processGuid string) (int, error)
	InstanceGuidsForProcessGuidAndIndex(processGuid string, index int) ([]string, error)

	Reserve(startAuction models.LRPStartAuction) error
	ReleaseReservation(startAuction models.LRPStartAuction) error
	Run(startAuction models.LRPStartAuction) error
	Stop(stopInstance models.StopLRPInstance) error
}

//simulation-only interface
type SimulationRepPoolClient interface {
	RepPoolClient

	TotalResources(repGuid string) Resources
	SimulatedInstances(repGuid string) []SimulatedInstance
	SetSimulatedInstances(repGuid string, instances []SimulatedInstance)
	Reset(repGuid string)
}

//simulation-only interface
type SimulationAuctionRepDelegate interface {
	AuctionRepDelegate
	SetSimulatedInstances(instances []SimulatedInstance)
	SimulatedInstances() []SimulatedInstance
}

func NewStartAuctionInfoFromLRPStartAuction(auction models.LRPStartAuction) StartAuctionInfo {
	return StartAuctionInfo{
		ProcessGuid: auction.DesiredLRP.ProcessGuid,
		DiskMB:      auction.DesiredLRP.DiskMB,
		MemoryMB:    auction.DesiredLRP.MemoryMB,

		InstanceGuid: auction.InstanceGuid,
		Index:        auction.Index,
	}
}

func NewStopAuctionInfoFromLRPStopAuction(auction models.LRPStopAuction) StopAuctionInfo {
	return StopAuctionInfo{
		ProcessGuid: auction.ProcessGuid,
		Index:       auction.Index,
	}
}

type StartAuctionBid struct {
	Rep   string
	Bid   float64
	Error string
}

type StartAuctionBids []StartAuctionBid

type StopAuctionBid struct {
	Rep           string
	InstanceGuids []string
	Bid           float64
	Error         string
}

type StopAuctionBids []StopAuctionBid

type Resources struct {
	DiskMB     int
	MemoryMB   int
	Containers int
}

type StartAuctionInfo struct {
	ProcessGuid  string
	InstanceGuid string
	DiskMB       int
	MemoryMB     int
	Index        int
}

func (info StartAuctionInfo) LRPIdentifier() models.LRPIdentifier {
	return models.LRPIdentifier{
		ProcessGuid:  info.ProcessGuid,
		Index:        info.Index,
		InstanceGuid: info.InstanceGuid,
	}
}

type StopAuctionInfo struct {
	ProcessGuid string
	Index       int
}

type SimulatedInstance struct {
	ProcessGuid  string
	InstanceGuid string
	Index        int
	MemoryMB     int
	DiskMB       int
}
<commit_msg>nuke lrp identifier<commit_after>package auctiontypes

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/cloudfoundry-incubator/runtime-schema/models"
)

//errors
var InsufficientResources = errors.New("insufficient resources for instance")
var NothingToStop = errors.New("found nothing to stop")

//AuctionRunner
type AuctionRunner interface {
	RunLRPStartAuction(auctionRequest StartAuctionRequest) (StartAuctionResult, error)
	RunLRPStopAuction(auctionRequest StopAuctionRequest) (StopAuctionResult, error)
}

type StartAuctionRequest struct {
	LRPStartAuction models.LRPStartAuction
	RepGuids        RepGuids
	Rules           StartAuctionRules
}

type StartAuctionResult struct {
	LRPStartAuction   models.LRPStartAuction
	Winner            string
	NumRounds         int
	NumCommunications int

	AuctionStartTime time.Time
	BiddingDuration  time.Duration
	Duration         time.Duration
	Events           AuctionEvents
}

type AuctionEvents []AuctionEvent

func (a AuctionEvents) String() string {
	s := ""
	round := 0
	for _, event := range a {
		if round != event.Round {
			s += fmt.Sprintf("%d:\n", event.Round)
			round = event.Round
		}
		components := []string{event.Event}
		if event.Duration > 0 {
			components = append(components, event.Duration.String())
		}
		if event.Communication > 0 {
			components = append(components, fmt.Sprintf("+%d", event.Communication))
		}
		if event.Info != "" {
			components = append(components, event.Info)
		}

		s += "  " + strings.Join(components, " ") + "\n"
	}

	return s
}

type AuctionEvent struct {
	Event         string
	Duration      time.Duration
	Round         int
	Communication int
	Info          string
}

type StopAuctionRequest struct {
	LRPStopAuction models.LRPStopAuction
	RepGuids       RepGuids
}

type StopAuctionResult struct {
	LRPStopAuction    models.LRPStopAuction
	Winner            string
	NumCommunications int
	BiddingDuration   time.Duration
	Duration          time.Duration
}

type StartAuctionRules struct {
	Algorithm              string
	MaxRounds              int
	MaxBiddingPoolFraction float64
	MinBiddingPool         int
	ComparisonPercentile   float64
}

type RepGuids []string

type RepPoolClient interface {
	BidForStartAuction(repGuids []string, startAuctionInfo StartAuctionInfo) StartAuctionBids
	BidForStopAuction(repGuids []string, stopAuctionInfo StopAuctionInfo) StopAuctionBids
	RebidThenTentativelyReserve(repGuids []string, startAuction models.LRPStartAuction) StartAuctionBids
	ReleaseReservation(repGuids []string, startAuction models.LRPStartAuction)
	Run(repGuid string, startAuction models.LRPStartAuction)
	Stop(repGuid string, stopInstance models.StopLRPInstance)
}

type AuctionRepDelegate interface {
	RemainingResources() (Resources, error)
	TotalResources() (Resources, error)
	NumInstancesForProcessGuid(processGuid string) (int, error)
	InstanceGuidsForProcessGuidAndIndex(processGuid string, index int) ([]string, error)

	Reserve(startAuction models.LRPStartAuction) error
	ReleaseReservation(startAuction models.LRPStartAuction) error
	Run(startAuction models.LRPStartAuction) error
	Stop(stopInstance models.StopLRPInstance) error
}

//simulation-only interface
type SimulationRepPoolClient interface {
	RepPoolClient

	TotalResources(repGuid string) Resources
	SimulatedInstances(repGuid string) []SimulatedInstance
	SetSimulatedInstances(repGuid string, instances []SimulatedInstance)
	Reset(repGuid string)
}

//simulation-only interface
type SimulationAuctionRepDelegate interface {
	AuctionRepDelegate
	SetSimulatedInstances(instances []SimulatedInstance)
	SimulatedInstances() []SimulatedInstance
}

func NewStartAuctionInfoFromLRPStartAuction(auction models.LRPStartAuction) StartAuctionInfo {
	return StartAuctionInfo{
		ProcessGuid: auction.DesiredLRP.ProcessGuid,
		DiskMB:      auction.DesiredLRP.DiskMB,
		MemoryMB:    auction.DesiredLRP.MemoryMB,

		InstanceGuid: auction.InstanceGuid,
		Index:        auction.Index,
	}
}

func NewStopAuctionInfoFromLRPStopAuction(auction models.LRPStopAuction) StopAuctionInfo {
	return StopAuctionInfo{
		ProcessGuid: auction.ProcessGuid,
		Index:       auction.Index,
	}
}

type StartAuctionBid struct {
	Rep   string
	Bid   float64
	Error string
}

type StartAuctionBids []StartAuctionBid

type StopAuctionBid struct {
	Rep           string
	InstanceGuids []string
	Bid           float64
	Error         string
}

type StopAuctionBids []StopAuctionBid

type Resources struct {
	DiskMB     int
	MemoryMB   int
	Containers int
}

type StartAuctionInfo struct {
	ProcessGuid  string
	InstanceGuid string
	DiskMB       int
	MemoryMB     int
	Index        int
}

type StopAuctionInfo struct {
	ProcessGuid string
	Index       int
}

type SimulatedInstance struct {
	ProcessGuid  string
	InstanceGuid string
	Index        int
	MemoryMB     int
	DiskMB       int
}
<|endoftext|>


<commit_before>package handlers_test

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	log "github.com/Sirupsen/logrus"
	"github.com/jrzimmerman/bestrida-server-go/handlers"
	strava "github.com/strava/go.strava"
)

func TestGetAthleteByIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var a *strava.AthleteDetailed
	if err := json.NewDecoder(rec.Body).Decode(&a); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.WithField("Athlete ID", a.Id).Info("Athlete returned from Strava")

	if a.Id != int64(id) {
		t.Errorf("unexpected athlete")
	}
}

func TestGetAthleteByIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetAthleteByIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStrava(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var as *[]strava.AthleteSummary
	if err := json.NewDecoder(rec.Body).Decode(&as); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete friends returned from Strava")
}

func TestGetSegmentsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var ss *[]strava.SegmentSummary
	if err := json.NewDecoder(rec.Body).Decode(&ss); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete segments returned from Strava")
}
<commit_msg>add athlete tests<commit_after>package handlers_test

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	log "github.com/Sirupsen/logrus"
	"github.com/jrzimmerman/bestrida-server-go/handlers"
	strava "github.com/strava/go.strava"
)

func TestGetAthleteByIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var a *strava.AthleteDetailed
	if err := json.NewDecoder(rec.Body).Decode(&a); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.WithField("Athlete ID", a.Id).Info("Athlete returned from Strava")

	if a.Id != int64(id) {
		t.Errorf("unexpected athlete")
	}
}

func TestGetAthleteByIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetAthleteByIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var as *[]strava.AthleteSummary
	if err := json.NewDecoder(rec.Body).Decode(&as); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete friends returned from Strava")
}

func TestGetFriendsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetFriendsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/friends", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaSuccess(t *testing.T) {
	id := 1027935

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusOK; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}

	// Unmarshal and check the response body
	var ss *[]strava.SegmentSummary
	if err := json.NewDecoder(rec.Body).Decode(&ss); err != nil {
		t.Errorf("unable to decode response: %s", err)
	}

	log.Info("Athlete segments returned from Strava")
}

func TestGetSegmentsByUserIDFromStravaFailureURL(t *testing.T) {
	id := "fred"

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}

func TestGetSegmentsByUserIDFromStravaFailureID(t *testing.T) {
	id := 0

	// Create the http request
	req, err := http.NewRequest("GET", fmt.Sprintf("/strava/athletes/%v/segments", id), nil)
	if err != nil {
		t.Error("unable to generate request", err)
	}

	// Send the request to the API
	rec := httptest.NewRecorder()
	handlers.API().ServeHTTP(rec, req)

	// Check the status code
	if exp := http.StatusInternalServerError; rec.Code != exp {
		t.Errorf("expected status code %v, got: %v", exp, rec.Code)
	}
}
<|endoftext|>


<commit_before>package stripe

import "encoding/json"

// List of values that BalanceTransactionStatus can take.
const (
	BalanceTransactionStatusAvailable BalanceTransactionStatus = "available"
	BalanceTransactionStatusPending   BalanceTransactionStatus = "pending"
)

// BalanceTransactionType is the list of allowed values for the balance transaction's type.
type BalanceTransactionType string

// List of values that BalanceTransactionType can take.
const (
	BalanceTransactionTypeAdjustment                      BalanceTransactionType = "adjustment"
	BalanceTransactionTypeAnticipationRepayment           BalanceTransactionType = "anticipation_repayment"
	BalanceTransactionTypeApplicationFee                  BalanceTransactionType = "application_fee"
	BalanceTransactionTypeApplicationFeeRefund            BalanceTransactionType = "application_fee_refund"
	BalanceTransactionTypeCharge                          BalanceTransactionType = "charge"
	BalanceTransactionTypeContribution                    BalanceTransactionType = "contribution"
	BalanceTransactionTypeIssuingAuthorizationHold        BalanceTransactionType = "issuing_authorization_hold"
	BalanceTransactionTypeIssuingAuthorizationRelease     BalanceTransactionType = "issuing_authorization_release"
	BalanceTransactionTypeIssuingAuthorizationDispute     BalanceTransactionType = "issuing_dispute"
	BalanceTransactionTypeIssuingAuthorizationTransaction BalanceTransactionType = "issuing_transaction"
	BalanceTransactionTypePayment                         BalanceTransactionType = "payment"
	BalanceTransactionTypePaymentFailureRefund            BalanceTransactionType = "payment_failure_refund"
	BalanceTransactionTypePaymentRefund                   BalanceTransactionType = "payment_refund"
	BalanceTransactionTypePayout                          BalanceTransactionType = "payout"
	BalanceTransactionTypePayoutCancel                    BalanceTransactionType = "payout_cancel"
	BalanceTransactionTypePayoutFailure                   BalanceTransactionType = "payout_failure"
	BalanceTransactionTypeRefund                          BalanceTransactionType = "refund"
	BalanceTransactionTypeStripeFee                       BalanceTransactionType = "stripe_fee"
	BalanceTransactionTypeTransfer                        BalanceTransactionType = "transfer"
	BalanceTransactionTypeTransferRefund                  BalanceTransactionType = "transfer_refund"
)

// BalanceTransactionSourceType consts represent valid balance transaction sources.
type BalanceTransactionSourceType string

// List of values that BalanceTransactionSourceType can take.
const (
	BalanceTransactionSourceTypeApplicationFee       BalanceTransactionSourceType = "application_fee"
	BalanceTransactionSourceTypeCharge               BalanceTransactionSourceType = "charge"
	BalanceTransactionSourceTypeDispute              BalanceTransactionSourceType = "dispute"
	BalanceTransactionSourceTypeIssuingAuthorization BalanceTransactionSourceType = "issuing.authorization"
	BalanceTransactionSourceTypeIssuingTransaction   BalanceTransactionSourceType = "issuing.transaction"
	BalanceTransactionSourceTypePayout               BalanceTransactionSourceType = "payout"
	BalanceTransactionSourceTypeRefund               BalanceTransactionSourceType = "refund"
	BalanceTransactionSourceTypeReversal             BalanceTransactionSourceType = "reversal"
	BalanceTransactionSourceTypeTransfer             BalanceTransactionSourceType = "transfer"
)

// BalanceTransactionReportingCategory represents reporting categories for balance transactions.
type BalanceTransactionReportingCategory string

// List of values that BalanceTransactionReportingCategory can take.
const (
	BalanceTransactionReportingCategoryAdvance                     BalanceTransactionReportingCategory = "advance"
	BalanceTransactionReportingCategoryAdvanceFunding              BalanceTransactionReportingCategory = "advance_funding"
	BalanceTransactionReportingCategoryCharge                      BalanceTransactionReportingCategory = "charge"
	BalanceTransactionReportingCategoryChargeFailure               BalanceTransactionReportingCategory = "charge_failure"
	BalanceTransactionReportingCategoryConnectCollectionTransfer   BalanceTransactionReportingCategory = "connect_collection_transfer"
	BalanceTransactionReportingCategoryConnectReservedFunds        BalanceTransactionReportingCategory = "connect_reserved_funds"
	BalanceTransactionReportingCategoryDispute                     BalanceTransactionReportingCategory = "dispute"
	BalanceTransactionReportingCategoryDisputeReversal             BalanceTransactionReportingCategory = "dispute_reversal"
	BalanceTransactionReportingCategoryFee                         BalanceTransactionReportingCategory = "fee"
	BalanceTransactionReportingCategoryIssuingAuthorizationHold    BalanceTransactionReportingCategory = "issuing_authorization_hold"
	BalanceTransactionReportingCategoryIssuingAuthorizationRelease BalanceTransactionReportingCategory = "issuing_authorization_release"
	BalanceTransactionReportingCategoryIssuingTransaction          BalanceTransactionReportingCategory = "issuing_transaction"
	BalanceTransactionReportingCategoryOtherAdjustment             BalanceTransactionReportingCategory = "other_adjustment"
	BalanceTransactionReportingCategoryPartialCaptureReversal      BalanceTransactionReportingCategory = "partial_capture_reversal"
	BalanceTransactionReportingCategoryPayout                      BalanceTransactionReportingCategory = "payout"
	BalanceTransactionReportingCategoryPayoutReversal              BalanceTransactionReportingCategory = "payout_reversal"
	BalanceTransactionReportingCategoryPlatformEarning             BalanceTransactionReportingCategory = "platform_earning"
	BalanceTransactionReportingCategoryPlatformEarningRefund       BalanceTransactionReportingCategory = "platform_earning_refund"
	BalanceTransactionReportingCategoryRefund                      BalanceTransactionReportingCategory = "refund"
	BalanceTransactionReportingCategoryRefundFailure               BalanceTransactionReportingCategory = "refund_failure"
	BalanceTransactionReportingCategoryRiskReservedFunds           BalanceTransactionReportingCategory = "risk_reserved_funds"
	BalanceTransactionReportingCategoryTax                         BalanceTransactionReportingCategory = "tax"
	BalanceTransactionReportingCategoryTopup                       BalanceTransactionReportingCategory = "topup"
	BalanceTransactionReportingCategoryTopupReversal               BalanceTransactionReportingCategory = "topup_reversal"
	BalanceTransactionReportingCategoryTransfer                    BalanceTransactionReportingCategory = "transfer"
	BalanceTransactionReportingCategoryTransferReversal            BalanceTransactionReportingCategory = "transfer_reversal"
)

// BalanceTransactionSource describes the source of a balance Transaction.
// The Type should indicate which object is fleshed out.
// For more details see https://stripe.com/docs/api#retrieve_balance_transaction
type BalanceTransactionSource struct {
	ApplicationFee       *ApplicationFee              `json:"-"`
	Charge               *Charge                      `json:"-"`
	Dispute              *Dispute                     `json:"-"`
	ID                   string                       `json:"id"`
	IssuingAuthorization *IssuingAuthorization        `json:"-"`
	IssuingTransaction   *IssuingAuthorization        `json:"-"`
	Payout               *Payout                      `json:"-"`
	Refund               *Refund                      `json:"-"`
	Reversal             *Reversal                    `json:"-"`
	Transfer             *Transfer                    `json:"-"`
	Type                 BalanceTransactionSourceType `json:"object"`
}

// BalanceTransactionParams is the set of parameters that can be used when retrieving a transaction.
// For more details see https://stripe.com/docs/api#retrieve_balance_transaction.
type BalanceTransactionParams struct {
	Params `form:"*"`
}

// BalanceTransactionListParams is the set of parameters that can be used when listing balance transactions.
// For more details see https://stripe.com/docs/api/#balance_history.
type BalanceTransactionListParams struct {
	ListParams       `form:"*"`
	AvailableOn      *int64            `form:"available_on"`
	AvailableOnRange *RangeQueryParams `form:"available_on"`
	Created          *int64            `form:"created"`
	CreatedRange     *RangeQueryParams `form:"created"`
	Currency         *string           `form:"currency"`
	Payout           *string           `form:"payout"`
	Source           *string           `form:"source"`
	Type             *string           `form:"type"`
}

// BalanceTransaction is the resource representing the balance transaction.
// For more details see https://stripe.com/docs/api/#balance.
type BalanceTransaction struct {
	APIResource
	Amount            int64                               `json:"amount"`
	AvailableOn       int64                               `json:"available_on"`
	Created           int64                               `json:"created"`
	Currency          Currency                            `json:"currency"`
	Description       string                              `json:"description"`
	ExchangeRate      float64                             `json:"exchange_rate"`
	ID                string                              `json:"id"`
	Fee               int64                               `json:"fee"`
	FeeDetails        []*BalanceTransactionFee            `json:"fee_details"`
	Net               int64                               `json:"net"`
	ReportingCategory BalanceTransactionReportingCategory `json:"reporting_category"`
	Source            *BalanceTransactionSource           `json:"source"`
	Status            BalanceTransactionStatus            `json:"status"`
	Type              BalanceTransactionType              `json:"type"`
}

// BalanceTransactionList is a list of transactions as returned from a list endpoint.
type BalanceTransactionList struct {
	APIResource
	ListMeta
	Data []*BalanceTransaction `json:"data"`
}

// BalanceTransactionFee is a structure that breaks down the fees in a transaction.
type BalanceTransactionFee struct {
	Amount      int64    `json:"amount"`
	Application string   `json:"application"`
	Currency    Currency `json:"currency"`
	Description string   `json:"description"`
	Type        string   `json:"type"`
}

// UnmarshalJSON handles deserialization of a Transaction.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (t *BalanceTransaction) UnmarshalJSON(data []byte) error {
	if id, ok := ParseID(data); ok {
		t.ID = id
		return nil
	}

	type balanceTransaction BalanceTransaction
	var v balanceTransaction
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}

	*t = BalanceTransaction(v)
	return nil
}

// UnmarshalJSON handles deserialization of a BalanceTransactionSource.
// This custom unmarshaling is needed because the specific
// type of transaction source it refers to is specified in the JSON
func (s *BalanceTransactionSource) UnmarshalJSON(data []byte) error {
	if id, ok := ParseID(data); ok {
		s.ID = id
		return nil
	}

	type balanceTransactionSource BalanceTransactionSource
	var v balanceTransactionSource
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}

	var err error
	*s = BalanceTransactionSource(v)

	switch s.Type {
	case BalanceTransactionSourceTypeApplicationFee:
		err = json.Unmarshal(data, &s.ApplicationFee)
	case BalanceTransactionSourceTypeCharge:
		err = json.Unmarshal(data, &s.Charge)
	case BalanceTransactionSourceTypeDispute:
		err = json.Unmarshal(data, &s.Dispute)
	case BalanceTransactionSourceTypeIssuingAuthorization:
		err = json.Unmarshal(data, &s.IssuingAuthorization)
	case BalanceTransactionSourceTypeIssuingTransaction:
		err = json.Unmarshal(data, &s.IssuingTransaction)
	case BalanceTransactionSourceTypePayout:
		err = json.Unmarshal(data, &s.Payout)
	case BalanceTransactionSourceTypeRefund:
		err = json.Unmarshal(data, &s.Refund)
	case BalanceTransactionSourceTypeReversal:
		err = json.Unmarshal(data, &s.Reversal)
	case BalanceTransactionSourceTypeTransfer:
		err = json.Unmarshal(data, &s.Transfer)
	}

	return err
}
<commit_msg>Properly deserialize `IssuingDispute` on `BalanceTransaction`<commit_after>package stripe

import "encoding/json"

// List of values that BalanceTransactionStatus can take.
const (
	BalanceTransactionStatusAvailable BalanceTransactionStatus = "available"
	BalanceTransactionStatusPending   BalanceTransactionStatus = "pending"
)

// BalanceTransactionType is the list of allowed values for the balance transaction's type.
type BalanceTransactionType string

// List of values that BalanceTransactionType can take.
const (
	BalanceTransactionTypeAdjustment                      BalanceTransactionType = "adjustment"
	BalanceTransactionTypeAnticipationRepayment           BalanceTransactionType = "anticipation_repayment"
	BalanceTransactionTypeApplicationFee                  BalanceTransactionType = "application_fee"
	BalanceTransactionTypeApplicationFeeRefund            BalanceTransactionType = "application_fee_refund"
	BalanceTransactionTypeCharge                          BalanceTransactionType = "charge"
	BalanceTransactionTypeContribution                    BalanceTransactionType = "contribution"
	BalanceTransactionTypeIssuingAuthorizationHold        BalanceTransactionType = "issuing_authorization_hold"
	BalanceTransactionTypeIssuingAuthorizationRelease     BalanceTransactionType = "issuing_authorization_release"
	BalanceTransactionTypeIssuingAuthorizationDispute     BalanceTransactionType = "issuing_dispute"
	BalanceTransactionTypeIssuingAuthorizationTransaction BalanceTransactionType = "issuing_transaction"
	BalanceTransactionTypePayment                         BalanceTransactionType = "payment"
	BalanceTransactionTypePaymentFailureRefund            BalanceTransactionType = "payment_failure_refund"
	BalanceTransactionTypePaymentRefund                   BalanceTransactionType = "payment_refund"
	BalanceTransactionTypePayout                          BalanceTransactionType = "payout"
	BalanceTransactionTypePayoutCancel                    BalanceTransactionType = "payout_cancel"
	BalanceTransactionTypePayoutFailure                   BalanceTransactionType = "payout_failure"
	BalanceTransactionTypeRefund                          BalanceTransactionType = "refund"
	BalanceTransactionTypeStripeFee                       BalanceTransactionType = "stripe_fee"
	BalanceTransactionTypeTransfer                        BalanceTransactionType = "transfer"
	BalanceTransactionTypeTransferRefund                  BalanceTransactionType = "transfer_refund"
)

// BalanceTransactionSourceType consts represent valid balance transaction sources.
type BalanceTransactionSourceType string

// List of values that BalanceTransactionSourceType can take.
const (
	BalanceTransactionSourceTypeApplicationFee       BalanceTransactionSourceType = "application_fee"
	BalanceTransactionSourceTypeCharge               BalanceTransactionSourceType = "charge"
	BalanceTransactionSourceTypeDispute              BalanceTransactionSourceType = "dispute"
	BalanceTransactionSourceTypeIssuingAuthorization BalanceTransactionSourceType = "issuing.authorization"
	BalanceTransactionSourceTypeIssuingDispute       BalanceTransactionSourceType = "issuing.dispute"
	BalanceTransactionSourceTypeIssuingTransaction   BalanceTransactionSourceType = "issuing.transaction"
	BalanceTransactionSourceTypePayout               BalanceTransactionSourceType = "payout"
	BalanceTransactionSourceTypeRefund               BalanceTransactionSourceType = "refund"
	BalanceTransactionSourceTypeReversal             BalanceTransactionSourceType = "reversal"
	BalanceTransactionSourceTypeTransfer             BalanceTransactionSourceType = "transfer"
)

// BalanceTransactionReportingCategory represents reporting categories for balance transactions.
type BalanceTransactionReportingCategory string

// List of values that BalanceTransactionReportingCategory can take.
const (
	BalanceTransactionReportingCategoryAdvance                     BalanceTransactionReportingCategory = "advance"
	BalanceTransactionReportingCategoryAdvanceFunding              BalanceTransactionReportingCategory = "advance_funding"
	BalanceTransactionReportingCategoryCharge                      BalanceTransactionReportingCategory = "charge"
	BalanceTransactionReportingCategoryChargeFailure               BalanceTransactionReportingCategory = "charge_failure"
	BalanceTransactionReportingCategoryConnectCollectionTransfer   BalanceTransactionReportingCategory = "connect_collection_transfer"
	BalanceTransactionReportingCategoryConnectReservedFunds        BalanceTransactionReportingCategory = "connect_reserved_funds"
	BalanceTransactionReportingCategoryDispute                     BalanceTransactionReportingCategory = "dispute"
	BalanceTransactionReportingCategoryDisputeReversal             BalanceTransactionReportingCategory = "dispute_reversal"
	BalanceTransactionReportingCategoryFee                         BalanceTransactionReportingCategory = "fee"
	BalanceTransactionReportingCategoryIssuingAuthorizationHold    BalanceTransactionReportingCategory = "issuing_authorization_hold"
	BalanceTransactionReportingCategoryIssuingAuthorizationRelease BalanceTransactionReportingCategory = "issuing_authorization_release"
	BalanceTransactionReportingCategoryIssuingTransaction          BalanceTransactionReportingCategory = "issuing_transaction"
	BalanceTransactionReportingCategoryOtherAdjustment             BalanceTransactionReportingCategory = "other_adjustment"
	BalanceTransactionReportingCategoryPartialCaptureReversal      BalanceTransactionReportingCategory = "partial_capture_reversal"
	BalanceTransactionReportingCategoryPayout                      BalanceTransactionReportingCategory = "payout"
	BalanceTransactionReportingCategoryPayoutReversal              BalanceTransactionReportingCategory = "payout_reversal"
	BalanceTransactionReportingCategoryPlatformEarning             BalanceTransactionReportingCategory = "platform_earning"
	BalanceTransactionReportingCategoryPlatformEarningRefund       BalanceTransactionReportingCategory = "platform_earning_refund"
	BalanceTransactionReportingCategoryRefund                      BalanceTransactionReportingCategory = "refund"
	BalanceTransactionReportingCategoryRefundFailure               BalanceTransactionReportingCategory = "refund_failure"
	BalanceTransactionReportingCategoryRiskReservedFunds           BalanceTransactionReportingCategory = "risk_reserved_funds"
	BalanceTransactionReportingCategoryTax                         BalanceTransactionReportingCategory = "tax"
	BalanceTransactionReportingCategoryTopup                       BalanceTransactionReportingCategory = "topup"
	BalanceTransactionReportingCategoryTopupReversal               BalanceTransactionReportingCategory = "topup_reversal"
	BalanceTransactionReportingCategoryTransfer                    BalanceTransactionReportingCategory = "transfer"
	BalanceTransactionReportingCategoryTransferReversal            BalanceTransactionReportingCategory = "transfer_reversal"
)

// BalanceTransactionSource describes the source of a balance Transaction.
// The Type should indicate which object is fleshed out.
// For more details see https://stripe.com/docs/api#retrieve_balance_transaction
type BalanceTransactionSource struct {
	ApplicationFee       *ApplicationFee              `json:"-"`
	Charge               *Charge                      `json:"-"`
	Dispute              *Dispute                     `json:"-"`
	ID                   string                       `json:"id"`
	IssuingAuthorization *IssuingAuthorization        `json:"-"`
	IssuingDispute       *IssuingDispute              `json:"-"`
	IssuingTransaction   *IssuingAuthorization        `json:"-"`
	Payout               *Payout                      `json:"-"`
	Refund               *Refund                      `json:"-"`
	Reversal             *Reversal                    `json:"-"`
	Transfer             *Transfer                    `json:"-"`
	Type                 BalanceTransactionSourceType `json:"object"`
}

// BalanceTransactionParams is the set of parameters that can be used when retrieving a transaction.
// For more details see https://stripe.com/docs/api#retrieve_balance_transaction.
type BalanceTransactionParams struct {
	Params `form:"*"`
}

// BalanceTransactionListParams is the set of parameters that can be used when listing balance transactions.
// For more details see https://stripe.com/docs/api/#balance_history.
type BalanceTransactionListParams struct {
	ListParams       `form:"*"`
	AvailableOn      *int64            `form:"available_on"`
	AvailableOnRange *RangeQueryParams `form:"available_on"`
	Created          *int64            `form:"created"`
	CreatedRange     *RangeQueryParams `form:"created"`
	Currency         *string           `form:"currency"`
	Payout           *string           `form:"payout"`
	Source           *string           `form:"source"`
	Type             *string           `form:"type"`
}

// BalanceTransaction is the resource representing the balance transaction.
// For more details see https://stripe.com/docs/api/#balance.
type BalanceTransaction struct {
	APIResource
	Amount            int64                               `json:"amount"`
	AvailableOn       int64                               `json:"available_on"`
	Created           int64                               `json:"created"`
	Currency          Currency                            `json:"currency"`
	Description       string                              `json:"description"`
	ExchangeRate      float64                             `json:"exchange_rate"`
	ID                string                              `json:"id"`
	Fee               int64                               `json:"fee"`
	FeeDetails        []*BalanceTransactionFee            `json:"fee_details"`
	Net               int64                               `json:"net"`
	ReportingCategory BalanceTransactionReportingCategory `json:"reporting_category"`
	Source            *BalanceTransactionSource           `json:"source"`
	Status            BalanceTransactionStatus            `json:"status"`
	Type              BalanceTransactionType              `json:"type"`
}

// BalanceTransactionList is a list of transactions as returned from a list endpoint.
type BalanceTransactionList struct {
	APIResource
	ListMeta
	Data []*BalanceTransaction `json:"data"`
}

// BalanceTransactionFee is a structure that breaks down the fees in a transaction.
type BalanceTransactionFee struct {
	Amount      int64    `json:"amount"`
	Application string   `json:"application"`
	Currency    Currency `json:"currency"`
	Description string   `json:"description"`
	Type        string   `json:"type"`
}

// UnmarshalJSON handles deserialization of a Transaction.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (t *BalanceTransaction) UnmarshalJSON(data []byte) error {
	if id, ok := ParseID(data); ok {
		t.ID = id
		return nil
	}

	type balanceTransaction BalanceTransaction
	var v balanceTransaction
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}

	*t = BalanceTransaction(v)
	return nil
}

// UnmarshalJSON handles deserialization of a BalanceTransactionSource.
// This custom unmarshaling is needed because the specific
// type of transaction source it refers to is specified in the JSON
func (s *BalanceTransactionSource) UnmarshalJSON(data []byte) error {
	if id, ok := ParseID(data); ok {
		s.ID = id
		return nil
	}

	type balanceTransactionSource BalanceTransactionSource
	var v balanceTransactionSource
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}

	var err error
	*s = BalanceTransactionSource(v)

	switch s.Type {
	case BalanceTransactionSourceTypeApplicationFee:
		err = json.Unmarshal(data, &s.ApplicationFee)
	case BalanceTransactionSourceTypeCharge:
		err = json.Unmarshal(data, &s.Charge)
	case BalanceTransactionSourceTypeDispute:
		err = json.Unmarshal(data, &s.Dispute)
	case BalanceTransactionSourceTypeIssuingAuthorization:
		err = json.Unmarshal(data, &s.IssuingAuthorization)
	case BalanceTransactionSourceTypeIssuingDispute:
		err = json.Unmarshal(data, &s.IssuingDispute)
	case BalanceTransactionSourceTypeIssuingTransaction:
		err = json.Unmarshal(data, &s.IssuingTransaction)
	case BalanceTransactionSourceTypePayout:
		err = json.Unmarshal(data, &s.Payout)
	case BalanceTransactionSourceTypeRefund:
		err = json.Unmarshal(data, &s.Refund)
	case BalanceTransactionSourceTypeReversal:
		err = json.Unmarshal(data, &s.Reversal)
	case BalanceTransactionSourceTypeTransfer:
		err = json.Unmarshal(data, &s.Transfer)
	}

	return err
}
<|endoftext|>


<commit_before>// Package bankaccount provides the /bank_accounts APIs
package bankaccount

import (
	"errors"
	"fmt"
	"strconv"

	stripe "github.com/stripe/stripe-go"
)

// Client is used to invoke /bank_accounts APIs.
type Client struct {
	B   stripe.Backend
	Key string
}

const (
	NewAccount       stripe.BankAccountStatus = "new"
	VerifiedAccount  stripe.BankAccountStatus = "verified"
	ValidatedAccount stripe.BankAccountStatus = "validated"
	ErroredAccount   stripe.BankAccountStatus = "errored"
)

// New POSTs a new bank account.
func New(params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().New(params)
}

func (c Client) New(params *stripe.BankAccountParams) (*stripe.BankAccount, error) {

	body := &stripe.RequestValues{}
	isCustomer := len(params.Customer) > 0

	var sourceType string
	if isCustomer {
		sourceType = "source"
	} else {
		sourceType = "external_account"
	}

	// Use token (if exists) or a dictionary containing a user’s bank account details.
	if len(params.Token) > 0 {
		body.Add(sourceType, params.Token)

		if params.Default {
			body.Add("default_for_currency", strconv.FormatBool(params.Default))
		}
	} else {
		body.Add(sourceType+"[object]", "bank_account")
		body.Add(sourceType+"[country]", params.Country)
		body.Add(sourceType+"[account_number]", params.Account)
		body.Add(sourceType+"[currency]", params.Currency)

		if isCustomer {
			body.Add(sourceType+"[account_holder_name]", params.AccountHolderName)
			body.Add(sourceType+"[account_holder_type]", params.AccountHolderType)
		}

		if len(params.Routing) > 0 {
			body.Add(sourceType+"[routing_number]", params.Routing)
		}

		if params.Default {
			body.Add(sourceType+"[default_for_currency]", strconv.FormatBool(params.Default))
		}
	}
	params.AppendTo(body)

	ba := &stripe.BankAccount{}
	var err error
	if isCustomer {
		err = c.B.Call("POST", fmt.Sprintf("/customers/%v/sources", params.Customer), c.Key, body, &params.Params, ba)
	} else {
		err = c.B.Call("POST", fmt.Sprintf("/accounts/%v/bank_accounts", params.AccountID), c.Key, body, &params.Params, ba)
	}

	return ba, err
}

// Get returns the details of a bank account.
func Get(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Get(id, params)
}

func (c Client) Get(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	var body *stripe.RequestValues
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &stripe.RequestValues{}
		params.AppendTo(body)
	}

	ba := &stripe.BankAccount{}
	var err error

	if len(params.Customer) > 0 {
		err = c.B.Call("GET", fmt.Sprintf("/customers/%v/bank_accounts/%v", params.AccountID, id), c.Key, body, commonParams, ba)
	} else if len(params.AccountID) > 0 {
		err = c.B.Call("GET", fmt.Sprintf("/accounts/%v/bank_accounts/%v", params.AccountID, id), c.Key, body, commonParams, ba)
	} else {
		err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
	}

	return ba, err
}

// Update updates a bank account.
func Update(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Update(id, params)
}

func (c Client) Update(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	var body *stripe.RequestValues
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &stripe.RequestValues{}

		if params.Default {
			body.Add("default_for_currency", strconv.FormatBool(params.Default))
		}

		params.AppendTo(body)
	}

	ba := &stripe.BankAccount{}
	var err error

	if len(params.Customer) > 0 {
		err = c.B.Call("POST", fmt.Sprintf("/customers/%v/bank_accounts/%v", params.Customer, id), c.Key, body, commonParams, ba)
	} else if len(params.AccountID) > 0 {
		err = c.B.Call("POST", fmt.Sprintf("/accounts/%v/bank_accounts/%v", params.AccountID, id), c.Key, body, commonParams, ba)
	} else {
		err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
	}

	return ba, err
}

// Del removes a bank account.
func Del(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Del(id, params)
}

func (c Client) Del(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	ba := &stripe.BankAccount{}
	var err error

	if len(params.Customer) > 0 {
		err = c.B.Call("DELETE", fmt.Sprintf("/customers/%v/bank_accounts/%v", params.Customer, id), c.Key, nil, nil, ba)
	} else if len(params.AccountID) > 0 {
		err = c.B.Call("DELETE", fmt.Sprintf("/accounts/%v/bank_accounts/%v", params.AccountID, id), c.Key, nil, nil, ba)
	} else {
		err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
	}

	return ba, err
}

// List returns a list of bank accounts.
func List(params *stripe.BankAccountListParams) *Iter {
	return getC().List(params)
}

func (c Client) List(params *stripe.BankAccountListParams) *Iter {
	body := &stripe.RequestValues{}
	var lp *stripe.ListParams
	var p *stripe.Params

	params.AppendTo(body)
	lp = &params.ListParams
	p = params.ToParams()

	return &Iter{stripe.GetIter(lp, body, func(b *stripe.RequestValues) ([]interface{}, stripe.ListMeta, error) {
		list := &stripe.BankAccountList{}
		var err error

		if len(params.Customer) > 0 {
			err = c.B.Call("GET", fmt.Sprintf("/customers/%v/bank_accounts", params.Customer), c.Key, b, p, list)
		} else if len(params.AccountID) > 0 {
			err = c.B.Call("GET", fmt.Sprintf("/accounts/%v/bank_accounts", params.AccountID), c.Key, b, p, list)
		} else {
			err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
		}

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}

// Iter is an iterator for lists of BankAccount.
// The embedded Iter carries methods with it;
// see its documentation for details.
type Iter struct {
	*stripe.Iter
}

// BankAccount returns the most recent BankAccount
// visited by a call to Next.
func (i *Iter) BankAccount() *stripe.BankAccount {
	return i.Current().(*stripe.BankAccount)
}

func getC() Client {
	return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}
<commit_msg>Pass extra parameters on bank account deletion<commit_after>// Package bankaccount provides the /bank_accounts APIs
package bankaccount

import (
	"errors"
	"fmt"
	"strconv"

	stripe "github.com/stripe/stripe-go"
)

// Client is used to invoke /bank_accounts APIs.
type Client struct {
	B   stripe.Backend
	Key string
}

const (
	NewAccount       stripe.BankAccountStatus = "new"
	VerifiedAccount  stripe.BankAccountStatus = "verified"
	ValidatedAccount stripe.BankAccountStatus = "validated"
	ErroredAccount   stripe.BankAccountStatus = "errored"
)

// New POSTs a new bank account.
func New(params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().New(params)
}

func (c Client) New(params *stripe.BankAccountParams) (*stripe.BankAccount, error) {

	body := &stripe.RequestValues{}
	isCustomer := len(params.Customer) > 0

	var sourceType string
	if isCustomer {
		sourceType = "source"
	} else {
		sourceType = "external_account"
	}

	// Use token (if exists) or a dictionary containing a user’s bank account details.
	if len(params.Token) > 0 {
		body.Add(sourceType, params.Token)

		if params.Default {
			body.Add("default_for_currency", strconv.FormatBool(params.Default))
		}
	} else {
		body.Add(sourceType+"[object]", "bank_account")
		body.Add(sourceType+"[country]", params.Country)
		body.Add(sourceType+"[account_number]", params.Account)
		body.Add(sourceType+"[currency]", params.Currency)

		if isCustomer {
			body.Add(sourceType+"[account_holder_name]", params.AccountHolderName)
			body.Add(sourceType+"[account_holder_type]", params.AccountHolderType)
		}

		if len(params.Routing) > 0 {
			body.Add(sourceType+"[routing_number]", params.Routing)
		}

		if params.Default {
			body.Add(sourceType+"[default_for_currency]", strconv.FormatBool(params.Default))
		}
	}
	params.AppendTo(body)

	ba := &stripe.BankAccount{}
	var err error
	if isCustomer {
		err = c.B.Call("POST", fmt.Sprintf("/customers/%v/sources", params.Customer), c.Key, body, &params.Params, ba)
	} else {
		err = c.B.Call("POST", fmt.Sprintf("/accounts/%v/bank_accounts", params.AccountID), c.Key, body, &params.Params, ba)
	}

	return ba, err
}

// Get returns the details of a bank account.
func Get(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Get(id, params)
}

func (c Client) Get(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	var body *stripe.RequestValues
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &stripe.RequestValues{}
		params.AppendTo(body)
	}

	ba := &stripe.BankAccount{}
	var err error

	if len(params.Customer) > 0 {
		err = c.B.Call("GET", fmt.Sprintf("/customers/%v/bank_accounts/%v", params.AccountID, id), c.Key, body, commonParams, ba)
	} else if len(params.AccountID) > 0 {
		err = c.B.Call("GET", fmt.Sprintf("/accounts/%v/bank_accounts/%v", params.AccountID, id), c.Key, body, commonParams, ba)
	} else {
		err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
	}

	return ba, err
}

// Update updates a bank account.
func Update(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Update(id, params)
}

func (c Client) Update(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	var body *stripe.RequestValues
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &stripe.RequestValues{}

		if params.Default {
			body.Add("default_for_currency", strconv.FormatBool(params.Default))
		}

		params.AppendTo(body)
	}

	ba := &stripe.BankAccount{}
	var err error

	if len(params.Customer) > 0 {
		err = c.B.Call("POST", fmt.Sprintf("/customers/%v/bank_accounts/%v", params.Customer, id), c.Key, body, commonParams, ba)
	} else if len(params.AccountID) > 0 {
		err = c.B.Call("POST", fmt.Sprintf("/accounts/%v/bank_accounts/%v", params.AccountID, id), c.Key, body, commonParams, ba)
	} else {
		err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
	}

	return ba, err
}

// Del removes a bank account.
func Del(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	return getC().Del(id, params)
}

func (c Client) Del(id string, params *stripe.BankAccountParams) (*stripe.BankAccount, error) {
	ba := &stripe.BankAccount{}
	var err error

	if len(params.Customer) > 0 {
		err = c.B.Call("DELETE", fmt.Sprintf("/customers/%v/bank_accounts/%v", params.Customer, id), c.Key, nil, &params.Params, ba)
	} else if len(params.AccountID) > 0 {
		err = c.B.Call("DELETE", fmt.Sprintf("/accounts/%v/bank_accounts/%v", params.AccountID, id), c.Key, nil, nil, ba)
	} else {
		err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
	}

	return ba, err
}

// List returns a list of bank accounts.
func List(params *stripe.BankAccountListParams) *Iter {
	return getC().List(params)
}

func (c Client) List(params *stripe.BankAccountListParams) *Iter {
	body := &stripe.RequestValues{}
	var lp *stripe.ListParams
	var p *stripe.Params

	params.AppendTo(body)
	lp = &params.ListParams
	p = params.ToParams()

	return &Iter{stripe.GetIter(lp, body, func(b *stripe.RequestValues) ([]interface{}, stripe.ListMeta, error) {
		list := &stripe.BankAccountList{}
		var err error

		if len(params.Customer) > 0 {
			err = c.B.Call("GET", fmt.Sprintf("/customers/%v/bank_accounts", params.Customer), c.Key, b, p, list)
		} else if len(params.AccountID) > 0 {
			err = c.B.Call("GET", fmt.Sprintf("/accounts/%v/bank_accounts", params.AccountID), c.Key, b, p, list)
		} else {
			err = errors.New("Invalid bank account params: either Customer or AccountID need to be set")
		}

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}

// Iter is an iterator for lists of BankAccount.
// The embedded Iter carries methods with it;
// see its documentation for details.
type Iter struct {
	*stripe.Iter
}

// BankAccount returns the most recent BankAccount
// visited by a call to Next.
func (i *Iter) BankAccount() *stripe.BankAccount {
	return i.Current().(*stripe.BankAccount)
}

func getC() Client {
	return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}
<|endoftext|>


<commit_before>package environments

import (
	"github.com/pufferpanel/apufferi/common"
	"github.com/pufferpanel/apufferi/logging"
	"github.com/pufferpanel/pufferd/cache"
	"github.com/pufferpanel/pufferd/utils"
)

func LoadEnvironment(environmentType, folder, id string, environmentSection map[string]interface{}) Environment {
	serverRoot := common.JoinPath(folder, id)
	rootDirectory := common.GetStringOrDefault(environmentSection, "root", serverRoot)
	cache := cache.CreateCache()
	wsManager := utils.CreateWSManager()
	switch environmentType {
	case "tty":
		logging.Debugf("Loading server as tty")
		t := &tty{BaseEnvironment: &BaseEnvironment{}}
		t.RootDirectory = rootDirectory
		t.ConsoleBuffer = cache
		t.WSManager = wsManager
		return t
	//case "docker":
	//	logging.Debugf("Loading server as tty")
	//	t := &docker{}
	//	t.RootDirectory = rootDirectory
	//	t.ConsoleBuffer = cache
	//	t.WSManager = wsManager
	//	return t
	default:
		logging.Debugf("Loading server as standard")
		s := &standard{BaseEnvironment: &BaseEnvironment{}}
		s.RootDirectory = rootDirectory
		s.ConsoleBuffer = cache
		s.WSManager = wsManager
		return s
	}
}
<commit_msg>And fix compile issue<commit_after>package environments

import (
	"github.com/pufferpanel/apufferi/common"
	"github.com/pufferpanel/apufferi/logging"
	"github.com/pufferpanel/pufferd/cache"
	"github.com/pufferpanel/pufferd/utils"
)

func LoadEnvironment(environmentType, folder, id string, environmentSection map[string]interface{}) Environment {
	serverRoot := common.JoinPath(folder, id)
	rootDirectory := common.GetStringOrDefault(environmentSection, "root", serverRoot)
	cache := cache.CreateCache()
	wsManager := utils.CreateWSManager()
	switch environmentType {
	case "tty":
		logging.Debugf("Loading server as tty")
		t := &tty{standard: &standard{BaseEnvironment: &BaseEnvironment{}}}
		t.RootDirectory = rootDirectory
		t.ConsoleBuffer = cache
		t.WSManager = wsManager
		return t
	//case "docker":
	//	logging.Debugf("Loading server as tty")
	//	t := &docker{}
	//	t.RootDirectory = rootDirectory
	//	t.ConsoleBuffer = cache
	//	t.WSManager = wsManager
	//	return t
	default:
		logging.Debugf("Loading server as standard")
		s := &standard{BaseEnvironment: &BaseEnvironment{}}
		s.RootDirectory = rootDirectory
		s.ConsoleBuffer = cache
		s.WSManager = wsManager
		return s
	}
}
<|endoftext|>


<commit_before>package srcgraph

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
	"sourcegraph.com/sourcegraph/srcgraph/buildstore"
	"sourcegraph.com/sourcegraph/srcgraph/task2"
	"sourcegraph.com/sourcegraph/util"

	"github.com/aybabtme/color/brush"
	"github.com/kr/fs"
	"github.com/sourcegraph/makex"
)

var mode = flag.String("mode", "test", "[test|keep|gen] 'test' runs test as normal; keep keeps around generated test files for inspection after tests complete; 'gen' generates new expected test data")
var match = flag.String("match", "", "run only test cases that contain this string")

func Test_SrcgraphCmd(t *testing.T) {
	actDir := buildstore.BuildDataDirName
	expDir := ".sourcegraph-data-exp"
	if *mode == "gen" {
		buildstore.BuildDataDirName = expDir
	}

	testRootDir, _ := filepath.Abs("testdata")
	testCases := getTestCases(testRootDir, *match)
	allPass := true
	for _, tcase := range testCases {
		func() {
			prevwd, _ := os.Getwd()
			os.Chdir(tcase.Dir)
			defer os.Chdir(prevwd)

			if *mode == "test" {
				defer os.RemoveAll(buildstore.BuildDataDirName)
			}

			t.Logf("Running test case %+v", tcase)
			context, err := NewJobContext(".", task2.DefaultContext)
			if err != nil {
				allPass = false
				t.Errorf("Failed to get job context due to error %s", err)
				return
			}
			context.CommitID = "test-commit"
			err = make__(nil, context, &makex.Default, false, true)
			if err != nil {
				allPass = false
				t.Errorf("Test case %+v returned error %s", tcase, err)
				return
			}
			if *mode != "gen" {
				same := compareResults(t, expDir, actDir)
				if !same {
					allPass = false
				}
			}
		}()
	}

	t.Logf("Ran test cases %+v", testCases)
	if allPass && *mode != "gen" {
		t.Log(brush.Green("** ALL PASS **").String())
	}
	if *mode == "gen" {
		t.Log(brush.DarkYellow(fmt.Sprintf("Expected test data dumped to %s directories", expDir)))
	}
	if *mode == "keep" {
		t.Log(brush.Cyan(fmt.Sprintf("Test files persisted in %s directories", actDir)))
	}
}

type testCase struct {
	Dir string
}

func compareResults(t *testing.T, expDir, actDir string) bool {
	diffOut, err := exec.Command("diff", "-ur", expDir, actDir).CombinedOutput()
	if err != nil {
		t.Fatalf("Could not execute diff due to error %s, diff output: %s", err, string(diffOut))
		return false
	}
	t.Logf("\n\n\n")
	t.Logf("###########################")
	t.Logf("##      TEST RESULTS     ##")
	t.Logf("###########################")
	if len(diffOut) > 0 {
		diffStr := string(diffOut)
		t.Errorf(diffStr)
		t.Errorf(brush.Red("** FAIL **").String())
		t.Errorf("output differed")
		return false
	} else if err != nil {
		t.Errorf(brush.Red("** ERROR **").String())
		t.Errorf("failed to compute diff: %s", err)
		return false
	} else {
		t.Logf(brush.Green("** PASS **").String())
		return true
	}
}

func getTestCases(testdir string, match string) []testCase {
	var testCases []testCase
	walker := fs.Walk(testdir)
	for walker.Step() {
		path := walker.Path()
		if walker.Stat().IsDir() && util.IsFile(filepath.Join(path, ".git/config")) {
			if strings.Contains(path, match) {
				testCases = append(testCases, testCase{Dir: path})
			}
		}
	}
	return testCases
}
<commit_msg>better test output<commit_after>package srcgraph

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
	"sourcegraph.com/sourcegraph/srcgraph/buildstore"
	"sourcegraph.com/sourcegraph/srcgraph/task2"
	"sourcegraph.com/sourcegraph/util"

	"github.com/aybabtme/color/brush"
	"github.com/kr/fs"
	"github.com/sourcegraph/makex"
)

var mode = flag.String("mode", "test", "[test|keep|gen] 'test' runs test as normal; keep keeps around generated test files for inspection after tests complete; 'gen' generates new expected test data")
var match = flag.String("match", "", "run only test cases that contain this string")

func Test_SrcgraphCmd(t *testing.T) {
	actDir := buildstore.BuildDataDirName
	expDir := ".sourcegraph-data-exp"
	if *mode == "gen" {
		buildstore.BuildDataDirName = expDir
	}

	testRootDir, _ := filepath.Abs("testdata")
	testCases := getTestCases(testRootDir, *match)
	allPass := true
	for _, tcase := range testCases {
		func() {
			prevwd, _ := os.Getwd()
			os.Chdir(tcase.Dir)
			defer os.Chdir(prevwd)

			if *mode == "test" {
				defer os.RemoveAll(buildstore.BuildDataDirName)
			}

			t.Logf("Running test case %+v", tcase)
			context, err := NewJobContext(".", task2.DefaultContext)
			if err != nil {
				allPass = false
				t.Errorf("Failed to get job context due to error %s", err)
				return
			}
			context.CommitID = "test-commit"
			err = make__(nil, context, &makex.Default, false, *Verbose)
			if err != nil {
				allPass = false
				t.Errorf("Test case %+v returned error %s", tcase, err)
				return
			}
			if *mode != "gen" {
				same := compareResults(t, tcase, expDir, actDir)
				if !same {
					allPass = false
				}
			}
		}()
	}

	if allPass && *mode != "gen" {
		t.Log(brush.Green("ALL CASES PASS").String())
	}
	if *mode == "gen" {
		t.Log(brush.DarkYellow(fmt.Sprintf("Expected test data dumped to %s directories", expDir)))
	}
	if *mode == "keep" {
		t.Log(brush.Cyan(fmt.Sprintf("Test files persisted in %s directories", actDir)))
	}
	t.Logf("Ran test cases %+v", testCases)
}

type testCase struct {
	Dir string
}

func compareResults(t *testing.T, tcase testCase, expDir, actDir string) bool {
	diffOut, err := exec.Command("diff", "-ur", expDir, actDir).CombinedOutput()
	if err != nil {
		t.Fatalf("Could not execute diff due to error %s, diff output: %s", err, string(diffOut))
		return false
	}
	if len(diffOut) > 0 {
		diffStr := string(diffOut)
		t.Errorf(brush.Red("FAIL").String())
		t.Errorf("test case %+v", tcase)
		t.Errorf(diffStr)
		t.Errorf("output differed")
		return false
	} else if err != nil {
		t.Errorf(brush.Red("ERROR").String())
		t.Errorf("test case %+v", tcase)
		t.Errorf("failed to compute diff: %s", err)
		return false
	} else {
		t.Logf(brush.Green("PASS").String())
		t.Logf("test case %+v", tcase)
		return true
	}
}

func getTestCases(testdir string, match string) []testCase {
	var testCases []testCase
	walker := fs.Walk(testdir)
	for walker.Step() {
		path := walker.Path()
		if walker.Stat().IsDir() && util.IsFile(filepath.Join(path, ".git/config")) {
			if strings.Contains(path, match) {
				testCases = append(testCases, testCase{Dir: path})
			}
		}
	}
	return testCases
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package util

import (
	"fmt"
	"github.com/apache/incubator-servicecomb-service-center/pkg/util"
	"github.com/apache/incubator-servicecomb-service-center/server/core/proto"
	"golang.org/x/net/context"
	"testing"
)

func TestGetLeaseId(t *testing.T) {

	_, err := GetLeaseId(util.SetContext(context.Background(), "cacheOnly", "1"), "", "", "")
	if err != nil {
		fmt.Printf(`GetLeaseId WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = GetLeaseId(context.Background(), "", "", "")
	if err == nil {
		fmt.Printf(`GetLeaseId failed`)
		t.FailNow()
	}
}

func TestGetInstance(t *testing.T) {
	_, err := GetInstance(util.SetContext(context.Background(), "cacheOnly", "1"), "", "", "")
	if err != nil {
		fmt.Printf(`GetInstance WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = GetInstance(context.Background(), "", "", "")
	if err == nil {
		fmt.Printf(`GetInstance failed`)
		t.FailNow()
	}

	_, err = GetAllInstancesOfOneService(util.SetContext(context.Background(), "cacheOnly", "1"), "", "")
	if err != nil {
		fmt.Printf(`GetAllInstancesOfOneService WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = GetAllInstancesOfOneService(context.Background(), "", "")
	if err == nil {
		fmt.Printf(`GetAllInstancesOfOneService failed`)
		t.FailNow()
	}

	QueryAllProvidersInstances(context.Background(), "")

	_, err = queryServiceInstancesKvs(context.Background(), "", 0)
	if err == nil {
		fmt.Printf(`queryServiceInstancesKvs failed`)
		t.FailNow()
	}
}

func TestInstanceExist(t *testing.T) {
	_, err := InstanceExist(util.SetContext(context.Background(), "cacheOnly", "1"), "", "", "")
	if err != nil {
		fmt.Printf(`InstanceExist WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = InstanceExist(context.Background(), "", "", "")
	if err == nil {
		fmt.Printf(`InstanceExist failed`)
		t.FailNow()
	}
}

func TestCheckEndPoints(t *testing.T) {
	_, err := CheckEndPoints(context.Background(), &proto.MicroServiceInstance{
		ServiceId: "a",
	})
	if err == nil {
		fmt.Printf(`CheckEndPoints failed`)
		t.FailNow()
	}
}

func TestDeleteServiceAllInstances(t *testing.T) {
	err := DeleteServiceAllInstances(context.Background(), "")
	if err == nil {
		fmt.Printf(`DeleteServiceAllInstances failed`)
		t.FailNow()
	}
}

func TestParseEndpointValue(t *testing.T) {
	epv := ParseEndpointIndexValue([]byte("x/y"))
	if epv.serviceId != "x" || epv.instanceId != "y" {
		fmt.Printf(`ParseEndpointIndexValue failed`)
		t.FailNow()
	}
}
<commit_msg>SCB-411 Add test code<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package util

import (
	"fmt"
	"github.com/apache/incubator-servicecomb-service-center/pkg/util"
	"github.com/apache/incubator-servicecomb-service-center/server/core/proto"
	"golang.org/x/net/context"
	"testing"
)

func TestGetLeaseId(t *testing.T) {

	_, err := GetLeaseId(util.SetContext(context.Background(), "cacheOnly", "1"), "", "", "")
	if err != nil {
		fmt.Printf(`GetLeaseId WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = GetLeaseId(context.Background(), "", "", "")
	if err == nil {
		fmt.Printf(`GetLeaseId failed`)
		t.FailNow()
	}
}

func TestGetInstance(t *testing.T) {
	_, err := GetInstance(util.SetContext(context.Background(), "cacheOnly", "1"), "", "", "")
	if err != nil {
		fmt.Printf(`GetInstance WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = GetInstance(context.Background(), "", "", "")
	if err == nil {
		fmt.Printf(`GetInstance failed`)
		t.FailNow()
	}

	_, err = GetAllInstancesOfOneService(util.SetContext(context.Background(), "cacheOnly", "1"), "", "")
	if err != nil {
		fmt.Printf(`GetAllInstancesOfOneService WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = GetAllInstancesOfOneService(context.Background(), "", "")
	if err == nil {
		fmt.Printf(`GetAllInstancesOfOneService failed`)
		t.FailNow()
	}

	QueryAllProvidersInstances(context.Background(), "")

	_, err = queryServiceInstancesKvs(context.Background(), "", 0)
	if err == nil {
		fmt.Printf(`queryServiceInstancesKvs failed`)
		t.FailNow()
	}
}

func TestInstanceExist(t *testing.T) {
	_, err := InstanceExist(util.SetContext(context.Background(), "cacheOnly", "1"), "", "", "")
	if err != nil {
		fmt.Printf(`InstanceExist WithCacheOnly failed`)
		t.FailNow()
	}

	_, err = InstanceExist(context.Background(), "", "", "")
	if err == nil {
		fmt.Printf(`InstanceExist failed`)
		t.FailNow()
	}
}

func TestCheckEndPoints(t *testing.T) {
	_, err := CheckEndPoints(context.Background(), &proto.MicroServiceInstance{
		ServiceId: "a",
	})
	if err == nil {
		fmt.Printf(`CheckEndPoints failed`)
		t.FailNow()
	}
}

func TestDeleteServiceAllInstances(t *testing.T) {
	err := DeleteServiceAllInstances(context.Background(), "")
	if err == nil {
		fmt.Printf(`DeleteServiceAllInstances failed`)
		t.FailNow()
	}
}

func TestParseEndpointValue(t *testing.T) {
	epv := ParseEndpointIndexValue([]byte("x/y"))
	if epv.serviceId != "x" || epv.instanceId != "y" {
		fmt.Printf(`ParseEndpointIndexValue failed`)
		t.FailNow()
	}
}

func TestGetInstanceCountOfOneService(t *testing.T) {
	_, err := GetInstanceCountOfOneService(context.Background(), "", "")
	if err == nil {
		fmt.Printf(`GetInstanceCountOfOneService failed`)
		t.FailNow()
	}
}
<|endoftext|>


<commit_before>package mockdb

import (
	"database/sql"
	"fmt"

	"github.com/Nivl/go-rest-tools/storage/db"
	"github.com/lib/pq"
	"github.com/stretchr/testify/mock"
)

var (
	// StringType represents a string argument
	StringType = mock.AnythingOfType("string")
	// InType represents an int argument
	InType = mock.AnythingOfType("int")

	// serverError represents a database connection error
	serverError = &pq.Error{
		Code:    "08006",
		Message: "error: connection failure",
		Detail:  "the connection to the database failed",
	}
)

func newConflictError(fieldName string) *pq.Error {
	return &pq.Error{
		Code:    db.ErrDup,
		Message: "error: duplicate field",
		Detail:  fmt.Sprintf("Key (%s)=(Google) already exists.", fieldName),
	}
}

// ExpectGet is a helper that expects a Get
func (mdb *Queryable) ExpectGet(typ string, runnable func(args mock.Arguments)) *mock.Call {
	getCall := mdb.On("Get", mock.AnythingOfType(typ), StringType, StringType)
	getCall.Return(nil)
	if runnable != nil {
		getCall.Run(runnable)
	}
	return getCall
}

// ExpectGetNotFound is a helper that expects a not found on a Get
func (mdb *Queryable) ExpectGetNotFound(typ string) *mock.Call {
	getCall := mdb.On("Get", mock.AnythingOfType(typ), StringType, StringType)
	getCall.Return(sql.ErrNoRows)
	return getCall
}

// ExpectGetError is a helper that expects a connection error on a Get
func (mdb *Queryable) ExpectGetError(typ string) *mock.Call {
	getCall := mdb.On("Get", mock.AnythingOfType(typ), StringType, StringType)
	getCall.Return(serverError)
	return getCall
}

// ExpectSelect is an helper that expects a connection error on a Select
func (mdb *Queryable) ExpectSelect(typ string, runnable func(args mock.Arguments)) *mock.Call {
	selectCall := mdb.On("Select", mock.AnythingOfType(typ), StringType, InType, InType)
	selectCall.Return(nil)
	if runnable != nil {
		selectCall.Run(runnable)
	}
	return selectCall
}

// ExpectSelectError is an helper that expects a Select
func (mdb *Queryable) ExpectSelectError(typ string) *mock.Call {
	selectCall := mdb.On("Select", mock.AnythingOfType(typ), StringType, InType, InType)
	selectCall.Return(serverError)
	return selectCall
}

// ExpectDeletion is a helper that expects a deletion
func (mdb *Queryable) ExpectDeletion() *mock.Call {
	return mdb.On("Exec", StringType, StringType).Return(nil, nil)
}

// ExpectDeletionError is a helper that expects a deletion to fail
func (mdb *Queryable) ExpectDeletionError() *mock.Call {
	return mdb.On("Exec", StringType, StringType).Return(nil, serverError)
}

// ExpectInsert is a helper that expects an insertion
func (mdb *Queryable) ExpectInsert(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(nil, nil)
}

// ExpectInsertError is a helper that expects an insert to fail
func (mdb *Queryable) ExpectInsertError(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(nil, serverError)
}

// ExpectInsertConflict is a helper that expects a conflict on an insertion
func (mdb *Queryable) ExpectInsertConflict(typ string, fieldName string) *mock.Call {
	conflictError := newConflictError(fieldName)
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(nil, conflictError)
}

// ExpectUpdate is a helper that expects an update
func (mdb *Queryable) ExpectUpdate(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(nil, nil)
}

// ExpectUpdateConflict is a helper that expects a conflict on an update
func (mdb *Queryable) ExpectUpdateConflict(typ string, fieldName string) *mock.Call {
	conflictError := newConflictError(fieldName)
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(nil, conflictError)
}

// ExpectUpdateError is a helper that expects an update to fail
func (mdb *Queryable) ExpectUpdateError(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(nil, serverError)
}
<commit_msg>fix(mockdb): fix returnng nil instead of an int on Exec()<commit_after>package mockdb

import (
	"database/sql"
	"fmt"

	"github.com/Nivl/go-rest-tools/storage/db"
	"github.com/lib/pq"
	"github.com/stretchr/testify/mock"
)

var (
	// StringType represents a string argument
	StringType = mock.AnythingOfType("string")
	// InType represents an int argument
	InType = mock.AnythingOfType("int")

	// serverError represents a database connection error
	serverError = &pq.Error{
		Code:    "08006",
		Message: "error: connection failure",
		Detail:  "the connection to the database failed",
	}
)

func newConflictError(fieldName string) *pq.Error {
	return &pq.Error{
		Code:    db.ErrDup,
		Message: "error: duplicate field",
		Detail:  fmt.Sprintf("Key (%s)=(Google) already exists.", fieldName),
	}
}

// ExpectGet is a helper that expects a Get
func (mdb *Queryable) ExpectGet(typ string, runnable func(args mock.Arguments)) *mock.Call {
	getCall := mdb.On("Get", mock.AnythingOfType(typ), StringType, StringType)
	getCall.Return(nil)
	if runnable != nil {
		getCall.Run(runnable)
	}
	return getCall
}

// ExpectGetNotFound is a helper that expects a not found on a Get
func (mdb *Queryable) ExpectGetNotFound(typ string) *mock.Call {
	getCall := mdb.On("Get", mock.AnythingOfType(typ), StringType, StringType)
	getCall.Return(sql.ErrNoRows)
	return getCall
}

// ExpectGetError is a helper that expects a connection error on a Get
func (mdb *Queryable) ExpectGetError(typ string) *mock.Call {
	getCall := mdb.On("Get", mock.AnythingOfType(typ), StringType, StringType)
	getCall.Return(serverError)
	return getCall
}

// ExpectSelect is an helper that expects a connection error on a Select
func (mdb *Queryable) ExpectSelect(typ string, runnable func(args mock.Arguments)) *mock.Call {
	selectCall := mdb.On("Select", mock.AnythingOfType(typ), StringType, InType, InType)
	selectCall.Return(nil)
	if runnable != nil {
		selectCall.Run(runnable)
	}
	return selectCall
}

// ExpectSelectError is an helper that expects a Select
func (mdb *Queryable) ExpectSelectError(typ string) *mock.Call {
	selectCall := mdb.On("Select", mock.AnythingOfType(typ), StringType, InType, InType)
	selectCall.Return(serverError)
	return selectCall
}

// ExpectDeletion is a helper that expects a deletion
func (mdb *Queryable) ExpectDeletion() *mock.Call {
	return mdb.On("Exec", StringType, StringType).Return(1, nil)
}

// ExpectDeletionError is a helper that expects a deletion to fail
func (mdb *Queryable) ExpectDeletionError() *mock.Call {
	return mdb.On("Exec", StringType, StringType).Return(0, serverError)
}

// ExpectInsert is a helper that expects an insertion
func (mdb *Queryable) ExpectInsert(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(1, nil)
}

// ExpectInsertError is a helper that expects an insert to fail
func (mdb *Queryable) ExpectInsertError(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(1, serverError)
}

// ExpectInsertConflict is a helper that expects a conflict on an insertion
func (mdb *Queryable) ExpectInsertConflict(typ string, fieldName string) *mock.Call {
	conflictError := newConflictError(fieldName)
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(0, conflictError)
}

// ExpectUpdate is a helper that expects an update
func (mdb *Queryable) ExpectUpdate(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(1, nil)
}

// ExpectUpdateConflict is a helper that expects a conflict on an update
func (mdb *Queryable) ExpectUpdateConflict(typ string, fieldName string) *mock.Call {
	conflictError := newConflictError(fieldName)
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(0, conflictError)
}

// ExpectUpdateError is a helper that expects an update to fail
func (mdb *Queryable) ExpectUpdateError(typ string) *mock.Call {
	return mdb.On("NamedExec", StringType, mock.AnythingOfType(typ)).Return(0, serverError)
}
<|endoftext|>