def test_cart_discount_query(client): client.cart_discounts.create( types.CartDiscountDraft( name=types.LocalizedString({"en:": "test discount"}), value=types.CartDiscountValueRelative(permyriad=10), cart_predicate="", sort_order="", requires_discount_code=False, )) client.cart_discounts.create( types.CartDiscountDraft( name=types.LocalizedString({"en:": "test discount"}), value=types.CartDiscountValueRelative(permyriad=10), cart_predicate="", sort_order="", requires_discount_code=False, )) # single sort query result = client.cart_discounts.query(sort="id asc") assert len(result.results) == 2 assert result.total == 2 # multiple sort queries result = client.cart_discounts.query(sort=["id asc", "name asc"]) assert len(result.results) == 2 assert result.total == 2
def test_product_update_add_price_current(client): product = client.products.create( types.ProductDraft( key="test-product", name=types.LocalizedString(en=f"my-product-1"), slug=types.LocalizedString(en=f"my-product-1"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), master_variant=types.ProductVariantDraft(sku="1", key="1"), publish=True, ) ) product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductAddPriceAction( sku="1", staged=False, price=types.PriceDraft( value=types.Money(cent_amount=1000, currency_code="GBP") ), ) ], ) assert product.master_data.staged is None assert len(product.master_data.current.master_variant.prices) == 1
def test_correlation_id_is_set_in_exception(client): product = client.products.create( types.ProductDraft( key="test-product", name=types.LocalizedString(en=f"my-product"), slug=types.LocalizedString(en=f"my-product"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), )) product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], ) # This should raise a version conflict error with pytest.raises(CommercetoolsError) as exc: client.products.update_by_id( id=product.id, version=1, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug3")) ], ) assert exc.value.correlation_id is not None
def test_get_by_key(client): product = client.products.create( types.ProductDraft( master_variant=types.ProductVariantDraft(sku="123"), publish=True, name=types.LocalizedString(nl="Test product"), slug=types.LocalizedString(en="my-product"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), )) variant = product.master_data.current.master_variant shopping_list = client.shopping_lists.create(draft=types.ShoppingListDraft( key="test-shopping-list", name=types.LocalizedString({"nl": "Verlanglijstje"}), description=types.LocalizedString({"nl": "Verlanglijstje van LabD"}), line_items=[ types.ShoppingListLineItemDraft(sku=variant.sku, quantity=1) ], )) assert shopping_list.key shopping_list = client.shopping_lists.get_by_key("test-shopping-list") assert shopping_list.name["nl"] == "Verlanglijstje" assert shopping_list.description["nl"] == "Verlanglijstje van LabD" assert shopping_list.line_items[0].variant.sku == "123" assert shopping_list.line_items[0].quantity == 1
def test_product_update(client): """Test the return value of the update methods. It doesn't test the actual update itself. TODO: See if this is worth testing since we're using a mocking backend """ product = client.products.create(types.ProductDraft(key="test-product")) assert uuid.UUID(product.id) assert product.key == "test-product" product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString(nl="nl-slug2")) ], ) assert product.key == "test-product" product = client.products.update_by_key( key="test-product", version=product.version, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString(nl="nl-slug2")) ], ) assert product.key == "test-product"
def cart_draft(client): product_1 = client.products.create( types.ProductDraft( key=f"product-1", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=f"my-product-1"), slug=types.LocalizedString(en=f"my-product-1"), publish=True, )) product_2 = client.products.create( types.ProductDraft( key=f"product-2", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=f"my-product-2"), slug=types.LocalizedString(en=f"my-product-2"), publish=True, )) return types.CartDraft( customer_id=str(uuid.uuid4()), customer_email="*****@*****.**", currency="GBP", anonymous_id=str(uuid.uuid4()), country="GB", inventory_mode=types.InventoryMode.NONE, tax_mode=types.TaxMode.PLATFORM, tax_rounding_mode=types.RoundingMode.HALF_EVEN, tax_calculation_mode=types.TaxCalculationMode.LINE_ITEM_LEVEL, line_items=[ types.LineItemDraft(product_id=product_1.id, quantity=1), types.LineItemDraft(product_id=product_2.id, quantity=2), ], locale="en", origin=types.CartOrigin.CUSTOMER, )
def test_state_flow(client, state_draft): state = client.states.create(state_draft) assert state.id new_name = types.LocalizedString({"en": "new_name"}) new_description = types.LocalizedString({"en": "new_description"}) update_actions = [ types.StateSetNameAction(name=new_name), types.StateSetDescriptionAction(description=new_description), types.StateChangeInitialAction(initial=True), types.StateSetRolesAction( roles=[types.StateRoleEnum.REVIEW_INCLUDED_IN_STATISTICS]), ] state = client.states.update_by_id(state.id, state.version, update_actions) assert state.name == new_name assert state.description == new_description assert state.initial is True assert len(state.roles) == 1 state = client.states.update_by_id(state.id, state.version, [types.StateSetRolesAction(roles=[])]) assert len(state.roles) == 0 deleted_state = client.states.delete_by_id(state.id, state.version) assert state.id == deleted_state.id
def test_get_by_id(client): product = client.products.create( types.ProductDraft( master_variant=types.ProductVariantDraft(sku="123"), publish=True, name=types.LocalizedString(nl="Test product"), ) ) shopping_list = client.shopping_lists.create( draft=types.ShoppingListDraft( name=types.LocalizedString({"nl": "Verlanglijstje"}), description=types.LocalizedString({"nl": "Verlanglijstje van LabD"}), line_items=[ types.ShoppingListLineItemDraft(product_id=product.id, quantity=1) ], ) ) assert shopping_list.id shopping_list = client.shopping_lists.get_by_id(shopping_list.id) assert shopping_list.name["nl"] == "Verlanglijstje" assert shopping_list.description["nl"] == "Verlanglijstje van LabD" assert shopping_list.line_items[0].product_id == product.id assert shopping_list.line_items[0].quantity == 1
def test_product_query(client): client.products.create( types.ProductDraft( key=f"product-1", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=f"my-product-1"), slug=types.LocalizedString(en=f"my-product-1"), publish=True, ) ) client.products.create( types.ProductDraft( key=f"product-2", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=f"my-product-2"), slug=types.LocalizedString(en=f"my-product-2"), publish=True, ) ) # single sort query result = client.products.query(sort="id asc", limit=2) assert len(result.results) == 2 assert result.total == 2 # multiple sort queries result = client.products.query(sort=["id asc", "name asc"]) assert len(result.results) == 2 assert result.total == 2
def test_category_update(client): """Test the return value of the update methods. It doesn't test the actual update itself. TODO: See if this is worth testing since we're using a mocking backend """ category = client.categories.create( types.CategoryDraft(key="test-category", slug=types.LocalizedString(nl="nl-slug"))) assert category.key == "test-category" category = client.categories.update_by_id( id=category.id, version=category.version, actions=[ types.CategoryChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], ) assert category.key == "test-category" category = client.categories.update_by_key( key="test-category", version=category.version, actions=[ types.CategoryChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], ) assert category.key == "test-category"
def test_product_update(client): """Test the return value of the update methods. It doesn't test the actual update itself. TODO: See if this is worth testing since we're using a mocking backend """ product = client.products.create( types.ProductDraft( key="test-product", master_variant=types.ProductVariantDraft(sku="1", key="1"), )) assert uuid.UUID(product.id) assert product.key == "test-product" product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], ) assert product.key == "test-product" assert product.master_data.published is False product = client.products.update_by_id( id=product.id, version=product.version, actions=[types.ProductPublishAction()]) assert product.master_data.published is True assert not product.master_data.current.master_variant.prices product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductSetPricesAction( sku="1", prices=[ types.PriceDraft(value=types.Money(cent_amount=1000, currency_code="GBP")) ], staged=False, ) ], ) assert len(product.master_data.current.master_variant.prices) == 1 product = client.products.update_by_key( key="test-product", version=product.version, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], ) assert product.key == "test-product"
def state_draft(): return types.StateDraft( key="test state", name=types.LocalizedString({"en": "test store"}), description=types.LocalizedString({"en": "test store"}), initial=False, type=types.StateTypeEnum.REVIEW_STATE, )
def test_payments_get_by_id(client): custom_type = client.types.create( types.TypeDraft( name=types.LocalizedString(en="myType"), key="payment-info", resource_type_ids=[types.ResourceTypeId.PAYMENT_INTERFACE_INTERACTION], field_definitions=[ types.FieldDefinition( type=types.CustomFieldStringType(), name="operations", label=types.LocalizedString(en="Operation"), required=False, ) ], ) ) payment = client.payments.create( types.PaymentDraft( key="test-payment", amount_planned=types.Money(cent_amount=2000, currency_code="GBP"), payment_method_info=types.PaymentMethodInfo( payment_interface="ADYEN", method="mc" ), transactions=[ types.TransactionDraft( type=types.TransactionType.CHARGE, amount=types.Money(cent_amount=2000, currency_code="GBP"), interaction_id="8525483242578266", state=types.TransactionState.SUCCESS, ) ], interface_interactions=[ types.CustomFieldsDraft( type=types.TypeResourceIdentifier(id=custom_type.id), fields=types.FieldContainer( { "operations": "CANCEL,CAPTURE,REFUND", "success": True, "psp_reference": "8525483242578266", "merchant_reference": "some reference", "reason": "82132:0005:10/2020", "amount": 2000, "payment_method": "mc", "event_date": "2019-01-24T11:04:17.000000Z", "currency_code": "GBP", "event_code": "AUTHORISATION", "merchant_account_code": "TestMerchant", } ), ) ], ) ) assert payment.id assert payment.key == "test-payment"
def create_products(client): for i in range(100): client.products.create( types.ProductDraft( key=f"test-product-{i}", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=f"my-product-{i}"), slug=types.LocalizedString(en=f"my-product-{i}"), ) )
def test_delete_by_key(client): shopping_list = client.shopping_lists.create(draft=types.ShoppingListDraft( key="test-shopping-list", name=types.LocalizedString({"nl": "Verlanglijstje"}), description=types.LocalizedString({"nl": "Verlanglijstje van LabD"}), )) assert shopping_list.id shopping_list = client.shopping_lists.delete_by_key( shopping_list.key, version=shopping_list.version)
def test_non_equality(): obj_1 = types.ProductDraft( slug=types.LocalizedString(en="test-2"), name=types.LocalizedString(en="test-1"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), ) obj_2 = types.ProductDraft( slug=types.LocalizedString(en="test-1"), name=types.LocalizedString(en="test-1"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), ) assert obj_1 != obj_2
def test_resource_update_conflict(client): """Test the return value of the update methods. It doesn't test the actual update itself. TODO: See if this is worth testing since we're using a mocking backend """ product = client.products.create( types.ProductDraft( key="test-product", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name={"en": "my-product"}, slug={"en": "foo-bar"}, )) assert product.version == 1 assert uuid.UUID(product.id) assert product.key == "test-product" product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], ) assert product.key == "test-product" assert product.version == 2 # This should raise a version conflict error with pytest.raises(CommercetoolsError) as exc: product = client.products.update_by_id( id=product.id, version=1, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug3")) ], ) assert exc.value.response.status_code == 409 assert exc.value.response.errors[0].current_version == 2 # Force it product = client.products.update_by_id( id=product.id, version=1, actions=[ types.ProductChangeSlugAction(slug=types.LocalizedString( nl="nl-slug2")) ], force_update=True, )
def test_products_create(client): custom_type = client.types.create( types.TypeDraft( name=types.LocalizedString(en="myType"), key="my-type", resource_type_ids=[types.ResourceTypeId.ASSET], field_definitions=[ types.FieldDefinition( name="foo", type=types.CustomFieldStringType(), label=types.LocalizedString(en="foo"), required=False, ) ], ) ) assert custom_type.id draft = types.ProductDraft( key="test-product", publish=True, name=types.LocalizedString(en=f"my-product"), slug=types.LocalizedString(en=f"my-product"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), master_variant=types.ProductVariantDraft( assets=[ types.AssetDraft( sources=[], name=types.LocalizedString(en="something"), custom=types.CustomFieldsDraft( type=types.TypeResourceIdentifier(id=custom_type.id), fields=types.FieldContainer(foo="bar"), ), ) ], prices=[ types.PriceDraft( value=types.CentPrecisionMoneyDraft( cent_amount=1000, currency_code="EUR" ), country="NL", ) ], ), ) product = client.products.create(draft) assert product.id assert product.master_data.current.master_variant.assets assert product.master_data.current.master_variant.prices
def test_product_update_add_change_price_staged(client): product = client.products.create( types.ProductDraft( key="test-product", name=types.LocalizedString(en=f"my-product-1"), slug=types.LocalizedString(en=f"my-product-1"), product_type=types.ProductTypeResourceIdentifier(key="dummy"), master_variant=types.ProductVariantDraft(sku="1", key="1"), ) ) product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductAddPriceAction( sku="1", price=types.PriceDraft( value=types.Money(cent_amount=1000, currency_code="GBP") ), ) ], ) assert product.master_data.current is None assert len(product.master_data.staged.master_variant.prices) == 1 price = product.master_data.staged.master_variant.prices[0] assert price.value.cent_amount == 1000 assert price.value.currency_code == "GBP" product = client.products.update_by_id( id=product.id, version=product.version, actions=[ types.ProductChangePriceAction( price_id=price.id, price=types.PriceDraft( value=types.Money(cent_amount=3000, currency_code="EUR") ), ) ], ) assert product.master_data.current is None assert len(product.master_data.staged.master_variant.prices) == 1 price = product.master_data.staged.master_variant.prices[0] assert price.value.cent_amount == 3000 assert price.value.currency_code == "EUR"
def _create_line_item_from_draft( self, draft: types.CartDraft, line_item_draft: types.LineItemDraft) -> types.LineItem: line_id = str(uuid.uuid4()) price = 1000 return types.LineItem( id=line_id, name=types.LocalizedString({"en": line_id}), price=types.Price(value=types.CentPrecisionMoney( currency_code=draft.currency, cent_amount=price)), taxed_price=types.TaxedItemPrice( total_net=types.CentPrecisionMoney( currency_code=draft.currency, cent_amount=price * (line_item_draft.quantity or 0), fraction_digits=2, ), total_gross=types.CentPrecisionMoney( currency_code=draft.currency, cent_amount=price * (line_item_draft.quantity or 0), fraction_digits=2, ), ), total_price=types.CentPrecisionMoney( currency_code=draft.currency, cent_amount=price * (line_item_draft.quantity or 0), ), quantity=line_item_draft.quantity, price_mode=types.LineItemPriceMode.PLATFORM, line_item_mode=types.LineItemMode.STANDARD, custom=utils.create_from_draft(line_item_draft.custom), )
def _create_from_draft(self, obj: types.ProductDraft, id: typing.Optional[str] = None) -> types.Product: object_id = str(uuid.UUID(id) if id is not None else uuid.uuid4()) product = types.Product( id=str(object_id), key=obj.key, product_type=obj.product_type, version=1, created_at=datetime.datetime.now(), last_modified_at=datetime.datetime.now(), ) product_data = types.ProductData( name=obj.name, categories=obj.categories, category_order_hints=obj.category_order_hints, description=obj.description, master_variant=obj.master_variant, slug=obj.slug or types.LocalizedString(), ) if obj.publish: product.master_data = types.ProductCatalogData( staged=None, current=product_data, published=True) else: product.master_data = types.ProductCatalogData(staged=product_data, current=None, published=False) return product
def test_http_server_expanding(commercetools_client, commercetools_http_server): os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" client = Client( project_key="unittest", client_id="client-id", client_secret="client-secret", scope=[], url=commercetools_http_server.api_url, token_url=f"{commercetools_http_server.api_url}/oauth/token", ) client.channels.create( ChannelDraft(key="FOO", roles=[ChannelRoleEnum.PRODUCT_DISTRIBUTION])) store = client.stores.create( StoreDraft( name=types.LocalizedString(nl="foo"), key="FOO", distribution_channels=[ChannelResourceIdentifier(key="FOO")], )) url = commercetools_http_server.api_url + f"/unittest/stores/{store.id}" response = requests.get( url, params={"expand": "distributionChannels[*]"}, headers={"Authorization": "Bearer token"}, ) assert response.status_code == 200, response.text data = response.json() assert data["distributionChannels"][0]["obj"]["key"] == "FOO"
def test_products_create(client): custom_type = client.types.create( types.TypeDraft(name=types.LocalizedString(en="myType"), resource_type_ids=[types.ResourceTypeId.ASSET], field_definitions=[types.FieldDefinition(name="foo")])) assert custom_type.id draft = types.ProductDraft( key="test-product", publish=True, master_variant=types.ProductVariantDraft( assets=[ types.AssetDraft(custom=types.CustomFieldsDraft( type=types.TypeResourceIdentifier(id=custom_type.id), fields=types.FieldContainer(foo="bar"), )) ], prices=[ types.PriceDraft( value=types.Money(cent_amount=1000, currency_code="EUR"), country="NL", ) ], ), ) product = client.products.create(draft) assert product.id assert product.master_data.current.master_variant.assets assert product.master_data.current.master_variant.prices
def test_product_projections_get_by_key(client): variant = types.ProductVariantDraft() product_create = client.products.create( types.ProductDraft( key="test-product", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=f"my-product"), slug=types.LocalizedString(en=f"my-product"), master_variant=variant, variants=[variant], publish=False, ) ) product = client.product_projections.get_by_key(product_create.key, staged=True) assert product.id == product_create.id assert product.key == product_create.key
def test_category_get_by_id(client): category = client.categories.create( types.CategoryDraft( key="test-category", name=types.LocalizedString(en="category"), slug=types.LocalizedString(en="something"), )) assert category.id assert category.key == "test-category" category = client.categories.get_by_id(category.id) assert category.id assert category.key == "test-category" with pytest.raises(HTTPError): client.categories.get_by_id("invalid")
def test_discount_code_query(client): client.discount_codes.create( types.DiscountCodeDraft(name=types.LocalizedString( {"en:": "test discount"}), code="1337")) client.discount_codes.create( types.DiscountCodeDraft(name=types.LocalizedString( {"en:": "test discount"}), code="1338")) # single sort query result = client.discount_codes.query(sort="id asc") assert len(result.results) == 2 assert result.total == 2 # multiple sort queries result = client.discount_codes.query(sort=["id asc", "name asc"]) assert len(result.results) == 2 assert result.total == 2
def test_query(client): shopping_list_draft = types.ShoppingListDraft( key="test-shopping-list", name=types.LocalizedString({"nl": "Verlanglijstje"}), description=types.LocalizedString({"nl": "Verlanglijstje van LabD"}), ) client.shopping_lists.create(draft=shopping_list_draft) # Update the key and create another one. shopping_list_draft.key = "test-shopping-list2" client.shopping_lists.create(draft=shopping_list_draft) result = client.shopping_lists.query(sort="id asc", limit=10) assert len(result.results) == 2 assert result.total == 2 result = client.shopping_lists.query(sort=["id asc", "name asc"], limit=1) assert len(result.results) == 1 assert result.total == 2
def test_products_get_by_key(client): product = client.products.create( types.ProductDraft( key="test-product", product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en="my-product"), slug=types.LocalizedString(en="my-product"), publish=True, ) ) assert product.id assert product.key == "test-product" product = client.products.get_by_key("test-product") assert product.id assert product.key == "test-product" with pytest.raises(HTTPError) as e: client.products.get_by_key("invalid")
def test_product_projections_query(client): for key in ["product-1", "product-2"]: variant = types.ProductVariantDraft() client.products.create( types.ProductDraft( key=key, product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=key), slug=types.LocalizedString(en=key), master_variant=variant, variants=[variant], publish=True, ) ) key = "product-3" client.products.create( types.ProductDraft( key=key, product_type=types.ProductTypeResourceIdentifier(key="dummy"), name=types.LocalizedString(en=key), slug=types.LocalizedString(en=key), master_variant=variant, variants=[variant], publish=False, ) ) # single sort query result = client.product_projections.query( sort="id asc", where=[f'slug(nl-NL="product-3")'], expand=["parent.category"] ) assert len(result.results) == 2 assert result.total == 2 assert result.results[0].key == "product-1" assert result.results[1].key == "product-2" # multiple sort queries result = client.product_projections.query(sort=["id asc", "name asc"]) assert len(result.results) == 2 assert result.total == 2
def test_product_discount_get_by_id(client): product_discount = client.product_discounts.create( types.ProductDiscountDraft( name=types.LocalizedString(nl="test-discount"), predicate="", value=types.ProductDiscountValueRelativeDraft(permyriad=10), is_active=True, sort_order="", ) ) assert product_discount.id