Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cart: update CartDefaultBehaviour to return real clones #323

Merged
merged 2 commits into from
Jun 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changelog
## v3.5.0 [upcoming]
**cart**
* Add convenience function to clone carts
* DefaultCartBehaviour now returns real cart clones to prevent data races on cart fields
* API
* **Breaking**: Update `DELETE /api/v1/cart` to actually clean the whole cart not only removing the cart items (introduces new route for the previous behaviour, see below)
* Add new endpoint `DELETE /api/v1/cart/deliveries/items` to be able to remove all cart items from all deliveries but keeping delivery info and other cart data untouched
Expand Down
3 changes: 2 additions & 1 deletion cart/application/cartService.go
Original file line number Diff line number Diff line change
Expand Up @@ -1253,5 +1253,6 @@ func (cs *CartService) UpdateDeliveryAdditionalData(ctx context.Context, session
return nil, err
}

return cart, nil
cart, _, err = cs.cartReceiverService.GetCart(ctx, session)
return cart, err
}
12 changes: 10 additions & 2 deletions cart/application/cartService_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,7 @@ func TestCartService_CartInEvent(t *testing.T) {
func createCartServiceWithDependencies() *cartApplication.CartService {
eventRouter := new(MockEventRouter)
eventRouter.On("Dispatch", mock.Anything, mock.Anything, mock.Anything).Return()
cartCache := new(MockCartCache)

crs := &cartApplication.CartReceiverService{}
crs.Inject(new(MockGuestCartServiceWithModifyBehaviour),
Expand All @@ -1021,7 +1022,7 @@ func createCartServiceWithDependencies() *cartApplication.CartService {
&struct {
CartCache cartApplication.CartCache `inject:",optional"`
}{
CartCache: new(MockCartCache),
CartCache: cartCache,
})

cs := &cartApplication.CartService{}
Expand Down Expand Up @@ -1049,7 +1050,14 @@ func createCartServiceWithDependencies() *cartApplication.CartService {
DefaultDeliveryCode: "default_delivery_code",
DeleteEmptyDelivery: false,
},
nil,
&struct {
CartValidator validation.Validator `inject:",optional"`
ItemValidator validation.ItemValidator `inject:",optional"`
CartCache cartApplication.CartCache `inject:",optional"`
PlaceOrderService placeorder.Service `inject:",optional"`
}{
CartCache: cartCache,
},
)
return cs
}
Expand Down
18 changes: 18 additions & 0 deletions cart/domain/cart/cart.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cart

import (
"bytes"
"encoding/gob"
"fmt"
"math/big"
Expand Down Expand Up @@ -174,6 +175,23 @@ func (c Cart) GetMainShippingEMail() string {
return ""
}

// Clone the current cart
func (c Cart) Clone() (Cart, error) {
cloned := Cart{}

b := new(bytes.Buffer)
err := gob.NewEncoder(b).Encode(c)
if err != nil {
return Cart{}, err
}
err = gob.NewDecoder(b).Decode(&cloned)
if err != nil {
return Cart{}, err
}

return cloned, nil
}

// GetContactMail returns the contact mail from the shipping address with fall back to the billing address
func (c Cart) GetContactMail() string {
// Get Email from either the cart
Expand Down
89 changes: 87 additions & 2 deletions cart/domain/cart/cart_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,104 @@
package cart_test

import (
"encoding/json"
"math/big"
"reflect"
"testing"

"flamingo.me/flamingo-commerce/v3/cart/domain/testutils"

"flamingo.me/flamingo-commerce/v3/cart/domain/placeorder"
"flamingo.me/flamingo-commerce/v3/cart/domain/testutils"
"github.com/stretchr/testify/require"

"github.com/stretchr/testify/assert"

cartDomain "flamingo.me/flamingo-commerce/v3/cart/domain/cart"
"flamingo.me/flamingo-commerce/v3/price/domain"
)

func assertDeepClone(t testing.TB, orig, cloned reflect.Value) {
t.Helper()
require.Equal(t, orig.Type(), cloned.Type())
switch orig.Kind() {
case reflect.Struct:
for i := 0; i < orig.NumField(); i++ {
assertDeepClone(t, orig.Field(i), cloned.Field(i))
}
case reflect.Slice, reflect.Array:
if orig.IsNil() {
return
}
assert.NotEqual(t, orig.Pointer(), cloned.Pointer())
for i := 0; i < orig.Len(); i++ {
assertDeepClone(t, orig.Index(i), cloned.Index(i))
}
case reflect.Map:
if orig.IsNil() {
return
}
assert.NotEqual(t, orig.Pointer(), cloned.Pointer())
iter := orig.MapRange()
for iter.Next() {
assertDeepClone(t, iter.Value(), cloned.MapIndex(iter.Key()))
}
case reflect.Ptr:
if orig.IsNil() {
return
}
assert.NotEqual(t, orig.Pointer(), cloned.Pointer())
assertDeepClone(t, orig.Elem(), cloned.Elem())
default:
}

}

func TestCart_Clone(t *testing.T) {
t.Parallel()
cart := cartDomain.Cart{
ID: "original",
BillingAddress: &cartDomain.Address{},
Purchaser: &cartDomain.Person{
Address: &cartDomain.Address{},
PersonalDetails: cartDomain.PersonalDetails{},
ExistingCustomerData: &cartDomain.ExistingCustomerData{ID: "1"},
},
Deliveries: []cartDomain.Delivery{
{
DeliveryInfo: cartDomain.DeliveryInfo{
Code: "code",
DeliveryLocation: cartDomain.DeliveryLocation{
Address: &cartDomain.Address{},
UseBillingAddress: false,
Code: "",
},
AdditionalData: map[string]string{"hello": "you"},
AdditionalDeliveryInfos: map[string]json.RawMessage{"foo": json.RawMessage("test")},
},
Cartitems: []cartDomain.Item{
{
AdditionalData: map[string]string{"hello": "you"},
},
},
ShippingItem: cartDomain.ShippingItem{
Title: "",
},
},
},
AdditionalData: cartDomain.AdditionalData{CustomAttributes: map[string]string{"hello": "you"}},
}

cloned, err := cart.Clone()
require.NoError(t, err)

assert.True(t, reflect.DeepEqual(cart, cloned), "cloned cart should have same values")

assertDeepClone(t, reflect.ValueOf(cart), reflect.ValueOf(cloned))

// some alibi changes to check that it is really a clone
cloned.AdditionalData.CustomAttributes["hello"] = "bar"
assert.Equal(t, "you", cart.AdditionalData.CustomAttributes["hello"])
}

func TestCart_GetMainShippingEMail(t *testing.T) {
t.Parallel()

Expand Down
Loading