Skip to content

Commit

Permalink
Simultaneous donations test
Browse files Browse the repository at this point in the history
  • Loading branch information
heynemann committed Nov 18, 2016
1 parent b04e00b commit 4050666
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 3 deletions.
54 changes: 54 additions & 0 deletions api/donation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api_test
import (
"fmt"
"net/http"
"sync"

"github.com/topfreegames/donations/models"

Expand Down Expand Up @@ -88,6 +89,59 @@ var _ = Describe("Game Handler", func() {
Expect(status).To(Equal(http.StatusOK))
Expect(body).To(Equal("{\"success\":true}"))
})

It("Should not donate more than allowed", func() {
var wg sync.WaitGroup
results := []map[string]interface{}{}

game, err := GetTestGame(app.MongoDb, app.Logger, true, map[string]interface{}{
"LimitOfCardsInEachDonationRequest": 2,
})
Expect(err).NotTo(HaveOccurred())

donation, err := GetTestDonationRequest(game, app.MongoDb, app.Logger)
Expect(err).NotTo(HaveOccurred())

playerID := uuid.NewV4().String()
payload := &api.DonationPayload{
Player: playerID,
Amount: 1,
}
jsonPayload, err := payload.ToJSON()
Expect(err).NotTo(HaveOccurred())

for i := 0; i < 10; i++ {
wg.Add(1)

go func(index int) {
defer wg.Done()
status, body := Post(
app,
fmt.Sprintf("/games/%s/donation-requests/%s/", game.ID, donation.ID),
string(jsonPayload),
)

results = append(results, map[string]interface{}{
"status": status,
"body": body,
})
}(i)
}

wg.Wait()

ok := 0
failed := 0
for _, result := range results {
if result["status"] == 200 {
ok++
} else {
failed++
}
}
Expect(ok).To(Equal(2))
Expect(failed).To(Equal(8))
})
})
})
})
6 changes: 3 additions & 3 deletions models/donation.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func (d *DonationRequest) Donate(player string, amount int, db *mgo.Database, lo
return err
}

err = d.ValidateDonationRequestLimit(game, logger)
err = d.ValidateDonationRequestLimit(game, amount, logger)
if err != nil {
log.E(l, err.Error(), func(cm log.CM) {
cm.Write(zap.Error(err))
Expand Down Expand Up @@ -188,9 +188,9 @@ func (d *DonationRequest) Donate(player string, amount int, db *mgo.Database, lo
}

//ValidateDonationRequestLimit ensures that no more than the allowed number of cards has been donated
func (d *DonationRequest) ValidateDonationRequestLimit(game *Game, logger zap.Logger) error {
func (d *DonationRequest) ValidateDonationRequestLimit(game *Game, amount int, logger zap.Logger) error {
item := game.Items[d.Item]
if d.GetDonationCount() >= item.LimitOfCardsInEachDonationRequest {
if d.GetDonationCount()+amount > item.LimitOfCardsInEachDonationRequest {
err := &errors.LimitOfCardsInDonationRequestReachedError{
GameID: game.ID,
DonationRequestID: d.ID,
Expand Down

0 comments on commit 4050666

Please sign in to comment.