Best Python code snippet using lisa_python
mutations.py
Source:mutations.py  
...138        variants = cleaned_input.get("variants")139        quantities = cleaned_input.get("quantities")140        if variants and quantities:141            for variant, quantity in zip(variants, quantities):142                add_variant_to_checkout(instance, variant, quantity)143    @classmethod144    def perform_mutation(cls, _root, info, **data):145        user = info.context.user146        # `perform_mutation` is overridden to properly get or create a checkout147        # instance here and abort mutation if needed.148        if user.is_authenticated:149            checkout, created = get_or_create_user_checkout(user)150            # If user has an active checkout, return it without any151            # modifications.152            if not created:153                return CheckoutCreate(checkout=checkout)154        else:155            checkout = models.Checkout()156        cleaned_input = cls.clean_input(info, checkout, data.get("input"))157        checkout = cls.construct_instance(checkout, cleaned_input)158        cls.clean_instance(checkout)159        cls.save(info, checkout, cleaned_input)160        cls._save_m2m(info, checkout, cleaned_input)161        return CheckoutCreate(checkout=checkout)162class CheckoutLinesAdd(BaseMutation):163    checkout = graphene.Field(Checkout, description="An updated Checkout.")164    class Arguments:165        checkout_id = graphene.ID(description="The ID of the Checkout.", required=True)166        lines = graphene.List(167            CheckoutLineInput,168            required=True,169            description=(170                "A list of checkout lines, each containing information about "171                "an item in the checkout."172            ),173        )174    class Meta:175        description = "Adds a checkout line to the existing checkout."176    @classmethod177    def perform_mutation(cls, _root, info, checkout_id, lines, replace=False):178        checkout = cls.get_node_or_error(179            info, checkout_id, only_type=Checkout, field="checkout_id"180        )181        variant_ids = [line.get("variant_id") for line in lines]182        variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)183        quantities = [line.get("quantity") for line in lines]184        check_lines_quantity(variants, quantities)185        # FIXME test if below function is called186        clean_shipping_method(187            checkout=checkout,188            method=checkout.shipping_method,189            discounts=info.context.discounts,190        )191        if variants and quantities:192            for variant, quantity in zip(variants, quantities):193                add_variant_to_checkout(checkout, variant, quantity, replace=replace)194        recalculate_checkout_discount(checkout, info.context.discounts)195        return CheckoutLinesAdd(checkout=checkout)196class CheckoutLinesUpdate(CheckoutLinesAdd):197    checkout = graphene.Field(Checkout, description="An updated Checkout.")198    class Meta:199        description = "Updates CheckoutLine in the existing Checkout."200    @classmethod201    def perform_mutation(cls, root, info, checkout_id, lines):202        return super().perform_mutation(root, info, checkout_id, lines, replace=True)203class CheckoutLineDelete(BaseMutation):204    checkout = graphene.Field(Checkout, description="An updated checkout.")205    class Arguments:206        checkout_id = graphene.ID(description="The ID of the Checkout.", required=True)207        line_id = graphene.ID(description="ID of the CheckoutLine to delete.")208    class Meta:209        description = "Deletes a CheckoutLine."210    @classmethod211    def perform_mutation(cls, _root, info, checkout_id, line_id):212        checkout = cls.get_node_or_error(213            info, checkout_id, only_type=Checkout, field="checkout_id"214        )215        line = cls.get_node_or_error(216            info, line_id, only_type=CheckoutLine, field="line_id"217        )218        if line and line in checkout.lines.all():219            line.delete()220        # FIXME test if below function is called221        clean_shipping_method(222            checkout=checkout,223            method=checkout.shipping_method,224            discounts=info.context.discounts,225        )226        recalculate_checkout_discount(checkout, info.context.discounts)227        return CheckoutLineDelete(checkout=checkout)228class CheckoutCustomerAttach(BaseMutation):229    checkout = graphene.Field(Checkout, description="An updated checkout.")230    class Arguments:231        checkout_id = graphene.ID(required=True, description="ID of the Checkout.")232        customer_id = graphene.ID(required=True, description="The ID of the customer.")233    class Meta:234        description = "Sets the customer as the owner of the Checkout."235    @classmethod236    def perform_mutation(cls, _root, info, checkout_id, customer_id):237        checkout = cls.get_node_or_error(238            info, checkout_id, only_type=Checkout, field="checkout_id"239        )240        customer = cls.get_node_or_error(241            info, customer_id, only_type=User, field="customer_id"242        )243        checkout.user = customer244        checkout.save(update_fields=["user"])245        return CheckoutCustomerAttach(checkout=checkout)246class CheckoutCustomerDetach(BaseMutation):247    checkout = graphene.Field(Checkout, description="An updated checkout")248    class Arguments:249        checkout_id = graphene.ID(description="Checkout ID", required=True)250    class Meta:251        description = "Removes the user assigned as the owner of the checkout."252    @classmethod253    def perform_mutation(cls, _root, info, checkout_id):254        checkout = cls.get_node_or_error(255            info, checkout_id, only_type=Checkout, field="checkout_id"256        )257        checkout.user = None258        checkout.save(update_fields=["user"])259        return CheckoutCustomerDetach(checkout=checkout)260class CheckoutAddressUpdate(BaseMutation, I18nMixin):261    checkout = graphene.Field(Checkout, description="An updated checkout")262    class Arguments:263        checkout_id = graphene.ID(required=True, description="ID of the Checkout.")264        address = AddressInput(265            required=True,266            description="The mailing address to where the checkout will be shipped.",267        )268    class Meta:269        description = "Update shipping address in the existing Checkout."270    @classmethod271    def perform_mutation(cls, _root, info, checkout_id, address):272        checkout = cls.get_node_or_error(273            info, checkout_id, only_type=Checkout, field="checkout_id"274        )275        address = cls.validate_address(276            address, instance=checkout.address277        )278        # FIXME test if below function is called279        clean_shipping_method(280            checkout=checkout,281            method=checkout.shipping_method,282            discounts=info.context.discounts,283        )284        with transaction.atomic():285            address.save()286            change_address_in_checkout(checkout, address)287        recalculate_checkout_discount(checkout, info.context.discounts)288        return CheckoutAddressUpdate(checkout=checkout)289class CheckoutEmailUpdate(BaseMutation):290    checkout = graphene.Field(Checkout, description="An updated checkout")291    class Arguments:292        checkout_id = graphene.ID(description="Checkout ID")293        email = graphene.String(required=True, description="email")294    class Meta:295        description = "Updates email address in the existing Checkout object."296    @classmethod297    def perform_mutation(cls, _root, info, checkout_id, email):298        checkout = cls.get_node_or_error(299            info, checkout_id, only_type=Checkout, field="checkout_id"300        )301        checkout.email = email302        cls.clean_instance(checkout)303        checkout.save(update_fields=["email"])304        return CheckoutEmailUpdate(checkout=checkout)305class CheckoutShippingMethodUpdate(BaseMutation):306    checkout = graphene.Field(Checkout, description="An updated checkout")307    class Arguments:308        checkout_id = graphene.ID(description="Checkout ID")309        shipping_method_id = graphene.ID(required=True, description="Shipping method")310    class Meta:311        description = "Updates the shipping address of the checkout."312    @classmethod313    def perform_mutation(cls, _root, info, checkout_id, shipping_method_id):314        checkout_id = from_global_id_strict_type(315            info, checkout_id, only_type=Checkout, field="checkout_id"316        )317        checkout = models.Checkout.objects.prefetch_related(318            "lines__variant__product__collections"319        ).get(pk=checkout_id)320        shipping_method = cls.get_node_or_error(321            info,322            shipping_method_id,323            only_type=ShippingMethod,324            field="shipping_method_id",325        )326        clean_shipping_method(327            checkout=checkout,328            method=shipping_method,329            discounts=info.context.discounts,330            remove=False,331        )332        checkout.shipping_method = shipping_method333        checkout.save(update_fields=["shipping_method"])334        recalculate_checkout_discount(checkout, info.context.discounts)335        return CheckoutShippingMethodUpdate(checkout=checkout)336class CheckoutComplete(BaseMutation):337    order = graphene.Field(Order, description="Placed order")338    class Arguments:339        checkout_id = graphene.ID(description="Checkout ID", required=True)340    class Meta:341        description = (342            "Completes the checkout. As a result a new order is created and "343            "a payment charge is made. This action requires a successful "344            "payment before it can be performed."345        )346    @classmethod347    def perform_mutation(cls, _root, info, checkout_id):348        checkout = cls.get_node_or_error(349            info, checkout_id, only_type=Checkout, field="checkout_id"350        )351        clean_checkout(checkout, info.context.discounts)352        payment = checkout.get_last_active_payment()353        with transaction.atomic():354            try:355                order_data = prepare_order_data(356                    checkout=checkout,357                    tracking_code=analytics.get_client_id(info.context),358                    discounts=info.context.discounts,359                )360            except InsufficientStock as e:361                raise ValidationError(f"Insufficient product stock: {e.item}")362            except voucher_model.NotApplicable:363                raise ValidationError("Voucher not applicable")364            except TaxError as tax_error:365                return ValidationError(366                    "Unable to calculate taxes - %s" % str(tax_error)367                )368        try:369            address = order_data["address"]  # type: models.Address370            gateway_process_payment(371                payment=payment,372                payment_token=payment.token,373                address=AddressData(**address.as_data()),374            )375        except PaymentError as e:376            abort_order_data(order_data)377            raise ValidationError(str(e))378        # create the order into the database379        order = create_order(380            checkout=checkout, order_data=order_data, user=info.context.user381        )382        # remove checkout after order is successfully paid383        checkout.delete()384        # return the success response with the newly created order data385        return CheckoutComplete(order=order)386class CheckoutUpdateVoucher(BaseMutation):387    checkout = graphene.Field(Checkout, description="An checkout with updated voucher")388    class Arguments:389        checkout_id = graphene.ID(description="Checkout ID", required=True)390        voucher_code = graphene.String(description="Voucher code")391    class Meta:392        description = (393            "DEPRECATED: Use CheckoutAddPromoCode or CheckoutRemovePromoCode instead. "394            "Adds voucher to the checkout. Query it without voucher_code "395            "field to remove voucher from checkout."396        )397    @classmethod398    def perform_mutation(cls, _root, info, checkout_id, voucher_code=None):399        checkout = cls.get_node_or_error(400            info, checkout_id, only_type=Checkout, field="checkout_id"401        )402        if voucher_code:403            try:404                voucher = voucher_model.Voucher.objects.active(date=timezone.now()).get(405                    code=voucher_code406                )407            except voucher_model.Voucher.DoesNotExist:408                raise ValidationError(409                    {"voucher_code": "Voucher with given code does not exist."}410                )411            try:412                add_voucher_to_checkout(checkout, voucher)413            except voucher_model.NotApplicable:414                raise ValidationError(415                    {"voucher_code": "Voucher is not applicable to that checkout."}416                )417        else:418            existing_voucher = get_voucher_for_checkout(checkout)419            if existing_voucher:420                remove_voucher_from_checkout(checkout)421        return CheckoutUpdateVoucher(checkout=checkout)422class CheckoutAddPromoCode(BaseMutation):423    checkout = graphene.Field(424        Checkout, description="The checkout with the added gift card or voucher"425    )426    class Arguments:427        checkout_id = graphene.ID(description="Checkout ID", required=True)428        promo_code = graphene.String(429            description="Gift card code or voucher code", required=True430        )431    class Meta:432        description = "Adds a gift card or a voucher to a checkout."433    @classmethod434    def perform_mutation(cls, _root, info, checkout_id, promo_code):435        checkout = cls.get_node_or_error(436            info, checkout_id, only_type=Checkout, field="checkout_id"437        )438        add_promo_code_to_checkout(checkout, promo_code, info.context.discounts)439        return CheckoutAddPromoCode(checkout=checkout)440class CheckoutRemovePromoCode(BaseMutation):441    checkout = graphene.Field(442        Checkout, description="The checkout with the removed gift card or voucher"443    )444    class Arguments:445        checkout_id = graphene.ID(description="Checkout ID", required=True)446        promo_code = graphene.String(447            description="Gift card code or voucher code", required=True448        )449    class Meta:450        description = "Remove a gift card or a voucher from a checkout."451    @classmethod452    def perform_mutation(cls, _root, info, checkout_id, promo_code):453        checkout = cls.get_node_or_error(454            info, checkout_id, only_type=Checkout, field="checkout_id"455        )456        remove_promo_code_from_checkout(checkout, promo_code)...test_checkout.py
Source:test_checkout.py  
1import unittest2from checkout import Checkout3class CheckoutTest(unittest.TestCase):4    def test_one_a(self):5        checkout = Checkout()6        checkout.scan("A")7        self.assertEqual(50, checkout.total)8    def test_two_a(self):9        checkout = Checkout()10        checkout.scan("A")11        checkout.scan("A")12        self.assertEqual(100, checkout.total)13    def test_three_a(self):14        checkout = Checkout()15        checkout.scan("A")16        checkout.scan("A")17        checkout.scan("A")18        self.assertEqual(130, checkout.total)19    def test_three_a(self):20        checkout = Checkout()21        checkout.scan("A")22        checkout.scan("A")23        checkout.scan("A")24        checkout.scan("A")25        checkout.scan("A")26        checkout.scan("A")27        self.assertEqual(260, checkout.total)28    def test_one_b(self):29        checkout = Checkout()30        checkout.scan("B")31        self.assertEqual(30, checkout.total)32    def test_two_b(self):33        checkout = Checkout()34        checkout.scan("B")35        checkout.scan("B")36        self.assertEqual(45, checkout.total)37    def test_three_b(self):38        checkout = Checkout()39        checkout.scan("B")40        checkout.scan("B")41        checkout.scan("B")42        checkout.scan("B")43        self.assertEqual(90, checkout.total)44    def test_simple(self):45        checkout = Checkout()46        checkout.scan("A")47        self.assertEqual(50, checkout.total)48        checkout.scan("B")49        self.assertEqual(80, checkout.total)50        checkout.scan("C")51        self.assertEqual(100, checkout.total)52        checkout.scan("D")53        self.assertEqual(115, checkout.total)54    def test_incremental(self):55        checkout = Checkout()56        checkout.scan("A")57        self.assertEqual(50, checkout.total)58        checkout.scan("B")59        self.assertEqual(80, checkout.total)60        checkout.scan("A")61        self.assertEqual(130, checkout.total)62        checkout.scan("A")63        self.assertEqual(160, checkout.total)64        checkout.scan("B")65        self.assertEqual(175, checkout.total)66        checkout.scan("C")67        self.assertEqual(195, checkout.total)68        checkout.scan("B")69        self.assertEqual(225, checkout.total)70        checkout.scan("C")71        self.assertEqual(245, checkout.total)72        checkout.scan("D")73        self.assertEqual(260, checkout.total)74        checkout.scan("D")75        self.assertEqual(275, checkout.total)76        checkout.scan("D")77        self.assertEqual(290, checkout.total)78        checkout.scan("C")79        self.assertEqual(310, checkout.total)80if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
