Best Python code snippet using localstack_python
factory.py
Source:factory.py  
...25                       arguments to the delegate method for creating the model26        :return: A model27        """28        args = {**self.default_args, **kwargs}29        model = self._do_create(**args)30        self.models.append(model)31        return model32    def _do_create(self, **kwargs) -> Any:33        """34        Overridden by implementors to perform the actual creation of the model.35        :param kwargs: Arguments for model creation36        :return: A model37        """38        pass39    def cleanup(self):40        """41        Cleans up after this factory by deleting all created models.42        """43        for model in self.models:44            self.db.session.delete(model)45        self.db.session.commit()46class PatientFactory(ModelFactory):47    def __init__(self, db: SQLAlchemy):48        super(PatientFactory, self).__init__(49            db,50            patientName="Test",51            patientSex="FEMALE",52            isPregnant=False,53            zone="37",54            villageNumber="37",55        )56    def create(self, **kwargs) -> Any:57        """58        Creates a new patient.59        :param kwargs: Keyword arguments60        :key patientId: Unique id of the patient to create61        :return:62        """63        return super().create(**kwargs)64    def _do_create(self, **kwargs) -> Any:65        from database.PatientRepoNew import PatientRepo66        return PatientRepo().create_model(dict(**kwargs))67class ReadingFactory(ModelFactory):68    def __init__(self, db: SQLAlchemy):69        super(ReadingFactory, self).__init__(70            db,71            bpSystolic=110,72            bpDiastolic=80,73            heartRateBPM=70,74            symptoms="",75            dateTimeTaken=1594514397,76            userId=1,77        )78    def create(self, **kwargs) -> Any:79        """80        Creates a new reading.81        :param kwargs: Keyword arguments82        :key readingId: Unique id of the patient to create83        :key patientId: Id of the patient to associate this reading with84        :return:85        """86        return super().create(**kwargs)87    def _do_create(self, **kwargs) -> Any:88        from database.ReadingRepoNew import ReadingRepo89        return ReadingRepo().create_model(dict(**kwargs))90class ReferralFactory(ModelFactory):91    def __init__(self, db: SQLAlchemy):92        super(ReferralFactory, self).__init__(93            db,94            dateReferred=1594514397,95            userId=1,96            referralHealthFacilityName="H0000",97        )98    def create(self, **kwargs):99        """100        Creates a new referral.101        :param kwargs: Keyword arguments102        :key patientId: Id of the patient to associate this referral with103        :key readingId: Id of the reading to associate this referral with104        :return:105        """106        return super().create(**kwargs)107    def _do_create(self, **kwargs) -> Any:108        from database.ReferralRepo import ReferralRepo109        return ReferralRepo().create_model(dict(**kwargs))110class FollowUpFactory(ModelFactory):111    def __init__(self, db: SQLAlchemy):112        super(FollowUpFactory, self).__init__(113            db, dateAssessed=1594514397, healthcareWorkerId=1114        )115    def create(self, **kwargs):116        """117        Creates a new followup.118        :param kwargs: Keyword arguments119        :key readingId: Id of the reading to associate this followup with120        :return:121        """122        return super().create(**kwargs)123    def _do_create(self, **kwargs) -> Any:124        from database.FollowUpRepo import FollowUpRepo125        return FollowUpRepo().create_model(dict(**kwargs))126class UserFactory(ModelFactory):127    def __init__(self, db: SQLAlchemy):128        super(UserFactory, self).__init__(129            db, password="password", healthFacilityName="H0000", role="ADMIN"130        )131    def create(self, **kwargs) -> Any:132        """133        Creates a new user.134        :param kwargs: Keyword arguments135        :key email: Unique email for the user136        :return: A ``User`` model137        """138        return super().create(**kwargs)139    def _do_create(self, **kwargs) -> Any:140        import data141        from config import flask_bcrypt142        from models import User, Role143        d = dict(**kwargs)144        role_name = d["role"]145        del d["role"]  # not an actual user field so delete if from the args146        # Hash the user's password so that they can login147        d["password"] = flask_bcrypt.generate_password_hash(d["password"])148        user = marshal.unmarshal(User, d)149        crud.create(user)150        role = crud.read(Role, name=role_name)151        user.roleIds = [role]152        data.db_session.commit()153        return user154class HealthFacilityFactory(ModelFactory):155    def __init__(self, db: SQLAlchemy):156        super(HealthFacilityFactory, self).__init__(db)157    def create(self, **kwargs) -> Any:158        """159        Creates a new health facility.160        :param kwargs: Keyword arguments161        :key healthFacilityName: Unique health facility name162        :return: A ``HealthFacility`` model163        """164        return super().create(**kwargs)165    def _do_create(self, **kwargs) -> Any:166        from database.HealthFacilityRepoNew import HealthFacilityRepo...forms.py
Source:forms.py  
1"""2Forms for the directory application.3"""4###############################################################5from collections import OrderedDict6from django import forms7from django.conf import settings8from django.forms.utils import ErrorDict9from .models import DirectoryEntry10###############################################################11class DirectoryEntryForm(forms.ModelForm):12    """13    A form for updating directory entries.14    """15    class Meta:16        model = DirectoryEntry17        exclude = ["active", "person", "type", "title", "office", "ordering"]18        widgets = {19            "url": forms.TextInput(attrs={"size": 80}),20            "note": forms.TextInput(attrs={"size": 80}),21        }22    class Media:23        css = {24            "all": (25                settings.STATIC_URL + "css/forms.css",26                settings.STATIC_URL + "css/twoColumn.css",27            )28        }29###############################################################30class DirectoryEntryPersonSubForm(forms.ModelForm):31    """32    The sub form for the person form.33    """34    subform_title = "Directory entry"35    class Meta:36        model = DirectoryEntry37        fields = ["active", "type", "title", "office", "url", "note"]38        widgets = {39            "url": forms.TextInput(attrs={"size": 50}),40            "note": forms.TextInput(attrs={"size": 50}),41        }42    def __init__(self, data=None, *args, **kwargs):43        """44        If instance is passed, then we must resolve this: it is a person!45        """46        if "instance" in kwargs and kwargs["instance"] is not None:47            person = kwargs["instance"]48            object_list = person.directoryentry_set.all()49            if object_list.count() > 0:50                kwargs["instance"] = object_list[0]51            else:52                del kwargs["instance"]  # no instance53        result = super(DirectoryEntryPersonSubForm, self).__init__(54            data, *args, **kwargs55        )56        # allow for this sub-object to *not* be created:57        if "instance" not in kwargs or kwargs["instance"] is None:58            f = forms.BooleanField(label="Create directory entry", required=False)59            self.fields = OrderedDict([("_do_create", f)] + list(self.fields.items()))60            self.initial["_do_create"] = True61            del self.fields["active"]  # of course it will be active, if created.62            # when NOT creating (if we could have)... nothing is required:63            if data and not data.get(self.get_do_create_field_name(), False):64                for key in self.fields:65                    self.fields[key].required = False66        return result67    def get_do_create_field_name(self):68        if self.prefix:69            prefix_field = self.prefix + "-" + "_do_create"70        else:71            prefix_field = "_do_create"72        return prefix_field73    def full_clean(self, *args, **kwargs):74        """75        Override clean behaviour when _do_create is *not* set.76        """77        self._errors = ErrorDict()78        if not self.is_bound:  # Stop further processing.79            return80        if "_do_create" in self.fields and not self.data.get(81            self.get_do_create_field_name(), False82        ):83            self.cleaned_data = {"_do_create": False}84        else:85            return super(DirectoryEntryPersonSubForm, self).full_clean(*args, **kwargs)86    def save(self, person, *args, **kwargs):87        """88        Each save() must reinsert the person, along with any other required89        fields that are not shown.90        """91        # allow for this sub-object to *not* be created:92        if "_do_create" in self.fields and self.cleaned_data["_do_create"] == False:93            return None94        original_commit = kwargs.get("commit", None)95        kwargs["commit"] = False96        obj = super(DirectoryEntryPersonSubForm, self).save(*args, **kwargs)97        obj.person = person98        if original_commit is not None:99            kwargs["commit"] = original_commit100        else:101            del kwargs["commit"]102        # check original commit:103        if original_commit != False:  # None \equiv True104            person.add_flag_by_name("directory")105        return super(DirectoryEntryPersonSubForm, self).save(*args, **kwargs)...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!!
