Best Python code snippet using localstack_python
pages.py
Source:pages.py  
1from collections import defaultdict2from datetime import date3from typing import TYPE_CHECKING, Dict, List4import graphene5from django.core.exceptions import ValidationError6from django.db import transaction7from ....attribute import AttributeType8from ....core.permissions import PagePermissions, PageTypePermissions9from ....page import models10from ....page.error_codes import PageErrorCode11from ...attribute.utils import AttributeAssignmentMixin12from ...core.mutations import ModelDeleteMutation, ModelMutation13from ...core.types.common import PageError, SeoInput14from ...core.utils import (15    clean_seo_fields,16    get_duplicates_ids,17    validate_slug_and_generate_if_needed,18)19from ...product.mutations.products import AttributeValueInput20if TYPE_CHECKING:21    from ....attribute.models import Attribute22class PageInput(graphene.InputObjectType):23    slug = graphene.String(description="Page internal name.")24    title = graphene.String(description="Page title.")25    content = graphene.String(26        description=("Page content. May consist of ordinary text, HTML and images.")27    )28    content_json = graphene.JSONString(description="Page content in JSON format.")29    attributes = graphene.List(30        graphene.NonNull(AttributeValueInput), description="List of attributes."31    )32    is_published = graphene.Boolean(33        description="Determines if page is visible in the storefront."34    )35    publication_date = graphene.String(36        description="Publication date. ISO 8601 standard."37    )38    seo = SeoInput(description="Search engine optimization fields.")39class PageCreateInput(PageInput):40    page_type = graphene.ID(41        description="ID of the page type that page belongs to.", required=True42    )43class PageCreate(ModelMutation):44    class Arguments:45        input = PageCreateInput(46            required=True, description="Fields required to create a page."47        )48    class Meta:49        description = "Creates a new page."50        model = models.Page51        permissions = (PagePermissions.MANAGE_PAGES,)52        error_type_class = PageError53        error_type_field = "page_errors"54    @classmethod55    def clean_attributes(cls, attributes: dict, page_type: models.PageType):56        attributes_qs = page_type.page_attributes57        attributes = AttributeAssignmentMixin.clean_input(58            attributes, attributes_qs, is_page_attributes=True59        )60        return attributes61    @classmethod62    def clean_input(cls, info, instance, data):63        cleaned_input = super().clean_input(info, instance, data)64        try:65            cleaned_input = validate_slug_and_generate_if_needed(66                instance, "title", cleaned_input67            )68        except ValidationError as error:69            error.code = PageErrorCode.REQUIRED70            raise ValidationError({"slug": error})71        is_published = cleaned_input.get("is_published")72        publication_date = cleaned_input.get("publication_date")73        if is_published and not publication_date:74            cleaned_input["publication_date"] = date.today()75        attributes = cleaned_input.get("attributes")76        page_type = (77            instance.page_type if instance.pk else cleaned_input.get("page_type")78        )79        if attributes and page_type:80            try:81                cleaned_input["attributes"] = cls.clean_attributes(82                    attributes, page_type83                )84            except ValidationError as exc:85                raise ValidationError({"attributes": exc})86        clean_seo_fields(cleaned_input)87        return cleaned_input88    @classmethod89    @transaction.atomic90    def _save_m2m(cls, info, instance, cleaned_data):91        super()._save_m2m(info, instance, cleaned_data)92        attributes = cleaned_data.get("attributes")93        if attributes:94            AttributeAssignmentMixin.save(instance, attributes)95class PageUpdate(PageCreate):96    class Arguments:97        id = graphene.ID(required=True, description="ID of a page to update.")98        input = PageInput(99            required=True, description="Fields required to update a page."100        )101    class Meta:102        description = "Updates an existing page."103        model = models.Page104        permissions = (PagePermissions.MANAGE_PAGES,)105        error_type_class = PageError106        error_type_field = "page_errors"107class PageDelete(ModelDeleteMutation):108    class Arguments:109        id = graphene.ID(required=True, description="ID of a page to delete.")110    class Meta:111        description = "Deletes a page."112        model = models.Page113        permissions = (PagePermissions.MANAGE_PAGES,)114        error_type_class = PageError115        error_type_field = "page_errors"116class PageTypeCreateInput(graphene.InputObjectType):117    name = graphene.String(description="Name of the page type.")118    slug = graphene.String(description="Page type slug.")119    add_attributes = graphene.List(120        graphene.NonNull(graphene.ID),121        description="List of attribute IDs to be assigned to the page type.",122    )123class PageTypeUpdateInput(PageTypeCreateInput):124    remove_attributes = graphene.List(125        graphene.NonNull(graphene.ID),126        description="List of attribute IDs to be assigned to the page type.",127    )128class PageTypeMixin:129    @classmethod130    def validate_attributes(131        cls,132        errors: Dict[str, List[ValidationError]],133        attributes: List["Attribute"],134        field: str,135    ):136        """All attributes must be page type attribute.137        Raise an error if any of the attributes are not page attribute.138        """139        if attributes:140            not_valid_attributes = [141                graphene.Node.to_global_id("Attribute", attr.pk)142                for attr in attributes143                if attr.type != AttributeType.PAGE_TYPE144            ]145            if not_valid_attributes:146                error = ValidationError(147                    "Only page type attributes allowed.",148                    code=PageErrorCode.INVALID.value,149                    params={"attributes": not_valid_attributes},150                )151                errors[field].append(error)152class PageTypeCreate(PageTypeMixin, ModelMutation):153    class Arguments:154        input = PageTypeCreateInput(155            description="Fields required to create page type.", required=True156        )157    class Meta:158        description = "Create a new page type."159        model = models.PageType160        permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)161        error_type_class = PageError162        error_type_field = "page_errors"163    @classmethod164    def clean_input(cls, info, instance, data):165        cleaned_input = super().clean_input(info, instance, data)166        errors = defaultdict(list)167        try:168            cleaned_input = validate_slug_and_generate_if_needed(169                instance, "name", cleaned_input170            )171        except ValidationError as error:172            error.code = PageErrorCode.REQUIRED.value173            errors["slug"].append(error)174        cls.validate_attributes(175            errors, cleaned_input.get("add_attributes"), "add_attributes"176        )177        if errors:178            raise ValidationError(errors)179        return cleaned_input180    @classmethod181    def _save_m2m(cls, info, instance, cleaned_data):182        super()._save_m2m(info, instance, cleaned_data)183        attributes = cleaned_data.get("add_attributes")184        if attributes is not None:185            instance.page_attributes.add(*attributes)186class PageTypeUpdate(PageTypeMixin, ModelMutation):187    class Arguments:188        id = graphene.ID(description="ID of the page type to update.")189        input = PageTypeUpdateInput(190            description="Fields required to update page type.", required=True191        )192    class Meta:193        description = "Update page type."194        model = models.PageType195        permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)196        error_type_class = PageError197        error_type_field = "page_errors"198    @classmethod199    def check_for_duplicates(cls, errors: Dict[str, List[ValidationError]], data: dict):200        """Check if any items are on both list for adding and removing.201        Raise error if some of items are duplicated.202        """203        add_attributes = data.get("add_attributes")204        remove_attributes = data.get("remove_attributes")205        duplicated_ids = get_duplicates_ids(add_attributes, remove_attributes)206        if duplicated_ids:207            error_msg = (208                "The same object cannot be in both list"209                "for adding and removing items."210            )211            error = ValidationError(212                error_msg,213                code=PageErrorCode.DUPLICATED_INPUT_ITEM.value,214                params={"attributes": duplicated_ids},215            )216            errors["attributes"].append(error)217    @classmethod218    def clean_input(cls, info, instance, data):219        errors = defaultdict(list)220        cls.check_for_duplicates(errors, data)221        cleaned_input = super().clean_input(info, instance, data)222        try:223            cleaned_input = validate_slug_and_generate_if_needed(224                instance, "name", cleaned_input225            )226        except ValidationError as error:227            error.code = PageErrorCode.REQUIRED228            errors["slug"].append(error)229        add_attributes = cleaned_input.get("add_attributes")230        cls.validate_attributes(errors, add_attributes, "add_attributes")231        remove_attributes = cleaned_input.get("remove_attributes")232        cls.validate_attributes(errors, remove_attributes, "remove_attributes")233        if errors:234            raise ValidationError(errors)235        return cleaned_input236    @classmethod237    def _save_m2m(cls, info, instance, cleaned_data):238        super()._save_m2m(info, instance, cleaned_data)239        remove_attributes = cleaned_data.get("remove_attributes")240        add_attributes = cleaned_data.get("add_attributes")241        if remove_attributes is not None:242            instance.page_attributes.remove(*remove_attributes)243        if add_attributes is not None:244            instance.page_attributes.add(*add_attributes)245class PageTypeDelete(ModelDeleteMutation):246    class Arguments:247        id = graphene.ID(required=True, description="ID of the page type to delete.")248    class Meta:249        description = "Delete a page type."250        model = models.PageType251        permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)252        error_type_class = PageError...test_utils.py
Source:test_utils.py  
2from django.test import TransactionTestCase3from companies.models import Company4from companies.tests.factories import CompanyFactory5from companies.utils import import_companies6def remove_attributes(data: Dict) -> Dict:7    attributes_to_remove = {"_state", "id"}8    for attribute in attributes_to_remove:9        del data[attribute]10    return data11class TestUtils(TransactionTestCase):12    def setUp(self):13        self.test_data = {}14        companies = [15            CompanyFactory.build().__dict__,16            CompanyFactory.build().__dict__,17        ]18        for data in companies:19            clean_data = remove_attributes(data)20            self.test_data[clean_data["cnpj"]] = clean_data21    def test_import_companies(self):22        """23        Should successfully import distinct Companies data into the database24        """25        self.assertEqual(Company.objects.count(), 0)26        with self.assertNumQueries(1):27            import_companies(self.test_data.values())28        self.assertEqual(Company.objects.count(), len(self.test_data))29        for cnpj, data in self.test_data.items():30            company = Company.objects.get(cnpj=cnpj)31            company_dict = remove_attributes(company.__dict__)32            self.assertEqual(company_dict, data)33    def test_import_companies_ignoring_duplicates(self):34        """35        Should successfully import Company data into the database ignoring36        duplicates37        """38        self.assertEqual(Company.objects.count(), 0)39        first_key = list(self.test_data.keys())[0]40        test_element = self.test_data[first_key]41        test_data = [test_element, test_element]42        with self.assertNumQueries(1):43            import_companies(test_data)44        self.assertEqual(Company.objects.count(), 1)45        company = Company.objects.get(cnpj=test_element["cnpj"])46        company_dict = remove_attributes(company.__dict__)...reduct.py
Source:reduct.py  
1def reduct(model, attributes, dec) :2    k = model.konsistensi_tabel(attrs, dec)34    remove_attributes = [] 5    for a in attributes:6        R = remove_attributes.copy()7        R.append(a) 8        S = set(attributes) - set(R)9        k_s = model.konsistensi_tabel(list(S), dec)10        if k_s == k:11            remove_attributes.append(a)1213    reduct = list(set(attributes) - set(remove_attributes))14    reduct.sort()
...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!!
